- C3d aggiornamento librerie ( 118015).
This commit is contained in:
SaraP
2024-10-29 15:01:17 +01:00
parent 881ce088e8
commit 3ab0db8937
38 changed files with 984 additions and 231 deletions
+82 -7
View File
@@ -17,12 +17,41 @@
#include <mb_operation_result.h>
#include <curve3d.h>
class MbPolymesh;
class MbPolymeshTopo;
class MbHalfedgeBoundaryCriterionBase;
class MATH_CLASS MbMeshCurvatureParams;
class MATH_CLASS MbDrapeShellParams;
class MATH_CLASS MbDrapeShellResults;
class MbPolymesh;
class MbFaceShell;
class MbPolymeshTopo;
class MbHalfedgeBoundaryCriterionBase;
class MbMeshCurvatureParams;
class MbDrapeShellParams;
class MbDrapeShellResults;
class MbRemeshParams;
class MbShellLinearizationParams;
class MbMergePolymeshParams;
//------------------------------------------------------------------------------
/** \brief \ru Создать полигональный объект по оболочке.
\en Create the polymesh by the shell. \~
\details \ru Создать полигональный объект по оболочке.
В нем будет сохранен маппинг от регионов и ребер сегментации к граням и ребрам оболочки.
Любые операции, изменяющие топологию сегментации, приведут к невалидности маппинга.
\en Create the polymesh by the shell.
Creates mapping from segmentation edges to shell edges and from segmentation regions to shell faces.
Any operations that change segmentation topology will lead to invalid mapping.
\param[in] params - \ru Параметры алгоритма.
\en The parameters. \~
\param[in] shell - \ru Оболочка.
\en The shell. \~
\param[in,out] mesh - \ru Полигональная сетка.
\en The polymesh. \~
\return \ru Код результата операции, rt_Success в случае успеха.
\en Returns the operation result code, rt_Success if polymesh has been created. \n
\ingroup Polygonal_Objects
\warning \ru В разработке.
\en Under development. \~
*/
// ---
MATH_FUNC( MbResultType ) CreatePolymeshByShell( const MbShellLinearizationParams & params, const MbFaceShell & shell, MbPolymesh & mesh );
//------------------------------------------------------------------------------
@@ -183,7 +212,7 @@ MATH_FUNC( bool ) CutPolymeshByPlane( const MbPlacement3D & place,
//------------------------------------------------------------------------------
/** \brief \ru Скопировать часть полигонального объекта в другой полигональный объект.
\en Copy the part of a polygonal object into another polyginal object. \~
\en Copy the part of a polygonal object into another polygonal object. \~
\param[in] mesh - \ru Оригинальный полигональный объект.
\en An original polygonal object. \~
\param[in] facets - \ru Набор копируемых фасетов.
@@ -207,6 +236,34 @@ MATH_FUNC( void ) CopyPolymeshPart( const MbPolymesh & mesh, const c3d::IndicesV
MATH_FUNC( bool ) IsPolymeshTriangulation( const MbPolymesh & mesh );
//------------------------------------------------------------------------------
/** \brief \ru Ремешировать полигональный объект.
\en Remesh a polygonal object. \~
\details \ru Ремешировать полигональный объект.
Он должен быть триангуляцией. Если метод ремешинга по кривизне, в сетке должен
присутствовать атрибут кривизн.
Атрибуты нормалей и кривизн будут удалены.
Если в сетке есть оболочка как параметрическая подложка, она будет использована для проецирования
вершин триангуляции.
\en Remesh a polygonal object.
The polymesh must contains only triangle facets.
For remeshing by curvature method a curvature attribute must be defined.
Deletes curvature and normal attributes.
If the polymesh has a shell as a parametric substrate, it will be used for a polymesh vertices projection. \~
\param[in] params - \ru Параметры алгоритма.
\en The parameters. \~
\param[in,out] mesh - \ru Полигональная сетка.
\en The polymesh. \~
\return \ru Код результата операции, rt_Success в случае успеха.
\en Returns the operation result code, rt_Success if remeshing is successful. \n
\ingroup Polygonal_Objects
\warning \ru В разработке.
\en Under development. \~
*/
// ---
MATH_FUNC( MbResultType ) Remesh( const MbRemeshParams & params, MbPolymesh & mesh );
//------------------------------------------------------------------------------
/** \brief \ru Рассчитать кривизны полигональной сетки.
\en Calculates mesh curvatures. \~
@@ -247,4 +304,22 @@ MATH_FUNC( MbResultType ) CalculatePolymeshCurvatures( const MbMeshCurvaturePara
*/
// ---
MATH_FUNC( MbResultType ) DrapeShell( const MbDrapeShellParams & params, MbDrapeShellResults & results );
//------------------------------------------------------------------------------
/** \brief \ru Объединить полигональный объект с другим полигональным объектом.
\en Merge a polygonal object with another polygonal object. \~
\param[in] meshFrom - \ru Полигональный объект, который копируется в meshTo.
\en A polygonal object, being copied into meshTo. \~
\param[in] params - \ru Параметры объединения.
\en Merging parameters. \~
\param[in-out] meshTo - \ru Полигональный объект, который аккумулирует результат объединения.
\en A polygonal object, accumulating merged objects. \~
\return \ru Код результата операции, rt_Success если объекты успешно объединены.
\en Returns the operation result code, rt_Success if the objects are successfully merged. \n
\warning \ru В разработке.
\en Under development.\~
*/ // ---
MATH_FUNC( MbResultType ) MergePolymeshes( const MbPolymesh & meshFrom, const MbMergePolymeshParams & params, MbPolymesh & meshTo );
#endif // __ACTION_POLYMESH_H
+50
View File
@@ -11,6 +11,8 @@
#include <wire_frame.h>
#include <wireframe_point.h>
class MbWireFrameFilletsParams;
class MbNurbsWireFrameParams;
@@ -128,6 +130,54 @@ MATH_FUNC( MbResultType ) NearPointProjection( const MbWireFrame & wir
MbWireFrameProjResult & result );
//------------------------------------------------------------------------------
/** \brief \ru Найти точки пересечения двух проволочных каркасов.
\en Calculate intersection points of two wire frames. \~
\details \ru Найти параметры точек пересечения двух проволочных каркасов. \n
\en Calculate the parameters of intersection points of two wireframes. \n \~
\param[in] wireFrame1 - \ru Первый каркас.
\en The first wireframe. \~
\param[in] wireFrame2 - \ru Второй каркас.
\en The second wireframe. \~
\param[in] eps - \ru Возможная максимальная погрешность найденных пересечений.
\en The intersection tolerance. \~
\param[out] result - \ru Пары точек пересечения каркасов.
\en The intersection pairs of wire frames. \~
\return \ru Возвращает код результата операции.
\en Returns the code of the operation result.
\ingroup WireFrame_Modeling
*/
// ---
MATH_FUNC( MbResultType ) WireFramesIntersect( const MbWireFrame & wireFrame1,
const MbWireFrame & wireFrame2,
double eps,
c3d::WireFramePointsPairsVector & result );
//------------------------------------------------------------------------------
/** \brief \ru Найти точки пересечения двух ребер с учетом толерантности вершин.
\en Calculate intersection points of two edges, taking into account the tolerance of the vertices. \~
\details \ru Найти точки пересечения двух ребер с учетом толерантности вершин. \n
\en Calculate intersection points of two edges, taking into account the tolerance of the vertices. \n \~
\param[in] edge1 - \ru Первое ребро.
\en The first edge. \~
\param[in] edge2 - \ru Второе ребро.
\en The second edge. \~
\param[in] eps - \ru Возможная максимальная погрешность найденных пересечений кривых, лежащих под ребрами.
\en The intersection tolerance of edge's curves. \~
\param[out] result - \ru Пары точек пересечения ребер c учетом толерантности вершин.
\en The intersection points of two edges, taking into account the tolerance of the vertices. \~
\return \ru Возвращает количество точек пересечения.
\en Returns the number of intersection points.
\ingroup WireFrame_Modeling
*/
// ---
MATH_FUNC( size_t ) EdgesIntersect( const MbEdge & edge1,
const MbEdge & edge2,
double eps,
c3d::EdgePointsPairsVector & result );
//------------------------------------------------------------------------------
/** \brief \ru Продлить каркас.
\en Extend the wire frame. \~
+14
View File
@@ -587,6 +587,20 @@ namespace c3d // namespace C3D
/// \ru Подсказка для атрибута имени ребра, используемого для восстановления имён скруглений. \en Hint for the edge name attribute used to recover fillet names.
constexpr TCHAR c3dStr_EdgeForFilletNamesRecover[] = _T( "c3d_EdgeEdgeForFilletNamesRecover" );
/// \ru Подсказки для сохраненного текущего вида. \en Hints for the saved current view.
/** \ru Подсказка для системы координат текущего вида.
Хранится в виде массива из 12 doubles (3D-точка начала координат, 3D-вектора осей X, Y, Z).
\en Hint for the local coordinate system of the current view.
Stored as an array of 12 doubles (3D-point of the coordinate system origin, 3D-vectors for X, Y, Z axes). \~ */
constexpr TCHAR c3dStr_SavedViewPlacement[] = _T( "c3d_SavedView_Placement" );
/** \ru Подсказка для вектора направления вверх текущего вида. Хранится в виде массива из 3 doubles.
\en Hint for the up-vector of the current view. Stored as an array of 3 doubles. \~*/
constexpr TCHAR c3dStr_SavedViewUpVector[] = _T( "c3d_SavedView_UpVector" );
/** \ru Подсказка для масштаба текущего вида. \en Hint for the scale of the current view. \~*/
constexpr TCHAR c3dStr_SavedViewScale[] = _T( "c3d_SavedView_Scale" );
} // namespace C3D
+5 -4
View File
@@ -123,7 +123,7 @@ struct MATH_CLASS cdet_query
struct cback_data ///< Data structure that notifies an app about collision detection event.
{
geom_element first, second; ///< Pair of geometric objects
geom_element first, second; ///< Pair of geometric objects.
cback_data(): first(), second() {}
};
@@ -371,9 +371,9 @@ typedef enum
//---
struct MATH_CLASS CDM_item_data
{
cdet_item comp; // Descriptor of the component owning the inctance.
cdet_item inst; // Descriptor of the instance.
cdet_app_item appItem; // Application pointer for the instance or the component.
cdet_item comp = CDET_NULL; // Descriptor of the component owning the inctance.
cdet_item inst = CDET_NULL; // Descriptor of the instance.
cdet_app_item appItem = CDET_APP_NULL; // Application pointer for the instance or the component.
CDM_item_data()
{
comp = inst = CDET_NULL;
@@ -385,6 +385,7 @@ struct MATH_CLASS CDM_item_data
//
//---
typedef CDM_exam_status (*CDM_exam_func)( cdet_query *, const CDM_item_data &, const CDM_item_data & );
typedef double (*CDM_tolerance_func)( cdet_query *, const CDM_item_data & );
/** \} */ // Collision_Detection
+40 -24
View File
@@ -9,11 +9,10 @@
#ifndef __CDET_UTILITY_H
#define __CDET_UTILITY_H
#include <cdet_data.h>
#include <cdm_types.h>
#include <conv_res_type.h>
#include <tool_cstring.h>
class MtRefItem;
class MbItem;
class MbSolid;
@@ -43,14 +42,20 @@ class CdCollisionManager; // Internal implementation of the collision detection
state, i.e. from the beginning. \~
*/
// ---
class MATH_CLASS CdCollisionDetection
class MATH_CLASS CdCollisionDetection
{
CdCollisionManager& detector;
CdCollisionManager * m_manager;
public:
CdCollisionDetection();
~CdCollisionDetection();
public:
/** \brief \ru Выдать сцену геометрического поиска, которую обслуживает модуль столкновений.
\en Get a geometric search scene, which is served by the collision detection utility. \~
*/
cdet_scene Scene() const;
public:
/**
\brief \ru Добавить твердое тело с заданным положением в набор для контроля столкновений.
@@ -65,13 +70,6 @@ public:
*/
cdet_item AddRay( const MbCartPoint3D & vertex, const MbVector3D & direction,
const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL );
/**
\brief \ru Добавить полигональный объект с заданным положением в набор для контроля столкновений.
\en Add a poligonal object with given placement to the collision detection set. \~
\return \ru Дескриптор объекта для контроля столкновений. \en Descriptor of object for collision detection. \~
*/
cdet_item AddMesh( const MbMesh & mesh, const MbPlacement3D & place
, cdet_app_item appItem = CDET_APP_NULL, double gap = 0. );
/**
\brief \ru Добавить новый компонент контроля столкновений и параметров близости.
\en Add a new component to track collisions and proximity parameters. \~
@@ -139,13 +137,34 @@ public:
\en The function will return CDM_RESULT_CollisionDetected if it detects at least one collision.
*/
cdet_result CheckCollisions();
/**
\brief \ru Выдать дескриптор клиентского приложения по дескриптору контрольного набора столкновений.
\en Get an application pointer by descriptor of the collision detection set.
*/
cdet_app_item AppItem( cdet_item cdItem ) const;
/**
\brief \ru Задать отклонение размеров тела наружу либо внутрь оболочки на величину допуска.
\en Set the allowed deviation of the solid size inside or outside the shell. \~
\param[in] cqItem - \ru Экземпляр сцены, как объект проверки на столкновение с другими.
\en An scene instance as an object to check collisions with others.
\param[in] delta - \ru Предельное отклонение размеров геометрического объекта от своего номинального размера.
\en The maximum deviation of a geometric object size from its nominal size.
\details \ru Величина отклонения может быть положительной или отрицательной, и определяет допуск,
влияющий на результат метода #CheckCollisions. Отрицательное отклонение (delta < 0)
определяет максимальную глубину пересечения с телом, чтобы не засчитывать столкновение.
Положительное отклонение (delta>0) определяет минимальное расстояние до тела,
с которым не засчитывается столкновение.
\en The delta value can be positive or negative, and defines the tolerance that affects
the #CheckCollisions result. A negative delta (delta < 0) defines the maximum interference depth
with a solid to count a status "no collision".
A positive delta (delta>0) defines the minimum distance to an object to count a status "no collision".
\note \ru По умолчанию каждое тело имеет нулевое отклонение размеров (delta = 0).
\en By default, each body has a zero size deviation (delta = 0).
\return \ru Функция вернет CDM_PARAMETER_Changed при успешной смене параметра настройки.
\en The function returns CDM_PARAMETER_Changed if the tolerance parameter was successfully changed.
*/
cdet_setting_result SetToleranceDelta( cdet_item cqItem, double delta );
public: // the functions below can be deprecated in future version.
/*
@@ -154,8 +173,10 @@ public: // the functions below can be deprecated in future version.
\return \ru Внутренняя структура данных представляющая добавленную модель. \en Internal data structure representing added solid data. \~
*/
cdet_item AddSolid( const MbLumpAndFaces & );
/// \note \ru Вызов устарел. Вместо него используйте AddInstance. \en The call is deprecated. Use AddInstance instead. \~
cdet_item AddMesh( const MbMesh & mesh, const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL, double delta = 0. );
/// \ru Добавить тело с заданным положением. \en Add a solid with a given placement.
DEPRECATE_DECLARE cdet_item AddSolid(const MbSolid &, const MbPlacement3D &, cdet_app_item = CDET_APP_NULL, double gap = 0.);
DEPRECATE_DECLARE cdet_item AddSolid(const MbSolid &, const MbPlacement3D &, cdet_app_item = CDET_APP_NULL, double delta = 0.);
/// \ru Удалить твердотельную модель или луч из детектора столкновений. \en Remove a solid model or ray from a collision detector.
void RemoveSolid( cdet_item );
/// \ru Выдать количество добавленных твердотельных моделей или лучей. \en Get number of added solid models or rays.
@@ -164,7 +185,7 @@ public: // the functions below can be deprecated in future version.
size_t SolidIndex( cdet_item cItem ) const;
/// \ru Вычисление минимального расстояния между объектами (см.функцию #SetDistanceTracking) \en Calculation of minimal distance between objects (see the function #SetDistanceTracking)
cdet_result DistanceQuery( CdProximityParameters & ) const;
/// \ru Вычисление минимального расстояния между объектами
/// \ru Вычисление минимального расстояния между объектами \en Calculation of minimal distance between objects. \~
cdet_result DistanceQuery( cdet_item, cdet_item, CdProximityParameters & ) const;
/// \ru Выключить из рассмотрения все модели. \en Exclude all models from consideration.
void FlushSolids();
@@ -187,6 +208,7 @@ public: /*
Deprecated and testing functions
*/
void SetCallback( CDM_exam_func );
// Use AppItem() insead this
/*DEPRECATE_DECLARE*/ cdet_app_item Component(size_t solIdx) const; // It in use yet.
// The func is deprecated. Use SetDistanceTracking instead.
@@ -208,19 +230,13 @@ private:
cdet_item AddItem( const MbItem & );
// Set an assembly to detect collisions between its elements
void SetAssembly( const MbAssembly & );
void UpdateGeometry();
void UpdateGeometry();
private:
OBVIOUS_PRIVATE_COPY( CdCollisionDetection );
};
//----------------------------------------------------------------------------------------
// Default implemention of the call CheckCollisions.
//---
inline cdet_result CdCollisionDetection::CheckCollisions()
{
cdet_query_result defaultQuery;
return CheckCollisions( defaultQuery );
}
/// \ru Узел дерева объемов. \en A node of the bounding volume tree.
typedef const MtRefItem * cdet_bvt_node;
/// \ru Пустое дерево объемов. \en An empty bounding volume tree.
+82 -72
View File
@@ -13,6 +13,8 @@
#include <solid.h>
#include <conv_res_type.h>
class MtRefItem;
/**
\addtogroup Collision_Detection
\{
@@ -23,61 +25,63 @@
*/
//----------------------------------------------------------------------------------------
/** \brief \ru Создать пустую сцену для обнаружения столкновений.
\en Create an empty collision detection scene. \~
\return \ru Дескриптор сцены для обнаружения столкновений и запросов на близость тел.
\en Descriptor of collision detection scene and proximity queries. \~
/**
\brief \ru Создать пустую сцену детектора столкновений.
\en Create an empty collision detection scene. \~
\return \ru Дескриптор сцены детектора столкновений и запросов на близость тел.
\en Descriptor of collision detection scene and proximity queries. \~
*/
//---
MATH_FUNC(cdet_scene) CDM_CreateScene();
//----------------------------------------------------------------------------------------
/** \brief \ru Удалить сцену обнаружения столкновений.
\en Delete collision detection scene. \~
\details \ru Данный метод освобождает память от внутренних структур данных, обслуживающих
детектор столкновений. Удаляемая сцена становится недействительной после
данного вызова.
\en This method releases memory from internal data structures maintaining
the collision detector. The removed collision scene is invalidated after this call. \~
\param[in] scn - \ru Сцена запросов на столкновения и близость тел.
\en Scene of the collision and proximity queries. \~
/**
\brief \ru Удалить сцену детектора столкновений.
\en Delete collision detection scene. \~
\details \ru Данный метод освобождает память от внутренних структур данных, обслуживающих
детектор столкновений. Удаляемая сцена становится недействительной после
данного вызова.
\en This method releases memory from internal data structures maintaining
the collision detector. The removed collision scene is invalidated after this call. \~
\param[in] scn - \ru Сцена запросов на столкновения и близость тел.
\en Scene of the collision and proximity queries. \~
*/
//---
MATH_FUNC(void) CDM_RemoveScene( cdet_scene scn );
//---------------------------------------------------------------------------------------
/**
\brief \ru Добавить новый компонент контроля столкновений и параметров близости.
\en Add a new component to track collisions and proximity parameters. \~
\param[in] comp - \ru Компонент, являющийся геометрическим объединением тел или
\brief \ru Добавить новый компонент в сцену детектора столкновений и задать параметры близости.
\en Add a new component to the collision detector scene and set proximity parameters. \~
\param[in] comp - \ru Компонент, являющийся геометрическим объединением тел или
полигональных объектов, наделенный собственной локальной системой координат.
\en A component that is a geometric union of bodies or polygonal objects. It have
its own local coordinate system. \~
\return \ru Новый компонет, зарегистрированный в сцене контроля столкновений.
\en New component registered in the collision control scene. \~
\details \ru Компонент позволяет объединять тела в геометрически-жесткие множества.
\en Component is able to unite solids into the rigid geometric sets. \~
\en A component that is a geometric union of bodies or polygonal objects. It have
its own local coordinate system. \~
\return \ru Новый компонет, зарегистрированный в сцене детектора столкновений.
\en New component registered in the collision detector scene. \~
\details \ru Компонент позволяет объединять тела в геометрически-жесткие множества.
\en Component is able to unite solids into the rigid geometric sets. \~
*/
//---
MATH_FUNC(cdet_item) CDM_AddComponent( cdet_scene scn, const CDM_component & comp );
//---------------------------------------------------------------------------------------
/**
\brief \ru Добавить экземпляр тела с заданным положением в набор для контроля столкновений.
\en Add a solid with given placement to the collision detection set. \~
\brief \ru Добавить экземпляр тела с заданным положением в сцену для детектора столкновений.
\en Add a solid with given placement to the collision detection scene. \~
\param[in] inst - \ru Запись экземпляра геометрического объекта (полигональное или граничное представление).
\en The instance record of geometric object (polygonal or boundary representation). \~
\return \ru Дескриптор объекта для контроля столкновений. \en Descriptor of object for collision detection. \~
\en The instance record of geometric object (polygonal or boundary representation). \~
\return \ru Дескриптор объекта для детектора столкновений.
\en Descriptor of object for collision detection. \~
\details
\par \ru Повторно-используемые элементы сцены
\en Reused scene elements.
\ru Один и тот же экземпляр класса 'MbItem' может быть добавлен в сцену сколько угодно раз с помощью данного вызова.
При многократном добавлении одного и того же геометрического объекта модуль столкновений создает только одну
поисковую структуру данных (BVT). Ресурсы памяти и времени вычислений, потраченные на создание такой структуры,
\en Reused scene elements. \~
\ru Один и тот же экземпляр класса 'MbItem' может быть добавлен в сцену сколько угодно раз с помощью данного вызова.
При многократном добавлении одного и того же геометрического объекта детектор столкновений создает только одну
поисковую структуру данных (BVT). Ресурсы памяти и времени вычислений, потраченные на создание такой структуры,
повторно используется для всех экземпляров сцены, основанные на одном и том же объекте 'MbItem'. \~
\en The same instance of the 'MbItem' class can be added to the scene as many times as necessary using this call.
When the same geometric object is added multiple times, the collision module creates only one
When the same geometric object is added multiple times, the collision detector creates only one
search data structure (BVT). The memory and computation time resources spent to create this structure,
are reused for all scene instances based on the same 'MbItem' object. \~
*/
@@ -86,14 +90,14 @@ MATH_FUNC(cdet_item) CDM_AddInstance( cdet_scene scn, const CDM_instance & inst
//---------------------------------------------------------------------------------------
/**
\brief \ru Добавить новый экземпляр тела в компонент контроля столкновений.
\en Add a new instance of a reused solid into the component. \~
\brief \ru Добавить новый экземпляр тела в компонент детектора столкновений.
\en Add a new instance of a reused solid into the component of the collision detector. \~
\param[in] compItem - \ru Компонент, которому будет принадлежать экземпляр.
\en A component to witch the instance will belong. \~
\param[in] inst - \ru Запись экземпляра геометрического объекта (полигональное или граничное представление).
\en The instance record of geometric object (polygonal or boundary representation). \~
\return \ru Новый экземпляр тела, зарегистрированный в аппарате контроля столкновений.
\en The new solid instance registered in the detector. \~
\return \ru Дескриптор экземпляра тела, зарегистрированный в сцене детектора столкновений.
\en Descriptor of solid instance registered in the detector. \~
\note \ru Значение compItem может быть нулевым. Значит просто вставка не будет
принадлежать ни одному компоненту.
\en The value compItem can be CDM_NULL. This just means that the
@@ -103,41 +107,41 @@ MATH_FUNC(cdet_item) CDM_AddInstance( cdet_scene scn, const CDM_instance & inst
MATH_FUNC(cdet_item) CDM_AddInstance( cdet_scene scn, cdet_item compItem, const CDM_instance & inst );
//---------------------------------------------------------------------------------------
/**
\brief \ru Удалить геометрический объект из сцены контроля столкновений.
\en Remove a geometric object from the set of collision detection. \~
\param[in] cItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Decriptor of object in collision detector scene. \~
/**
\brief \ru Удалить геометрический объект из сцены детектора столкновений.
\en Remove a geometric object from the scene of collision detector. \~
\param[in] scnItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Decriptor of object in collision detector scene. \~
*/
//---
MATH_FUNC(void) CDM_RemoveItem( cdet_scene scn, cdet_item cItem );
MATH_FUNC(void) CDM_RemoveItem( cdet_scene scn, cdet_item scnItem );
//---------------------------------------------------------------------------------------
/**
\brief \ru Поменять текущее положение геометрического объекта в наборе.
/**
\brief \ru Поменять текущее положение геометрического объекта в сцене.
\en Change current position of a geometric object. \~
\param[in] cItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Decriptor of object in collision detector scene. \~
\param[in] scnItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Decriptor of object in collision detector scene. \~
\param[in] place - \ru Положение, которое занимает объект в глобальной СК.
\en The placement that the object takes in global space. \~
*/
//---
MATH_FUNC(void) CDM_Reposition( cdet_scene scn, cdet_item cItem, const MbPlacement3D & place );
MATH_FUNC(void) CDM_Reposition( cdet_scene scn, cdet_item scnItem, const MbPlacement3D & place );
//---------------------------------------------------------------------------------------
/**
\brief \ru Запросить поиск столкновений между элементами сцены.
\en Request a collision search between scene elements. \~
\return \ru Коды результата контроля столкновений и измерение расстояния.
\return \ru Коды результата детектора столкновений и измерение расстояния.
\en Collision control result codes and distance measurement. \~
\details
\ru Осуществляется поиск столкновения между элементами сцены согласно запроса `cdQuery`,
а именно проверяются пары, как на уровне сборки, включая компоненты целиком, так и
на уровне отдельных компонент. Клиентское приложение имеет возможность настроить запрос
\ru Осуществляется поиск столкновения между элементами сцены согласно запроса `cdQuery`,
а именно проверяются пары, как на уровне сборки, включая компоненты целиком, так и
на уровне отдельных компонент. Клиентское приложение имеет возможность настроить запрос
так, чтобы искать столкновения не всех со всеми, а только между группами объектов.
\en The search for collisions between scene elements is performed according to the `cdQuery`
structure, namely, pairs are checked both at the root level, including entire components,
and at the level within a component. The client application has the ability to configure
\en The search for collisions between scene elements is performed according to the `cdQuery`
structure, namely, pairs are checked both at the root level, including entire components,
and at the level within a component. The client application has the ability to configure
the query so as to search not for collisisons "all with all", but only between groups of objects. \~
*/
//---
@@ -145,39 +149,45 @@ MATH_FUNC(cdet_result) CDM_CheckCollisions( cdet_scene scn, cdet_query & cdQuery
//---------------------------------------------------------------------------------------
/**
\brief \ru Проверить столкновения между геометрическими объектами набора.
\en Check collisions between geometric objects of the set. \~
\return \ru Коды результата контроля столкновений и измерение расстояния.
\brief \ru Проверить столкновения между геометрическими объектами сцены.
\en Check collisions between geometric objects of the scene. \~
\return \ru Коды результата детектора столкновений и измерение расстояния.
\en Collision control result codes and distance measurement. \~
*/
//---
MATH_FUNC(cdet_result) CDM_CheckCollisions( cdet_scene scn );
//---------------------------------------------------------------------------------------
/**
\brief \ru Выдать дескриптор клиентского приложения по дескриптору объекта сцены детктора столкновений.
\en Get an application pointer by object descriptor of the collision detection scenet. \~
\param[in] cItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Object descriptor in the collision detector scene.
\return cdet_app_item - \ru Дескриптор клиентского приложения.
\en Descriptor of client application. \~
/**
\brief \ru Выдать дескриптор клиентского приложения по дескриптору объекта сцены детектора столкновений.
\en Get an application pointer by object descriptor of the collision detector scene. \~
\param[in] scnItem - \ru Дескриптор объекта в сцене детектора столкновений.
\en Object descriptor in the collision detector scene. \~
\return \ru Дескриптор клиентского приложения.
\en Descriptor of client application. \~
*/
//---
MATH_FUNC(cdet_app_item) CDM_AppItem( cdet_scene scn, cdet_item cItem );
MATH_FUNC(cdet_app_item) CDM_AppItem( cdet_scene scn, cdet_item scnItem );
//---------------------------------------------------------------------------------------
/**
\brief \ru Экспортировать сцену поиска столкновений в модель C3D.
\en Export collision detection scene into C3D model.
\return \ru Результат конвертирования
/**
\brief \ru Экспортировать сцену детектора столкновений в модель C3D.
\en Export collision detector scene into C3D model. \~
\param[in] c3dFile - \ru Имя файла.
\en The name of the file. \~
\return \ru Результат конвертирования.
\en Result of converting operation. \~
*/
//---
MATH_FUNC(MbeConvResType) CDM_ExportToC3D( cdet_scene scn, const TCHAR * c3dFile );
/*
The functions below can be deprecated in future version.
*/
//---------------------------------------------------------------------------------------
/**
\brief \ru Исключить из рассмотрения все модели.
\en Exclude all models from consideration. \~
*/
//---
MATH_FUNC(void) CDM_ClearScene( cdet_scene scn );
/** \} */ // Collision_Detection
+29
View File
@@ -25,6 +25,20 @@ class CdCollisionManager;
typedef CdCollisionManager * cdet_scene;
//----------------------------------------------------------------------------------------
/** \brief \ru Результат смены настроек алгоритма поиска столкновений.
\en The result of changing the collision search settings. \~
*/
enum cdet_setting_result
{
/// \ru Параметр настройки изменен успешно.
/// \en The setting parameter was applied successfully.
CDM_PARAMETER_Applied = 1
/// \ru Параметр не удается сменить, поскольку он определяется функцией обратного вызова.
/// \en The parameter cannot be changed because it is defined by a callback function.
, CDM_PARAMETER_NotChanged
};
//---------------------------------------------------------------------------------------
// \ru Структура, определяющая экземпляр геометрического объекта (полигональное или граничное представление).
// \en The structure specifing the instance of geometric object (polygonal or boundary representation).
@@ -55,6 +69,21 @@ struct CDM_component
CDM_component(const MbPlacement3D & lcs, cdet_app_item aItem) : place(lcs), appItem(aItem) {};
};
//---------------------------------------------------------------------------------------
// \ru Структура, определяющая луч в сцене детектора столкновений.
// \en The structure defining the ray in the collision detector scene.
struct CDM_ray
{
MbCartPoint3D origin = MbCartPoint3D::origin; // \ru Вершина луча. \en Vertex of ray.
MbVector3D axisZ = MbVector3D::zAxis; // \ru Направление луча. \en Direction of ray.
MbPlacement3D place = MbPlacement3D::global; // \ru Положение, которое занимает луч в глобальной СК. \en The placement that the ray takes in global space.
cdet_app_item appItem = CDET_APP_NULL; // \ru Геометрический объект пользователя. \en User geometric item.
CDM_ray() = default;
CDM_ray(const CDM_ray &) = default;
CDM_ray(const MbCartPoint3D & vertex, const MbVector3D & direction, const MbPlacement3D & lcs, cdet_app_item aItem)
: origin(vertex), axisZ(direction), place(lcs), appItem(aItem) {};
};
//---------------------------------------------------------------------------------------
// Callback enquiries
//---
+10 -1
View File
@@ -128,7 +128,9 @@ enum MbeIOPermiss {
iop_rValidationProperties, ///< \ru Разрешение на чтение контрольных параметров - объёма, площади поверхности, центра масс. \en Import validation properties - volume, surface area, centroid.
iop_wValidationProperties, ///< \ru Разрешение на запись контрольных параметров - объёма, площади поверхности, центра масс. \en Export validation properties - volume, surface area, centroid.
iop_rStyle, ///< \ru Разрешение на чтение элементов оформления (цвет, начертание, и т.п.). \en Import appearance.
iop_wStyle, ///< \ru Разрешение на запись элементов оформления (цвет, начертание, и т.п.). \en Export appearance.
iop_wStyle, ///< \ru Разрешение на запись элементов оформления (цвет, начертание, и т.п.). \en Export appearance
iop_rCS, ///< \ru Разрешение на чтение систем координат. \en Import coordinate sistems.
iop_wCS, ///< \ru Разрешение на запись систем координат. \en Export coordinate sistems.
iop_END
};
@@ -524,6 +526,9 @@ public:
/// \ru Создавать раскрашенные копии компонент при импорте. \en Create colored replicas of components on import.
virtual bool ImportComponentsWithColoredReplica() { return false; }
/// \ru Определить способ формирования визуальных свойст при чтении из C3D. \en Specify the way how visual properties form while reading from C3D.
virtual ColorProcessing GetC3DVisualPropertiesResolutionStrategy() const { return ColorProcessing::cr_Both; }
}; // IConvertorProperty3D
@@ -571,6 +576,7 @@ public:
double appUnitsFactor; ///< \ru Единицы длины модели пользовательского приложения. \en Length units of the model used in user application.
bool attatchIdAttributes; ///< \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute.
bool auditEnabled;
ColorProcessing visualPropertiesFormation; ///< \ru Способ формирования визуальных свойст при чтении из C3D. \en The way how visual properties form while reading from C3D.
SPtr<IProductIdMaker> pruductIdMaker; ///< \ru Генератор однострочного идентификатора по данным об изделии. \en Generator of a single-line id based on product information attribute.
SPtr<IScaleRequestor> scaleRequester; /// \ru Запросчик масштабного коэффициента единиц длины. \en Scale requester.
SPtr<IStitchRequestor> stitchRequester; /// \ru Запросчик сшивки. \en Stitch requester.
@@ -706,6 +712,9 @@ public:
/// \ru Получить пользовательский преобразователь строк. \en Get user string transformer.
SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const override;
/// \ru Определить способ формирования визуальных свойст при чтении из C3D. \en Specify the way how visual properties form while reading from C3D.
ColorProcessing GetC3DVisualPropertiesResolutionStrategy() const override;
OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D )
}; // IConvertorProperty3D
+5 -2
View File
@@ -31,10 +31,13 @@ class MATH_CLASS MbDuplicationSolid : public MbCreator {
protected:
DuplicationValues * _parameters; ///< \ru Параметры размножения. \en Parameters of duplication.
c3d::ItemIndices _faceIndices; ///< \ru Индексы выбранных граней оболочки. \en Indices of selected shell faces.
bool _adaptMode; ///< \ru Режим адаптации открытых оболочек. \en Open shell instances adaptation mode.
public:
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbDuplicationSolid( const DuplicationValues &, const MbSNameMaker & );
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbDuplicationSolid( const DuplicationValues &, const c3d::ItemIndices & faceIndices, bool adaptMode, const MbSNameMaker & );
private:
MbDuplicationSolid( const MbDuplicationSolid &, MbRegDuplicate * );
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
@@ -84,7 +87,7 @@ IMPL_PERSISTENT_OPS( MbDuplicationSolid )
\en Original face set. \~
\param[in] params - \ru Параметры размножения.
\en Parameters of duplication. \~
\param[out] res - \ru Код результата операции.
\param[out] resCode - \ru Код результата операции.
\en Operation result code. \~
\param[out] resShell - \ru Построенный набор граней.
\en Constructed set of faces. \~
@@ -94,7 +97,7 @@ IMPL_PERSISTENT_OPS( MbDuplicationSolid )
*/
MATH_FUNC (MbCreator *) CreateDuplication( const MbFaceShell & solid,
const MbDuplicationSolidParams & params,
MbResultType & res,
MbResultType & resCode,
c3d::ShellSPtr & resShell );
+4 -1
View File
@@ -30,8 +30,11 @@ public:
public:
/// \ru Конструктор устарел и будет удален. \en Constructor deprecated and will be deleted.
//DEPRECATE_DECLARE
explicit MbFaceFilletMaker( MbeCopyMode , const MbSectionData & data );
/// \ru Конструктор. \en Constructor.
explicit MbFaceFilletMaker( MbeCopyMode /*Будет удалено*/, const MbSectionData & data );
explicit MbFaceFilletMaker( const MbSectionData & data );
/// \ru Деструктор. \en Destructor.
~MbFaceFilletMaker();
+38
View File
@@ -35,10 +35,16 @@ class MATH_CLASS MbMedianShell : public MbCreator {
private :
MedianShellFaces faces; ///< \ru Выбранные грани. \en Selected faces .
MedianShellValues parameters; ///< \ru Параметры срединной оболочки. \en Parameters of median shell.
MbPrecision precision; ///< \ru Точность построения срединной оболочки. \en The precision of the construction of median shell.
public:
/// \ru Конструктор по выбранным граням и параметрам срединной оболочки. \en Constructor by selected faces and parameters of median shell.
MbMedianShell( const MedianShellFaces & faces, const MedianShellValues & params, const MbSNameMaker & snMaker );
/// \ru Конструктор по выбранным граням, параметрам срединной оболочки и точности построения. \en Constructor by selected faces, parameters of median shell and construction precision.
MbMedianShell( const MedianShellFaces & faces,
const MedianShellValues & params,
const MbSNameMaker & snMaker,
const MbPrecision & precision );
/// \ru Деструктор. \en Destructor.
virtual ~MbMedianShell();
@@ -102,6 +108,7 @@ IMPL_PERSISTENT_OPS( MbMedianShell )
\ingroup Model_Creators
*/
// ---
DEPRECATE_DECLARE_REPLACE( CreateMedianShell with MbMedianShellResults )
MATH_FUNC (MbCreator *) CreateMedianShell( const MbFaceShell & solid,
const MbMedianShellParams & params,
MbResultType & res,
@@ -109,4 +116,35 @@ MATH_FUNC (MbCreator *) CreateMedianShell( const MbFaceShell & solid,
c3d::ShellSPtr & shell );
//------------------------------------------------------------------------------
/** \brief \ru Построить срединную оболочку между выбранными парами граней тела.
\en Build a median shell between selected faces of solid. \~
\details \ru Построить срединную оболочку между выбранными парами граней тела.
Грани должны принадлежать одному и тому же телу.
Одновременно с построением оболочки функция создаёт её строитель.\n
\en Build a median shell between suitable selected face pairs of solid.
Suitable face pairs should be offset from each other.
The faces must belong to the same body.
The function simultaneously creates the shell and its constructor.\n \~
\param[in] solid - \ru Исходное тело.
\en The initial solid. \~
\param[in] parameters - \ru Параметры операции.
\en Parameters of operation. ~
\param[out] resType - \ru Код результата операции.
\en Operation result code. \~
\param[out] results - \ru Результат операции, включающий множество граней для создания срединной оболочки.
\en Operation result contains set of faces for build a median shell. \~
\param[out] shell - \ru Построенная срединная оболочка.
\en Constructed median shell. \~
\result \ru Возвращает строитель оболочки.
\en Returns the shell constructor. \~
\ingroup Model_Creators
*/
// ---
MATH_FUNC (MbCreator *) CreateMedianShell( const MbFaceShell & solid,
const MbMedianShellParams & params,
MbResultType & resType,
MbMedianShellResults & results,
c3d::ShellSPtr & shell );
#endif // __CR_MEDIAN_SHELL_H
+14 -3
View File
@@ -31,19 +31,29 @@ class MbFaceFilletMaker;
*/
// ---
class MATH_CLASS MbSectionShell : public MbCreator {
public:
/// \ru Опция выбора результата. \en Option for the result selection.
enum class MbeSelectOption {
firstFaces, ///< \ru Первый набор граней. \en The first set of faces.
secondFaces, ///< \ru Второй набор граней. \en The second set of faces.
filletFaces ///< \ru Грани скругления. \en The fillet faces.
};
protected :
MbSectionData sectionData; ///< \ru Данные о поверхности переменного сечения. \en Data about mutable section surface.
MbSectionData sectionData; ///< \ru Данные о поверхности переменного сечения. \en Data about mutable section surface.
MbeSelectOption selectFaces; ///< \ru Опция выбора результата. \en Option for the result selection.
c3d::IndicesVector partsIndicies;///< \ru Индексы частей скругления, которыми подрезать базовые объекты. \en Indices of the fillet parts by which to cut the base objects.
/** \brief \ru Конструктор.
\en Constructor. \~
\param[in] data - \ru Данные о поверхности переменного сечения.
\en Data about mutable section surface. \~
\param[in] opt - \ru Опция выбора результата.
\en Option for the result selection. \~
\param[in] names - \ru Именователь грани оболочки.
\en Generating face names. \~
*/
MbSectionShell( const MbSectionData & data, const c3d::IndicesVector & indices = c3d::IndicesVector() );
MbSectionShell( const MbSectionData & data, MbeSelectOption opt, const c3d::IndicesVector & indices = c3d::IndicesVector() );
private :
MbSectionShell( const MbSectionShell & init, MbRegDuplicate * ireg );
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
@@ -144,7 +154,8 @@ DEPRECATE_DECLARE_REPLACE( Create with MbFaceFilletMaker )
\en Returns the constructor of operation. \~
*/
static
c3d::CreatorSPtr Create( const MbFaceFilletMaker & fMaker,
c3d::CreatorSPtr Create( const MbFaceFilletMaker & fMaker,
MbeSelectOption option,
const c3d::IndicesVector & indices = c3d::IndicesVector() );
private :
+26 -4
View File
@@ -115,7 +115,7 @@ public:
{
for ( size_t i = 0, n = _attributes.size(); i < n; ++i )
{
if ( _attributes[i] != nullptr )
if ( _attributes[i] )
{
T * pAttr = CastHalfedgeAttribute<T>( _attributes[i].get() );
if ( pAttr != nullptr )
@@ -131,7 +131,7 @@ public:
{
for ( size_t i = 0, n = _attributes.size(); i < n; ++i )
{
if ( _attributes[i] != nullptr )
if ( _attributes[i] )
{
const T * pAttr = CastHalfedgeAttribute<T>( _attributes[i].get() );
if ( pAttr != nullptr )
@@ -141,19 +141,41 @@ public:
return nullptr;
}
/// \ru Получить атрибут по индексу. \en Get an attribute by index.
MbHalfedgeAttrBase * GetHalfedgeAttributeByIndex( size_t ind )
{
MbHalfedgeAttrBase * pAttr( nullptr );
if ( ind < _attributes.size() )
pAttr = _attributes[ind].get();
return pAttr;
}
/// \ru Получить атрибут по индексу. \en Get an attribute by index.
const MbHalfedgeAttrBase * GetHalfedgeAttributeByIndex( size_t ind ) const
{
MbHalfedgeAttrBase * pAttr( nullptr );
if ( ind < _attributes.size() )
pAttr = _attributes[ind].get();
return pAttr;
}
/// \ru Удалить атрибут заданного типа. \en Remove an attribute of the specified type.
template<class T>
void DeleteHalfedgeAttribute()
{
std::vector<T *> toDel;
for ( size_t i = 0, n = _attributes.size(); i < n; ++i )
{
if ( _attributes[i] != nullptr )
if ( _attributes[i] )
{
T * pAttr = CastHalfedgeAttribute<T>( _attributes[i].get() );
if ( pAttr != nullptr )
DeleteHalfedgeAttribute( pAttr );
toDel.push_back( pAttr );
}
}
for ( auto * pAttr : toDel )
DeleteHalfedgeAttribute( pAttr );
}
/// \ru Удалить атрибут. \en Remove the attribute.
+13 -13
View File
@@ -1,4 +1,4 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
@@ -42,7 +42,7 @@ inline bool Less( const Type * t, const BasicIGES & o ) {
if ( !r )
return false;
return ::IsLessThanSArrayItems( t, r );
return t < r ;
}
@@ -233,7 +233,7 @@ struct CONV_CLASS TextItemIGES {
// структура текста
// ---
struct CONV_CLASS TextIGES : public BasicIGES {
PArray<TextItemIGES> arr;
std::vector <TextItemIGES*> arr;
TextIGES();
@@ -295,7 +295,7 @@ template<> bool IsLessThanSArrayItems< DirectionIGES const* > ( DirectionIGES co
// 124 матрица трансформации
// ---
struct CONV_CLASS MatrixIGES : public BasicIGES {
SArray<double> matr;
std::vector<double> matr;
MatrixIGES();
virtual bool operator == ( const BasicIGES & o ) const;
virtual bool operator < ( const BasicIGES & o ) const;
@@ -315,14 +315,14 @@ struct CONV_CLASS RationalBSplineCurveIGES : public BasicCurveIGES {
int32 periodic; // 1 - Периодическая
// 0 - Непериодическая
// Значения последовательностей узлов
SArray<double> sequence; // значения от -degree до 1 + upperIndexSum
std::vector<double> sequence; // значения от -degree до 1 + upperIndexSum
// массив весовых коэффициентов размером 1 + upperIndexSum
SArray<double> weight;
std::vector<double> weight;
// массив координат контрольных точек размером 1 + upperIndexSum
SArray<double> x;
SArray<double> y;
SArray<double> z;
std::vector<double> x;
std::vector<double> y;
std::vector<double> z;
double u0, u1; // начальное и конечное значение параметрических координат
double xNorm, yNorm, zNorm;
@@ -343,8 +343,8 @@ struct CONV_CLASS LeaderIGES : public BasicCurveIGES {
// координаты стрелки
double xHead, yHead;
// координаты конца линии
SArray<double> x;
SArray<double> y;
std::vector<double> x;
std::vector<double> y;
int formArrow; // 0,4 никакой 1,2,3,11 обычная стрелка 9,10 засечка 5,6,7,8 точка
LeaderIGES();
@@ -378,8 +378,8 @@ struct CONV_CLASS WitnessLineIGES : public BasicCurveIGES {
int32 interpretFlag;
double z; // displacement
// координаты конца линии N >= 3 и нечетное
SArray<double> x;
SArray<double> y;
std::vector<double> x;
std::vector<double> y;
WitnessLineIGES();
virtual bool operator == ( const BasicIGES & o ) const;
+5
View File
@@ -100,6 +100,11 @@ struct MATH_CLASS MbCurvature
return ::atan( ( k1 + k2 ) / delta ) / M_PI_2;
}
/// \ru Получить изогнутость. \en Get curvedness.
double Curvedness() const
{
return ::sqrt( ( k1 * k1 + k2 * k2 ) * c3d::ONE_HALF );
}
/// \ru Преобразовать согласно матрице.
void Transform( const MbMatrix3D & matr )
{
+3
View File
@@ -35,6 +35,9 @@ typedef std::pair<MbCartPoint3D, MbCartPoint3D> SpacePointsPair; ///< \ru П
typedef std::pair<MbCartPoint3D, MbVector3D> SpacePointVector; ///< \ru Пара точка-вектор. \en Pair point-vector.
typedef std::pair<MbCartPoint3D, MbVector3D> PointVector3D; ///< \ru Пара точка-вектор. \en Pair point-vector.
typedef std::pair<double, MbCartPoint3D> ParamSpacePointPair; ///< \ru Пара double-точка. \en Pair double-point.
typedef std::vector<ParamSpacePointPair> ParamSpacePointVector; ///< \ru Вектор пар double-точка. \en Vector of double-point pairs.
}
+11 -9
View File
@@ -559,7 +559,8 @@ public:
MbeFairCurvature accountCurvature; ///< \ru Учет кривизны в концевых точках. \en Accounting for curvature at end points. \~
MbeFairVector accountInflexVector; ///< \ru Учет вектора в точке перегиба при построении NURBzS кривой (0 - направление звена S-полигона, 1 - направление касательной). \en How to take into account the vector at the inflection point at creating NURBzS (0 - direction of segment of S-polygon, 1 - direction of tangent to curve). \~
bool tangentCorrectBspline;///< \ru Сохранение вектора в точке перегиба при построении B-кривой (0 - направление звена S-полигона, 1 - направление касательной). \en Save the vector at the inflection point at creating B-curve (0 - direction of segment of S-polygon, 1 - direction of tangent to curve). \~
bool yesLoop; ///< \ru Разрешить петли S-полигона. \en Allow loops of S-polygon \~
bool yesShiftClosedArray; ///< \ru Флаг разрешает сдвиг замкнутого контура. \en The flag enables closed loop shifting. \~
MbeFixPntTng fixPntTng; ///< \ru Фиксировать точки на касательных / касательные в точках. \en Fix the points on tangents / the tangents on points.
MbeFairApprox approx; ///< \ru Метод аппроксимации. \en Approx method. \~
MbeFairMethod create; ///< \ru Исходные ГО: 1 - опорная ломаная, 2 - касательная ломаная. \en Initial GD: 1 - base polyline, 2 - tangent polyline. \~
@@ -572,10 +573,11 @@ public:
double clothoidLMax; ///< \ru Максимальная длина начального участка клотоиды. \en Max length of initial part of Clothoid. \~
size_t clothoidSegms; ///< \ru Количество сегментов аппроксимирующей клотоиду кривой. \en Number of segments of curve approximated the Clothoid. \~
size_t numberOfIterationsBSpl; ///< \ru Количество итераций построения B-сплайна (заданное и фактическое). \en The number of iterations for building the B-spline (given and actual).
double realAccuracyBSpl; ///< \ru Точность построения B-сплайна (заданная и фактическая). \en The accuracy of creating the B-spline (given and actual).
size_t numberOfIterationsBSpl; ///< \ru Количество итераций построения B-сплайна (заданное и фактическое). \en The number of iterations for building the B-spline (given and actual).
double realAccuracyBSpl; ///< \ru Точность построения B-сплайна (заданная и фактическая). \en The accuracy of creating the B-spline (given and actual).
/// \ru Параметры аппроксимации V-кривой. \en Params of Approximation of V-curve.
size_t defaultEndTngs; ///< \ru Способ построения концевых касательных на окружности (1) аффинное построение (0) упрощенное (2)
bool switchEndTangents; ///< \ru Флаги учета значений концевых касательных. \en Flags accounting tangents values.
bool switchEndCurvature; ///< \ru Флаги учета значений кривизны. \en Flags accounting curvature values.
MbVector3D firstTangent; ///< \ru Касательная в начальной точке. \en Tangent in the first point.
@@ -584,12 +586,12 @@ public:
double lastCurvature; ///< \ru Значение кривизны в конечной точке. \en Curvature in the last point.
bool smoothTorsion; ///< \ru Флаг сглаживания кручения пространственной кривой (false - незамкнут, true - замкнут). \en Sign of smoothing of torsion of curve (false - not smoothed, true - smoothed).
double clearanceNoisy; ///< \ru Коридор отклонения сглаживающей кривой от зашумленных точек; \en Corridor of smoothing curve deviation from noisy points;
size_t clearanceNoisyIteration; ///< \ru Количество итераций сглаживания зашумленных точек. \en Number of iterations of smoothing noisy points.
double scaleParam; ///< \ru Параметр масштабирования. \en Scaling parameter.
size_t clearanceNoisyIteration; ///< \ru Количество итераций сглаживания зашумленных точек. \en Number of iterations of smoothing noisy points.
double scaleParam; ///< \ru Параметр масштабирования. \en Scaling parameter.
bool switchFixFirstPointAtNoisy; ///< \ru Флаг фиксации сплайна в начальной точке. \en Flag of fixing a spline at the first point.
bool switchFixLastPointAtNoisy; ///< \ru Флаг фиксации сплайна в конечной точке. \en Flag of fixing a spline at the last point.
const MbNurbs3D * referenceCurve; ///< \ru Кривая для сравнения с результатом аппроксимации. \en Curve for result comparing.
const MbNurbs3D * referenceCurve; ///< \ru Кривая для сравнения с результатом аппроксимации. \en Curve for result comparing.
/// \ru Выходные параметры. \en Output parameters.
MbeFairWarning warning; ///< \ru Предупреждение о работе. \en The operation warning. \~
@@ -603,12 +605,11 @@ public:
public:
/// \ru Пустой конструктор. \en Empty constructor.
MbFairCurveData() :
fairing( fairSmooth_Yes ), arrange( false ), subdivision( fairSubdiv_Single ),
fairing( fairSmooth_Yes ), arrange( false ), yesLoop( false ), yesShiftClosedArray( true ), subdivision( fairSubdiv_Single ),
accountCurvature( fairCur_No ), accountInflexVector( fairVector_Tangent ),
tangentCorrectBspline( true ),
fixPntTng( fixPntTng_NotFix ),
//approx( fairApprox_KnotsSpline ), create( 1 ), degreeBSpline( 8 ),
approx( fairApprox_IsoSpline ), create( fairMethod_Polyline ), degreeBSpline( 8 ), //DEBUG 2020 25
approx( fairApprox_IsoSpline ), create( fairMethod_Polyline ), degreeBSpline( 8 ),
outFormat( fairFormat_Close ),
nSegments( 4 ), numSegment( 0 ), tParam( 0.1 ),
clothoidRMin( 50.0 ), clothoidLMax( 200.0 ), clothoidSegms( 10 ), numberOfIterationsBSpl( 1000 ),
@@ -616,6 +617,7 @@ public:
prt( nullptr ),
#endif
realAccuracyBSpl( METRIC_ACCURACY*0.1 ),
defaultEndTngs( 0 ),
switchEndTangents( false ), switchEndCurvature( false ),
firstCurvature( 0.0 ), lastCurvature( 0.0 ), smoothTorsion( false ),
clearanceNoisy( 0.002 ), clearanceNoisyIteration( 10 ), scaleParam( 1.0 ),
+17 -3
View File
@@ -671,7 +671,8 @@ enum MbeProgBarId_Mesh
{
pBar_SimplifyMesh_byTrianglesCount = pbarId_PointsSurface_End + 1, ///< \ru Упрощение триангуляции по числу треугольников. \en Simplifying triangulation by number of triangles.
pBar_SimplifyMesh_byTolerance, ///< \ru Упрощение триангуляции по точности. \en Simplifying triangulation by tolerance.
pBar_AlignObjects ///< \ru Совмещение объектов. \en Object alignment.
pBar_AlignObjects, ///< \ru Совмещение объектов. \en Object alignment.
pBar_Remesh ///< \ru Ремешинг. \en Remeshing.
};
@@ -686,7 +687,7 @@ enum MbeFairSubdivision
fairSubdiv_No = 0, ///< \ru Без уплотнения. \en Without subdivision.
fairSubdiv_Single = 1, ///< \ru Однократное уплотнение. \en Single subdivision.
fairSubdiv_Double = 2, ///< \ru Двукратное уплотнение. \en Double subdivision.
fairSubdiv_Thrice = 3 ///< \ru Двукратное уплотнение. \en Double subdivision.
fairSubdiv_Thrice = 3 ///< \ru Трехкратное уплотнение. \en Double subdivision.
};
//------------------------------------------------------------------------------
@@ -736,9 +737,22 @@ enum MbeFairVector
enum MbeFixPntTng
{
fixPntTng_NotFix = 0, ///< \ru Не фиксировать точки на касательных / касательные в точках. \en Do not fix the points on tangents / the tangents on points.
fixPntTng_Fix = 1, ///< \ru Фиксировать точки на касательных / касательные в точках. \en Fix the points on tangents / the tangents on points.
fixPntTng_Fix = 1 ///< \ru Фиксировать точки на касательных / касательные в точках. \en Fix the points on tangents / the tangents on points.
};
//------------------------------------------------------------------------------
/** \brief \ru Флаг построения гладких кривых.
\en Flag of smooth curves construction. \~
*/
//---
enum MbDefaultTngs
{
onAffin = 0, ///< \ru Построение аффинно инвариантно. \en The construction is affine invariant.
onCircle = 1 ///< \ru Построение на окружности. \en Construction on a circle.
};
//------------------------------------------------------------------------------
/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Формат сплайна.
\en Construction of smooth curves based on a three-dimensional polyline. Spline Format. \~
+2
View File
@@ -687,6 +687,7 @@ enum MbePrompt
IDS_PROP_0285, ///< \ru Минимальное расстояние между гранями. \en Minimal equidistant value.
IDS_PROP_0286, ///< \ru Максимальное расстояние между гранями. \en Maximal equidistant value.
IDS_PROP_0291, ///< \ru Замена группы граней. \en Replacement group of faces.
IDS_PROP_0292, ///< \ru Удаление скруглений меньших радиуса. \en Remove fillets less then radius.
IDS_PROP_0293, ///< \ru Удаление замкнутых граней вращения меньших радиуса. \en Remove the closed faces of revolution less then radius.
IDS_PROP_0294, ///< \ru Удаление замкнутых граней вращения меньших радиуса c прилегающими скруглениями. \en Remove the closed faces of revolution less then radius with adjacent fillets.
@@ -856,6 +857,7 @@ enum MbePrompt
IDS_PROP_0471, ///< \ru Сохранять параметризацию. \en Save parameterization.
IDS_PROP_0472, ///< \ru Строить на продолжении. \en Build on continuation.
IDS_PROP_0499, ///< \ru Есть оболочка-подложка. \en Has the substrate shell.
IDS_PROP_0500, ///< \ru Число фасетов. \en Number of facets.
IDS_PROP_0501, ///< \ru Число вершин. \en Number of vertices.
IDS_PROP_0502, ///< \ru Число ребер. \en Number of edges.
+1 -1
View File
@@ -465,7 +465,7 @@ public:
*/
bool LineIntersection( const MbFloatAxis3D & line,
MbFloatPoint3D & crossPnt,
float & tRes );
float & tRes ) const;
/** \brief \ru Найти индекс треугольника или четырехугольника, ближайших к точке.
\en Find index of triangle or quadrangle which is closest to a point. \~
+4 -3
View File
@@ -33,7 +33,7 @@ class HalfedgeVisitor;
// ---
enum class MbeTypeAttr
{
ta_Undefined, ///< \ru Тип атрибута не определен. \en Attribute's type is not defined.
ta_Undefined = 0, ///< \ru Тип атрибута не определен. \en Attribute's type is not defined.
ta_BoolValuesFacet, ///< \ru Тип атрибута MbHalfedgeAttrBoolFacet. \en Attribute's type is MbHalfedgeAttrBoolFacet.
ta_BoolValuesEdge, ///< \ru Тип атрибута MbHalfedgeAttrBoolEdge. \en Attribute's type is MbHalfedgeAttrBoolEdge.
ta_BoolValuesVertex, ///< \ru Тип атрибута MbHalfedgeAttrBoolVertex. \en Attribute's type is MbHalfedgeAttrBoolVertex.
@@ -65,7 +65,7 @@ enum class MbeTypeAttr
ta_SegmentationSurface, ///< \ru Тип атрибута MbHalfedgeAttrSurfaces. \en Attribute's type is MbHalfedgeAttrSurfaces.
ta_Parameters2DEdgeDependent, ///< \ru Тип атрибута MbHalfedgeAttrParamByEdge. \en Attribute's type is MbHalfedgeAttrParamByEdge.
ta_Strains, ///< \ru Тип атрибута MbHalfedgeAttrStrains. \en Attribute's type is MbHalfedgeAttrSizetVertex.
ta_ContainerFacet, ///< \ru Внутренний тип атрибута MbHalfedgeAttrContainerFacet. \en Attribute's inner type is MbHalfedgeAttrContainerFacet.
ta_ContainerFacet = 1000, ///< \ru Внутренний тип атрибута MbHalfedgeAttrContainerFacet. \en Attribute's inner type is MbHalfedgeAttrContainerFacet.
ta_ContainerEdge, ///< \ru Внутренний тип атрибута MbHalfedgeAttrContainerEdge. \en Attribute's inner type is MbHalfedgeAttrContainerEdge.
ta_ContainerVertex, ///< \ru Внутренний тип атрибута MbHalfedgeAttrContainerVertex. \en Attribute's inner type is MbHalfedgeAttrContainerVertex.
ta_BoolFlagsFacet, ///< \ru Внутренний тип атрибута MbHalfedgeAttrSelectFacet. \en Attribute's inner type is MbHalfedgeAttrSelectFacet.
@@ -85,7 +85,8 @@ enum class MbeTypeAttr
ta_Rosy, ///< \ru Внутренний тип атрибута MbHalfedgeAttrRosy. \en Attribute's inner type is MbHalfedgeAttrRosy.
ta_Moto, ///< \ru Внутренний тип атрибута MbHalfedgeAttrMoto. \en Attribute's inner type is MbHalfedgeAttrMoto.
ta_ComplFacet, ///< \ru Внутренний тип атрибута MbHalfedgeAttrComplFacet. \en Attribute's inner type is MbHalfedgeAttrComplFacet.
ta_Fiber ///< \ru Внутренний тип атрибута FiberNodeState. \en Attribute's inner type is FiberNodeState.
ta_Fiber, ///< \ru Внутренний тип атрибута FiberNodeState. \en Attribute's inner type is FiberNodeState.
ta_SegmentationShellMap, ///< \ru Внутренний тип атрибута MbHalfedgeAttrShellMap. \en Attribute's inner type is MbHalfedgeAttrShellMap.
};
+15
View File
@@ -428,6 +428,7 @@ class MATH_CLASS MbDuplicationSolidParams
private:
DPtr<DuplicationValues> _duplicationValues; ///< \ru Параметры копирования. \en Copy parameters.
c3d::IndicesVector _selIndices; ///< \ru Индексы выбранных граней оболочки. \en Indices of selected shell faces.
bool _adaptMode; ///< \ru Режим адаптации открытых оболочек. \en Open shell instances adaptation mode.
MbSNameMaker _names; ///< \ru Именователь операции. \en An object defining names generation in the operation.
public:
mutable IProgressIndicator * _progress; ///< \ru Индикатор прогресса выполнения операции. \en A progress indicator of the operation.
@@ -441,6 +442,7 @@ public:
MbDuplicationSolidParams ( const DPtr<DuplicationValues> & values, IProgressIndicator * prog = nullptr )
: _duplicationValues ( values ) // May be nullptr
, _selIndices ( )
, _adaptMode ( false )
, _names ( )
, _progress ( prog )
{
@@ -457,6 +459,7 @@ public:
IProgressIndicator * prog = nullptr )
: _duplicationValues ( values ) // May be nullptr
, _selIndices ( )
, _adaptMode ( false )
, _names ( )
, _progress ( prog )
{
@@ -475,6 +478,8 @@ public:
const MbCartPoint3D * center, bool isAlongAxis,
IProgressIndicator * prog = nullptr )
: _duplicationValues ( new DuplicationMeshValues(isPolar, dir1, step1, num1, dir2, step2, num2, center, isAlongAxis) )
, _selIndices()
, _adaptMode( false )
, _names()
, _progress( prog )
{ }
@@ -482,6 +487,8 @@ public:
/// \ru Конструктор на основе #DuplicationMatrixValues для копирования по матрицам. \en Constructor based on #DuplicationMatrixValues to copy by grid.
MbDuplicationSolidParams( const MbMatrix3D & matr, IProgressIndicator * prog = nullptr )
: _duplicationValues( new DuplicationMatrixValues(matr) )
, _selIndices()
, _adaptMode( false )
, _names()
, _progress( prog )
{ }
@@ -489,6 +496,8 @@ public:
/// \ru Конструктор на основе #DuplicationMatrixValues для копирования по матрицам. \en Constructor based on #DuplicationMatrixValues to copy by grid.
MbDuplicationSolidParams( const SArray<MbMatrix3D> & matr, IProgressIndicator * prog = nullptr )
: _duplicationValues( new DuplicationMatrixValues(matr) )
, _selIndices()
, _adaptMode( false )
, _names()
, _progress( prog )
{ }
@@ -496,6 +505,8 @@ public:
/// \ru Конструктор на основе #DuplicationMatrixValues для копирования по матрицам. \en Constructor based on #DuplicationMatrixValues to copy by grid.
MbDuplicationSolidParams( const std::vector<MbMatrix3D> & matr, IProgressIndicator * prog = nullptr )
: _duplicationValues( new DuplicationMatrixValues(matr) )
, _selIndices()
, _adaptMode( false )
, _names()
, _progress( prog )
{ }
@@ -506,6 +517,10 @@ public:
void GetFacesIndices( c3d::IndicesVector & selIndices ) const { selIndices = _selIndices; }
/// \ru Установить индексы выбранных граней оболочки. \en Set indices of selected shell faces.
void SetFacesIndices( c3d::IndicesVector & selIndices ) { _selIndices = selIndices; }
/// \ru Режим адаптации открытых оболочек. \en Open shell instances adaptation mode.
bool IsAdaptMode() const { return _adaptMode; }
/// \ru Режим адаптации открытых оболочек. \en Open shell instances adaptation mode.
void SetAdaptMode( bool enable ) { _adaptMode = enable; }
/// \ru Получить именователь операции. \en Get the object defining names generation in the operation.
const MbSNameMaker & GetNameMaker() const { return _names; }
/// \ru Установить именователь операции. \en Set the object defining names generation in the operation.
+10
View File
@@ -1339,6 +1339,7 @@ private:
MbSurfaceFitConstraint _fitConstraint; ///< \ru Ограничение. \en Constraint.
size_t _pointsFittingMax; ///< \ru Максимальное количество точек для вписывания. \en Maximum count of fitting points.
bool _withRefinement; ///< \ru Уточнять ли поверхность по всем точкам. \en Refine the surface by all the points or not.
bool _closed; ///< \ru Вписать замкнутую поверхность. \en Fit a closed surface.
///< \ru Предельные значения параметров аналитических поверхностей. \en Thresholds for analytical surfaces parameters.
double _angleConeMin; ///< \ru Минимально возможный половинный угол конуса (градусы). \en Mininmum allowed cone half-angle ( degrees ).
@@ -1360,6 +1361,7 @@ private:
, _valueReject ( 0. )
, _pointsFittingMax ( 10000 )
, _withRefinement ( false )
, _closed ( false )
, _order ( c3d::NURBS_DEGREE )
, _countCpMax ( c3d::NURBS_POINTS_MAX_COUNT )
, _smoothCoef ( METRIC_ACCURACY )
@@ -1380,6 +1382,7 @@ public:
, _valueReject ( 0. )
, _pointsFittingMax ( 10000 )
, _withRefinement ( false )
, _closed ( false )
, _order ( c3d::NURBS_DEGREE )
, _countCpMax ( c3d::NURBS_POINTS_MAX_COUNT )
, _smoothCoef ( METRIC_ACCURACY )
@@ -1400,6 +1403,7 @@ public:
, _valueReject ( rejectValue )
, _pointsFittingMax ( 10000 )
, _withRefinement ( false )
, _closed ( false )
, _order ( c3d::NURBS_DEGREE )
, _countCpMax ( c3d::NURBS_POINTS_MAX_COUNT )
, _smoothCoef ( METRIC_ACCURACY )
@@ -1423,6 +1427,7 @@ public:
, _valueReject ( rejectValue )
, _pointsFittingMax ( 10000 )
, _withRefinement ( false )
, _closed ( false )
, _order ( c3d::NURBS_DEGREE )
, _countCpMax ( c3d::NURBS_POINTS_MAX_COUNT )
, _smoothCoef ( METRIC_ACCURACY )
@@ -1444,6 +1449,7 @@ public:
, _valueReject ( 0. )
, _pointsFittingMax ( 10000 )
, _withRefinement ( false )
, _closed ( false )
, _order ( order )
, _countCpMax ( countCpMax )
, _smoothCoef ( smoothCoef )
@@ -1482,6 +1488,8 @@ public:
size_t GetPointsFittingMax() const { return _pointsFittingMax; }
/// \ru Выдать флаг уточнения поверхности по всем точкам. \en Get the flag of surface refinement by all the points.
bool GetWithRefinement() const { return _withRefinement; }
/// \ru Выдать флаг замкнутости вписываемой поверхности. \en Get the flag of surface closedness.
bool GetClosed() const { return _closed; }
/// \ru Установить предельные значения параметров аналитических поверхностей. \en Set thresholds for analytical surfaces parameters.
void SetAnalyticBounds( double angleConeMin, double angleConeMax, double radiusAnalyticShapeMax )
{
@@ -1770,6 +1778,8 @@ public:
void SetPointsFittingMax( size_t value ) { _pointsFittingMax = value; }
/// \ru Установить флаг уточнения поверхности по всем точкам. \en Set the flag of surface refinement by all the points.
void SetWithRefinement( bool value ) { _withRefinement = value; }
/// \ru Установить флаг замкнутости вписываемой поверхности. \en Set the flag of surface closedness.
void SetClosed( bool closed ) { _closed = closed; }
OBVIOUS_PRIVATE_COPY( MbSurfaceFitToGridParameters )
};
+154 -5
View File
@@ -14,13 +14,124 @@
#include <mb_placement3d.h>
#include <mb_data.h>
#include <templ_sptr.h>
#include <polymesh.h>
#include <topology.h>
#include <curve3d.h>
class MATH_CLASS MbFaceShell;
class MATH_CLASS MbHalfedgeAttrSizetEdge;
class MATH_CLASS MbHalfedgeAttrDoubleEdge;
class MATH_CLASS MbHalfedgeAttrBoolVertex;
class MbPolymesh;
class MbFaceShell;
class MbHalfedgeAttrSizetEdge;
class MbHalfedgeAttrDoubleEdge;
class MbHalfedgeAttrBoolVertex;
//------------------------------------------------------------------------------
/** \brief \ru Параметры ремешинга.
\en Remeshing parameters. \~
\details \ru Параметры ремешинга.
\en Remeshing parameters.
\ingroup Polygonal_Objects
\warning \ru В разработке.
\en Under development. \~
*/
// ---
class MATH_CLASS MbRemeshParams
{
public:
//------------------------------------------------------------------------------
/** \brief \ru Перечисление методов ремешинга.
\en Enumeration for remeshing methods. \~
*/
// ---
enum class MethodRemesh
{
incrementalUniform, ///< \ru Однородный инкрементальный ремешинг. \en Uniform incremental remeshing.
incrementalCurvature ///< \ru Инкрементальный ремешинг по кривизне. \en Curvature incremental remeshing.
};
private:
MethodRemesh _method; ///< \ru Метод ремешинга. \en A remeshing method.
double _targetLength; ///< \ru Целевой размер ребра фасета для однородного метода. \en A target facet edge length for the uniform method.
double _tolCurvature; ///< \ru Относительная точность для метода по кривизне. \en A relative tolerance for the curvature method.
double _angleEdge; ///< \ru Угол для автоматической разбивки ребер сегментации по сломам (градусы), если меньше нуля - не учитывается. \en A angle for automatic segmentation edges splitting (degrees). It is not used if negative. \~
c3d::IndicesVector _fixedEdges; ///< \ru Фиксированные ребра сетки. \en Mesh edges to be fixed.
public:
mutable IProgressIndicator * _progress; ///< \ru Индикатор прогресса выполнения операции. \en A progress indicator of the operation.
public:
/// \ru Конструктор. \en Constructor.
MbRemeshParams( IProgressIndicator * prog = nullptr );
/// \ru Деструктор. \en Destructor.
~MbRemeshParams();
/// \ru Инициализировать как однородный инкрементальный ремешинг. \en Initialize as a uniform incremental remeshing.
void InitIncrementalUniform( double targetLength, const c3d::IndicesVector & fixedEdges, double angleEdge = -1. );
/// \ru Инициализировать как инкрементальный ремешинг по кривизне. \en Initialize as an incremental remeshing by curvature.
void InitIncrementalCurvature( double tolCurvature, const c3d::IndicesVector & fixedEdges, double angleEdge = -1. );
///< \ru Получить целевой размер ребра фасета. \en Get the target facet edge length.
double GetTargetLength() const { return _targetLength; }
///< \ru Получить относительная точность. \en Get the relative tolerance.
double GetCurvatureTolerance() const { return _tolCurvature; }
///< \ru Получить угол для разбивки ребер сегментации. \en Get the angle for segmentation edges splitting.
double GetAngleEdge() const { return _angleEdge; }
///< \ru Получить способ вычисления. \en Get the calculation method.
MethodRemesh GetMethod() const { return _method; }
///< \ru Получить фиксированные ребра. \en Get fixed edges.
const c3d::IndicesVector & GetFixedEdges() const { return _fixedEdges; }
///< \ru Зафиксировать открытые границы. \en Fix open borders.
void FixOpenBorders( MbPolymesh & mesh );
OBVIOUS_PRIVATE_COPY( MbRemeshParams );
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры линеаризации оболочки.
\en Parameters for the shell linearization. \~
\details \ru Параметры линеаризации оболочки.
Для каждой заданной группы граней будет создан один регион в полигональном объекте.
\en Parameters for the shell linearization.
Creates one polymesh region for every given face group. \~
\ingroup Polygonal_Objects
\warning \ru В разработке.
\en Under development. \~
*/
// ---
class MATH_CLASS MbShellLinearizationParams
{
private:
bool _b2d; ///< \ru Флаг создания атрибута параметров. \en A parametrers attribute creation flag. \~
bool _bNormals; ///< \ru Флаг создания атрибута нормалей. \en A normals attribute creation flag. \~
bool _bCurvatures; ///< \ru Флаг создания атрибута кривизн. \en A curvatures attribute creation flag. \~
MbStepData _stepData; ///< \ru Данные для расчета шага. \en Data for the step calculation. \~
std::vector<c3d::IndicesVector> _faceGroups; ///< \ru Группы граней. \en Face groups.
c3d::IndicesVector _fixedEdges; ///< \ru Фиксированные ребра оболочки. \en Constrained shell edges.
public:
/// \ru Конструктор. \en Constructor.
MbShellLinearizationParams( const MbStepData & data, bool b2d, bool bNormals, bool bCurvatures, const std::vector<c3d::IndicesVector> & faceGroups, const c3d::IndicesVector & fixedEdges );
/// \ru Конструктор. \en Constructor.
MbShellLinearizationParams( const MbStepData & data, bool b2d, bool bNormals, bool bCurvatures, const std::vector<std::vector<MbItemIndex>> & faceGroups );
/// \ru Конструктор. \en Constructor.
MbShellLinearizationParams( const MbStepData & data, bool b2d, bool bNormals, bool bCurvatures, const MbFaceShell & shell, const std::vector<std::vector<const MbFace*>> & faceGroups );
/// \ru Деструктор. \en Destructor.
~MbShellLinearizationParams() {}
// \ru Получить данные для расчета шага. \en Get data for the step calculation. \~
const MbStepData & GetStepData() const { return _stepData; }
// \ru Получить группы граней. \en Get face groups. \~
const std::vector<c3d::IndicesVector> & GetFaceGroups() const { return _faceGroups; }
// \ru Получить фиксированные ребра. \en Get constrained edges. \~
const c3d::IndicesVector & GetFixedEdges() const { return _fixedEdges; }
// \ru Нужно ли создавать атрибут параметров. \en Check if parameters attribute should be created. \~
bool IsUvNeeded() const { return _b2d; }
// \ru Нужно ли создавать атрибут нормалей. \en Check if normals attribute should be created. \~
bool IsNormalsNeeded() const { return _bNormals; }
// \ru Нужно ли создавать атрибут кривизн. \en Check if curvatures attribute should be created. \~
bool IsCurvaturesNeeded() const { return _bCurvatures; }
OBVIOUS_PRIVATE_COPY( MbShellLinearizationParams );
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры операции расчета кривизн полигональной сетки.
@@ -316,4 +427,42 @@ public:
OBVIOUS_PRIVATE_COPY( MbDrapeShellResults );
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры объединения полигональных объектов.
\en Parameters for polymesh merging. \~
\details \ru Параметры объединения полигональных объектов. \n
Параметры содержат информацию о соответствующих рёбрах из объединяемых полигональных объектов, при объединении эти рёбра должны быть склеены.
Первый компонент пары - индекс ребра топологии полигонального объекта, который копируется.
Второй компонент пары - индекс ребра топологии полигонального объекта, который аккумулирует результат объединения.
\en Parameters for polymesh merging. \n
Parameters may contain information about corresponding edges from polymeshes being merged - these edges will be marked as twins.
The first pair element is the edge index from the topology of a polymesh being copied.
The second pair element is the edge index from the topology of a polymesh accumulating merged objects. \~
\warning \ru В разработке.
\en Under development. \~
*/
// ---
class MATH_CLASS MbMergePolymeshParams
{
private:
c3d::IndicesPairsVector _edgePairs; ///< \ru Пары ребер, которые должны быть склеены. \en Pairs of edges being merged with each other. \~
public:
/// \ru Конструктор. \en Constructor.
MbMergePolymeshParams() : _edgePairs() {}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMergePolymeshParams( const c3d::IndicesPairsVector & edgePairs ) : _edgePairs( edgePairs ) {}
/// \ru Деструктор. \en Destructor.
~MbMergePolymeshParams() {}
public:
// \ru Получить пары соответствующих ребер. \en Get the pairs of corresponding edges. \~
const c3d::IndicesPairsVector & GetEdgePairs() const { return _edgePairs; }
// \ru Установить пары соответствующих ребер. \en Set the pairs of corresponding edges. \~
void SetEdgePairs( const c3d::IndicesPairsVector & edgePairs ) { _edgePairs = edgePairs; }
OBVIOUS_PRIVATE_COPY( MbMergePolymeshParams );
}; // MbMergePolymeshParams
#endif // __OP_POLYMESH_PARAMETERS_H
+79 -18
View File
@@ -2619,6 +2619,7 @@ public:
enum ShellObstacleType {
sot_ToShell = 0, ///< \ru До оболочки. \en To shell.
sot_ThroughShellLayer, ///< \ru Через первый слой оболочки (до первого выхода из оболочки). \en Through the first shell layer.
sot_ToShellWithoutCut, ///< \ru До оболочки без подрезки. \en To shell without cutting.
sot_Total, ///< \ru Количество всех режимов. \en Number of all modes.
};
/** \brief \ru Варианты представления результирующего тела.
@@ -2789,6 +2790,22 @@ public:
\en Returns true, if initialization was successful or false otherwise. \~
*/
bool InitByShell ( ExtensionType t, LateralKind k, const MbFace * f, const MbSolid * s );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации удлинения до оболочки или через оболочку.
\en Initialization function of extension up to a shell or through a shell. \~
\param[in] t - \ru Тип удлинения.
\en Type of extension. \~
\param[in] k - \ru Способ построения боковых рёбер.
\en Method of construction of the lateral edges. \~
\param[in] sh - \ru Целевая оболочка до (грани) которой выполняется удлинение оболочки по ребрам.
\en Target shell (to the face of which) the working shell will be extending by the edges. \~
\param[in] sot - \ru Режим обрезки с помощью оболочки.
\en Cutting mode using shell. \~
\return \ru Возвращает true, если инициализация была выполнена успешно.
\en Returns true, if initialization was successful or false otherwise. \~
*/
bool InitByShell( ExtensionType t, LateralKind k, const MbFaceShell * sh, ShellObstacleType sot = sot_ToShell );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации удлинения до оболочки или через оболочку.
@@ -2821,6 +2838,18 @@ public:
ShellObstacleType GetObstacleType() const { return toShellType; }
/// \ru Получить вариант представления результирующего тела. \en Get options for representing the resulting body.
ExtensionOutput GetOutput() const { return output; }
/** \brief \ru Замена оболочки (и ее выбранной грани).
\en Replacement of shell (and its selected face). \~
\details \ru Замена оболочки (и ее выбранной грани). Оболочка копируется.
\en Replacement of shell (and its selected face). The shell is copied. \~
\param[in] f - \ru Грань оболочки для остановки удлинения.
\en Shell face as stopper of elongation. \~
\param[in] sh - \ru Целевая оболочка до (грани) которой выполняется удлинение оболочки по ребрам.
\en Target shell (to the face of which) the working shell will be extending by the edges. \~
\return \ru Возвращает true, если инициализация была выполнена успешно.
\en Returns true, if initialization was successful or false otherwise. \~
*/
bool SetShell( const MbFace * f, const MbFaceShell * sh );
/** \brief \ru Замена оболочки (и ее выбранной грани).
\en Replacement of shell (and its selected face). \~
\details \ru Замена оболочки (и ее выбранной грани). Оболочка копируется.
@@ -3208,6 +3237,16 @@ public:
ma_max = 3 ///< \ru Записывать, для граней скругления, создаваемых при filletType !=tf_none, принимать толщину как максимальное значение среди соседних граней. \en Write. With setted flag filletType !=tf_none, the median thickness calculated as maximal value of adjanced faces.
};
/** \brief \ru Вид входных граней.
\en Input faces mode. \~
\details \ru Уточняет как трактуются заданные пары граней.
\en Clarifies how the specified face pairs are interpreted. \~
*/
enum InputMode {
im_pairs = 0, ///< \ru Пары граней. \en Pairs of faces.
im_twogroups = 1 ///< \ru Две группы граней. Первая грань в каждой паре идет в первую группу, вторая - во вторую. \en Two groups of faces. First face in each pair goes to the first group, second face goes to the second group.
};
public:
FilletType filletType; ///< \ru Флаг обработки скруглений. \en Fillet processing flag.
MedianAttr medianAttribute; ///< \ru Флаг расчета и записи толщины срединной оболочки в атрибуты граней. \en The flag of calculation and writing into face attributes the value of median shell thickness .
@@ -3215,16 +3254,22 @@ public:
double dmin; ///< \ru Минимальный параметр эквидистантности. \en Minimal equidistation value.
double dmax; ///< \ru Максимальный параметр эквидистантности. \en Maximal equidistation value.
bool cutByBordes; ///< \ru Флаг подрезки срединной оболочки границами родительской оболочки. \en Flag indicates is need to truncate median shell by parent shell faces.
InputMode inputMode; ///< \ru Вид входных граней. \en Input faces mode.
bool detectPairs; ///< \ru При заданном построении по двум наборам граней, попробовать распознать в них пары эквидистантных граней. \en When two groups of faces are specified, try to detect pairs of offset faces in them.
c3d::BoolPair groupsInvNormals; ///< \ru При заданном построении по двум наборам граней каждый флаг из пары задает признак инвертирования нормалей для соответствующего набора граней. \en When two groups of faces are specified each flag from pair indicates inversion of normals for corresponding group.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MedianShellValues()
: filletType ( tf_average )
, medianAttribute ( ma_none )
, position ( 0.5 )
, dmin ( 0.0 )
, dmax ( 0.0 )
, cutByBordes ( false )
: filletType ( tf_average )
, medianAttribute ( ma_none )
, position ( 0.5 )
, dmin ( 0.0 )
, dmax ( 0.0 )
, cutByBordes ( false )
, inputMode ( im_pairs )
, detectPairs ( false )
, groupsInvNormals( false, false )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
MedianShellValues( const MedianShellValues & other )
@@ -3234,6 +3279,9 @@ public:
, dmin ( other.dmin )
, dmax ( other.dmax )
, cutByBordes ( other.cutByBordes )
, inputMode ( other.inputMode )
, detectPairs ( other.detectPairs )
, groupsInvNormals ( other.groupsInvNormals )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MedianShellValues( double pos, double d1, double d2, bool cut )
@@ -3243,20 +3291,24 @@ public:
, dmin ( d1 )
, dmax ( d2 )
, cutByBordes ( cut )
, inputMode ( im_pairs )
, detectPairs ( false )
, groupsInvNormals ( false, false )
{}
public:
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MedianShellValues & obj, double accuracy ) const
{
if ( filletType == obj.filletType &&
medianAttribute == obj.medianAttribute &&
(::fabs(dmin - obj.dmin) < accuracy) &&
(::fabs(dmax - obj.dmax) < accuracy) &&
(::fabs(position - obj.position) < accuracy) &&
cutByBordes == obj.cutByBordes )
return true;
return false;
return ( filletType == obj.filletType ) &&
( medianAttribute == obj.medianAttribute ) &&
( ::fabs(dmin - obj.dmin) < accuracy ) &&
( ::fabs(dmax - obj.dmax) < accuracy ) &&
( ::fabs(position - obj.position) < accuracy ) &&
( cutByBordes == obj.cutByBordes ) &&
( inputMode == obj.inputMode ) &&
( detectPairs == obj.detectPairs ) &&
( groupsInvNormals == obj.groupsInvNormals );
}
/// \ru Выдать тип скругления. \en Get type of fillet.
@@ -3278,6 +3330,10 @@ public:
dmin = other.dmin;
dmax = other.dmax;
cutByBordes = other.cutByBordes;
inputMode = other.inputMode;
detectPairs = other.detectPairs;
groupsInvNormals = other.groupsInvNormals;
return *this;
}
@@ -3377,7 +3433,7 @@ KNOWN_OBJECTS_RW_REF_OPERATORS( MedianShellFaces ) // \ru Для работы с
\ingroup Shell_Building_Parameters
*/
// ---
class MATH_CLASS MbMedianShellParams {
class MATH_CLASS MbMedianShellParams : public MbPrecision {
private:
c3d::IndicesPairsVector _faceIndexes; ///< \ru Набор пар индексов выбранных граней(может быть пустым). \en Set of selected face indices pairs(can be empty).
MedianShellValues _params; ///< \ru Параметры операции. \en The operation parameters.
@@ -3385,6 +3441,11 @@ private:
public:
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMedianShellParams( const c3d::IndicesPairsVector & faceIndexes, const MedianShellValues & params, const MbSNameMaker & operNames );
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMedianShellParams( const c3d::IndicesSet & facesSet1,
const c3d::IndicesSet & facesSet2,
const MedianShellValues & params,
const MbSNameMaker & operNames );
/// \ru Получить именователь операции. \en Get the object defining names generation in the operation.
const MbSNameMaker & GetNameMaker() const { return *_operNames; }
/// \ru Получить параметры операции. \en Get the operation parameters.
@@ -3404,14 +3465,14 @@ OBVIOUS_PRIVATE_COPY( MbMedianShellParams )
\ingroup Shell_Building_Parameters
*/
// ---
struct MATH_CLASS MbMedianShellResults {
struct MATH_CLASS MbMedianShellResults : MbOperationResults {
public:
MedianShellFaces _medianFaces; ///< \ru Информация о гранях исходного тела, на базе которых выполнено построение. \en The source solid faces data, on the basis of which was performed the building of median shell.
c3d::SolidSPtr _solid; ///< \ru Результирующее тело срединной оболочки. \en The resultant solid of median shell.
public:
/// \ru Конструктор. \en Constructor.
MbMedianShellResults() : _medianFaces(), _solid() {}
MbMedianShellResults() : MbOperationResults(), _medianFaces(), _solid() {}
OBVIOUS_PRIVATE_COPY( MbMedianShellResults )
};
+5 -5
View File
@@ -262,9 +262,9 @@ public:
// ---
class MATH_CLASS MbWireFrameProjParams : public MbPrecision {
private:
MbCartPoint3D _point; ///< \ru Точка для проецирования. \en Projection point.
c3d::WireFramePointPair _range; ///< \ru Диапазон поиска проекции. Может быть не задан. \en Projection search range. May not be specified.
bool _ext; ///< \ru Признак выхода за пределы диапазона поиска или за пределы областей связных контуров каркаса. \en Sign of going beyond the search range or beyond the areas of connected frame contours.
MbCartPoint3D _point; ///< \ru Точка для проецирования. \en Projection point.
c3d::WireFramePointsPair _range; ///< \ru Диапазон поиска проекции. Может быть не задан. \en Projection search range. May not be specified.
bool _ext; ///< \ru Признак выхода за пределы диапазона поиска или за пределы областей связных контуров каркаса. \en Sign of going beyond the search range or beyond the areas of connected frame contours.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
@@ -302,7 +302,7 @@ public:
\param[in] ext - \ru Признак выхода за пределы диапазона поиска или за пределы областей связных контуров каркаса.
\en Sign of going beyond the search range or beyond the areas of connected frame contours. \~
*/
MbWireFrameProjParams( const MbCartPoint3D & point, const c3d::WireFramePointPair & range, bool ext )
MbWireFrameProjParams( const MbCartPoint3D & point, const c3d::WireFramePointsPair & range, bool ext )
: MbPrecision()
, _point( point )
, _range( range )
@@ -321,7 +321,7 @@ public:
/// \ru Задан ли диапазон. \en Is the range set?
bool IsRangeSet() const { return _range.first.IsValid() && _range.second.IsValid(); }
/// \ru Выдать диапазон поиска. \en Give search range.
const c3d::WireFramePointPair & GetRange() const { return _range; }
const c3d::WireFramePointsPair & GetRange() const { return _range; }
/// \ru Выдать признак выхода за пределы диапазона поиска. \en Get sign of going beyond the search range.
bool GetExt() const { return _ext; }
/// \ru Выдать точку для проецирования. \en Get projection point.
+7
View File
@@ -13,6 +13,7 @@
#include <model_item.h>
class MbPolymeshTopo;
class MbFaceShell;
//------------------------------------------------------------------------------
/** \brief \ru Полигональный объект модели - представление топологии в виде halfedge объекта.
@@ -86,6 +87,12 @@ public:
MbPolymeshTopo * SetTopo() { return _pTopo; } // \ru Получить для редактирования топологию полигонального объекта. \en Get the topology of the polygonal object for editing.
const MbPolymeshTopo * GetTopo() const { return _pTopo; } // \ru Получить топологию полигонального объекта. \en Get the topology of the object.
/// \ru Заменить топологию на присланную. \en Replace the topology by the given one.
bool ReplaceTopo( MbPolymeshTopo * pTopo );
/// \ru Получить оболочку-подложку. \en Get the substrate shell.
const MbFaceShell * GetSubstrateShell() const;
/// \ru Удалить оболочку-подложку. \en Delete the substrate shell.
void DeleteSubstrateShell();
private:
// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default.
+38
View File
@@ -14,6 +14,7 @@
#include <halfedge.h>
class MbMesh;
class MbFaceShell;
class MbCube;
class MbAttributeContainer;
@@ -284,6 +285,14 @@ public:
\en Returns true, if the ray intersects a facet. \~
*/
virtual bool FindLineIntersection( const MbAxis3D & ray, MbCartPoint3D & pntCross, double & tRes, size_t & iFacet ) const = 0;
/** \brief \ru Триангулировать заданный фасет.
\en Triangulate a given facet. \~
\param[in] iFacet - \ru Индекс фасета, который нужно триангулировать.
\en The index of a facet being triangulated. \~
\return \ru Возвращает true, если триангуляция прошла успешно.
\en Returns true, if the triangulation is successful. \~
*/
virtual bool TriangulateFacet( size_t iFacet ) = 0;
// \ru Функции для работы с топологией сегментации. \en Functions for working with the topology of a segmentation.
@@ -505,6 +514,30 @@ public:
SegmTopo().DeleteHalfedgeAttribute<T>();
}
/// \ru Получить сеточный атрибут по индексу для изменения. \en Get the mesh attribute by index for editing.
MbHalfedgeAttrBase * GetMeshHalfedgeAttributeByIndex( size_t ind )
{
return MeshTopo().GetHalfedgeAttributeByIndex( ind );
}
/// \ru Получить сеточный атрибут по индексу. \en Get the mesh attribute by index.
const MbHalfedgeAttrBase * GetMeshHalfedgeAttributeByIndex( size_t ind ) const
{
return GetMeshTopo().GetHalfedgeAttributeByIndex( ind );
}
/// \ru Получить сегментационный атрибут по индексу для изменения. \en Get the segmentation attribute by index for editing.
MbHalfedgeAttrBase * GetSegmHalfedgeAttributeByIndex( size_t ind )
{
return SegmTopo().GetHalfedgeAttributeByIndex( ind );
}
/// \ru Получить сегментационный атрибут по индексу. \en Get the segmentation attribute by index.
const MbHalfedgeAttrBase * GetSegmHalfedgeAttributeByIndex( size_t ind ) const
{
return GetSegmTopo().GetHalfedgeAttributeByIndex( ind );
}
/// \ru Удалить сеточный атрибут. \en Delete the given mesh attribute.
void DeleteMeshHalfedgeAttribute( MbHalfedgeAttrBase * pAttr )
{
@@ -517,6 +550,11 @@ public:
SegmTopo().DeleteHalfedgeAttribute( pAttr );
}
/// \ru Получить оболочку-подложку. \en Get the substrate shell.
virtual const MbFaceShell * GetSubstrateShell() const = 0;
/// \ru Удалить оболочку-подложку. \en Delete the substrate shell.
virtual void DeleteSubstrateShell() = 0;
private:
/// \ru Получить топологию сетки для изменения. \en Get the topology of a mesh for editing.
virtual MbHalfedge & MeshTopo() = 0;
+3
View File
@@ -118,6 +118,9 @@ public:
/// \ru Функция присваивания указателем. \en A function of assignment by pointer.
template <class _T>
SPtr<T> & assign( const SPtr<_T> & elem ) { return assign( elem.get() ); }
/// \ru Обменяться указателями с другим SPtr. \en Swap pointers with another SPtr.
template <class _T>
void swap( SPtr<_T> & other ) { std::swap( m_pI, other.m_pI ); }
/// \ru Функция освобождения объекта. \en A function of release an object.
SPtr<T> & assign( std::nullptr_t ) { return reset(); }
/// \ru Функция освобождения объекта. \en A function of release an object.
+5 -1
View File
@@ -42,7 +42,11 @@ public:
\ingroup Base_Tools
*/
// ---
template<class T> class VisitorImpl
template<class T> class
#if !defined ( C3D_WINDOWS )
MATH_CLASS
#endif
VisitorImpl
{
public:
virtual void Visit( T & ) = 0; ///< \ru Функция, обрабатывающая посещение объекта. \en A function processing a visit of an object.
+31 -2
View File
@@ -1027,6 +1027,11 @@ public :
/// \ru Выдать соседнюю грань. \en Get adjacent face.
MbFace * GetFaceMinus() const { return orientation ? curveEdge->GetFaceMinus() : curveEdge->GetFacePlus(); }
/// \ru Установить грань слева. \en Set a face on the left.
void SetFacePlus ( MbFace * f ) { orientation ? curveEdge->SetFacePlus( f ) : curveEdge->SetFaceMinus( f ); }
/// \ru Установить грань справа. \en Set a face on the right.
void SetFaceMinus( MbFace * f ) { orientation ? curveEdge->SetFaceMinus( f ) : curveEdge->SetFacePlus( f ); }
/// \ru Выдать вершину-начало. \en Get the start vertex.
const MbVertex & GetBegVertex() const { return orientation ? curveEdge->GetBegVertex() : curveEdge->GetEndVertex(); }
/// \ru Выдать вершину-конец. \en Get the end vertex.
@@ -1980,6 +1985,9 @@ public:
/// \ru Выдать множество граничных ребер грани. \en Get a set of boundary face edges.
template <class ConstEdgesVector>
void GetBoundaryEdges( ConstEdgesVector & ) const;
/// \ru Выдать множество граничных ребер грани. \en Get a set of boundary face edges.
template <class ConstEdgesSet>
void GetBoundaryEdgesSet( ConstEdgesSet & ) const;
/// \ru Дать топологическое состояние. \en Get topological state.
bool GetTopologyState( ptrdiff_t & cntAdjacentFaces, RPArray<const MbFace> *& adjacentFaces,
@@ -2141,8 +2149,7 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const
template <class ConstEdgesVector>
void MbFace::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const
{
for ( size_t i = 0, loopsCnt = loops.size(); i < loopsCnt; ++i ) {
const MbLoop * loop = loops[i];
for ( const auto & loop : loops ) {
if ( loop == nullptr )
continue;
MbCurveEdge * edge = nullptr;
@@ -2158,6 +2165,28 @@ void MbFace::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const
}
}
//------------------------------------------------------------------------------
// \ru Выдать множество граничных ребер грани. \en Get a set of boundary face edges.
// ---
template <class ConstEdgesSet>
void MbFace::GetBoundaryEdgesSet( ConstEdgesSet & boundaryEdges ) const
{
for ( const auto & loop : loops ) {
if ( loop == nullptr )
continue;
MbCurveEdge * edge = nullptr;
for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) {
const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( j );
if ( orientEdge == nullptr )
continue;
edge = const_cast<MbCurveEdge *>(&orientEdge->GetCurveEdge());
if ( edge->IsBoundaryFace() ) {
boundaryEdges.emplace( edge );
}
}
}
}
//------------------------------------------------------------------------------
// \ru Выдать множество смежных граней. \en Get a set of adjacent faces.
+29 -17
View File
@@ -263,6 +263,8 @@ public :
bool ExchangeFaces( size_t i1, size_t i2 );
/// \ru Установить правильную (текущую) информацию в ребрах о соединяемых ими гранях и параметры поверхностей по данным циклов граней (setBounds = true). \en Set the correct (the current) information in edges about the connected by them faces and parameters of surfaces by loops of faces (setBounds = true).
void MakeRight( bool setBounds = false );
/// \ru Проверить оболочку на наличие краевых рёбер. \en Cehck whether the shell has boundary edges.
void UpdateBoundary();
/// \ru Верно ли установлены указатели в ребрах на соединяемые ими грани. \en Are the pointers in edges to the connected by them faces correctly set?
bool IsRight() const;
/// \ru Обнулить указатели в ребрах на отсутствующую в оболочке грань. \en Set to null in edges the pointers to a face which is absent face
@@ -766,6 +768,9 @@ public :
/// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell.
template <class ConstEdgesVector>
bool GetBoundaryEdges( ConstEdgesVector & ) const;
/// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell.
template <class ConstEdgesSet>
bool GetBoundaryEdgesSet( ConstEdgesSet & ) const;
// \ru Для множества рёбер найти множество их номеров. \en For a set of edges find a set of their indices.
template <class CurvesArray, class ItemIndices>
@@ -1346,23 +1351,30 @@ template <class ConstEdgesVector>
bool MbFaceShell::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const
{
const size_t boundaryCnt = boundaryEdges.size();
for ( size_t i = 0, facesCnt = faceSet.size(); i < facesCnt; ++i ) {
const MbFace * face = faceSet[i];
if ( face == nullptr )
continue;
for ( size_t j = 0, loopsCnt = face->GetLoopsCount(); j < loopsCnt; ++j ) {
const MbLoop * loop = face->_GetLoop( j );
if ( loop == nullptr )
continue;
for ( size_t k = 0, edgesCnt = loop->GetEdgesCount(); k < edgesCnt; ++k ) {
const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( k );
if ( orientEdge != nullptr ) {
c3d::ConstEdgeSPtr edge( &orientEdge->GetCurveEdge() );
if ( edge->IsBoundaryFace() )
boundaryEdges.push_back( edge );
}
}
}
for ( const auto & face : faceSet ) {
if ( face != nullptr )
face->GetBoundaryEdges( boundaryEdges );
}
if ( boundaryEdges.size() > boundaryCnt )
return true;
return false;
}
//------------------------------------------------------------------------------
// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell.
// ---
template <class ConstEdgesSet>
bool MbFaceShell::GetBoundaryEdgesSet( ConstEdgesSet & boundaryEdges ) const
{
const size_t boundaryCnt = boundaryEdges.size();
for ( const auto & face : faceSet ) {
if ( face != nullptr )
face->GetBoundaryEdgesSet( boundaryEdges );
}
if ( boundaryEdges.size() > boundaryCnt )
+3 -2
View File
@@ -19,8 +19,9 @@
#include <math_define.h>
#include <vector>
class MATH_CLASS MbWireFrame;
class MATH_CLASS MbSpaceContourCreationParams;
class MbWireFrame;
class MbSpaceContourCreationParams;
class MbWireFramePoint;
template <class Item>
class MbSpaceContourCreationResults;
+150 -34
View File
@@ -10,20 +10,136 @@
#ifndef __WIREFRAME_POINT_H
#define __WIREFRAME_POINT_H
#include <mb_cart_point3d.h>
#include <io_tape.h>
class MbWireFrame;
class MATH_CLASS MbWireFramePoint;
class MbWireFrame;
class MbWireFramePoint;
class MbEdgePoint;
class MbEdge;
namespace c3d // namespace C3D
{
typedef std::pair<MbWireFramePoint, MbWireFramePoint> WireFramePointPair;
typedef std::pair<MbWireFramePoint, MbWireFramePoint> WireFramePointsPair;
typedef std::vector<WireFramePointsPair> WireFramePointsPairsVector;
typedef std::pair<MbEdgePoint, MbEdgePoint> EdgePointsPair;
typedef std::vector<EdgePointsPair> EdgePointsPairsVector;
} // namespace C3D
//-------------------------------------------------------------------------------
/** \brief \ru Точка на ребре.
\en A point on an edge. \~
\details \ru Точка на ребре. Точка лежит на ребре, учитывая толерантность вершин. Содержит информацию о параметре ребра. \n
\en A point on an edge. A point belong to the edge, taking into account the tolerance of the vertices. It contains information about edge parameter. \n \~
\warning \ru В разработке.
\en Under development. \~
\ingroup Data_Structures
*/
// ---
class MATH_CLASS MbEdgePoint {
private:
MbCartPoint3D _point; ///< \ru Точка на ребре с учетом толерантности вершин. \en A point on the edge taking into account vertex tolerance.
double _edgeParam; ///< \ru Параметр на ребре. \en Parameter on the edge.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MbEdgePoint()
: _point ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL )
, _edgeParam( UNDEFINED_DBL )
{
}
/// \ru Конструктор копирования. \en Copy constructor.
MbEdgePoint( const MbEdgePoint & other )
: _point ( other._point )
, _edgeParam( other._edgeParam )
{}
/// \ru Инициализация. \en Initialization.
void Init( const MbCartPoint3D & point,
double edgeParam )
{
_point = point;
_edgeParam = edgeParam;
}
/** \brief \ru Инициализация по параметрам.
\en Initialization by parameters. \~
\details \ru Инициализация точки по вершине ребра.
\en Point's initialization by edge's vertex. \~
\param[in] edge - \ru Ребро.
\en Edge. \~
\param[in] begVertex - \ru Начальная вершина.
\en Starting vertex. \~
*/
void InitPointOnVertex( const MbEdge & edge,
bool begVertex );
/** \brief \ru Инициализация по параметрам.
\en Initialization by parameters. \~
\details \ru Инициализация точки на ребре по параметру ребра.
\en Initialization a point on an edge by edge's parameter. \~
\param[in] edge - \ru Ребро.
\en Edge. \~
\param[in] edgeParam - \ru Параметр на ребре.
\en Edge parameter. \~
*/
void InitPointOnEdge( const MbEdge & edge,
double edgeParam );
/// \ru Выдать точку. \en Get point.
const MbCartPoint3D & GetEdgePoint() const { return _point; }
/// \ru Выдать параметр на ребре. \en Get edge parameter.
double GetEdgeParam() const { return _edgeParam; }
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MbEdgePoint & other, double accuracy ) const;
/// \ru Преобразовать элемент согласно матрице. \en Transform element by matrix.
void Transform( const MbMatrix3D & matrix ) { _point.Transform( matrix ); }
/// \ru Поворот точки вокруг произвольной оси \en rotate a point around an arbitrary axis.
void Rotate( const MbAxis3D & axis, double angle ) { _point.Rotate( axis, angle ); }
/// \ru Сдвиг точки на произвольный вектор \en Move a point around on arbitrary vector.
void Move( const MbVector3D & to ) { _point.Move( to ); }
/// \ru Проверка на корректность созданного объекта. \en Checking the correctness of the created object.
bool IsValid() const
{
return _point.x != UNDEFINED_DBL &&
_point.y != UNDEFINED_DBL &&
_point.z != UNDEFINED_DBL &&
_edgeParam != UNDEFINED_DBL;
}
/// \ru Оператор присваивания. \en Assignment operator.
const MbEdgePoint & operator = ( const MbEdgePoint & other ) {
_point = other._point;
_edgeParam = other._edgeParam;
return *this;
}
/// \ru Оператор сравнения. \en Comparison operator.
bool operator == ( const MbEdgePoint & other ) const {
return ::fabs( _edgeParam - other._edgeParam ) < DOUBLE_EPSILON &&
_point == other._point;
}
/// \ru Оператор сравнения. \en Comparison operator.
bool operator < ( const MbEdgePoint & other ) const {
return _edgeParam - other._edgeParam < -DOUBLE_EPSILON;
}
/// \ru Проверить на равенство. \en Check for an equality.
bool IsEqual( const MbEdgePoint & other, double tRegion, double mEpsilon ) const {
return ::fabs( _edgeParam - other._edgeParam ) < tRegion &&
_point.DistanceToPoint( other._point ) < mEpsilon;
}
KNOWN_OBJECTS_RW_REF_OPERATORS( MbEdgePoint ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. \~
};
//-------------------------------------------------------------------------------
/** \brief \ru Точка на каркасе.
\en Wire frame point. \~
@@ -36,26 +152,31 @@ typedef std::pair<MbWireFramePoint, MbWireFramePoint> WireFramePointPair;
// ---
class MATH_CLASS MbWireFramePoint {
private:
MbCartPoint3D _point; ///< \ru Точка на ребре каркаса с учетом толерантности вершин. \en A point on a frame edge taking into account vertex tolerance.
size_t _edgeIndex; ///< \ru Номер ребра каркаса. \en Frame edge number.
double _edgeParam; ///< \ru Параметр на ребре каркаса. \en Parameter on the edge of the frame.
MbEdgePoint _edgePoint; ///< \ru Точка на ребре каркаса с учетом толерантности вершин. \en A point on a frame edge taking into account vertex tolerance.
size_t _edgeIndex; ///< \ru Номер ребра каркаса. \en Frame edge number.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MbWireFramePoint()
: _point ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL )
, _edgeIndex( SYS_MAX_T )
, _edgeParam( UNDEFINED_DBL )
: _edgePoint( )
, _edgeIndex( SYS_MAX_T )
{
}
/// \ru Конструктор копирования. \en Copy constructor.
MbWireFramePoint( const MbWireFramePoint & other )
: _point ( other._point )
: _edgePoint( other._edgePoint )
, _edgeIndex( other._edgeIndex )
, _edgeParam( other._edgeParam )
{}
/// \ru Инициализация. \en Initialization.
void Init( const MbEdgePoint & edgePoint,
size_t edgeIndex )
{
_edgePoint = edgePoint;
_edgeIndex = edgeIndex;
}
/** \brief \ru Инициализация по параметрам.
\en Initialization by parameters. \~
\details \ru Инициализация вершины ребра каркаса по параметрам.
@@ -87,28 +208,25 @@ public:
double edgeParam );
/// \ru Выдать точку. \en Get point.
const MbCartPoint3D & GetEdgePoint() const { return _point; }
const MbCartPoint3D & GetEdgePoint() const { return _edgePoint.GetEdgePoint(); }
/// \ru Выдать номер ребра. \en Get edge number.
size_t GetEdgeIndex() const { return _edgeIndex; }
/// \ru Выдать параметр на ребре. \en Get edge parameter.
double GetEdgeParam() const { return _edgeParam; }
double GetEdgeParam() const { return _edgePoint.GetEdgeParam(); }
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MbWireFramePoint & other, double accuracy ) const;
/// \ru Преобразовать элемент согласно матрице. \en Transform element by matrix.
void Transform( const MbMatrix3D & matrix ) { _point.Transform( matrix ); }
void Transform( const MbMatrix3D & matrix ) { _edgePoint.Transform( matrix ); }
/// \ru Поворот точки вокруг произвольной оси \en rotate a point around an arbitrary axis.
void Rotate( const MbAxis3D & axis, double angle ){ _point.Rotate( axis, angle ); }
void Rotate( const MbAxis3D & axis, double angle ) { _edgePoint.Rotate( axis, angle ); }
/// \ru Сдвиг точки на произвольный вектор \en Move a point around on arbitrary vector.
void Move( const MbVector3D & to ){ _point.Move( to ); }
void Move( const MbVector3D & to ) { _edgePoint.Move( to ); }
/// \ru Проверка на корректность созданного объекта. \en Checking the correctness of the created object.
bool IsValid() const
{
return _point.x != UNDEFINED_DBL &&
_point.y != UNDEFINED_DBL &&
_point.z != UNDEFINED_DBL &&
_edgeIndex != SYS_MAX_T &&
_edgeParam != UNDEFINED_DBL;
return _edgePoint.IsValid() &&
_edgeIndex != SYS_MAX_T;
}
/// \ru Установить номер ребра. \en Set edge number.
@@ -116,33 +234,31 @@ public:
/// \ru Оператор присваивания. \en Assignment operator.
const MbWireFramePoint & operator = ( const MbWireFramePoint & other ) {
_point = other._point;
_edgePoint = other._edgePoint;
_edgeIndex = other._edgeIndex;
_edgeParam = other._edgeParam;
return *this;
}
/// \ru Оператор сравнения. \en Comparison operator.
bool operator == ( const MbWireFramePoint & other ) const {
return _edgeIndex == other._edgeIndex &&
::fabs( _edgeParam - other._edgeParam ) < DOUBLE_EPSILON &&
_point == other._point;
return _edgeIndex == other._edgeIndex &&
_edgePoint == other._edgePoint;
}
/// \ru Оператор сравнения. \en Comparison operator.
bool operator < ( const MbWireFramePoint & other ) const {
bool res = _edgeIndex < other._edgeIndex;
if (_edgeIndex == other._edgeIndex) {
res = _edgeParam - other._edgeParam < -DOUBLE_EPSILON;
}
if ( _edgeIndex == other._edgeIndex )
res =_edgePoint < other._edgePoint;
return res;
}
/// \ru Проверить на равенство. \en Check for an equality.
bool IsEqual( const MbWireFramePoint & other, double tRegion, double mEpsilon ) const {
return _edgeIndex == other._edgeIndex &&
::fabs( _edgeParam - other._edgeParam ) < tRegion &&
_point.DistanceToPoint( other._point ) < mEpsilon;
return _edgeIndex == other._edgeIndex &&
_edgePoint.IsEqual( other._edgePoint, tRegion, mEpsilon );
}
KNOWN_OBJECTS_RW_REF_OPERATORS( MbWireFramePoint ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. \~
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.