- C3d aggiornamento delle librerie ( 117931).
This commit is contained in:
SaraP
2022-12-16 15:24:30 +01:00
parent 4e8d0af1a3
commit c8860b2e96
51 changed files with 2319 additions and 886 deletions
+6
View File
@@ -532,8 +532,14 @@ MATH_FUNC (int) LineCircle( const MbLine & line,
/** \brief \ru Найти точки пересечения двух кривых.
\en Calculate intersection points of two curves. \~
\details \ru Найти параметры точек пересечения двух произвольных кривых. \n
Точка касания определяется по коллинеарности касательных векторов к кривым в точке пересечения. \n
Если точка пересечения совпадает с точкой стыка составной кривой, то касательность будет определяться по \n
коллинеарности касательных векторов для каждого сегмента составной кривой. \n
Общий метод вызывается, если нет частной функции пересечения. \n
\en Calculate the parameters of intersection points of two arbitrary curves. \n
The touching point is determined by the collinearity of the tangent vectors to the curves at the point of intersection. \n
If the intersection point coincides with the junction point of the compound curve, then the tangency will be determined \n
by the collinearity of the tangent vectors for each segment of the compound curve. \n
The general method is used if there is no special function for intersection. \n \~
\param[in] pCurve1 - \ru Первая кривая.
\en The first curve. \~
+92 -32
View File
@@ -1156,37 +1156,58 @@ MATH_FUNC (MbResultType) CreateContourFillets( const MbContour3D & contour,
//-------------------------------------------------------------------------------
/** \brief \ru Построить кривые, оборачивающие поверхность.
\en Construct curves that wrap the surface. \~
\details \ru Построить кривые, оборачивающие поверхность, так чтобы точка xy плоскости кривых совпала бы с точкой uv поверхности и
угол между координатными кривыми "X" на плоскости и "U" на поверхности был бы равен angle. \n
\en Construction of curves that wrap the surface, so that the point xy of the plane would be coincides with the point uv of the surface
and the angle between the coordinate curves "X" on the plane and "U" on the surface would be equal to angle. \n \~
\param[in] parameters - \ru Параметры для переноса копий двумерных кривых на другой носитель.
\en Parameters for transferring copies of two-dimensional curves on another medium. \~
parameters.curves \ru Двумерные кривые на плоскости "XY" локальной системы коорданат.
\en Two-dimensional curves on the "XY" plane of the local coordinate system. \~
parameters.place \ru Локальная система коорданат (ЛСК).
\en The local coordinate system (LCS). \~
parameters.xy \ru Точка на плоскости "XY" локальной системы координат.
\en A point on the "XY" plane of the local coordinate system. \~
parameters.surface \ru Поверхность.
\en The surface. \~
parameters.uv \ru Точка на параметрической плоскости "UV" поверхности.
\en A point on the parametric plane " UV " of the surface. \~
parameters.angle \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности.
\en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
parameters.sense \ru Совпадение направлений оси "X" ЛСК и оси "U" поверхности.
\en The coincidence of the directions of the "X" axis of the LSC and the "U" axis of the surface. \~
parameters.equals \ru Соответствует ли длина кривых оригиналам на криволинейных поверхностях?.
\en Does the curves length correspond to the originals on curved surfaces? \~
\param[out] surfaceCurves - \ru Построенные кривые на поверхности.
\en Constructed curves on the surface. \~
\return \ru true - если построение выполнено успешно, false - в противном случае. \n
\en true - if the build is successful, false - otherwise. \n
\details \ru Построить кривые, оборачивающие поверхность. \n
\en Construction of curves that wrap the surface. \n \~
\param[in] parameters - \ru Параметры #MbCurvesWrappingParams для переноса копий двумерных кривых на другой носитель.
\en Parameters #MbCurvesWrappingParams for transferring copies of two-dimensional curves on another medium. \~
\param[out] surfaceCurves - \ru Построенные 2д-кривые.
\en Constructed 2d-curves. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & parameters,
c3d::PlaneCurvesSPtrVector & surfaceCurves );
//-------------------------------------------------------------------------------
/** \brief \ru Построить кривые, оборачивающие поверхность.
\en Construct curves that wrap the surface. \~
\details \ru Построить кривые, оборачивающие поверхность. \n
\en Construction of curves that wrap the surface. \n \~
\param[in] parameters - \ru Параметры #MbCurvesWrappingParams для переноса копий двумерных кривых на другой носитель.
\en Parameters #MbCurvesWrappingParams for transferring copies of two-dimensional curves on another medium. \~
\param[out] resultCurves - \ru Построенные 3д-кривые на присланной поверхности.
\en Constructed 3d-curves based on the input surface. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & parameters,
c3d::SpaceCurvesSPtrVector & resultCurves );
//-------------------------------------------------------------------------------
/** \brief \ru Построить кривые, оборачивающие поверхность.
\en Construct curves that wrap the surface. \~
\details \ru Построить кривые, оборачивающие поверхность. \n
\en Construction of curves that wrap the surface. \n \~
\deprecated \ru Функция устарела, взамен использовать #CurvesWrapping с умными указателями.
\en The function is deprecated, instead use #CurvesWrapping with the smart pointers. \~
\param[in] parameters - \ru Параметры #MbCurvesWrappingParams для переноса копий двумерных кривых на другой носитель.
\en Parameters #MbCurvesWrappingParams for transferring copies of two-dimensional curves on another medium. \~
\param[out] resultCurves - \ru Построенные 3д-кривые на присланной поверхности.
\en Constructed 3d-curves based on the input surface. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
DEPRECATE_DECLARE_REPLACE( CurvesWrapping with SpaceCurvesSPtrVector or PlaneCurvesSPtrVector )
MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & parameters,
std::vector<MbSurfaceCurve *> & surfaceCurves );
RPArray<MbCurve3D> & resultCurves );
//-------------------------------------------------------------------------------
@@ -1194,17 +1215,56 @@ MATH_FUNC (MbResultType) CurvesWrapping( const MbCurvesWrappingParams & paramete
\en Construct a unwrapping curve/contour. \~
\details \ru Построение развертки кривой/контура на плоскость. \n
\en Construction unwrapping of the curve/contour on a plane. \n \~
\param[in] params - \ru Параметры разворачивания.
\en Unwrapping parameters. \~
\param[in] resultCurves - \ru Развёрнутые кривые.
\en Unwrapped curves. \~
\param[in] params - \ru Параметры разворачивания #MbCurvesWrappingParams.
\en Unwrapping parameters #MbCurvesWrappingParams. \~
\param[in] resultCurves - \ru Развёрнутые 2д-кривые.
\en Unwrapped 2d-curves. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & params,
std::vector<SPtr<MbCurve>> & resultCurves );
c3d::PlaneCurvesSPtrVector & surfaceCurves );
//-------------------------------------------------------------------------------
/** \brief \ru Построить развертку кривой/контура на плоскость.
\en Construct a unwrapping curve/contour. \~
\details \ru Построение развертки кривой/контура на плоскость. \n
\en Construction unwrapping of the curve/contour on a plane. \n \~
\param[in] params - \ru Параметры разворачивания #MbCurvesWrappingParams.
\en Unwrapping parameters #MbCurvesWrappingParams. \~
\param[in] resultCurves - \ru Развёрнутые 3д-кривые на присланной плоскости.
\en Unwrapped 3d-curves on the input plane. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & parameters,
c3d::SpaceCurvesSPtrVector & resultCurves );
//-------------------------------------------------------------------------------
/** \brief \ru Построить развертку кривой/контура на плоскость.
\en Construct a unwrapping curve/contour. \~
\details \ru Построение развертки кривой/контура на плоскость. \n
\en Construction unwrapping of the curve/contour on a plane. \n \~
\deprecated \ru Функция устарела, взамен использовать #CurvesWrapping с умными указателями.
\en The function is deprecated, instead use #CurvesWrapping with the smart pointers. \~
\param[in] params - \ru Параметры разворачивания #MbCurvesWrappingParams.
\en Unwrapping parameters #MbCurvesWrappingParams. \~
\param[in] resultCurves - \ru Развёрнутые 3д-кривые на присланной плоскости.
\en Unwrapped 3d-curves on the input plane. \~
\return \ru Возвращает код результата операции.
\en Returns operation result code. \~
\ingroup Curve3D_Modeling
*/
// ---
DEPRECATE_DECLARE_REPLACE( CurvesUnwrapping with SpaceCurvesSPtrVector or PlaneCurvesSPtrVector )
MATH_FUNC (MbResultType) CurvesUnwrapping( const MbCurvesWrappingParams & parameters,
RPArray<MbCurve3D> & resultCurves );
//------------------------------------------------------------------------------
+604 -135
View File
@@ -18,16 +18,16 @@
#include <templ_s_array.h>
#include <mb_enum.h>
#include <mb_cart_point.h>
#include <curve3d.h>
#include <surface.h>
class MATH_CLASS MbCartPoint3D;
class MATH_CLASS MbVector3D;
class MATH_CLASS MbPlacement3D;
class MATH_CLASS MbAxis3D;
class MATH_CLASS MbCurve3D;
class MATH_CLASS MbPlaneCurve;
class MATH_CLASS MbSurface;
class IProgressIndicator;
class MATH_CLASS IProgressIndicator;
////////////////////////////////////////////////////////////////////////////////
@@ -75,8 +75,7 @@ class IProgressIndicator;
\param[out] plane_curve - \ru Требуемая окружность или дуга.
\en The required circle or an arc. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
const MbCartPoint & surface_uv,
MbPlaneCurve *& plane_curve );
@@ -108,8 +107,7 @@ MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
\param[out] plane_curve - \ru Требуемая окружность или дуга.
\en The required circle or an arc. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
const MbCartPoint3D & point,
MbPlaneCurve *& plane_curve );
@@ -141,8 +139,7 @@ MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
\param[out] plane_curve - \ru Требуемая окружность или дуга.
\en The required circle or an arc. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
const MbPlacement3D & place,
MbPlaneCurve *& plane_curve );
@@ -160,8 +157,7 @@ MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface,
\return \ru true, если можно построить.
\en true if it can be constructed. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
MATH_FUNC (bool) IsPossibleRadiusDimension3D( const MbSurface & surface );
@@ -171,13 +167,12 @@ MATH_FUNC (bool) IsPossibleRadiusDimension3D( const MbSurface & surface );
\details \ru Результат замера расстояния и угла между поверхностями.
\en The result of measurement of dimension and angle between surfaces. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
enum MbeSurfAxesMeasureRes
{
// \ru ошибочные результат \en mistaken result
samr_SurfSurf_Failed = -3, ///< \ru Ошибка при работе с поверхностями. \en An error is occurred while working with surfaces.
samr_AxisSurf_Failed = -2, ///< \ru Ошибка при работе с осью и поверхностю. \en An error is occurred while working with axis and surface.
samr_AxisSurf_Failed = -2, ///< \ru Ошибка при работе с осью и поверхностью. \en An error is occurred while working with axis and surface.
samr_AxisAxis_Failed = -1, ///< \ru Ошибка при работе с осями. \en An error is occurred while working with axes.
// \ru пустой результат \en an empty result.
samr_Undefined = 0, ///< \ru Не получилось или не измерялось. \en Failed or didn't measured.
@@ -228,8 +223,7 @@ enum MbeSurfAxesMeasureRes
\return \ru Вариант полученного замера или вариант ошибки.
\en The variant of the obtained measurement or the variant of error. \~
\ingroup Algorithms_3D
*/
// ---
*/ // ---
MATH_FUNC (MbeSurfAxesMeasureRes) SurfAxesDistAngle( const MbSurface & surface1, bool sameSense1,
const MbSurface & surface2, bool sameSense2,
MbAxis3D & axis1, bool & exist1,
@@ -242,62 +236,111 @@ MATH_FUNC (MbeSurfAxesMeasureRes) SurfAxesDistAngle( const MbSurface & surface1,
//------------------------------------------------------------------------------
/** \brief \ru Расстояние между точками на поверхности.
\en Distance between points on surface. \~
\details \ru Класс содержит данные о расстоянии между точками и координатами этих точек
на поверхностях.
\en The class contains data about the distance between points and their coordinates
on surfaces. \~
/** \brief \ru Расстояние между точками на объектах (кривая-кривая, кривая-поверхность или поверхность-поверхность).
\en Distance between points on objects (curve-curve, curve-surface, surface-surface). \~
\details \ru Класс содержит данные о расстоянии между точками и координатами этих точек на объектах.
\en The class contains data about the distance between points and their coordinates on objects surfaces. \~
\ingroup Algorithms_3D
*/
// ---
class MATH_CLASS MbSurfDist {
friend class MbMinMaxSurfDists;
*/ // ---
template <class Param1, class Param2>
class MbItemItemDist {
template <typename Par1, typename Par2>
friend class MbMinMaxItemItemDistances;
private:
double d; ///< \ru Расстояние. \en Distance.
MbCartPoint uv1; ///< \ru Параметр на первой поверхности. \en Parameter on the first surface.
MbCartPoint uv2; ///< \ru Параметр на второй поверхности. \en Parameter on the second surface.
uint8 sign; ///< \ru Знак расстояния. \en Sign of direction.
double d; ///< \ru Расстояние. \en Distance.
Param1 par1; ///< \ru Параметр на первом объекте. \en Parameter on the first object.
Param2 par2; ///< \ru Параметр на втором объекте. \en Parameter on the second object.
uint8 sign; ///< \ru Знак расстояния. \en Sign of direction.
public:
/// \ru Параметрическая точка (1D или 2D). \en Parametric point (1D or 2D).
struct ParamPoint {
double x;
double y;
bool s;
ParamPoint( double t ) : x( t ), y( t ), s( false ) {}
ParamPoint( const MbCartPoint & p ) : x( p.x ), y( p.y ), s( true ) {}
};
public:
/// \ru Конструктор. \en Constructor.
MbSurfDist() : d( UNDEFINED_DBL ), uv1(), uv2(), sign( 1 ) {}
MbItemItemDist() : d( UNDEFINED_DBL ), par1(), par2(), sign( 1 ) {}
/// \ru Конструктор по данным. \en The constructor by data.
MbSurfDist( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ) { Init( _d, _uv1, _uv2, plus ); }
MbItemItemDist( double _d, const Param1 & _par1, const Param2 & _par2, bool plus ) { Init( _d, _par1, _par2, plus ); }
/// \ru Конструктор копирования. \en Copy constructor.
MbSurfDist( const MbSurfDist & other ) { Init( other ); }
MbItemItemDist( const MbItemItemDist & other ) { Init( other ); }
/// \ru Деструктор. \en The destructor.
virtual ~MbSurfDist() {}
virtual ~MbItemItemDist() {}
public:
/// \ru Функция копирования. \en Copy function.
void Init( const MbSurfDist & obj ) { d = obj.d; uv1 = obj.uv1; uv2 = obj.uv2; sign = obj.sign; }
void Init( const MbItemItemDist & obj ) { d = obj.d; par1 = obj.par1; par2 = obj.par2; sign = obj.sign; }
/// \ru Получить расстояние. \en Get distance.
double GetDistance() const { return d; }
double GetDistance() const { return d; }
/// \ru Получить точку на первой поверхности. \en Get the point on the first surface.
const MbCartPoint & GetPointOne() const { return uv1; }
const Param1 & GetParamOne() const { return par1; }
/// \ru Получить точку на второй поверхности. \en Get the point on the second surface.
const MbCartPoint & GetPointTwo() const { return uv2; }
const Param2 & GetParamTwo() const { return par2; }
/// \ru Расстояние положительное? \en Is the distance positive?
bool IsPositive() const { return (sign > 0); }
bool IsPositive() const { return (sign > 0); }
/// \ru Расстояние отрицательное? \en Is the distance negative?
bool IsNegative() const { return (sign < 1); }
bool IsNegative() const { return (sign < 1); }
/// \ru Оператор присваивания. \en Assignment operator.
const MbSurfDist & operator = ( const MbSurfDist & other ) { Init( other ); return (*this); }
const MbItemItemDist & operator = ( const MbItemItemDist & other ) { Init( other ); return (*this); }
private:
void Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus );
// \ru Инициализатор. \en Initializer.
void Init( double _d, const Param1 & _par1, const Param2 & _par2, bool plus )
{
d = _d;
par1 = _par1;
par2 = _par2;
sign = plus ? 1 : 0;
}
};
//------------------------------------------------------------------------------
// MbItemItemDist typedefs
// ---
typedef MbItemItemDist<double, double> MbCurvCurvDist;
typedef MbItemItemDist<double, MbCartPoint> MbCurvSurfDist;
typedef MbItemItemDist<MbCartPoint, double> MbSurfCurvDist;
typedef MbItemItemDist<MbCartPoint, MbCartPoint> MbSurfSurfDist;
DEPRECATE_DECLARE_REPLACE( MbSurfSurfDist )
typedef MbSurfSurfDist MbSurfDist; // old
//------------------------------------------------------------------------------
// \ru инициализатор \en Initializer
// сортировать по возрастанию расстояния
// ---
inline void MbSurfDist::Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus )
template <class ItemItemDist>
bool ItemItemDistCompFunc( const ItemItemDist & sd1, const ItemItemDist & sd2 )
{
d = _d;
uv1 = _uv1;
uv2 = _uv2;
sign = plus ? 1 : 0;
bool isFirstLessSecond = false;
const double mEps = LENGTH_EPSILON;
const double pEps = PARAM_EPSILON;
double d1 = sd1.GetDistance();
double d2 = sd2.GetDistance();
if ( d1 < d2 - mEps )
isFirstLessSecond = true;
else if ( ::fabs( d1 - d2 ) <= mEps ) {
const typename ItemItemDist::ParamPoint parOne1( sd1.GetParamOne() );
const typename ItemItemDist::ParamPoint parOne2( sd2.GetParamOne() );
if ( parOne1.x < parOne2.x - pEps )
isFirstLessSecond = true;
else if ( parOne1.s && parOne2.s && ::fabs( parOne1.x - parOne2.x ) <= pEps ) {
if ( parOne1.y < parOne2.y - pEps )
isFirstLessSecond = true;
else if ( ::fabs( parOne1.y - parOne2.y ) <= pEps ) {
if ( d1 < d2 )
isFirstLessSecond = true;
}
}
}
return isFirstLessSecond;
}
@@ -307,85 +350,316 @@ inline void MbSurfDist::Init( double _d, const MbCartPoint & _uv1, const MbCartP
\details \ru Расстояния с точками между поверхностями.
\en Distances between surfaces with points. \~
\ingroup Algorithms_3D
*/
// ---
class MATH_CLASS MbMinMaxSurfDists {
*/ // ---
template <class Param1, class Param2>
class MbMinMaxItemItemDistances {
private :
SArray<MbSurfDist> surfDistances; ///< \ru Расстояние и параметры на поверхностях. \en Distance and parameters on surfaces.
mutable double midDistance; ///< \ru Среднее расстояние. \en Average distance.
mutable double minDistance; ///< \ru Минимальное расстояние. \en Minimal distance.
mutable double maxDistance; ///< \ru Максимальное расстояние. \en Maximal distance.
mutable bool sorted; ///< \ru Признак сортированности. \en Attribute of being sorted.
std::vector< MbItemItemDist<Param1,Param2> > allDistances; ///< \ru Расстояние и параметры на поверхностях. \en Distance and parameters on surfaces.
mutable double midDistance; ///< \ru Среднее расстояние. \en Average distance.
mutable double minDistance; ///< \ru Минимальное расстояние. \en Minimal distance.
mutable double maxDistance; ///< \ru Максимальное расстояние. \en Maximal distance.
mutable bool sorted; ///< \ru Признак сортированности. \en Attribute of being sorted.
public:
MbMinMaxSurfDists( size_t nReserve = 0 ); ///< \ru Конструктор. \en Constructor.
virtual ~MbMinMaxSurfDists(); ///< \ru Деструктор. \en Destructor.
/// \ru Конструктор. \en Constructor.
MbMinMaxItemItemDistances( size_t nReserve = 0 )
: allDistances( )
, midDistance ( UNDEFINED_DBL )
, minDistance ( UNDEFINED_DBL )
, maxDistance ( UNDEFINED_DBL )
, sorted ( false )
{
allDistances.reserve( std_min( nReserve, (size_t)c3d::COUNT_MAX ) );
}
/// \ru Деструктор. \en Destructor.
virtual ~MbMinMaxItemItemDistances()
{
RemoveAll( true );
}
public:
bool IsEmpty() const { return (surfDistances.Count() < 1); } ///< \ru Есть ли замеры? \en Are there any measurements?
size_t GetCount() const { return surfDistances.Count(); } ///< \ru Количество замеров. \en The number of measurements.
ptrdiff_t GetMaxIndex() const { return surfDistances.MaxIndex(); } ///< \ru Индекс последнего замера. \en Index of the last measurement
void Reserve( size_t nReserve ); ///< \ru Зарезервировать память под nReserve элементов. \en Reserve memory for 'nReserve' elements.
void RemoveAll( bool bAdjustMemory ); ///< \ru Удалить все элементы \en Delete all elements.
void AdjustMemory(); ///< \ru Освободить лишнюю память \en Free the unnecessary memory.
bool IsEmpty() const { return allDistances.empty(); } ///< \ru Есть ли замеры? \en Are there any measurements?
size_t GetCount() const { return allDistances.size(); } ///< \ru Количество замеров. \en The number of measurements.
ptrdiff_t GetMaxIndex() const { return ((ptrdiff_t)allDistances.size() - 1); } ///< \ru Индекс последнего замера. \en Index of the last measurement
/// \ru Зарезервировать память под nReserve элементов. \en Reserve memory for 'nReserve' elements.
void Reserve( size_t nReserve )
{
allDistances.reserve( allDistances.size() + nReserve );
}
/// \ru Удалить все элементы. \en Delete all elements.
void RemoveAll( bool freeMemory )
{
allDistances.clear();
if ( freeMemory ) {
allDistances.shrink_to_fit();
}
midDistance = minDistance = maxDistance = UNDEFINED_DBL;
}
/// \ru Освободить лишнюю память. \en Free the unnecessary memory.
void AdjustMemory()
{
allDistances.shrink_to_fit();
}
public:
/// \ru Получить расстояние по индексу. \en Get the distance by the index.
bool GetDistance( size_t k, double & d ) const;
bool GetDistance( size_t k, double & d ) const
{
if ( k < allDistances.size() ) {
d = allDistances[k].GetDistance();
return true;
}
return false;
}
/// \ru Получить расстояние со знаком, по индексу. \en Get the signed distance by the index.
bool GetSignedDistance( size_t k, double & d ) const;
bool GetSignedDistance( size_t k, double & d ) const
{
if ( k < allDistances.size() ) {
d = allDistances[k].GetDistance();
if ( allDistances[k].IsNegative() )
d = -d;
return true;
}
return false;
}
/// \ru Считаем ли вы расстояние отрицательным. \en Whether the distance is negative.
bool IsNegativeDistance( size_t k ) const { return ((k < surfDistances.Count()) ? surfDistances[k].IsNegative() : false); }
/// \ru Получить минимальное расстояние. \en Get minimal distance.
bool GetMinDistance( double & d ) const;
/// \ru Получить максимальное расстояние. \en Get maximal distance.
bool GetMaxDistance( double & d ) const;
/// \ru Получить среднее расстояние. \en Get average distance.
bool GetMidDistance( double & d ) const;
/// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface.
bool GetSurfDistance( size_t k, double & d, MbCartPoint & uv1, MbCartPoint & uv2 ) const;
/// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface.
bool GetSurfDistance( size_t k, double & d, bool & plus, MbCartPoint & uv1, MbCartPoint & uv2 ) const;
/// \ru Добавить расстояние и точки на поверхностях. \en Add distance and points on surface.
bool AddSurfDistance( double distance, bool plus, const MbCartPoint & uv1, const MbCartPoint & uv2,
bool bAddEqual, double eps = LENGTH_EPSILON );
/// \ru Сортировать по возрастанию расстояния. \en Sort by distance in the ascending order.
void Sort();
/// \ru Убрать объекты с одинаковыми расстояниями. \en Remove objects with similar distances.
void RemoveEqualDistances( double eps = LENGTH_EPSILON );
bool IsNegativeDistance( size_t k ) const { return ((k < allDistances.size()) ? allDistances[k].IsNegative() : false); }
void operator = ( const MbMinMaxSurfDists & ); ///< \ru Оператор присваивания. \en Assignment operator.
/// \ru Получить минимальное расстояние. \en Get minimal distance.
bool GetMinDistance( double & d ) const
{
bool res = false;
size_t count = allDistances.size();
if ( count > 0 ) {
if ( minDistance != UNDEFINED_DBL ) {
d = minDistance;
res = true;
}
else if ( count > 1 ) {
minDistance = MB_MAXDOUBLE;
for ( size_t k = 0; k < count; ++k ) {
double curDistance = allDistances[k].GetDistance();
if ( curDistance < minDistance ) {
minDistance = curDistance;
res = true;
}
}
if ( res )
d = minDistance;
else
minDistance = UNDEFINED_DBL;
}
else {
minDistance = allDistances.front().GetDistance();
d = minDistance;
res = true;
}
}
return res;
}
/// \ru Получить максимальное расстояние. \en Get maximal distance.
bool GetMaxDistance( double & d ) const
{
bool res = false;
size_t count = allDistances.size();
if ( count > 0 ) {
if ( maxDistance != UNDEFINED_DBL ) {
d = maxDistance;
res = true;
}
else if ( count > 1 ) {
maxDistance = -MB_MAXDOUBLE;
for ( size_t k = 0; k < count; ++k ) {
double curDistance = allDistances[k].GetDistance();
if ( curDistance > maxDistance ) {
maxDistance = curDistance;
res = true;
}
}
if ( res )
d = maxDistance;
else
maxDistance = UNDEFINED_DBL;
}
else {
maxDistance = allDistances.front().GetDistance();
d = maxDistance;
res = true;
}
}
return res;
}
/// \ru Получить среднее расстояние. \en Get average distance.
bool GetMidDistance( double & d ) const
{
bool res = false;
size_t count = allDistances.size();
if ( count > 0 ) {
if ( count > 1 ) {
if ( midDistance != UNDEFINED_DBL ) {
d = midDistance;
res = true;
}
else {
midDistance = 0.0;
for ( size_t k = 0; k < count; ++k )
midDistance += allDistances[k].GetDistance();
midDistance /= ((double)count);
d = midDistance;
res = true;
}
}
else {
midDistance = allDistances.front().GetDistance();
d = midDistance;
res = true;
}
}
return res;
}
/// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface.
bool GetItemDistance( size_t k, double & d, Param1 & par1, Param2 & par2 ) const
{
if ( k < allDistances.size() ) {
d = allDistances[k].GetDistance();
par1 = allDistances[k].GetParamOne();
par2 = allDistances[k].GetParamTwo();
return true;
}
return false;
}
DEPRECATE_DECLARE_REPLACE( GetItemDistance )
bool GetSurfDistance( size_t k, double & d, Param1 & par1, Param2 & par2 ) const
{
return GetItemDistance( k, d, par1, par2 );
}
/// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface.
bool GetItemDistance( size_t k, double & d, bool & plus, Param1 & par1, Param2 & par2 ) const
{
if ( k < allDistances.size() ) {
d = allDistances[k].GetDistance();
par1 = allDistances[k].GetParamOne();
par2 = allDistances[k].GetParamTwo();
plus = allDistances[k].IsPositive();
return true;
}
return false;
}
DEPRECATE_DECLARE_REPLACE( GetItemDistance )
bool GetSurfDistance( size_t k, double & d, bool & plus, Param1 & par1, Param2 & par2 ) const
{
return GetItemDistance( k, d, plus, par1, par2 );
}
/// \ru Добавить расстояние и точки на поверхностях. \en Add distance and points on surface.
bool AddItemDistance( double d, bool plus, const Param1 & par1, const Param2 & par2,
bool addEqual, double eps = LENGTH_EPSILON )
{
if ( ::fabs( d ) < LENGTH_EPSILON )
d = 0.0;
C3D_ASSERT( d >= 0 );
if ( d > 0.0 ) {
size_t count = allDistances.size();
bool add = true;
if ( !addEqual ) {
for ( size_t k = 0; k < count; ++k ) {
if ( ::fabs( d - allDistances[k].GetDistance() ) < eps ) {
add = false;
break;
}
}
}
if ( add ) {
if ( count > 0 ) {
if ( maxDistance != UNDEFINED_DBL && d > maxDistance )
maxDistance = d;
else if ( minDistance != UNDEFINED_DBL && d < minDistance )
minDistance = d;
}
else
minDistance = maxDistance = d;
MbItemItemDist<Param1,Param2> surfDistance( d, par1, par2, plus );
allDistances.push_back( surfDistance );
midDistance = UNDEFINED_DBL;
return true;
}
}
return false;
}
/// \ru Добавить расстояние и точки на поверхностях. \en Add distance and points on surface.
DEPRECATE_DECLARE_REPLACE( AddItemDistance )
bool AddSurfDistance( double d, bool plus, const Param1 & par1, const Param2 & par2,
bool addEqual, double eps = LENGTH_EPSILON )
{
return AddItemDistance( d, plus, par1, par2, addEqual, eps );
}
/// \ru Сортировать по возрастанию расстояния. \en Sort by distance in the ascending order.
void Sort()
{
if ( allDistances.size() > 1 ) {
std::sort( allDistances.begin(), allDistances.end(), ItemItemDistCompFunc< MbItemItemDist<Param1,Param2> > );
minDistance = allDistances.front().GetDistance();
maxDistance = allDistances.back().GetDistance();
sorted = true;
}
}
/// \ru Убрать объекты с одинаковыми расстояниями. \en Remove objects with similar distances.
void RemoveEqualDistances( double eps = LENGTH_EPSILON )
{
if ( allDistances.size() > 1 ) {
if ( !sorted )
Sort();
bool wasRemoved = false;
for ( ptrdiff_t k = ((ptrdiff_t)allDistances.size() - 1); k > 0; k-- ) {
ptrdiff_t m = k - 1;
double dThis = allDistances[k].GetDistance();
double dPrev = allDistances[m].GetDistance();
if ( ::fabs( dThis - dPrev ) < eps ) {
allDistances.erase( allDistances.begin() + m );
wasRemoved = true;
}
}
if ( wasRemoved ) {
midDistance = UNDEFINED_DBL;
minDistance = allDistances.front().GetDistance();
maxDistance = allDistances.back().GetDistance();
}
}
}
/// \ru Оператор присваивания. \en Assignment operator.
void operator = ( const MbMinMaxItemItemDistances & other )
{
allDistances = other.allDistances; // \ru расстояние и параметры на поверхностях
midDistance = other.midDistance; // \ru среднее расстояние
minDistance = other.minDistance; // \ru минимальное расстояние
maxDistance = other.maxDistance; // \ru максимальное расстояние
sorted = other.sorted; // \ru признак сортированности
}
private:
MbMinMaxSurfDists( const MbMinMaxSurfDists & );
MbMinMaxItemItemDistances( const MbMinMaxItemItemDistances & );
};
//------------------------------------------------------------------------------
// \ru выдать расстояние \en get the distance
// MbMinMaxSurfSurfDists typedefs
// ---
inline bool MbMinMaxSurfDists::GetDistance( size_t k, double & d ) const
{
if ( k < surfDistances.Count() ) {
d = surfDistances[k].GetDistance();
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru выдать расстояние со знаком \en get signed distance
// ---
inline bool MbMinMaxSurfDists::GetSignedDistance( size_t k, double & d ) const
{
if ( k < surfDistances.Count() ) {
d = surfDistances[k].GetDistance();
if ( surfDistances[k].IsNegative() )
d = -d;
return true;
}
return false;
}
typedef MbMinMaxItemItemDistances<double, double> MbMinMaxCurvCurvDists;
typedef MbMinMaxItemItemDistances<double, MbCartPoint> MbMinMaxCurvSurfDists;
typedef MbMinMaxItemItemDistances<MbCartPoint, double> MbMinMaxSurfCurvDists;
typedef MbMinMaxItemItemDistances<MbCartPoint, MbCartPoint> MbMinMaxSurfSurfDists;
DEPRECATE_DECLARE_REPLACE( MbMinMaxSurfSurfDists )
typedef MbMinMaxItemItemDistances<MbCartPoint, MbCartPoint> MbMinMaxSurfDists; // old
//------------------------------------------------------------------------------
@@ -405,16 +679,16 @@ inline bool MbMinMaxSurfDists::GetSignedDistance( size_t k, double & d ) const
\en The number of points by v (the first surface) \~
\param[in] dir - \ru Вектор заданного направления (если нет, то по нормали).
\en The vector of direction (if not set then by the normal). \~
\param[in] orient - \ru Направление поиска.
\en Direction of search. \~
\param[in] useEqualDistances - \ru Оставлять равные равные расстояния.
\param[in] orient - \ru Относительное направление поиска.
\en Relative search direction. \~
\param[in] useEqualDistances - \ru Оставлять равные расстояния.
\en Whether to use the equal distances. \~
\param[in] surface2 - \ru Вторая поверхность.
\en The second surface. \~
\param[in,out] nMin - \ru Кол-во регистрируемых минимумов.
\en The number of registrated minimums. \~
\param[in,out] nMax - \ru Кол-во регистрируемых максимумов.
\en The number of registrated maximums. \~
\param[in,out] nMin - \ru Количество регистрируемых минимумов.
\en The number of recorded minimums. \~
\param[in,out] nMax - \ru Количество регистрируемых максимумов.
\en The number of recorded maximums. \~
\param[out] allResults - \ru Все результаты.
\en All results. \~
\param[out] minResults - \ru Результаты-минимумы.
@@ -426,21 +700,216 @@ inline bool MbMinMaxSurfDists::GetSignedDistance( size_t k, double & d ) const
\return \ru Возвращает результат замера (получен, не получен или же процесс был прерван).
\en Returns the result of measurement (obtained, not obtained, or the process has been aborted). \~
\ingroup Algorithms_3D
*/
// ---
MATH_FUNC (MbeProcessState) MinMaxDistances( const MbSurface & surface1,
ptrdiff_t u1cnt,
ptrdiff_t v1cnt,
const MbVector3D * dir,
const MbeSenseValue & orient,
bool useEqualDistances,
const MbSurface & surface2,
ptrdiff_t & nMin,
ptrdiff_t & nMax,
MbMinMaxSurfDists & allResults,
MbMinMaxSurfDists & minResults,
MbMinMaxSurfDists & maxResults,
IProgressIndicator * indicator = nullptr );
*/ // ---
//DEPRECATE_DECLARE_REPLACE( MinMaxSurfaceSurfaceGridDistances )
MATH_FUNC (MbeProcessState) MinMaxDistances( const MbSurface & surface1,
ptrdiff_t u1cnt,
ptrdiff_t v1cnt,
const MbVector3D * dir,
const MbeSenseValue & orient,
bool useEqualDistances,
const MbSurface & surface2,
ptrdiff_t & nMin,
ptrdiff_t & nMax,
MbMinMaxSurfSurfDists & allResults,
MbMinMaxSurfSurfDists & minResults,
MbMinMaxSurfSurfDists & maxResults,
IProgressIndicator * indicator = nullptr );
//------------------------------------------------------------------------------
/** \brief \ru Параметры операции сеточного поиска минимумов и максимумов.
\en Parameters of the operation of the grid search for minima and maxima. \~
\details \ru Параметры операции сеточного поиска минимумов и максимумов расстояний между объектами.
\en Parameters of the grid search operation for minima and maxima of distances between objects. \~
\ingroup Algorithms_3D
*/ // ---
class MATH_CLASS MbMinMaxGridDistancesParams {
public:
c3d::ConstSpaceItemSPtr srcItem; ///< \ru Базовый объект (кривая или поверхность). \en Base object (curve or surface). \~
c3d::IndicesPair srcSplitsCount; ///< \ru Количество разбиений (точек). \en Number of partitions (points). \~
c3d::ConstSpaceItemSPtr dstItem; ///< \ru Целевой объект (кривая или поверхность). \en Target object (curve or surface). \~
MbVector3D projDirection; ///< \ru Вектор заданного направления (если нет, то по нормали). \en he vector of direction (if not set then by the normal). \~
MbeSenseValue projOrient; ///< \ru Относительное направление поиска. \en Relative search direction. \~
bool useEqualDistances; ///< \ru Оставлять равные расстояния. \en Whether to use the equal distances. \~
size_t desiredMinimaNumber; ///< \ru Желаемое число выдаваемых минимумов. \en Desired minima number.
size_t desiredMaximaNumber; ///< \ru Желаемое число выдаваемых максимумов. \en Desired maxima number.
VERSION version; ///< \ru Версия. \en Version.
private:
mutable IProgressIndicator * progress; ///< \ru Индикатор прогресса выполнения операции. \en A progress indicator of the operation.
private:
MbMinMaxGridDistancesParams(); // \ru Не реализовано. \en Not implemented.
public:
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMinMaxGridDistancesParams( const MbSurface & srcSurface,
size_t srcUCnt,
size_t srcVCnt,
const MbSurface & dstSurface,
VERSION ver = Math::DefaultMathVersion() )
: srcItem ( &srcSurface )
, srcSplitsCount ( srcUCnt, srcVCnt )
, dstItem ( &dstSurface )
, projDirection ( )
, projOrient ( orient_BOTH )
, useEqualDistances ( false )
, desiredMinimaNumber( 1 )
, desiredMaximaNumber( 1 )
, version ( ver )
, progress ( nullptr )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMinMaxGridDistancesParams( const MbSurface & srcSurface,
size_t srcUCnt,
size_t srcVCnt,
const MbVector3D * dir,
const MbeSenseValue & orient,
bool useEqualDists,
const MbSurface & dstSurface,
size_t nMin,
size_t nMax,
VERSION ver = Math::DefaultMathVersion() )
: srcItem ( &srcSurface )
, srcSplitsCount ( srcUCnt, srcVCnt )
, dstItem ( &dstSurface )
, projDirection ( )
, projOrient ( orient )
, useEqualDistances ( useEqualDists )
, desiredMinimaNumber( nMin )
, desiredMaximaNumber( nMax )
, version ( ver )
, progress ( nullptr )
{
SetProjectionDirection( dir, orient );
}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMinMaxGridDistancesParams( const MbCurve3D & srcCurve,
size_t srcTCnt,
const MbSurface & dstSurface,
VERSION ver = Math::DefaultMathVersion() )
: srcItem ( &srcCurve )
, srcSplitsCount ( srcTCnt, 0 )
, dstItem ( &dstSurface )
, projDirection ( )
, projOrient ( orient_BOTH )
, useEqualDistances ( false )
, desiredMinimaNumber( 1 )
, desiredMaximaNumber( 1 )
, version ( ver )
, progress ( nullptr )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MbMinMaxGridDistancesParams( const MbCurve3D & srcCurve,
size_t srcTCnt,
const MbCurve3D & dstCurve,
VERSION ver = Math::DefaultMathVersion() )
: srcItem ( &srcCurve )
, srcSplitsCount ( srcTCnt, 0 )
, dstItem ( &dstCurve )
, projDirection ( )
, projOrient ( orient_BOTH )
, useEqualDistances ( false )
, desiredMinimaNumber( 1 )
, desiredMaximaNumber( 1 )
, version ( ver )
, progress ( nullptr )
{}
public:
/// \ru Получить базовый объект. \en Get base object.
const MbSpaceItem & GetBaseItem () const { return *srcItem; }
/// \ru Получить целевой объект. \en Get target object.
const MbSpaceItem & GetTargetItem() const { return *dstItem; }
/// \ru Получить количество разбиений базового объекта. \en Get base object splits count.
const c3d::IndicesPair & GetBaseSplitsCount() const { return srcSplitsCount; }
/// \ru Получить общий вектора поиска. \en Get general search direction.
bool GetProjectionDirection( MbVector3D & dir, MbeSenseValue & orient ) const
{
if ( projDirection.Length() > LENGTH_EPSILON ) {
dir = projDirection;
orient = projOrient;
return true;
}
return false;
}
/// \ru Получить общий вектора поиска. \en Get general search direction.
bool GetUseEqualDistances() const { return useEqualDistances; }
/// \ru Получить желаемое число выдаваемых минимумов. \en Get desired minima number.
size_t GetDesiredMinimaNumber() const { return desiredMinimaNumber; }
/// \ru Получить желаемое число выдаваемых максимумов. \en Get desired maxima number.
size_t GetDesiredMaximaNumber() const { return desiredMaximaNumber; }
/// \ru Получить версию. \en Get version.
VERSION GetVersion() const { return version; }
public:
/// \ru Установить общее направление поиска. \en Set general search direction.
bool SetProjectionDirection( const MbVector3D * dirPtr, MbeSenseValue orient )
{
if ( dirPtr != nullptr ) {
const MbVector3D & dir = *dirPtr;
double dirLen = dir.Length();
if ( dirLen > LENGTH_EPSILON && dirLen < c3d::MAX_LENGTH ) {
projDirection = dir;
projOrient = orient;
return true;
}
}
return false;
}
/// \ru Установить флаг использования одинаковых расстояний. \en Set flag to use equal distances.
void SetUseEqualDistances( bool useEqualDists ) { useEqualDistances = useEqualDists; }
/// \ru Установить желаемые числа выдаваемых минимумов и максимумов. \en Get desired minima and maxima numbers.
void SetDisiredMinMaxNumbers( size_t minNum, size_t maxNum ) { desiredMinimaNumber = minNum; desiredMaximaNumber = maxNum; }
public:
/// \ru Установить внешний индикатор прогресса выполнения. \en Set external progress indicator.
void SetProgressIndicator( IProgressIndicator * prog ) { progress = prog; }
/// \ru Установить внешний индикатор прогресса выполнения. \en Set external progress indicator.
IProgressIndicator * TakeProgressIndicator() const { return progress; }
OBVIOUS_PRIVATE_COPY( MbMinMaxGridDistancesParams )
};
//------------------------------------------------------------------------------
/** \brief \ru Результаты операции сеточного поиска минимумов и максимумов.
\en Results of the operation of the grid search for minima and maxima. \~
\details \ru Результаты операции сеточного поиска минимумов и максимумов расстояний между объектами.
\en Results of the grid search operation for minima and maxima of distances between objects. \~
\ingroup Algorithms_3D
*/ // ---
template <class Param1, class Param2>
class MbMinMaxGridDistancesResults {
public:
MbMinMaxItemItemDistances<Param1, Param2> allResults; ///< \ru Все результаты. \en All results. \~
MbMinMaxItemItemDistances<Param1, Param2> minResults; ///< \ru Результаты-минимумы. \en Results-minimums. \~
MbMinMaxItemItemDistances<Param1, Param2> maxResults; ///< \ru Результаты-максимумы. \en Results-maximums. \~
public:
/// \ru Получить фактическое число минимумов. \en Get real minima number.
size_t GetActualMinimaNumber() const { return minResults.GetCount(); }
/// \ru Получить фактическое число максимумов. \en Get desired maxima number.
size_t GetActualMaximaNumber() const { return maxResults.GetCount(); }
};
//------------------------------------------------------------------------------
/** \brief \ru Экстремальные расстояния между объектами (кривыми или поверхностями).
\en Extreme distances between objects (curves or surfaces). \~
\details \ru Экстремальные расстояния между объектами по сетке на первом объекте,
причем замеры выполняются в заданном направлении (если есть вектор)
или по нормалям к первому объекту.
\en Extreme distances between objects along the grid on the first object,
and measurements are taken in a given direction (if there is a vector)
or along the normal to the first object. \~
\param[in] params - \ru Параметры операции сеточного поиска минимумов и максимумов.
\en Parameters of the operation of the grid search for minima and maxima. \~
\param[out] results - \ru Результаты операции сеточного поиска минимумов и максимумов.
\en Results of the operation of the grid search for minima and maxima. \~
\return \ru Возвращает результат замера (получен, не получен или же процесс был прерван).
\en Returns the result of measurement (obtained, not obtained, or the process has been aborted). \~
\ingroup Algorithms_3D
*/ // ---
MATH_FUNC (MbeProcessState) MinMaxSurfaceSurfaceGridDistances( const MbMinMaxGridDistancesParams & params,
MbMinMaxGridDistancesResults<MbCartPoint, MbCartPoint> & results );
#endif // __ALG_DIMENSION_H
+36
View File
@@ -403,6 +403,42 @@ DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireCount )
IMPL_PERSISTENT_OPS( MbWireCount )
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать атрибут MbColor в атрибут MbVisual.
\en Convert MbColor attribute into MbVisual attribute. \~
\details \ru Создать атрибут MbVisual, в котором компонент diffuse содержит
значение атрибута MbColor, а остальные значения по умолчанию. \n
\en Create a MbVisual attribute where the diffuse component contains
the value of MbColor attribute and the rest contain default values. \n \~
\param[in] cAttr - \ru Атрибут MbColor.
\en MbColor attribute. \~
\result \ru Возвращает указатель на созданный атрибут MbVisual.
\en Returns a pointer to the created MbVisual attribute. \~
\ingroup Model_Attributes
*/
// ---
MATH_FUNC( SPtr<MbVisual> ) ColorToVisual( const MbColor & cAttr );
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать атрибуты цвета в атрибут MbVisual.
\en Convert color attributes into MbVisual attribute. \~
\details \ru Создать новый атрибут MbVisual на базе заданного атрибута MbVisual,
в котором компонент diffuse содержит заданный MbColor. \n
\en Create a MbVisual attribute on base of the MbVisual attribute
where the diffuse component contains the value of the MbColor attribute. \n \~
\param[in] cAttr - \ru Атрибут MbColor.
\en MbColor attribute. \~
\param[in] vAttr - \ru Атрибут MbVisual.
\en MbVisual attribute. \~
\result \ru Возвращает указатель на созданный атрибут MbVisual.
\en Returns a pointer to the created MbVisual attribute. \~
\ingroup Model_Attributes
*/
// ---
MATH_FUNC( SPtr<MbVisual> ) ColorToVisual( const MbColor & cAttr, const MbVisual & vAttr );
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать цвет по трём компонентам в uint32.
\en Convert a color by 3 components in uint32. \~
+82 -8
View File
@@ -119,14 +119,63 @@ public:
/// \ru Удалить все атрибуты из контейнера. \en Delete all attributes from container.
bool RemoveAttributes( bool onDeleteOwner = false );
/// \ru Добавить атрибут в контейнер. \en Add attribute in container.
MbAttribute * AddAttribute( MbAttribute *, bool checkSame = true );
/// \ru Добавить атрибут в контейнер (всегда копирует атрибут). \en Add attribute in container (always copies the attribute).
MbAttribute * AddAttribute( const MbAttribute &, bool checkSame = true );
/// \ru Выдать атрибуты заданного семейства. \en Get attributes of a given family.
void GetAttributes( c3d::AttrVector &, MbeAttributeType aFamily, MbeAttributeType subType ) const;
/// \ru Выдать атрибуты заданного типа. \en Get attributes of a given type.
void GetAttributes( c3d::AttrVector &, MbeAttributeType aType ) const;
/** \brief \ru Добавить атрибут в контейнер.
\en Add attribute in container. \~
\details \ru Добавить атрибут в контейнер (добавляет оригинал атрибута, если это возможно).
В случае простого атрибута, если он уже есть, его данные заменены данными входного атрибута.
Во избежание утечек рекомендуется владеть атрибутом по счетчику ссылок (явно или через SPtr). \n
\en Add attribute in container (adds the original attribute if it's possible).
In the case of a simple attribute, if it already exists, its data is replaced by the data of the input attribute.
To avoid leaks, it is recommended to own the attribute by reference count (explicitly or via SPtr). \n \~
\param[in] attr - \ru Атрибут.
\en Attribute. \~
\param[in] checkSame - \ru Флаг поиска такого же по содержанию атрибута в контейнере. Атрибут не будет добавлен, если найден такой же.
\en Search flag for an attribute containing the same content. Attribute will not be added if the same attribute is found. \~
\return \ru Возвращает указатель на добавленный атрибут или нулевой указатель.
\en Returns a pointer to the added attribute or null pointer. \~
*/
MbAttribute * AddAttribute( MbAttribute * attr, bool checkSame = true );
/** \brief \ru Добавить атрибут в контейнер (добавляет копию атрибута, если его можно добавить).
\en Add attribute in container (adds a copy of the attribute if it can be added). \~
\details \ru Добавить атрибут в контейнер (добавляет копию атрибута, если его можно добавить).
В случае простого атрибута, если он уже есть, его данные заменены данными входного атрибута. \n
\en Add attribute in container (adds a copy of the attribute if it can be added).
In the case of a simple attribute, if it already exists, its data is replaced by the data of the input attribute. \n \~
\param[in] attr - \ru Атрибут.
\en Attribute. \~
\param[in] checkSame - \ru Флаг поиска такого же по содержанию атрибута в контейнере. Атрибут не будет добавлен, если найден такой же.
\en Search flag for an attribute containing the same content. Attribute will not be added if the same attribute is found. \~
\return \ru Возвращает указатель на добавленный атрибут или нулевой указатель.
\en Returns a pointer to the added attribute or null pointer. \~
*/
MbAttribute * AddAttribute( const MbAttribute & attr, bool checkSame = true );
/** \brief \ru Выдать атрибуты заданного типа или семейства.
\en Get attributes of a given type or family. \~
\details \ru Выдать атрибуты заданного типа или семейства атрибутов. Если тип атрибутов задан как at_Undefined, \n
то выдаются все атрибуты заданного семейства, иначе возвращаются атрибуты заданного типа.
\en Get attributes of a given type or family of attributes. If the attribute type is set to at_Undefined, \n
then all attributes of the given family are returned, otherwise the attributes of the given type are returned. \~
\param[out] attrs - \ru Массив возвращаемых атрибутов.
\en An array of returned attributes.\~
\param[in] aFamily - \ru Выбранное семейство возвращаемых атрибутов.
\en A family of returned attributes. \~
\param[in] subType - \ru Выбранный тип возращаемых атрибутов.
\en A type of returned attributes. \~
*/
void GetAttributes( c3d::AttrVector & attrs, MbeAttributeType aFamily, MbeAttributeType subType ) const;
/** \brief \ru Выдать атрибуты заданного типа.
\en Get attributes of a given type. \~
\details \ru Выдать атрибуты заданного типа.
\en Get attributes of a given type. \~
\param[out] attrs - \ru Массив возвращаемых атрибутов.
\en An array of returned attributes.\~
\param[in] aType - \ru Выбранный тип возращаемых атрибутов.
\en A type of returned attributes. \~
*/
void GetAttributes( c3d::AttrVector & attrs, MbeAttributeType aType ) const;
/// \ru Выдать атрибуты по строке описания. \en Get attributes using sample of description string.
void GetCommonAttributes( c3d::AttrVector &, const c3d::string_t & samplePrompt, MbeAttributeType subType = at_Undefined, bool firstFound = false ) const;
/// \ru Выдать строковые атрибуты по строке содержания. \en Get string attributes using sample of contents of the string.
@@ -341,4 +390,29 @@ MATH_FUNC (bool) AddCommonAttributes( const MbAttributeContainer & srcItem,
MATH_FUNC (bool) RemoveCommonAttributes( MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt );
//------------------------------------------------------------------------------
/** \brief \ru Преобразовать атрибуты цвета.
\en Convert color attributes. \~
\details \ru Преобразовать атрибуты цвета, исключив атрибут MbColor из контейнера.
При наличии только атрибута MbColor, он заменяется на атрибут MbVisual, в котором
компонент diffuse содержит значение атрибута MbColor, а остальные значения по умолчанию.
При наличии пары атрибутов MbColor и MbVisual, компонент diffuse атрибута MbVisual
заменяется на значение атрибута MbColor, а атрибут MbColor удаляется. \n
\en Convert color attributes and exclude the attribute MbColor from the container.
If there is only the MbColor attribute in the container, it is replaced by
the MbVisual attribute, in which the diffuse component contains the value of
the MbColor attribute, and the rest - default values.
If there is a pair of MbColor and MbVisual attributes, the diffuse component
of the MbVisual attribute is replaced with the value of the MbColor attribute,
and the MbColor attribute is deleted. \n \~
\param[in/out] attrItem - \ru Объект с атрибутами.
\en Object with attributes. \~
\result \ru Возвращает true, если атрибуты были изменены.
\en Returns 'true' if the attributes were was changed. \~
\ingroup Model_Attributes
*/
// ---
MATH_FUNC( bool ) ConvertColorAttributes( MbAttributeContainer & attrItem );
#endif // __ATTRIBUTE_CONTAINER_H
+12 -5
View File
@@ -101,22 +101,23 @@ struct MATH_CLASS cdet_query
};
// If message is CDET_INCLUDED, then cback_data::first is in cback_data::second.
cback_res operator() ( message code, cback_data & cData ) { return func( this, code, cData ); }
cback_res operator() ( message code, cback_data & cData ) { return func( this, code, cData ); }
protected:
typedef cback_res (*cback_func)( cdet_query *, message, cback_data & );
cdet_query( cback_func _func ) : func(_func) {}
cdet_query( const cdet_query & cQuery ) : func(cQuery.func) {}
~cdet_query() {}
OBVIOUS_PRIVATE_COPY( cdet_query );
cdet_query & operator = ( const cdet_query & cQuery ) { func = cQuery.func; return *this; }
private:
cback_func func;
};
//----------------------------------------------------------------------------------------
//
// Simple collision query data to search for the first detected interference.
//---
struct MATH_CLASS cdet_query_result: public cdet_query
{
@@ -127,6 +128,12 @@ struct MATH_CLASS cdet_query_result: public cdet_query
, result( CDET_RESULT_NoIntersection )
{}
cdet_query_result( const cdet_query_result & cQuery )
: cdet_query( cQuery )
, result( cQuery.result )
{}
private:
static cback_res QueryFunc( cdet_query * query, message code, cback_data & )
{
@@ -134,7 +141,7 @@ private:
cdet_query_result * q = static_cast<cdet_query_result*>( query );
switch( code )
{
case CDET_QUERY_STARTED: // The collision query is started for all solids of the set
case CDET_QUERY_STARTED: // The collision query is started for all solids of the scene.
{
q->result = CDET_RESULT_NoIntersection;
return CBACK_VOID;
@@ -154,7 +161,7 @@ private:
};
//----------------------------------------------------------------------------------------
// The structure queries first founded collision faces
// The structure queries first founded collision faces.
//---
struct MATH_CLASS cdet_first_collided: public cdet_query
{
+23 -1
View File
@@ -455,6 +455,28 @@ bool CheckInexactVertices( const VerticesVector & vertArr, double mAcc, Vertices
}
//------------------------------------------------------------------------------
/** \brief \ru Является ли кривая пересечения неточной.
\en Is the curve of intersection inaccurate. \~
\details \ru Является ли кривая пересечения неточной (оценочно). \n
Наличие неточных кривых пересечения не является серьезным дефектом.
В большинстве случаев никак не влияет на результат операций.
Незначительно влияет на расчет МЦХ. \n
\en Is the curve of intersection inaccurate (estimated). \n
The presence of inaccurate curves of intersection is not a serious defect.
In most cases, does not affect on the result of operations.
Can slightly affect the calculation of the MIP. \n \~
\param[in] curve - \ru Кривая пересечения.
\en The curve of intersection. \~
\param[in] mMaxAcc - \ru Порог отбора неточного ребра.
\en Accuracy selection inaccurate curves of intersection. \~
\return \ru Возвращает true, если кривая пересечения неточная.
\en Returns true, if the curve of intersection is inaccurate. \~
\ingroup Algorithms_3D
*/ //---
MATH_FUNC (bool) IsInexactIntersectionCurve( const MbSurfaceIntersectionCurve & curve, double mMaxAcc );
//------------------------------------------------------------------------------
/** \brief \ru Является ли кривая пересечения ребра неточной.
\en Is the curve of intersection edges inaccurate. \~
@@ -469,7 +491,7 @@ bool CheckInexactVertices( const VerticesVector & vertArr, double mAcc, Vertices
\param[in] edge - \ru Ребро оболочки.
\en The edge of the shell. \~
\param[in] mMaxAcc - \ru Порог отбора неточного ребра.
\en Accuracy selection inaccurate ribs. \~
\en Accuracy selection inaccurate edges. \~
\return \ru Возвращает true, если ребро неточное.
\en Returns true, if the edge is inaccurate. \~
\ingroup Algorithms_3D
+35 -33
View File
@@ -300,6 +300,9 @@ struct C3DConverterDebugSettings {
/// \ru Включить вывод статистики импортируемых объектов. \en Enable logging the statistic of imported objects.
bool cerrOutImportStatistic;
/// \ru Добавлять целочисленный атрибут со значением id элемента из обменного файла. \en Attach int attribute which's value based on id from exchange file.
bool attachThisIdAttribute;
/// \ru Идентификатор элемента, для которого сделать вывод информации для тонкой отладки. \en Id of element for each save data for fine debugging.
ptrdiff_t elementIdFineDebug;
@@ -313,6 +316,7 @@ struct C3DConverterDebugSettings {
, cerrOutIntermediateTreeTraverse( false )
, cerrOutImportStatistic( false )
, saveModelTwin( false )
, attachThisIdAttribute( false )
, elementIdFineDebug( -1 )
, pathFineDebug()
{
@@ -486,11 +490,10 @@ public:
virtual C3DConverterDebugSettings GetDebugSettings() const { return C3DConverterDebugSettings(); };
/// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute.
virtual bool AttatchIdAttributes() const { return true; }
DEPRECATE_DECLARE_REPLACE( GetDebugSettings ) virtual bool AttatchIdAttributes() const { return true; }
/// \ru Получить пользовательский преобразователь строк. \en Get user string transformer.
virtual SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const { return SPtr<IC3DCharEncodingTransformer>(nullptr); }
}; // IConvertorProperty3D
@@ -551,58 +554,58 @@ public:
public:
ConvConvertorProperty3D(); ///< \ru Конструктор. \en Constructor.
virtual ~ConvConvertorProperty3D() {};///< \ru Деструктор. \en Destructor.
~ConvConvertorProperty3D() override {};///< \ru Деструктор. \en Destructor.
/// \ru Получить имя документа. \en Get document's name.
virtual const std::string GetDocumentName () const { return docName; };
const std::string GetDocumentName () const override { return docName; };
/// \ru Получить имя файла для конвертирования. \en Get file name for converting.
virtual const c3d::path_string FullFilePath () const { return fileName; };
const c3d::path_string FullFilePath () const override { return fileName; };
/// \ru Является ли файл текстовым. \en Whether the file is a text file.
virtual bool IsFileAscii () const;
bool IsFileAscii () const override;
/// \ru Получить версию формата при экспорте. \en Get the version of format for export.
virtual long int GetFormatVersion () const;
long int GetFormatVersion () const override;
/// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ).
virtual bool IsOutOnlySurfaces() const;
bool IsOutOnlySurfaces() const override;
/// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly.
virtual bool IsAssembling () const { return true; };
bool IsAssembling () const override { return true; };
/// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type.
virtual bool GetIoPermission( MbeIOPermiss nPermission ) const;
bool GetIoPermission( MbeIOPermiss nPermission ) const override;
/// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types.
virtual void GetIoPermissions( std::vector<bool>& ioPermissions ) const;
void GetIoPermissions( std::vector<bool>& ioPermissions ) const override;
/// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type.
virtual void SetIoPermission( MbeIOPermiss nPermission, bool isSet );
void SetIoPermission( MbeIOPermiss nPermission, bool isSet ) override;
/// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter.
virtual bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const;
bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const override;
/// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter.
virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString );
void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ) override;
/// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects.
virtual eTextForm GetAnnotationTextRepresentation () const;
eTextForm GetAnnotationTextRepresentation () const override;
/** \brief \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат).
\en Export components into separate files ( if provided in format). \~
\note \ru ЭКСПЕРИМЕНТАЛЬНАЯ.
\en EXPEREIMENTAL \~.
*/
virtual bool ExportComponentsSeparately() const;
bool ExportComponentsSeparately() const override;
/// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in.
virtual MbPlacement3D GetOriginLocation() const;
MbPlacement3D GetOriginLocation() const override;
/// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented.
virtual bool ReplaceLocationsToRight() const;
bool ReplaceLocationsToRight() const override;
/** \brief \ru Сшивать ли поверхности автоматически.
\en If surfaces should be stitched automatically. \~
\return \ru true - Сшивать поверхности автоматически, false - Спросить пользователя, сшивать ли поверхности.
\en true - Stitch surfaces automatically, false - Ask user first time. \~
\param[out] stitchPrecision - \ru Точность сшивки.
\en Stitch precision. \~
*/ virtual bool EnableAutoStitch( double& /*stitchPrecision*/ ) const;
*/ bool EnableAutoStitch( double& /*stitchPrecision*/ ) const override;
/// \ru Получить множитель единиц длины по отношению к миллиметру. \en Get the factor of the length units to millimeters.
virtual double LengthUnitsFactor() const;
double LengthUnitsFactor() const override;
/** \brief \ru Получить множитель единиц длины по отношению к миллиметру в модели приложения.
\en Get the factor of the length units to millimeters in the application model. \~
*/
virtual double AppLengthUnitsFactor() const;
double AppLengthUnitsFactor() const override;
/** \brief \ru Сделать запись в журнал конвертирования.
\en Make a record in the converter report. \~
@@ -613,41 +616,40 @@ public:
\param[in] msgText - \ru Код сообщения.
\en Message code. \~
*/
virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText );
void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ) override;
// /** \brief \ru Следует ли показывать сообщения и диалоги пользователю. \en Whether to show messages and dialog to the user. \~
// \details \ru Обеспечивает работу через API. \en Provide possibility for work via API. \~
// \return \ru true - обычная работа, false - через API. \en true - ordinary work, false - via API. \~
// */
virtual bool CanShowMessages() const;
bool CanShowMessages() const override;
/// \ru Дать данные вычисления триангуляции (для конвертера STL и VRML). \en Get data for step calculation during triangulation (for STL, VRML only).
virtual MbStepData TesselationParameters() const;
MbStepData TesselationParameters() const override;
/// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly).
virtual MbStepData LOD0TesselationParameters() const;
MbStepData LOD0TesselationParameters() const override;
/// \ru Получить флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only).
virtual bool DualSeams() const;
bool DualSeams() const override;
/// \ru Задать флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only).
virtual void DualSeams( bool );
void DualSeams( bool );
/// \ru Получить настройки для выдачи отладочной информации. \en Get the settings of debug info.
virtual C3DConverterDebugSettings GetDebugSettings() const;
/// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute.
virtual bool AttatchIdAttributes() const;
C3DConverterDebugSettings GetDebugSettings() const override;
/// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces.
virtual bool JoinSimilarFaces() const { return joinSimilarFaces; }
bool JoinSimilarFaces() const override { return joinSimilarFaces; }
/// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells.
virtual bool AddRemovedFacesAsShells() const { return addRemovedFacesAsShells; }
bool AddRemovedFacesAsShells() const override { return addRemovedFacesAsShells; }
/// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier.
virtual SPtr<IProductIdMaker> ProductIdentifierGenerator() const { return SPtr<IProductIdMaker>( new NameProductIdMaker() ); }
/// \ru Получить пользовательский преобразователь строк. \en Get user string transformer.
virtual SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const;
SPtr<IC3DCharEncodingTransformer> GetUserCharEncodingTransformer() const override;
OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D )
}; // IConvertorProperty3D
//------------------------------------------------------------------------------
/** \brief \ru Преобразование строк с использованием установленной локали.
\en Transform strings using the set locale.
+3 -1
View File
@@ -384,7 +384,9 @@ namespace c3d {
// \ru Очистить. \en Clear.
inline void Clear() {
delete[] data;
if( data != nullptr )
delete[] data;
data = nullptr;
count = 0;
}
+64 -53
View File
@@ -24,16 +24,18 @@ class MATH_CLASS MbDraftSolidParams;
// ---
class MATH_CLASS MbDraftSolid: public MbCreator {
protected:
double angle; ///< \ru Угол уклона. \en Draft angle.
c3d::ItemIndices faceIndices; ///< \ru Индексы множества уклоняемых граней. \en Indices of faces to draft.
SArray<MbEdgeFacesIndexes> edgeIndices; ///< \ru Индексы множества нейтральных ребер. \en Indices of edges to draft.
MbeFacePropagation fp; ///< \ru Признак захвата граней ( face propagation ). \en Flag of face propagation.
double angle; ///< \ru Угол уклона. \en Draft angle.
c3d::ItemIndices faceIndices; ///< \ru Индексы множества уклоняемых граней. \en Indices of faces to draft.
SArray<MbEdgeFacesIndexes> edgeIndices; ///< \ru Индексы множества нейтральных ребер. \en Indices of edges to draft.
MbeFacePropagation fp; ///< \ru Признак захвата граней ( face propagation ). \en Flag of face propagation.
// \ru Атрибуты, определяющие направление тяги (pull direction) и нейтральную изолинию уклона. \en Attributes determining the pull direction and the neutral isoline of the draft.
MbPlacement3D * np; ///< \ru Нейтральная плоскость ( neutral plane ) ( не обязателен ). \en Neutral plane (optional).
ptrdiff_t edgeNb; ///< \ru Номер прямолинейного ребра, направляющего уклон ( не обязателен ). \en The index of straight edge specifying the draft (optional).
SArray<ptrdiff_t> * pl; ///< \ru Линии разъема (ребра) ( parting line ) ( не обязателен ). \en Parting lines (of edge) (optional).
bool reverse; ///< \ru Обратное направление тяги. \en Reverse pull direction.
bool step; ///< \ru Ступенчатый способ уклона. \en Stepwise method of draft.
MbPlacement3D * np; ///< \ru Нейтральная плоскость ( neutral plane ) ( не обязателен ). \en Neutral plane (optional).
ptrdiff_t edgeNb; ///< \ru Номер прямолинейного ребра, направляющего уклон ( не обязателен ). \en The index of straight edge specifying the draft (optional).
SArray<ptrdiff_t> * pl; ///< \ru Линии разъема (ребра) ( parting line ) ( не обязателен ). \en Parting lines (of edge) (optional).
bool reverse; ///< \ru Обратное направление тяги. \en Reverse pull direction.
bool step; ///< \ru Ступенчатый способ уклона. \en Stepwise method of draft.
bool rebuildFillets; ///< \ru Перестраивать ли скругления. \en Whether to rebuild the fillets.
public:
/// \ru Конструктор уклона по известной нейтральной плоскости. \en Constructor of drafting by the given neutral plane.
@@ -42,17 +44,19 @@ public:
const std::vector<MbItemIndex> & faceInds, // номера множества уклоняемых граней
MbeFacePropagation faceProp, // признак захвата граней
bool rev, // обратное направление тяги
const MbSNameMaker & n )
: MbCreator ( n )
, angle ( ang )
, faceIndices( faceInds )
, edgeIndices( )
, fp ( faceProp )
, np ( new MbPlacement3D( nPlace ) )
, edgeNb ( -1 )
, pl ( nullptr )
, reverse ( rev )
, step ( false )
const MbSNameMaker & n,
bool _rebuildFillets = false )
: MbCreator ( n )
, angle ( ang )
, faceIndices ( faceInds )
, edgeIndices ( )
, fp ( faceProp )
, np ( new MbPlacement3D( nPlace ) )
, edgeNb ( -1 )
, pl ( nullptr )
, reverse ( rev )
, step ( false )
, rebuildFillets( _rebuildFillets )
{
}
/// \ru Конструктор уклона по линии разъема \en Constructor of drafting by the parting line
@@ -63,17 +67,20 @@ public:
const SArray<ptrdiff_t> & partLines, // линии разъема (ребра) (parting line) (не обязателен)
bool rev, // обратное направление тяги
bool st, // ступенчатый способ уклона
const MbSNameMaker & n )
: MbCreator ( n )
, angle ( ang )
, faceIndices( )
, edgeIndices( )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( new SArray<ptrdiff_t>( partLines ) )
, reverse ( rev )
, step ( st )
const MbSNameMaker & n,
bool _rebuildFillets = false )
: MbCreator ( n )
, angle ( ang )
, faceIndices ( )
, edgeIndices ( )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( new SArray<ptrdiff_t>( partLines ) )
, reverse ( rev )
, step ( st )
, rebuildFillets( _rebuildFillets )
{
}
/// \ru Конструктор уклона по линии разъема и уклоняемым граням \en Constructor of drafting by the parting line and drafting faces
@@ -85,17 +92,19 @@ public:
const SArray<ptrdiff_t> & partLines, // линии разъема (ребра) (parting line) (не обязателен)
bool rev, // обратное направление тяги
bool st, // ступенчатый способ уклона
const MbSNameMaker & n )
: MbCreator ( n )
, angle ( ang )
, faceIndices( faceInds )
, edgeIndices( )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( new SArray<ptrdiff_t>( partLines ) )
, reverse ( rev )
, step ( st )
const MbSNameMaker & n,
bool _rebuildFillets = false )
: MbCreator ( n )
, angle ( ang )
, faceIndices ( faceInds )
, edgeIndices ( )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( new SArray<ptrdiff_t>( partLines ) )
, reverse ( rev )
, step ( st )
, rebuildFillets( _rebuildFillets )
{
}
@@ -108,17 +117,19 @@ public:
const SArray<MbEdgeFacesIndexes> & edgeInds, // индексы множества нейтральных ребер
bool rev, // обратное направление тяги
bool st, // ступенчатый способ уклона
const MbSNameMaker & n )
: MbCreator ( n )
, angle ( ang )
, faceIndices( faceInds )
, edgeIndices( edgeInds )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( nullptr )
, reverse ( rev )
, step ( st )
const MbSNameMaker & n,
bool _rebuildFillets = false )
: MbCreator ( n )
, angle ( ang )
, faceIndices ( faceInds )
, edgeIndices ( edgeInds )
, fp ( faceProp )
, np ( nPlace ? new MbPlacement3D( *nPlace ) : nullptr )
, edgeNb ( edgeInd )
, pl ( nullptr )
, reverse ( rev )
, step ( st )
, rebuildFillets( _rebuildFillets )
{
}
+10 -10
View File
@@ -423,7 +423,7 @@ public :
\return \ru Выполнено ли построение.
\en Whether the construction is performed. \~
*/
bool CreateWireFrame( SPtr<MbWireFrame> & frame, MbeCopyMode sameShell );
bool CreateWireFrame( SPtr<MbWireFrame> & frame, MbeCopyMode sameShell );
/** \brief \ru Построить точечный каркас по исходным данным.
\en Create a point-frame from the source data. \~
@@ -452,7 +452,7 @@ public :
\return \ru Выполнено ли построение.
\en Whether the construction is performed. \~
*/
bool CreatePointFrame( SPtr<MbPointFrame> & frame, MbeCopyMode sameShell );
bool CreatePointFrame( SPtr<MbPointFrame> & frame, MbeCopyMode sameShell );
/** \brief \ru Создать полигональный объект по исходным данным.
\en Create a polygonal object from the source data. \~
@@ -481,7 +481,7 @@ public :
\return \ru Выполнено ли построение.
\en Whether the construction is performed. \~
*/
bool CreateMesh( SPtr<MbMesh> & mesh, MbeCopyMode sameShell );
bool CreateMesh( SPtr<MbMesh> & mesh, MbeCopyMode sameShell );
/// \ru Выдать свойства объекта. \en Get properties of the object.
virtual void GetProperties( MbProperties & );
@@ -511,23 +511,23 @@ public :
/// \ru Установить версию объектов. \en Set the objects version.
virtual void SetYourVersion( VERSION version, bool forAll );
/// \ru Выдать версию объекта. \en Get the object version.
VERSION GetYourVersion() const { return names->GetMathVersion(); }
VERSION GetYourVersion() const { return names->GetMathVersion(); }
/// \ru Выдать именователь объекта. \en Get the name-maker.
const MbSNameMaker & GetYourNameMaker() const { return *names; }
/// \ru Выдать именователь объекта для редактирования. \en Get the object's name-maker for editing.
MbSNameMaker & SetYourNameMaker() { return *names; }
/// \ru Установить именователь объекта. \en Set the object's name-maker.
void SetNameMaker( const MbSNameMaker & n ) { names->SetNameMaker( n ); }
void SetNameMaker( const MbSNameMaker & n ) { names->SetNameMaker( n, true ); }
/// \ru Выдать главное имя объекта. \en Get the main name of the object.
SimpleName GetMainName() const { return names->GetMainName(); }
SimpleName GetMainName() const { return names->GetMainName(); }
/// \ru Установить главное имя объекта. \en Set the main name of the object.
void SetMainName( SimpleName n ) { names->SetMainName(n); }
void SetMainName( SimpleName n ) { names->SetMainName(n); }
/// \ru Выдать флаг состояния. \en Get the flag of state.
MbeProcessState GetStatus() const { return status; }
/// \ru Установить флаг состояния. \en Set the flag of state.
void SetStatus( MbeProcessState l ) { status = l; }
void SetStatus( MbeProcessState l ) { status = l; }
/** \brief \ru Регистрировать объект.
\en Register the object. \~
@@ -540,13 +540,13 @@ public :
The function sets a flag that allow to write the object once and to use the references to the recorded instance in the other records.
Reading is performed once too, in other cases of reading the address of the already read object is used. \~
*/
void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); }
void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); }
/** \} */
private:
// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default
MbCreator & operator = ( const MbCreator & );
MbCreator & operator = ( const MbCreator & );
DECLARE_PERSISTENT_CLASS( MbCreator )
}; // MbCreator
+3
View File
@@ -85,6 +85,9 @@ public:
double Step( double t, double sag ) const override; // \ru Вычисление шага аппроксимации \en Calculate step of approximation
// \ru Продлить кривую. \en Extend the curve. \~
MbResultType Extend( const MbCurveExtensionParameters3D & parameters, c3d::SpaceCurveSPtr & resCurve ) const override;
MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const override;
void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction
+13
View File
@@ -280,6 +280,19 @@ public:
*/
ptrdiff_t FindSegment( double & t, double & tSeg ) const;
/** \brief \ru Найти параметер контура.
\en Find a contour segment. \~
\details \ru Найти параметер контура по номеру сегмента и параметру сегмента. \n
\en Find a contour parameter by segment number and segment parameter. \n \~
\param[in] iSeg - \ru Номер сегмента (индекс).
\en Segment nukmber (index). \~
\param[in] tSeg - \ru Параметр сегмента контура.
\en Segment parameter. \~
\return \ru Возвращает параметр контура или UNDEFINED_DBL в случае неудачи.
\en Returns the contour parameter or UNDEFINED_DBL if fdailure. \~
*/
double FindParameter( size_t iSeg, double tSeg ) const;
size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments.
template <class CurvesVector>
void GetSegments( CurvesVector & curves ) const; ///< \ru Получить кривые контура. \en Get contour segments.
+3
View File
@@ -740,6 +740,9 @@ public :
/// \ru Третья производная на продолжении кривой. \en The third derivative on the curve extension.
void ExtThirdDer ( double t, MbVector & td ) const;
/// \ru Продлить кривую. \en Extend the curve. \~
MbResultType Extend( const MbCurveExtensionParameters & parameters, c3d::PlaneCurveSPtr & resCurve ) const override;
/** \} */
/** \ru \name Общие функции кривой
\en \name Common functions of curve
+4 -1
View File
@@ -782,7 +782,10 @@ public:
/// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend an open NURBS-curve by tangents.
bool ExtendNurbs( double, double, bool bmerge = false );
/// \ru Продлить кривую. \en Extend the curve. \~
MbResultType Extend( const MbCurveExtensionParameters3D & parameters, c3d::SpaceCurveSPtr & resCurve ) const override;
/// \ru Преобразовать узловой вектор в зажатый (если кривая замкнута и clm = false) или разжатый (если кривая не замкнута и clm = true). \en Transform knot vector to a clamped one (if the curve is closed and clm = false) or unclamped one (if the curve is open and clm = true).
bool UnClamped( bool clm, bool savePointsCount = false );
/// \ru Преобразовать кривую в коническое сечение, если это возможно. \en Transform a curve into a conic section if it is possible.
+1 -1
View File
@@ -95,7 +95,7 @@ private:
\en The Loop is declared inside DXFFace. \~
\ingroup DXF_Exchange
*/
class CONV_CLASS DXFLoop {
class DXFLoop {
public:
SArray<MbCartPoint3D> points; ///< \ru Набор точек. \en Point set.
+328
View File
@@ -0,0 +1,328 @@
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief \ru Составная функция.
\en Composite Function. \~
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __FUNC_COMPOSITE_FUNCTION_H
#define __FUNC_COMPOSITE_FUNCTION_H
#include <function.h>
#include <templ_sptr.h>
#include <templ_rp_array.h>
#include <mb_enum.h>
//------------------------------------------------------------------------------
/** \brief \ru Составная функция.
\en Composite function. \~
\details \ru Скалярная cоставная функция скалярного параметра состоит из набора функций (сегментов). \n
В составной функции начало каждого последующего сегмента стыкуется с концом предыдущего.
Составная функция является замкнутой, если конец последнего сегмента стыкуется с началом первого сегмента.\n
Начальное значение параметра составной функции равно нулю.
Параметрическая длина составной функции равна сумме параметрических длин составляющих её сегментов. \n
В качестве сегментов составной функции не используются другие составные функции.
Если составную функцию нужно построить на основе других составных функций,
то последние должны рассматриваться как совокупность составляющих их функций, а не как единые функции.\n
\en Scalar composite function of scalar parameter consists of a set of functions (segments). \n \~
The beginning of each subsequent segment of composite function is joined to the end of the previous one.
Composite function is closed if the end of last segment is joined to the beginning of the first segment.\n
If the segments of a composite function are not smoothly joined then the composite function will have breaks.
The initial value of the composite function is equal to zero.
The parametric length of a composite function is equal to the sum of the parametric lengths of components of its segments. \n
Other composite curves are not used as segments of the composite function.
If it is required to create a composite function based on other composite functions,
then the latter must be regarded as a set of their functions, and not as single functions. \n
\ingroup Functions
*/
// ---
class MATH_CLASS MbCompositeFunction : public MbFunction {
protected :
RPArray<MbFunction> segments; ///< \ru Множество сегментов cоставной функции. \en A set of composite function segments.
bool closed; ///< \ru Признак замкнутости функции. \en An attribute of function closedness.
double paramLength; ///< \ru Параметрическая длина функции. \en Parametric length of a composite function.
public :
/// \ru Конструктор по функции. \en Constructor by function.
MbCompositeFunction( MbFunction & segment, bool same ); // \ru same - функции или их копии \en Sames - functions or their copies
/// \ru Конструктор по набору функции. \en Constructor by functions.
template <class FunctionVector>
MbCompositeFunction( const FunctionVector & initSegments, bool same ); // \ru same - функции или их копии \en same - functions or their copies
protected:
MbCompositeFunction(); ///< \ru Пустой контур. \en Empty composite function.
MbCompositeFunction( const MbCompositeFunction & ); ///< \ru Конструктор копирования. \en Copy constructor.
public :
virtual ~MbCompositeFunction();
public:
// \ru Общие функции математического объекта. \en Common functions of mathematical object.
MbeFunctionType IsA () const override; // \ru Тип элемента. \en A type of element.
MbFunction & Duplicate() const override; // \ru Сделать копию элемента. \en Create a copy of the element.
bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const override; // \ru Являются ли объекты равными. \en Determine whether objects are equal
bool IsSimilar( const MbFunction & ) const override; // \ru Являются ли объекты подобными. \en Determine whether objects are similar.
bool SetEqual ( const MbFunction & ) override; // \ru Сделать равным \en Make equal
void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of the object
double GetTMax () const override; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter
double GetTMin () const override; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter
bool IsClosed () const override; // \ru Замкнутость функции \en A function closedness
void SetClosed( bool cl ) override; // \ru Замкнутость функции \en A function closedness
double Value ( double & t ) const override; // \ru Значение функции для t \en The value of function for a given t
double FirstDer ( double & t ) const override; // \ru Первая производная по t \en The first derivative with respect to t
double SecondDer ( double & t ) const override; // \ru Вторая производная по t \en The second derivative with respect to t
double ThirdDer ( double & t ) const override; // \ru Третья производная по t \en The third derivative with respect to t
double _Value ( double t ) const override; // \ru Значение функции для t \en The value of function for a given t
double _FirstDer ( double t ) const override; // \ru Первая производная по t \en The first derivative with respect to t
double _SecondDer ( double t ) const override; // \ru Вторая производная по t \en The second derivative with respect to t
double _ThirdDer ( double t ) const override; // \ru Третья производная по t \en The third derivative with respect to t
// \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~
void Explore( double & t, bool ext,
double & val, double & fir, double * sec, double * thr ) const override;
// \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value.
double Argument( double & val ) const override;
void Inverse( MbRegTransform * iReg = nullptr ) override; // \ru Изменить направление \en Change direction
double Step( double t, double sag ) const override;
double DeviationStep( double t, double angle ) const override;
/// \ru Создать функцию из части функции между параметрами t1 и t2 c выбором направления sense. \en Create a function in part of the function between the parameters t1 and t2 choosing the direction.
MbFunction * Trimmed( double t1, double t2, int sense ) const override;
// \ru Разбить функцию точкой с параметром t и вернуть отрезанную часть. \en Function break by the parameter t, and cut off part of the function: begs == true - save the initial half, beg == false - save the final half.
MbFunction * BreakFunction( double t, bool beg ) override;
void Break( double t1, double t2 ); ///< \ru Выделить часть функции. \en Select a part of a function.
double MinValue ( double & t ) const override; // \ru Минимальное значение функции \en The minimum value of function
double MaxValue ( double & t ) const override; // \ru Максимальное значение функции \en The maximum value of function
double MidValue () const override; // \ru Среднее значение функции \en The middle value of function
bool IsGood () const override; // \ru Корректность функции \en Correctness of function
bool IsConst() const override;
bool IsLine () const override;
/// \ru Сместить функцию. \en Shift a function.
void SetOffsetFunc( double off, double scale ) override;
bool SetLimitParam( double newTMin, double newTMax ) override; // \ru Установить область изменения параметра \en Set range of parameter
void SetLimitValue( size_t n, double newValue ) override; // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at start point, 2 - at end point)
double GetLimitValue( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at start point, 2 - at end point)
void SetLimitDerive( size_t n, double newValue, double dt ) override; // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at start point, 2 - at end point)
double GetLimitDerive( size_t n ) const override; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at start point, 2 - at end point)
bool InsertValue( double t, double newValue ) override; // \ru Установить значение для параметра t. \en Set the value for the pdrdmeter t.
/// \ ru Определение точек излома контура. \en The determination of contour smoothness break points.
void BreakPoints( std::vector<double> & vBreaks, double precision = ANGLE_REGION ) const override;
/** \} */
/** \ru \name Функции работы с сегментами контура
\en \name Function for working with segments of contour
\{ */
/// \ru Инициализация по набору кривых (sameCurves - функции или их копии). \en Initialize by curves (sameCurves - curves or their copies).
template <class FunctionVector>
bool Init( const FunctionVector & initSegments, bool same, bool cls );
/** \brief \ru Найти сегмент контура.
\en Find a contour segment. \~
\details \ru Найти сегмент контура по параметру контура. \n
\en Find a contour segment by parameter on contour. \n \~
\param[in,out] t - \ru Параметр контура.
\en Composite function parameter. \~
\param[out] tSeg - \ru Параметр сегмента контура.
\en Composite function segment parameter. \~
\return \ru Возвращает номер сегмента в случае успешного выполнения или -1.
\en Returns the segment number in case of successful execution or -1. \~
*/
ptrdiff_t FindSegment( double & t, double & tSeg ) const;
/** \brief \ru Найти параметер контура.
\en Find a contour segment. \~
\details \ru Найти параметер контура по номеру сегмента и параметру сегмента. \n
\en Find a contour parameter by segment number and segment parameter. \n \~
\param[in] iSeg - \ru Номер сегмента (индекс).
\en Segment nukmber (index). \~
\param[in] tSeg - \ru Параметр сегмента контура.
\en Segment parameter. \~
\return \ru Возвращает параметр контура или UNDEFINED_DBL в случае неудачи.
\en Returns the contour parameter or UNDEFINED_DBL if fdailure. \~
*/
double FindParameter( size_t iSeg, double tSeg ) const;
size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments.
template <class CurvesVector>
void GetSegments( CurvesVector & curves ) const; ///< \ru Получить функции контура. \en Get contour segments.
void DetachSegments(); ///< \ru Отцепить все сегменты контура. \en Detach all segments of contour.
void DeleteSegments(); ///< \ru Отсоединить используемые сегменты и удалить остальные. \en Delete used segments and remove other segments.
void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент контура. \en Delete the segment of contour.
MbFunction * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент контура. \en Detach the segment of contour.
const MbFunction * GetSegment( size_t ind ) const { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index.
MbFunction * SetSegment( size_t ind ) { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index.
void SetSegment ( MbFunction & newSegment, size_t ind, bool same ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour.
void AddSegment ( MbFunction & newSegment, bool same ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour.
void AddAtSegment ( MbFunction & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур перед сегментом с индексом ind. \en Add a segment to the contour before the segment with index ind.
void AddAfterSegment( MbFunction & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур после сегмента с индексом ind. \en Add a segment to the contour after the segment with index ind.
/** \brief \ru Добавить (усеченную) копию сегмента в конец контура.
\en Add a (truncated) segment copy to the end of the contour. \~
\details \ru Добавить (усеченную) копию сегмента в конец контура. \n
\en Add a (truncated) segment copy to the end of the contour. \n \~
\param[in] pBasis- \ru Исходная функция.
\en Initial function. \~
\param[in] t1 - \ru Начальный параметр усечения.
\en Truncation starting parameter. \~
\param[in] t2 - \ru Конечный параметр усечения.
\en Truncation ending parameter. \~
\param[in] sense - \ru Направление усеченной функции относительно исходной. \n
sense = 1 - направление функции сохраняется.
sense = -1 - направление функции меняется на обратное.
\en Direction of a trimmed function in relation to an initial function.
sense = 1 - direction does not change.
sense = -1 - direction changes to the opposite value. \~
\return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую.
\en Returns, if successful, a non-zero pointer to the added function. \~
*/
MbFunction * AddSegment( MbFunction & pBasis, double t1, double t2, int sense );
void SegmentsAdd( MbFunction & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking.
/// \ru Cбросить переменные кэширования. \en Reset variables caching.
void Clear() {
CalculateParamLengthAndClosed(); // \ru Параметрическая длина контура. \en Parametric length of a contour.
}
/// \ru Управление распределением памяти в массиве segments. \en Control of memory allocation in the array "segments".
void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место. \en Reserve space.
void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory.
/// \ru Проверка непрерывности контура. \en Check for contour continuity.
bool CheckConnection( double eps = METRIC_PRECISION ) const;
void CalculateParamLength(); ///< \ru Рассчитать параметрическую длину. \en Calculate parametric length.
void CheckClosed( double eps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour.
private:
void SetClosed(); // \ru Проверить и установить признак замкнутости контура. \en Check and set closedness attribute of contour.
void CalculateParamLengthAndClosed(); // \ru Посчитать параметрическую длину и признак замкнутости \en Calculate parametric length and closedness attribute
ptrdiff_t _FindSegment( double & t, double & tSeg ) const; // \ru Нахождение сегмента контура \en Finding of a contour segment
DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCompositeFunction )
MbCompositeFunction & operator = ( const MbCompositeFunction & ); // Not implemented.
}; // MbCompositeFunction
IMPL_PERSISTENT_OPS( MbCompositeFunction )
//------------------------------------------------------------------------------
// \ru Конструктор по набору функций. \en Constructor by functions.
// ---
template <class FunctionVector>
MbCompositeFunction::MbCompositeFunction( const FunctionVector & initSegments, bool same )
: MbFunction ( )
, segments ( initSegments.size(), 1 )
, closed ( false )
, paramLength( 0.0 ) // параметрическая длина контура не рассчитана
{
const size_t count = initSegments.size();
if ( count > 0 ) {
for ( size_t i = 0; i < count; ++i ) {
const MbFunction * initSegment = initSegments[i];
if ( initSegment != nullptr ) {
if ( initSegment->IsA() == ft_CompositeFunction ) { // \ru Присланный контур удаляет владелец. \en contour should be deleted by owner.
const MbCompositeFunction * cntr = static_cast<const MbCompositeFunction *>( initSegment );
MbCompositeFunction * contour = const_cast<MbCompositeFunction *>( cntr );
size_t cnt = contour->segments.size();
for ( size_t j = 0; j < cnt; j++ ) {
MbFunction * seg = contour->segments[j];
if ( seg != nullptr ) {
MbFunction * segment = same ? seg : static_cast<MbFunction *>( &seg->Duplicate() );
segments.push_back( segment );
segment->AddRef();
}
}
}
else {
MbFunction * segment = same ? const_cast<MbFunction *>( initSegment ) : static_cast<MbFunction *>( &initSegment->Duplicate() );
segments.push_back( segment );
segment->AddRef();
}
}
}
CalculateParamLengthAndClosed();
}
}
//------------------------------------------------------------------------------
// \ru Инициализация по набору функций. \en Initialize by functions.
// ---
template <class FunctionVector>
bool MbCompositeFunction::Init( const FunctionVector & initSegments, bool sames, bool cls )
{
size_t count = initSegments.size();
if ( count > 0 ) {
::AddRefItems( initSegments );
DeleteSegments();
segments.reserve( count );
for ( size_t i = 0; i < count; ++i ) {
const MbFunction * initSegment = initSegments[i];
if ( initSegment != nullptr ) {
if ( initSegment->IsA() == ft_CompositeFunction ) { // \ru Присланный контур удаляет владелец. \en contour should be deleted by owner.
const MbCompositeFunction * cntr = static_cast<const MbCompositeFunction *>( initSegment );
MbCompositeFunction * contour = const_cast<MbCompositeFunction *>( cntr );
size_t cnt = contour->segments.size();
for ( size_t j = 0; j < cnt; j++ ) {
MbFunction * seg = contour->segments[j];
if ( seg != nullptr ) {
MbFunction * segment = sames ? seg : static_cast<MbFunction *>( &seg->Duplicate() );
segments.push_back( segment );
segment->AddRef();
}
}
}
else {
MbFunction * segment = sames ? const_cast<MbFunction *>( initSegment ) : static_cast<MbFunction *>( &initSegment->Duplicate() );
segments.push_back( segment );
segment->AddRef();
}
}
}
::DecRefItems( initSegments );
CalculateParamLength();
closed = cls;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Получить функции. \en Get segments.
// ---
template <class CurvesVector>
void MbCompositeFunction::GetSegments( CurvesVector & funcs ) const
{
size_t segmentsCnt = segments.size();
funcs.reserve( funcs.size() + segmentsCnt );
SPtr<MbFunction> function;
for ( size_t k = 0; k < segmentsCnt; ++k ) {
function = const_cast<MbFunction *>(segments[k]);
if ( function != nullptr ) {
funcs.push_back( function );
::DetachItem( function );
}
}
}
#endif // __FUNC_COMPOSITE_FUNCTION_H
+4 -2
View File
@@ -25,15 +25,17 @@
class MATH_CLASS MbConstFunction : public MbFunction {
public :
double value; ///< \ru Значение функции. \en The value of function.
double tmin; ///< \ru Начало области определения. \en Beginning of domain.
double tmax; ///< \ru Конец области определения. \en Ending of domain.
public :
MbConstFunction( double v ); ///< \ru Конструктор по значению. \en Constructor by the value.
MbConstFunction( double v, double t1 = 0.0, double t2 = 1.0 ); ///< \ru Конструктор по значению. \en Constructor by the value.
private:
MbConstFunction( const MbConstFunction & );
public :
virtual ~MbConstFunction();
public:
void Init ( double v ); ///< \ru Инициализация по значению. \en Initialization by the value.
void Init ( double v, double t1 = 0.0, double t2 = 1.0 ); ///< \ru Инициализация по значению. \en Initialization by the value.
public:
// \ru Общие функции математического объекта \en Common functions of mathematical object
MbeFunctionType IsA() const override; // \ru Тип элемента \en A type of element
+6 -1
View File
@@ -61,6 +61,7 @@ enum MbeFunctionType {
ft_NurbsFunction = 10, ///< \ru NURBS функция. \en NURBS function.
ft_CurveCoordinate = 11, ///< \ru Функция координаты кривой. \en Function by curve coordinate.
ft_CompositeFunction = 100, ///< \ru Составная функция. \en Composite function.
ft_CharacterFunction = 101, ///< \ru Символьная функция. \en Symbolic function.
ft_AnalyticalFunction = 102, ///< \ru Символьная функция на модельном выражении. \en Symbolic function in model expression.
@@ -86,9 +87,11 @@ private:
public :
virtual ~MbFunction();
public:
/** \ru \name Общие функции математического объекта
\en \name Common functions of mathematical object
\{ */
/// \ru Тип элемента. \en A type of element.
virtual MbeFunctionType IsA() const = 0;
/// \ru Сделать копию элемента. \en Create a copy of the element.
@@ -103,10 +106,12 @@ public:
virtual void GetProperties( MbProperties & ) = 0;
/// \ru Записать свойства объекта. \en Set properties of the object.
virtual void SetProperties( const MbProperties & ) = 0;
/** \} */
/** \ru \name Общие функции
\en \name Common functions
\{ */
/// \ru Вернуть максимальное значение параметра. \en Get the maximum value of parameter.
virtual double GetTMax() const = 0;
/// \ru Вернуть минимальное значение параметра. \en Get the minimum value of parameter.
@@ -216,7 +221,7 @@ public:
/// \ru Вернуть середину параметрического диапазона. \en Return the middle of parametric range.
double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); }
/// \ru Параметрическая длина. \en The parametric length.
double GetParamLength () const { return GetTMax()-GetTMin(); }
double GetParamLength () const { return GetTMax() - GetTMin(); }
/// \ru Находится ли параметр в области определения функции. \en Whether the parameter belongs to the function domain.
bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps <= t && t <= GetTMax()+eps ); }
/// \ru Подготовить к записи регистрируемый объект. \en Prepare for writing the registered object.
+20 -4
View File
@@ -68,11 +68,10 @@ private:
typedef enum
{
GCE_STATE_Unknown = 0 ///< \ru О состоянии ничего не известно. \en State is unknown.
, GCE_STATE_WellConstrained ///< \ru Полностью определенная система - все степени свободы нулевые. \en Well-constrained system - all degrees of freedom are zero.
, GCE_STATE_UnderConstrained ///< \ru Недоопределенная система - имеются ненулевые степени свободы. \en Underconstrained system - there are non-zero degrees of freedom.
, GCE_STATE_WellConstrained ///< \ru Полностью определенная система - все степени свободы нулевые. \en Well-constrained system: all degrees of freedom are zero.
, GCE_STATE_UnderConstrained ///< \ru Недоопределенная система - имеются ненулевые степени свободы. \en Underconstrained system: there are non-zero degrees of freedom.
, GCE_STATE_UnresolvedRedundancy ///< \ru Имеются не удовлетворенные избыточные ограничения. There are unresolved redundant constraints.
, GCE_STATE_OverConstrained = GCE_STATE_UnresolvedRedundancy
/*
/*
\ru Идентификаторы не менять (возможна запись в файлы)!
\en Don't change identifiers (record to files is possible)!
*/
@@ -108,8 +107,20 @@ DEPRECATE_DECLARE GCE_FUNC(GCE_s_state) GCE_StateOfSystem( GCE_system gSys );
/**
\brief \ru Выдать состояние определенности системы ограничений.
\en Get constraint system definition state.
\param[in] gSys - \ru Система ограничений.
\en System of constraints. \~
\details
\ru Функция вернет состояние #GCE_STATE_Underconstrained, если имеется хотя бы
один геометрический объект с ненулевой степенью свободы.
Состояние #GCE_STATE_WellConstrained означает, что геометрия полностью определена, а другое
состояние #GCE_STATE_UnresolvedRedundancy означает, что в модели имеются нерешенные
избыточные ограничения.
\en The function will return #GCE_STATE_Underconstrained if there is at least
one geometric object with nonzero degree of freedom. State code #GCE_STATE_WellConstrained
means that the geometry is fully-defined. And the other state is #GCE_STATE_UnresolvedRedundancy
means there are unresolved redundant constraints (non solved overdefinition). \n
\return \ru Одно из состояний, перечисленного набором: "Система недоопределена",
"Полностью определена" или "Есть не решенные избыточные ограничения".
\en One of the states enumerated by a set: "Under-defined", "Well-defined" and
@@ -280,6 +291,11 @@ GCE_FUNC(constraint_item) GCE_FormFixedLength( GCE_system, geom_item );
//---
GCE_FUNC(constraint_item) GCE_FormFixedCoordinate( GCE_system, geom_coord<> );
//----------------------------------------------------------------------------------------
// Deprecated value. It will be removed after 2023.
//---
const GCE_s_state GCE_STATE_OverConstrained = GCE_STATE_UnresolvedRedundancy;
/*
Deprecated typenames and constants (2019.06)
*/
+1
View File
@@ -992,6 +992,7 @@ GCE_FUNC(constraint_item) GCE_AddCoincidence( GCE_system gSys, geom_item g[2] );
*/
//---
GCE_FUNC(constraint_item) GCE_AddPointOnPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], double k );
GCE_FUNC(constraint_item) GCE_AddPointOnPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], var_item k );
//----------------------------------------------------------------------------------------
/** \brief \ru Ограничение "Точка на участке кривой по коэффициенту его длины".
+2 -1
View File
@@ -292,7 +292,6 @@ typedef enum
/*
Statuses resulting the evaluation (call GCE_Evaluate).
*/
, GCE_STATUS_Solved // Ограничение решено
, GCE_STATUS_NotSolved // Не решено по каким-то причинам
, GCE_STATUS_NotConsistent // Не решено из-за противоречия с другими ограничениями.
, GCE_STATUS_OverConstrained // Не решено избыточное ограничение, противоречащее другим.
@@ -695,6 +694,8 @@ struct GCE_CLASS geom_point
geom_point( geom_item g, point_type pnt ) : geom( g ), pntName( pnt ) {}
};
const GCE_c_status GCE_STATUS_Solved = GCE_STATUS_Undefined; // Deprecated. It will be removed in 2023.
#endif // __GCE_TYPES_H
// eof
+34 -2
View File
@@ -477,9 +477,9 @@ GCM_FUNC(GCM_constraint) GCM_AddDistance( GCM_system gSys, GCM_geom g1, GCM_geom
specifies a linear interval dimension between two geometric objects.
In a failed call, the function returns a handle to an empty object GCM_NULL.\~
\note \ru Значение dVal может быть знакопеременным для ориентируемых объектов. Установка опции
\note \ru Значение iVal может быть знакопеременным для ориентируемых объектов. Установка опции
выравнивания подчиняется тем же правилам, что и для управляющего размера.
\en Value of dVal can be positive as well as negative for oriented objects. Setting the alignment option
\en Value of iVal can be positive as well as negative for oriented objects. Setting the alignment option
follows the same rules as for driving dimensions.\~
*/
//---
@@ -520,6 +520,38 @@ GCM_FUNC(GCM_constraint) GCM_AddDistance( GCM_system gSys, GCM_geom g1, GCM_geom
GCM_FUNC(GCM_constraint) GCM_AddAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2, GCM_geom axis, double dVal );
GCM_FUNC(GCM_constraint) GCM_AddAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2, double dVal );
//----------------------------------------------------------------------------------------
/** \brief \ru Задать ограничение, устанавливающее допустимый интервал углов между парой геометрических объектов.
\en Set a constraint that specifies the allowed angle interval between a pair of geometric objects. \~
\param[in] gSys - \ru Система ограничений.
\en System of constraints. \~
\param[in] g1 - \ru Дескриптор первого объекта.
\en Descriptor of first object. \~
\param[in] g2 - \ru Дескриптор второго объекта.
\en Descriptor of second object. \~
\param[in] axis - \ru Дескриптор оси вращения (может быть равен GCM_NULL).
\en Descriptor of rotation axis (may be equal to GCM_NULL). \~
\param[in] iVal - \ru Значение допустимого интервала углов.
\en The value of the allowed angle interval. \~
\param[in] aVal - \ru Опция выравнивания.
\en Alignment option. \~
\return \ru Дескриптор нового ограничения c типом GCM_ANGLE.
\en Descriptor of the created constraint of type GCM_ANGLE. \~
\details \ru Эта функция создает в системе размерное ограничение с типом GCM_ANGLE,
которое задает интервальный угловой размер между двумя геометрическими объектами.
В случае неудачного вызова, функция вернет дескриптор пустого объекта GCM_NULL.
\en The function creates a dimensional constraint of type GCM_ANGLE, which
specifies an angular interval dimension between two geometric objects.
In a failed call, the function returns a handle to an empty object GCM_NULL.\~
\note \ru Длина интервала допустимых углов (iVal) не может превышать 2*Пи.
\en The length of the interval of allowable angles (iVal) cannot exceed 2*pi.\~
*/
//---
GCM_FUNC(GCM_constraint) GCM_AddAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2, GCM_geom axis, GCM_interval iVal );
GCM_FUNC(GCM_constraint) GCM_AddAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2, GCM_interval iVal );
//----------------------------------------------------------------------------------------
/** \brief \ru Задать ограничение, устанавливающее радиус геометрического объекта.
\en To create a constraint which specifies a radius of geometric objects. \~
+6 -4
View File
@@ -43,8 +43,8 @@ struct GCM_CLASS GCM_c_params
GCM_c_type m_Type; ///< \ru Тип сопряжения. \en Type of mating.
GCM_alignment m_Align;
GCM_tan_choice m_TanChoice;
GCM_angle_type m_AngType;
GCM_scale m_scale;
GCM_angle_type m_AngType;
GCM_scale m_Scale;
GCM_coord_name m_CrdName;
double m_RealPar; ///< \ru Вещественный параметр. \en Real parameter.
MtParVariant m_Interval;
@@ -55,11 +55,13 @@ struct GCM_CLASS GCM_c_params
, m_Align( GCM_NO_ALIGNMENT )
, m_TanChoice( GCM_TAN_NONE )
, m_AngType( GCM_NONE_ANGLE )
, m_scale ( GCM_NO_SCALE )
, m_Scale(GCM_NO_SCALE)
, m_CrdName( GCM_NULL_CRD )
, m_RealPar( UNDEFINED_DBL )
, m_Interval()
{}
private:
static const GCM_scale m_scale = GCM_NO_SCALE; // MA: Deprecated data field. Use m_Scale.
};
@@ -308,7 +310,7 @@ inline void ItConstraintItem::GetParams( GCM_c_params & pars ) const
pars.m_Align = AlignType();
pars.m_TanChoice = TangencyChoice();
pars.m_AngType = AngleType();
pars.m_scale = _ScaleType();
pars.m_Scale = _ScaleType();
pars.m_CrdName = _CoordName();
GCM_interval interval;
if ( _DimValue().GetInterval(interval) )
+19 -4
View File
@@ -307,7 +307,10 @@ struct GCM_CLASS ItConstraintsEnum : public MtRefItem
virtual void Restart() = 0;
};
class MtConstraintManager; // Internal implementation of the solver
class MtConstraintManager; // Internal implementation of 3D solver.
class MtBlackboxManager; // Internal implementation of Blackbox manager.
//----------------------------------------------------------------------------------------
/** \brief \ru Геометрический решатель.
@@ -376,10 +379,12 @@ public:
/** \brief \ru Добавить ограничение для тройки геометрических объектов.
\en Add constraint of three geometric objects. \~
*/
ItConstraintItem * AddConstraint ( MtMateType, MtArgument, MtArgument, MtArgument, MtParVariant p1 = MtParVariant::undef );
ItConstraintItem * AddConstraint ( MtMateType, MtArgument, MtArgument, MtArgument,
MtParVariant p1 = MtParVariant::undef, MtParVariant p2 = MtParVariant::undef );
/// \ru Добавить ограничение. \en Add constraint.
ItConstraintItem * AddConstraint( MtArgument, MtArgument, const GCM_c_params &, MtResultCode3D & );
/** \brief \ru Добавить черный ящик в систему ограничений.
\en Add black box to the constraint system. \~
\param[in] bBox - \ru Интерфейс чёрного ящика.
@@ -642,9 +647,15 @@ public:
*/
//protected:
/// \ru Функция будет удалена из API. Использовать Evalute(). \en The call is deprecated. Use ChangeDefinition() instead this.
/// \ru Функция будет удалена из API. Использовать Evalute(). \en The call is deprecated. Use Evaluate() instead this.
MtResultCode3D Solve( bool diagQuery );
// Internal use only
GCM_geom _QueryArgument( const MtArgument & gArg );
protected:
const ItGeom * _SetDependencyGeom( MtGeomId gId, const ItGeom * gItem );
protected:
MtGeomSolver();
~MtGeomSolver();
@@ -652,6 +663,10 @@ protected:
private:
MtConstraintManager * _Impl();
const MtConstraintManager * _Impl() const;
MtBlackboxManager * _BBoxMan();
const MtBlackboxManager * _BBoxMan() const;
MtBlackboxManager * myBBManager;
private:
MtGeomSolver( const MtGeomSolver & );
@@ -695,7 +710,7 @@ GCM_FUNC(SPtr<MtGeomSolver>) GCM_GetSolver( GCM_system gSys );
Internal use only.
*/
//---
GCM_geom GCM_QueryArgument( GCM_system gSys, const MtArgument & gArg );
//GCM_geom GCM_QueryArgument( GCM_system gSys, const MtArgument & gArg );
/*
Deprecated typenames
+6 -4
View File
@@ -144,6 +144,7 @@ typedef enum
//---
typedef enum
{
GCM_MIN_ALIGNMENT = -1, // Minimum value of alignment.
/*
(!) Do not change the constants (they are written to file permanently).
*/
@@ -167,10 +168,10 @@ typedef enum
*/
GCM_ALIGNED = 1, ///< \ru ЛСК с одинаковой ориентацией. \en Axis aligned local coordinate systems. \~
GCM_ROTATED = 9, ///< Ротационное (вращательной) выравнивание элементов паттерна.
GCM_ALIGN_WITH_AXIAL_GEOM = 10, ///< Выровнять с объектом, задающим ось.
GCM_MAX_ALIGNMENT, // Maximum value of this enum
GCM_MIN_ALIGNMENT= -1, // Minimum value of this enum
GCM_ALIGN_WITH_AXIAL_GEOM = 10, ///< Выровнять с объектом, задающим ось.
GCM_MAX_ALIGNMENT, // Maximum value of alignment.
GCM_ANY_ALIGNMENT // It is used internally for matching to any alignment value.
} GCM_alignment;
//----------------------------------------------------------------------------------------
@@ -507,6 +508,7 @@ struct GCM_CLASS GCM_c_arg
{ GCM_PATTERNED GCM_geom GCM_geom GCM_geom double GCM_alignment GCM_scale }
{ GCM_LINEAR_PATTERN GCM_geom GCM_geom GCM_geom GCM_alignment }
{ GCM_ANGULAR_PATTERN GCM_geom GCM_geom GCM_geom GCM_alignment }
{ GCM_PATTERN_COORDINATE GCM_pattern, GCM_coord_name, GCM_geom }
{ GCM_TRANSMITTION not specified }
{ GCM_CAM_MECHANISM not specified }
{ GCM_RADIUS GCM_geom double }
+3 -1
View File
@@ -1,4 +1,4 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
@@ -239,6 +239,8 @@ struct CONV_CLASS TextIGES : public BasicIGES {
virtual bool operator == ( const BasicIGES & o ) const;
virtual bool operator < ( const BasicIGES & o ) const;
private:
TextIGES( const TextIGES& );
};
+251 -222
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -540,7 +540,7 @@ public:
struct MATH_CLASS MbFairCurveData {
public:
bool closed; ///< \ru Признак замкнутости кривой. \en Sign of closed curve \~
bool closed; ///< \ru Формат замкнутости кривой вида UnClamped. \en Format of closed curve as UnClamped\~
MbeFairSmoothing fairing; ///< \ru Сглаживание (без сглаживания, со сглаживанием, со сглаживанием и исправлением острых углов, со сглаживанием зашумленных точек). \en Smoothing of curve: 0 - disable, 1 - enable, 2 - enable and correct acute angles \~
bool arrange; ///< \ru Перераспределение точек по контуру (false - без перераспределения, true - с перераспределением). \en Redistribution of points (false - without of distribution, true - with distribution) . \~
MbeFairSubdivision subdivision; ///< \ru Коэффициент уплотнения кривой. \en Curve subdivision coefficient . \~
@@ -561,6 +561,9 @@ 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. \~
SArray<int> arrayFixPntTngSign; ///< \ru Признаки учета касательных на точках / точек на касательных. \en Signs of points on tangents / tangents on points.
SArray<size_t> arrayFixNoisyNum; ///< \ru Номера точек точных значений зашумленных точек. \en Signs of exactly noisy points.
size_t numberOfIterationsBSpl; ///< \ru Количество итераций построения B-сплайна (заданное и фактическое). \en The number of iterations for building the B-spline (given and actual).
size_t numberOfIterationsVCurve; ///< \ru Количество итераций построения V-кривой (заданное и фактическое). \en The number of iterations for building the V-curve (given and actual).
double realAccuracyBSpl; ///< \ru Точность построения B-сплайна (заданная и фактическая). \en The accuracy of creating the B-spline (given and actual).
@@ -592,7 +595,7 @@ public:
public:
/// \ru Пустой конструктор. \en Empty constructor.
MbFairCurveData() :
closed( false ), fairing( fairSmooth_Yes ), arrange( false ), subdivision( fairSubdiv_Single ),
closed( true ), fairing( fairSmooth_Yes ), arrange( false ), subdivision( fairSubdiv_Single ),
accountCurvature( fairCur_No ), accountInflexVector( fairVector_Tangent ),
tangentCorrectBspline( true ),
fixPntTng( fixPntTng_NotFix ),
+90 -97
View File
@@ -28,7 +28,6 @@ class MATH_CLASS MbDimension : public MbLegend {
public:
/// \ru Конструктор. \en Constructor
MbDimension();
/// \ru Деструктор. \en Destructor.
virtual ~MbDimension();
@@ -39,11 +38,11 @@ public:
/**\ru \name Общие функции геометрического объекта.
\en \name Common functions of a geometric object.
\{ */
MbeSpaceType Type() const override;
bool IsSimilar ( const MbSpaceItem & ) const override;
MbeSpaceType Type() const override;
bool IsSimilar ( const MbSpaceItem & ) const override;
private: // \ru Не реализованные методы класса \en Non-implemented methods of class
void operator = ( const MbDimension & ); // \ru Не реализовано \en Not implemented
void operator = ( const MbDimension & ); // \ru Не реализовано \en Not implemented
DECLARE_PERSISTENT_CLASS( MbDimension )
};
@@ -53,13 +52,12 @@ private: // \ru Не реализованные методы класса \en N
/** \brief \ru Линейный размер.
\en Linear dimension. \~
\ingroup Legend
*/
// ---
*/ // ---
class MATH_CLASS MbLinearDimension : public MbDimension {
private:
MbCartPoint3D base1; ///< \ru Первая точка привязки размера. \en First dimension anchor point.
MbCartPoint3D base2; ///< \ru Вторая точка привязки размера. \en Second dimension anchor point.
MbCartPoint3D startDimensionCurve; ///< \ru Точка начала размерной линии. \en Starting point of dimension line.
MbCartPoint3D base1; ///< \ru Первая точка привязки размера. \en First dimension anchor point.
MbCartPoint3D base2; ///< \ru Вторая точка привязки размера. \en Second dimension anchor point.
MbCartPoint3D startDimensionCurve; ///< \ru Точка начала размерной линии. \en Starting point of dimension line.
public:
/** \brief \ru Конструктор.
@@ -68,56 +66,55 @@ public:
\en Constructor.\n \~
\param[in] base1 - \ru Первая точка привязки размера.
\en First dimension anchor point. \~
\param[in] base2 - \ru Вторая точка привязки размера.
\param[in] base2 - \ru Вторая точка привязки размера.
\en Second dimension anchor point. \~
\param[in] startDimension - \ru Точка начала размерной линии.
\en Starting point of dimension line. \~
\param[in] startDimension - \ru Точка начала размерной линии.
\en Starting point of dimension line. \~
*/
MbLinearDimension(const MbCartPoint3D& base1, const MbCartPoint3D& base2, const MbCartPoint3D& startDimensionCurve);
MbLinearDimension( const MbCartPoint3D & base1, const MbCartPoint3D & base2, const MbCartPoint3D & startDimensionCurve );
protected:
MbLinearDimension(const MbLinearDimension& ); ///< \ru Конструктор копирования. \en Copy-constructor.
MbLinearDimension( const MbLinearDimension & ); ///< \ru Конструктор копирования. \en Copy-constructor.
public:
/**\ru \name Общие функции геометрического объекта.
\en \name Common functions of a geometric object.
\{ */
MbeSpaceType IsA() const override;
MbSpaceItem & Duplicate(MbRegDuplicate * = nullptr) const override;
bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const override;
bool SetEqual(const MbSpaceItem &) override;
void Transform(const MbMatrix3D &, MbRegTransform * = nullptr) override;
void Move(const MbVector3D &, MbRegTransform * = nullptr) override;
void Rotate(const MbAxis3D &, double, MbRegTransform * = nullptr) override;
double DistanceToPoint(const MbCartPoint3D &) const override;
void AddYourGabaritTo(MbCube &) const override;
void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override;
bool IsSame( const MbSpaceItem &, double /*accuracy*/ = LENGTH_EPSILON ) const override;
bool SetEqual( const MbSpaceItem & ) override;
void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override;
void Move( const MbVector3D &, MbRegTransform * = nullptr ) override;
void Rotate( const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override;
double DistanceToPoint( const MbCartPoint3D & ) const override;
void AddYourGabaritTo( MbCube & ) const override;
void CalculateMesh( const MbStepData &, const MbFormNote &, MbMesh & ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
// \ru Тестовые функции геометрического объекта \en Test functions of a geometric object
MbProperty & CreateProperty(MbePrompt /*n*/) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties(MbProperties &) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties(const MbProperties &) override; // \ru Записать свойства объекта \en Set properties of object
MbProperty & CreateProperty( MbePrompt /*n*/ ) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object
public:
/// \ru Инициализировать по двум точкам привязки и точке начала размерной линии. \en Initialize by two reference points and the starting point of the dimension line.
void Init(const MbCartPoint3D& base1, const MbCartPoint3D& base2, const MbCartPoint3D& startDimensionCurve);
void Init( const MbCartPoint3D & base1, const MbCartPoint3D & base2, const MbCartPoint3D & startDimensionCurve );
/// \ru Получить первую точку привязки размера. \en Get the first dimension snap point.
MbCartPoint3D GetBasePoint1() const { return base1; }
void SetBasePoint1(const MbCartPoint3D& val) { base1 = val; }
void SetBasePoint1( const MbCartPoint3D & val ) { base1 = val; }
/// \ru Получить вторую точку привязки размера. \en Get the second dimension snap point.
MbCartPoint3D GetBasePoint2() const { return base2; }
void SetBasePoint2(const MbCartPoint3D& val) { base2 = val; }
void SetBasePoint2( const MbCartPoint3D & val ) { base2 = val; }
/// \ru Получить первую точку привязки размера. \en Get the first dimension snap point.
MbCartPoint3D GetStartDimensionCurvePoint() const { return startDimensionCurve; }
void SetStartDimensionCurvePoint(const MbCartPoint3D& val) { startDimensionCurve = val; }
void SetStartDimensionCurvePoint( const MbCartPoint3D & val ) { startDimensionCurve = val; }
private: // \ru Не реализованные методы класса \en Non-implemented methods of class
void operator = ( const MbLinearDimension & ); // \ru Не реализовано \en Not implemented
void operator = ( const MbLinearDimension & ); // \ru Не реализовано \en Not implemented
DECLARE_PERSISTENT_CLASS(MbLinearDimension)
DECLARE_PERSISTENT_CLASS(MbLinearDimension)
};
@@ -125,69 +122,67 @@ private: // \ru Не реализованные методы класса \en N
/** \brief \ru Угловой размер.
\en Angular dimension. \~
\ingroup Legend
*/
// ---
*/ // ---
class MATH_CLASS MbAngularDimension : public MbDimension {
private:
MbCartPoint3D base1; ///< \ru Первая точка привязки размера. \en First dimension anchor point.
MbCartPoint3D base2; ///< \ru Вторая точка привязки размера. \en Second dimension anchor point.
MbCartPoint3D center; ///< \ru Точка центра. \en Center point.
MbCartPoint3D base1; ///< \ru Первая точка привязки размера. \en First dimension anchor point.
MbCartPoint3D base2; ///< \ru Вторая точка привязки размера. \en Second dimension anchor point.
MbCartPoint3D center; ///< \ru Точка центра. \en Center point.
public:
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор.\n
\en Constructor.\n \~
\param[in] base1 - \ru Первая точка привязки размера.
\en First dimension anchor point. \~
\param[in] center - \ru Точка центра.
\en Center point. \~
\param[in] base1 - \ru Первая точка привязки размера.
\en First dimension anchor point. \~
\param[in] center - \ru Точка центра.
\en Center point. \~
\param[in] base2 - \ru Вторая точка привязки размера.
\en Second dimension anchor point. \~
\en Second dimension anchor point. \~
*/
MbAngularDimension(const MbCartPoint3D& center, const MbCartPoint3D& base1, const MbCartPoint3D& base2);
MbAngularDimension( const MbCartPoint3D & center, const MbCartPoint3D & base1, const MbCartPoint3D & base2 );
protected:
MbAngularDimension(const MbAngularDimension& ); ///< \ru Конструктор копирования. \en Copy-constructor.
MbAngularDimension( const MbAngularDimension & ); ///< \ru Конструктор копирования. \en Copy-constructor.
public:
/**\ru \name Общие функции геометрического объекта.
\en \name Common functions of a geometric object.
\{ */
MbeSpaceType IsA() const override;
MbSpaceItem & Duplicate(MbRegDuplicate * = nullptr) const override;
bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const override;
bool SetEqual(const MbSpaceItem &) override;
void Transform(const MbMatrix3D &, MbRegTransform * = nullptr) override;
void Move(const MbVector3D &, MbRegTransform * = nullptr) override;
void Rotate(const MbAxis3D &, double, MbRegTransform * = nullptr) override;
double DistanceToPoint(const MbCartPoint3D &) const override;
void AddYourGabaritTo(MbCube &) const override;
void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override;
bool IsSame( const MbSpaceItem &, double /*accuracy*/ = LENGTH_EPSILON ) const override;
bool SetEqual( const MbSpaceItem & ) override;
void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override;
void Move( const MbVector3D &, MbRegTransform * = nullptr ) override;
void Rotate( const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override;
double DistanceToPoint( const MbCartPoint3D & ) const override;
void AddYourGabaritTo( MbCube & ) const override;
void CalculateMesh( const MbStepData &, const MbFormNote &, MbMesh & ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
// \ru Тестовые функции геометрического объекта \en Test functions of a geometric object
MbProperty & CreateProperty(MbePrompt /*n*/) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties(MbProperties &) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties(const MbProperties &) override; // \ru Записать свойства объекта \en Set properties of object
MbProperty & CreateProperty( MbePrompt /*n*/ ) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object
public:
/// \ru Инициализировать по двум точкам привязки и точке центра. \en Initialize by two reference points and center point.
void Init(const MbCartPoint3D& center, const MbCartPoint3D& base1, const MbCartPoint3D& base2);
void Init( const MbCartPoint3D & center, const MbCartPoint3D & base1, const MbCartPoint3D & base2 );
/// \ru Получить первую точку привязки размера. \en Get the first dimension snap point.
MbCartPoint3D GetBasePoint1() const { return base1; }
void SetBasePoint1(const MbCartPoint3D& val) { base1 = val; }
void SetBasePoint1( const MbCartPoint3D & val ) { base1 = val; }
/// \ru Получить вторую точку привязки размера. \en Get the second dimension snap point.
MbCartPoint3D GetBasePoint2() const { return base2; }
void SetBasePoint2(const MbCartPoint3D& val) { base2 = val; }
void SetBasePoint2( const MbCartPoint3D & val ) { base2 = val; }
/// \ru Получить точку центра. \en Get center point.
MbCartPoint3D GetCenterPoint() const { return center; }
void SetCenterPoint(const MbCartPoint3D& val) { center = val; }
void SetCenterPoint( const MbCartPoint3D & val ) { center = val; }
private: // \ru Не реализованные методы класса \en Non-implemented methods of class
void operator = (const MbAngularDimension &); // \ru Не реализовано \en Not implemented
void operator = ( const MbAngularDimension & ); // \ru Не реализовано \en Not implemented
DECLARE_PERSISTENT_CLASS(MbAngularDimension)
};
@@ -197,15 +192,14 @@ private: // \ru Не реализованные методы класса \en N
/** \brief \ru Радиальный размер.
\en Radial dimension. \~
\ingroup Legend
*/
// ---
*/ // ---
class MATH_CLASS MbRadialDimension : public MbDimension
{
private:
MbCartPoint3D center; ///< \ru Точка центра окружности. \en Center point of circle.
MbCartPoint3D circle; ///< \ru Точка на окружности. \en Point on a circle.
MbPlacement3D placement; ///< \ru Местная система координат размера. \en Local coordinate system of the dimension.
bool diametral; ///< \ru Признак того что размер диаметральный. \en Sign of the fact that the diametrical dimension.
MbCartPoint3D center; ///< \ru Точка центра окружности. \en Center point of circle.
MbCartPoint3D circle; ///< \ru Точка на окружности. \en Point on a circle.
MbPlacement3D placement; ///< \ru Местная система координат размера. \en Local coordinate system of the dimension.
bool diametral; ///< \ru Признак того, что размер диаметральный. \en Sign of the fact that the diametrical dimension.
public:
/** \brief \ru Конструктор.
@@ -213,61 +207,60 @@ public:
\details \ru Конструктор.\n
\en Constructor.\n \~
\param[in] center - \ru Точка центра окружности.
\en Center point of circle. \~
\param[in] circle - \ru Точка на окружности.
\en Point on a circle. \~
\param[in] dimensionPlacement - \ru Местная система координат размера.
\en Local coordinate system of the dimension. \~
\param[in] diametral - \ru Признак того что размер диаметральный.
\en Sign of the fact that the diametrical dimension. \~
\en Center point of circle. \~
\param[in] circle - \ru Точка на окружности.
\en Point on a circle. \~
\param[in] dimensionPlacement - \ru Местная система координат размера.
\en Local coordinate system of the dimension. \~
\param[in] diametral - \ru Признак того, что размер диаметральный.
\en Sign of the fact that the diametrical dimension. \~
*/
MbRadialDimension(const MbCartPoint3D& center, const MbCartPoint3D& circle, const MbPlacement3D& dimensionPlacement, bool diametral);
MbRadialDimension( const MbCartPoint3D & center, const MbCartPoint3D & circle, const MbPlacement3D & dimensionPlacement, bool diametral );
protected:
MbRadialDimension(const MbRadialDimension&); ///< \ru Конструктор копирования. \en Copy-constructor.
MbRadialDimension( const MbRadialDimension & ); ///< \ru Конструктор копирования. \en Copy-constructor.
public:
/**\ru \name Общие функции геометрического объекта.
\en \name Common functions of a geometric object.
\{ */
MbeSpaceType IsA() const override;
MbSpaceItem & Duplicate(MbRegDuplicate * = nullptr) const override;
bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const override;
bool SetEqual(const MbSpaceItem &) override;
void Transform(const MbMatrix3D &, MbRegTransform * = nullptr) override;
void Move(const MbVector3D &, MbRegTransform * = nullptr) override;
void Rotate(const MbAxis3D &, double, MbRegTransform * = nullptr) override;
double DistanceToPoint(const MbCartPoint3D &) const override;
void AddYourGabaritTo(MbCube &) const override;
void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
MbSpaceItem & Duplicate( MbRegDuplicate * = nullptr ) const override;
bool IsSame( const MbSpaceItem &, double /*accuracy*/ = LENGTH_EPSILON ) const override;
bool SetEqual( const MbSpaceItem & ) override;
void Transform( const MbMatrix3D &, MbRegTransform * = nullptr ) override;
void Move( const MbVector3D &, MbRegTransform * = nullptr ) override;
void Rotate( const MbAxis3D &, double angle, MbRegTransform * = nullptr ) override;
double DistanceToPoint( const MbCartPoint3D & ) const override;
void AddYourGabaritTo( MbCube & ) const override;
void CalculateMesh( const MbStepData &, const MbFormNote &, MbMesh & ) const override; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh.
// \ru Тестовые функции геометрического объекта \en Test functions of a geometric object
MbProperty & CreateProperty(MbePrompt /*n*/) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties(MbProperties &) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties(const MbProperties &) override; // \ru Записать свойства объекта \en Set properties of object
MbProperty & CreateProperty( MbePrompt /*n*/ ) const override; // \ru Создать собственное свойство \en Create own property
void GetProperties( MbProperties & ) override; // \ru Выдать свойства объекта \en Get properties of the object
void SetProperties( const MbProperties & ) override; // \ru Записать свойства объекта \en Set properties of object
public:
/// \ru Инициализировать по центру, точке на окружности, плейсменту. \en Initialize by Initialize by center, point on circle and placement.
void Init(const MbCartPoint3D& center, const MbCartPoint3D& circle, const MbPlacement3D& dimensionPlacement, bool diametral);
void Init( const MbCartPoint3D & center, const MbCartPoint3D & circle, const MbPlacement3D & dimensionPlacement, bool diametral );
/// \ru Получить точку центра окружности. \en Get center point of circle.
MbCartPoint3D GetCenterPoint() const { return center; }
void SetCenterPoint(const MbCartPoint3D& val) { center = val; }
void SetCenterPoint( const MbCartPoint3D & val ) { center = val; }
/// \ru Получить точку на окружности. \en Get point on a circle.
MbCartPoint3D GetCirclePoint() const { return circle; }
void SetCirclePoint(const MbCartPoint3D& val) { circle = val; }
void SetCirclePoint( const MbCartPoint3D & val ) { circle = val; }
/// \ru Получить vестная система координат размера. \en Get local coordinate system of the dimension.
MbPlacement3D GetPlacement() const { return placement; }
void SetPlacement(const MbPlacement3D& val) { placement = val; }
void SetPlacement( const MbPlacement3D & val ) { placement = val; }
/// \ru Получить признак того что размер диаметральный. \en Get sign of the fact that the diametrical dimension.
bool IsDiametral() const { return diametral; }
void SetDiametral(bool val) { diametral = val; }
void SetDiametral( bool val ) { diametral = val; }
private: // \ru Не реализованные методы класса \en Non-implemented methods of class
void operator = (const MbRadialDimension &); // \ru Не реализовано \en Not implemented
void operator = ( const MbRadialDimension & ); // \ru Не реализовано \en Not implemented
DECLARE_PERSISTENT_CLASS(MbRadialDimension)
};
+4 -1
View File
@@ -270,10 +270,13 @@ enum MbResultType {
rt_DiscriminantSurfaceFar, ///< \ru Дискриминантная поверхность далеко от сечения. \en The discriminant surface far from section.
rt_CrossOrderError, ///< \ru Нарушен порядок взаимного пересечения кривых. \en The order of mutual intersection of curves is violated.
// \ru Ошибки построения удлинения кривой. \en Build failure of the curve extension.
rt_WrongExtensionLength, ///< \ru Некорректная длина продления. \en Incorrect extension length.
rt_WrongExtensionWayValue, ///< \ru Неизвестный способ продления. \en Unknown extension way.
rt_StampToolHoleError, ///< \ru Ошибка, в области штамповки не должно быть вырезов. \en Error, the stamping area contains holes.
rt_CurveClosedAtStart, ///< \ru Кривая замкнулась в начале. \en The curve has been closed at start point.
rt_CurveClosedAtEnd, ///< \ru Кривая замкнулась в конце. \en The curve has been closed at end point.
rt_CurveClosedBothSides, ///< \ru Кривая замкнулась с двух сторон. \en The curve has been closed at both sides.
// \ru !!! СТРОКИ ВСТАВЛЯТЬ СТРОГО ПЕРЕД ЭТОЙ СТРОКОЙ !!!! \en !!! INSERT LINES STRICTLY BEFORE THIS LINE !!!!
rt_ErrorTotal // \ru НИЖЕ НЕ ДОБАВЛЯТЬ! \en DON'T ADD BELOW!
};
+1 -1
View File
@@ -292,7 +292,7 @@ bool MbPntMatingData<Vector>::IsValid() const
isValid = !attach && (isTangLen || (isTangDer1 && tangentDer1->Length() > lenEps));
break;
case trt_SmoothG2 :
isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 ));
isValid = isTangLen && (isTangDer1 && ( tangent->Orthogonal( *tangentDer1 ) || tangentDer1->IsDegenerate()));
break;
case trt_SmoothG3:
isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 )) && isTangDer2;
+3 -2
View File
@@ -722,8 +722,8 @@ enum MbePrompt
IDS_PROP_0362, ///< \ru Вес поверхности 2. \en Weight of surface 2.
IDS_PROP_0363, ///< \ru Производная в начале. \en Derivative at the beginning.
IDS_PROP_0364, ///< \ru Производная в конце. \en Derivative at the end.
IDS_PROP_0365, ///< \ru Установлена нормаль в начале. \en The normal is set at the beginning.
IDS_PROP_0366, ///< \ru Установлена нормаль в конце. \en The normal is set at the end.
IDS_PROP_0365, ///< \ru Нормаль в начале. \en The normal at the beginning.
IDS_PROP_0366, ///< \ru Нормаль в конце. \en The normal at the end.
IDS_PROP_0367, ///< \ru Множитель длины производной в начале. \en The derivative length modifier at the beginning.
IDS_PROP_0368, ///< \ru Множитель длины производной в конце. \en The derivative length modifier at the end.
IDS_PROP_0370, ///< \ru Кривая на поверхности 0. \en Curve on surface 0.
@@ -1232,6 +1232,7 @@ enum MbePrompt
IDS_ITEM_1154, // "Угол наклона"
IDS_PROP_1155, // "СК паттерн."
IDS_PROP_1156, // "Координата СК паттерна."
IDS_PROP_1157, // "Опция масштабируемости паттерна GCM_scale."
IDS_PROP_1199, // The last id for C3D Solver
// \ru Новые описания без группировки \en New unsorted descriptions
+66 -35
View File
@@ -161,7 +161,7 @@ enum MbeSmoothingMethod
\ingroup Data_Structures
*/
// ---
template<class Point, class Vector>
template<class Point, class Vector, class Nurbs>
class MbApproxNurbsParameters
{
private:
@@ -174,6 +174,7 @@ private:
std::vector<Point> _approxPoints; ///< \ru Аппроксимируемая полилиния. \en Polyline to be approximated.
c3d::DoubleVector _approxParams; ///< \ru Параметры точек полилинии. \en Points parameters.
std::vector<MbApproxWeightConstraint<Vector>> _approxWeights; ///< \ru Веса точек полилинии. \en Points weights.
const Nurbs * _pReference; ///< \ru Кривая для сравнения с результатом аппроксимации. \en Curve for result comparing.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
@@ -183,6 +184,7 @@ public:
, _coefSmoothing ( -1. )
, _tolerance ( c3d::DELTA_MIN )
, _bClosed ( false )
, _pReference ( nullptr )
{}
/// \ru Конструктор копирования. \en The copy constructor.
@@ -203,6 +205,7 @@ public:
_approxPoints = other._approxPoints;
_approxParams = other._approxParams;
_approxWeights = other._approxWeights;
_pReference = other._pReference;
}
/** \brief \ru Инициализировать по точкам, создать равномерный узловой вектор.
@@ -249,12 +252,16 @@ public:
double extendBeg = 0.,
double extendEnd = 0. )
{
InitPoints( aPt );
if ( _approxPoints.empty() )
return;
_bClosed = bClosed;
_order = order;
_methodSmoothing = typeSmoothing;
_methodSmoothing = order > 3 ? typeSmoothing : MbeSmoothingMethod::sm_Curvature;
_coefSmoothing = smooth;
_tolerance = tolerance;
_approxPoints = aPt;
if ( bClosed )
{
if ( aPt.back().DistanceToPoint( aPt.front() ) > PARAM_EPSILON )
@@ -294,12 +301,15 @@ public:
MbeSmoothingMethod typeSmoothing,
double tolerance )
{
InitPoints( aPt );
if ( _approxPoints.empty() )
return;
_bClosed = false;
_order = order;
_methodSmoothing = typeSmoothing;
_coefSmoothing = smooth;
_tolerance = tolerance;
_approxPoints = aPt;
ParameterizeByLength( aPt, _approxParams );
_approxWeights.resize( aPt.size() );
@@ -336,12 +346,15 @@ public:
Vector * pDerBeg = nullptr,
Vector * pDerEnd = nullptr )
{
InitPoints( aPt );
if ( _approxPoints.empty() )
return;
_bClosed = bClosed;
_order = order;
_methodSmoothing = MbeSmoothingMethod::sm_CurvatureVariance;
_methodSmoothing = order > 3 ? MbeSmoothingMethod::sm_CurvatureVariance : MbeSmoothingMethod::sm_Curvature;
_coefSmoothing = 0.;
_tolerance = tolerance;
_approxPoints = aPt;
if ( bClosed )
{
@@ -350,36 +363,30 @@ public:
}
ParameterizeByLength( _approxPoints, _approxParams );
if ( bFixBeginEnd.first && _approxPoints.size() > 2 )
{
// Дублируем первую точку еще и как аппроксимационную для устойчивости наименьших квадратов.
const Point ptNew( _approxPoints[0] );
const auto prmNew( _approxParams[0] );
_approxPoints.insert( _approxPoints.begin() + 1, ptNew );
_approxParams.insert( _approxParams.begin() + 1, prmNew );
}
if ( bFixBeginEnd.second && _approxPoints.size() > 2 )
{
// Дублируем последнюю точку еще и как аппроксимационную для устойчивости наименьших квадратов.
const Point ptNew( _approxPoints.back() );
const auto prmNew( _approxParams.back() );
_approxPoints.insert( _approxPoints.begin() + _approxPoints.size() - 1, ptNew );
_approxParams.insert( _approxParams.begin() + _approxParams.size() - 1, prmNew );
}
_approxWeights.resize( _approxPoints.size() );
if ( bFixBeginEnd.first )
_approxWeights[0].SetWeightPoint( -1. );
if ( bFixBeginEnd.second )
_approxWeights.back().SetWeightPoint( -1. );
if ( bClosed )
{
if ( bFixBeginEnd.first || bFixBeginEnd.second )
_approxWeights[0].SetWeightPoint( -1. );
if ( pDerBeg != nullptr )
_approxWeights[0].SetWeightDerivative( -1., *pDerBeg );
if ( pDerBeg != nullptr || pDerEnd != nullptr )
_approxWeights[0].SetWeightDerivative( -1., pDerBeg != nullptr ? *pDerBeg : *pDerEnd );
}
else
{
if ( bFixBeginEnd.first )
_approxWeights[0].SetWeightPoint( -1. );
if ( pDerEnd != nullptr )
_approxWeights.back().SetWeightDerivative( -1., *pDerEnd );
if ( bFixBeginEnd.second )
_approxWeights.back().SetWeightPoint( -1. );
if ( pDerBeg != nullptr )
_approxWeights[0].SetWeightDerivative( -1., *pDerBeg );
if ( pDerEnd != nullptr )
_approxWeights.back().SetWeightDerivative( -1., *pDerEnd );
}
}
public:
@@ -401,8 +408,16 @@ public:
const c3d::DoubleVector & GetPointsParameters() const { return _approxParams; }
/// \ru Получить веса точек. \en Get point's weights.
const std::vector<MbApproxWeightConstraint<Vector>> & GetPointsWeights() const { return _approxWeights; }
///< \ru Получить кривую для сравнения. \en Get curve for result comparing.
const Nurbs * GetReferenceCurve() const { return _pReference; }
/// \ru Определен ли коэффициент сглаживания. \en Whether smoothing coefficient defined.
bool IsSmoothDefined() const { return ::fabs( _coefSmoothing ) > EXTENT_EPSILON; }
/// \ru Установить вес точки с заданным индексом. \en Set weight for point with specified index.
void SetPointWeight( size_t idx, double weight ) { _approxWeights[idx].SetWeightPoint( weight ); }
/// \ru Установить вес производной и саму производную для точки с заданным индексом. \en Set derivative weight and derivative itself for point with specified index.
void SetWeightDerivative( size_t idx, double weight, const Vector & der ) { _approxWeights[idx].SetWeightDerivative( weight, der ); }
///< \ru Установить кривую для сравнения. \en Set curve for result comparing.
void SetReferenceCurve( const Nurbs * pCurve ) { _pReference = pCurve; }
private:
/** \brief \ru Создать равномерный узловой вектор.
@@ -450,6 +465,22 @@ public:
aKt.push_back( end );
}
}
/// \ru Выбросить дублирующиеся точки из исходных данных. \en Remove duplicated points from the initial data.
void InitPoints( const std::vector<Point> & aPt )
{
_approxPoints.clear();
if ( !aPt.empty() )
{
_approxPoints.reserve( aPt.size() );
_approxPoints.push_back( aPt.front() );
for ( size_t i = 1, n = aPt.size(); i < n; ++i )
{
const auto & pnt = aPt[i];
if ( pnt.DistanceToPoint( _approxPoints.back() ) > PARAM_EPSILON )
_approxPoints.push_back( pnt );
}
}
}
}; // MbApproxNurbsParameters
@@ -611,8 +642,8 @@ public:
\en Under development. \~
*/
// ---
MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters<MbCartPoint3D, MbVector3D> & param,
MbApproxNurbsCurveResult<MbNurbs3D> & result );
MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters<MbCartPoint3D, MbVector3D, MbNurbs3D> & param,
MbApproxNurbsCurveResult<MbNurbs3D> & result );
//-------------------------------------------------------------------------------
@@ -630,7 +661,7 @@ MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParamet
\en Under development. \~
*/
// ---
MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters<MbCartPoint, MbVector> & param,
MbApproxNurbsCurveResult<MbNurbs> & result );
MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters<MbCartPoint, MbVector, MbNurbs> & param,
MbApproxNurbsCurveResult<MbNurbs> & result );
#endif // __MB_SMOOTH_NURBS_FIT_CURVE_H
+1
View File
@@ -148,6 +148,7 @@ public:
private:
MbEmbodimentNode();
MbEmbodimentNode( const MbEmbodimentNode * emb );
};
//----------------------------------------------------------------------------------------
+19
View File
@@ -58,6 +58,25 @@ public:
/// \ru Деструктор. \en Destructor.
~MbPrecision() {}
public:
/** \brief \ru Получить максимальную метрическую толерантность.
\en Get the maximum metric tolerance. \~
\details \ru Получить максимальную допустимую метрическую толерантность.\n
\en Get the maximum allowable metric tolerance.\n \~
\return \ru Возвращает величину максимальной метрической толерантности.
\en Returns the value of maximum metric tolerance. \~
*/
static double GetMaxMetricTolerance();
/** \brief \ru Получить максимальную угловую толерантность.
\en Get the maximum angular tolerance. \~
\details \ru Получить максимальную допустимую угловую толерантность.\n
\en Get the maximum allowable angular tolerance.\n \~
\return \ru Возвращает величину максимальной угловой толерантности.
\en Returns the value of maximum angular tolerance. \~
*/
static double GetMaxAngleTolerance();
public:
/// \ru Функция инициализации. \en Initialization function.
void Init( const MbPrecision & other ) {
+133 -59
View File
@@ -620,7 +620,7 @@ public:
/// \ru Текущий способ продления кривой. \en The Current way to extend the curve. \~
MbeCurveExtensionWays GetWayToExtend() const { return _extensionWay; }
/// \ru Текущая длина (в метрическом пространстве), на которую продлевается кривая. \en Current length (in metric space) the curve extended to. \~
/// \ru Длина (в метрическом пространстве), на которую продлевается кривая. \en The length (in metric space) the curve extended to. \~
double GetExtensionLength() const { return _extensionLength; }
/// \ru Проверка на равенство. \en Check if *this == other. \~
@@ -629,9 +629,6 @@ public:
/// \ru Оператор присваивания. \en Assignment operator. \~
MbCurveExtensionEnds & operator=( const MbCurveExtensionEnds & other );
/// \ru Проверить, допустимы ли параметры для алгоритма. \en Check if the parameters are available for the algorithm execution. \~
MbResultType CheckValid() const;
KNOWN_OBJECTS_RW_REF_OPERATORS( MbCurveExtensionEnds ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
@@ -801,7 +798,7 @@ public:
VERSION GetVersion() const { return _operName->GetMathVersion(); }
/// \ru Минимальная величина зазора (в параметрическом пространстве) для случая, когда запрещено создания замкнутых кривых. \en Minimal gap value (in parametric space) for case when closed result curves are forbidden. \~
static double GetMinUnclosedGap() { return Math::paramPrecision; }
double GetMinUnclosedGap() const { return GetPrecision(); }
/// \ru Оператор присваивания. \en Assignment operator. \~
MbCurveExtensionParameters & operator=( const MbCurveExtensionParameters & other );
@@ -1015,84 +1012,157 @@ public:
//------------------------------------------------------------------------------
/** \brief \ru Параметры для переноса копий двумерных кривых на другой носитель.
\en Parameters for transferring copies of two-dimensional curves on another medium. \~
\details \ru Точка xy плоскости XY локальной системы координат должна совпадать с точкой uv параметрической области UV поверхности. \n
\en The point xy of the XY plane of the local coordinate system must coincide with the point uv of the parametric region UV of the surface. \n \~
\ingroup Curve3D_Building_Parameters
\details \ru Точка xy плоскости XY локальной системы координат должна совпадать с точкой uv
параметрической области UV поверхности.
При параметрах angle = 0 и sense = true наложение плоскости на поверхность
делается таким образом, что оси 'xy' плоскости и 'uv' поверхности соответственно сопадают.
При параметрах angle = 0 и sense = false наложение плоскости на поверхность делается таким образом,
что оси 'y' плоскости и 'v' поверхности сопадают, оси 'x' и 'u' направлены протиположно.
Далее, значение угла angle показывает, насколько нужно повернуть систему координат XY плоскости
относительно её оси Z. \n
\en The point xy of the XY plane of the local coordinate system must coincide with the point uv of the
parametric region UV of the surface.
With parameters angle = 0 and sense = true the overlay of the plane on the surface matches 'x' and 'y' plane axes
to the 'u' and 'v' surface axes.
With parameters angle = 0 and sense = false the overlay of the plane on the surface matches 'y' plane axis
to the 'v' surface axis, with 'x' and 'u' axes directed oppositely.
Then the value of 'angle' shows how much the plane coordinate system XY is turned in respect to its Z axis. \n \~
\ingroup Curve3D_Building_Parameters
*/ // ---
class MATH_CLASS MbCurvesWrappingParams {
class MATH_CLASS MbCurvesWrappingParams : public MbPrecision {
private:
c3d::PlaneCurvesSPtrVector curves; ///< \ru Двумерные кривые, копии которых будут перенесены на другой носитель. \en 2d curves, copies of which will be transferred to another medium. \~
c3d::ConstSurfaceSPtr surface; ///< \ru Поверхность. \en The surface. \~
MbPlacement3D place; ///< \ru Локальная система координат (ЛСК). \en The local coordinate system (LCS) of the curves. \~
MbCartPoint xy; ///< \ru Точка привязки на плоскости XY локальной системы координат. \en The anchor point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~
MbCartPoint uv; ///< \ru Точка привязки в параметрической плоскости "UV" параметров поверхности. \en The anchor point in the parametric plane "UV" of the surface parameters. \~
double angle; ///< \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
bool sense; ///< \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности? \en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~
bool equals; ///< \ru Должны ли длины кривых на другом носителе соответствовать оригиналам? \en Should the lengths of the curves on another medium match the originals? \~
VERSION version; ///< \ru Версия алгоритма. \en The version. \~
public:
std::vector<const MbCurve *> curves; ///< \ru Двумерные кривые, копии которых будут перенесены на другой носитель. \en , copies of which will be transferred to another medium. \~
MbPlacement3D place; ///< \ru Локальная система координат (ЛСК). \en The local coordinate system (LCS) of the curves. \~
MbCartPoint xy; ///< \ru Точка привязки на плоскости XY локальной системы координат. \en The anchor point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~
const MbSurface & surface; ///< \ru Поверхность. \en The surface. \~
MbCartPoint uv; ///< \ru Точка привязки в параметрической плоскости "UV" параметров поверхности. \en The anchor point in the parametric plane "UV" of the surface parameters. \~
double angle; ///< \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
bool sense; ///< \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности? \en Do the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~
bool equals; ///< \ru Должны ли длины кривых на другом носителе соответствовать оригиналам? \en Should the lengths of the curves on another medium match the originals? \~
double accuracy;///< \ru Точность построения. \en The accuracy. \~
VERSION version; ///< \ru Версия алгоритма. \en The version. \~
public:
/// \ru Конструктор. \en Constructor. \~
MbCurvesWrappingParams( std::vector<const MbCurve *> & crs, const MbPlacement3D & pl_, const MbCartPoint & xy_,
const MbSurface & sur, const MbCartPoint & uv_, double ang, bool sen, bool equ, double acc, VERSION ver )
: curves ( crs )
, place ( pl_ )
, xy ( xy_ )
, surface ( sur )
, uv ( uv_ )
, angle ( ang )
, sense ( sen )
, equals ( equ )
, accuracy( acc )
, version ( ver )
{}
/// \ru Конструктор копирования. \en Copy constructor. \~
MbCurvesWrappingParams( const MbCurvesWrappingParams & other );
/** \brief \ru Конструктор.
\en Constructor.\~
\details \ru Конструктор.
\en Constructor.\~
\param[in] curves_ - \ru Двумерные кривые, копии которых будут свёрнуты/развёрнуты.
\en 2d curves, copies of which will be wrapped/unwrapped. \~
\param[in] place_ - \ru Локальная система координат (ЛСК) плоскости.
\en The local coordinate system (LCS) of the plane. \~
\param[in] xy_ - \ru Точка привязки на плоскости, которая будет привязана к uv-точке на поверхности.
\en The anchor point on the plane that will be aligned with the uv point on the parametric plane of the surface. \~
\param[in] surface_ - \ru Поверхность для сворачивания/разворачивания.
\en The surface to wrap to/unwrap from. \~
\param[in] uv_ - \ru Точка привязки на поверхности в параметрической плоскости "UV". Будет привязана к xy-точке на плоскости.
\en The anchor uv point on the parametric plane of the surface that will be aligned with the xy point on the plane.\~
\param[in] angle_ - \ru Угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности.
\en The angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
\param[in] sense_ - \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности.
\en Whether the directions of the "X" axis of the LSC and the "U" axis of the surface coincide? \~
\param[in] equals_ - \ru Должны ли длины кривых на другом носителе соответствовать оригиналам.
\en Should the lengths of the curves on another medium match the originals?\~
\param[in] accuracy_ - \ru Точность построения.
\en The accuracy. \~
\param[in] copyCurves_ - \ru Сохранить ли в этом классе параметров копии кривых.
\en Whether to save the curves copies in this parameter class. \~
\param[in] copySurface_ - \ru Сохранить ли в классе параметров копию поверхности.
\en Whether to save the surface copy in this parameter class. \~
\param[in] ver_ - \ru Версия алгоритма.
\en The version. \~
*/
MbCurvesWrappingParams( const c3d::PlaneCurvesSPtrVector & curves_,
const MbPlacement3D & place_,
const MbCartPoint & xy_,
const MbSurface & surface_,
const MbCartPoint & uv_,
double angle_,
bool sense_,
bool equals_,
double accuracy_,
bool copyCurves_,
bool copySurface_,
VERSION ver_ );
/** \brief \ru Конструктор копирования.
\en Copy constructor.\~
\details \ru Конструктор копирования.
\en Copy constructor.\~
\param[in] copyCurves - \ru Создать копии кривых.
\en Create copies of the curves. \~
\param[in] copySurface - \ru Создать копию поверхности.
\en Create a copy of the surface. \~
*/
MbCurvesWrappingParams( const MbCurvesWrappingParams & other, bool copyCurves, bool copySurface );
/// \ru Деструктор. \ en Destructor.
~MbCurvesWrappingParams() {}
public:
/// \ru Дать двумерные кривые. \en Get two-dimensional curves. \~
const std::vector<const MbCurve *> & GetCurves() const { return curves; }
/// \ru Дать количество кривые. \en Get two-dimensional curves count. \~
size_t GetCurvesCount() const { return curves.size(); }
void GetCurves( c3d::PlaneCurvesSPtrVector & retCurves ) const;
/// \ru Дать количество кривых. \en Get two-dimensional curves count. \~
size_t GetCurvesCount() const { return curves.size(); }
/// \ru Дать двумерную кривую. \en Get two-dimensional curve by index. \~
const MbCurve * GetCurve( size_t i ) const { return curves[i]; }
const c3d::PlaneCurveSPtr & GetCurve( size_t i ) const { return curves[i]; }
/// \ru Заменить двумерную кривую. \en Set two-dimensional curve by index. \~
void SetCurve( size_t i, const MbCurve & c ) { if ( i < curves.size() ) curves[i] = &c; }
void SetCurve( size_t i, const MbCurve & c ) { if ( i < curves.size() ) curves[i].assign( const_cast<MbCurve *>(&c)); }
/// \ru Заменить двумерную кривую. \en Set two-dimensional curve by index. \~
void SetCurve( size_t i, MbCurve * c ) { if ( i < curves.size() && c != nullptr ) curves[i].assign(c); }
/// \ru Дать локальную систему координат. \en Get the local coordinate system. \~
const MbPlacement3D & GetPlacement() const { return place; }
const MbPlacement3D & GetPlacement() const { return place; }
/// \ru Установить локальную систему координат. \en Set the local coordinate system. \~
void SetPlacement( const MbPlacement3D & p ) { place = p; }
void SetPlacement( const MbPlacement3D & p ) { place = p; }
/// \ru Дать точку на плоскости XY локальной системы координат. \en Get a point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~
const MbCartPoint & GetPlacePoint() const { return xy; }
const MbCartPoint & GetPlacePoint() const { return xy; }
/// \ru Установить точку на плоскости XY локальной системы координат. \en Set a point on the "XY" plane of the LCS that will be aligned with the uv point on the parametric plane of the surface. \~
void SetPlacePoint( const MbCartPoint & p ) { xy = p; }
void SetPlacePoint( const MbCartPoint & p ) { xy = p; }
/// \ru Дать поверхность. \en Get the surface. \~
const MbSurface & GetSurface() const { return surface; }
const MbSurface & GetSurface() const;
/// \ru Дать поверхность. \en Get the surface. \~
const c3d::ConstSurfaceSPtr & GetSurfacePtr() const { return surface; }
/// \ru Установить поверхность. \en Set the surface. \~
void SetSurface ( MbSurface & surf ) { surface.assign( &surf ); }
/// \ru Установить поверхность. \en Set the surface. \~
void SetSurfacePtr( const c3d::ConstSurfaceSPtr & surf ) { if ( surf != nullptr ) surface = surf; }
/// \ru Дать точку в области параметров поверхности. \en Get a point on the parametric plane "UV" of the surface corresponding to the point xy on the plane. \~
const MbCartPoint & GetSurfacePoint() const { return uv; }
const MbCartPoint & GetSurfacePoint() const { return uv; }
/// \ru Установить точку в области параметров поверхности. \en Set a point on the parametric plane "UV" of the surface corresponding to the point xy on the plane. \~
void SetSurfacePoint( const MbCartPoint & p ) { uv = p; }
void SetSurfacePoint( const MbCartPoint & p ) { uv = p; }
/// \ru Дать угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en Get the angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
double GetAngle() const { return angle; }
double GetAngle() const { return angle; }
/// \ru Установить угол поворота плоскости "XY" ЛСК и параметрической плоскости "UV" поверхности. \en Set the angle of rotation of the LSC "XY" plane and the parametric "UV" plane of the surface. \~
void SetAngle( double a ) { angle = a; }
void SetAngle( double a ) { angle = a; }
/// \ru Совпадают ли направления оси "X" ЛСК и оси "U" поверхности. \en Does the coincidence of the directions of the "X" axis of the LSC and the "U" axis of the surface. \~
bool IsSense() const { return sense; }
void SetSense( bool s ) { sense = s; }
bool IsSense() const { return sense; }
void SetSense( bool s ) { sense = s; }
/// \ru Соответствует ли длина кривых в плоскости и на поверхности? \en Does the curves length correspond to the originals on the surface? \~
bool IsEquals() const { return equals; }
void SetEquals( bool e ) { equals = e; }
bool IsEquals() const { return equals; }
void SetEquals( bool e ) { equals = e; }
/// \ru Дать точность построения. \en Get an accuracy. \~
double GetAccuracy() const { return accuracy; }
void SetAccuracy( double acc ) { accuracy = acc; }
double GetAccuracy() const { return GetPrecision(); }
void SetAccuracy( double acc ) { SetPrecision( acc ); }
/// \ru Версия алгоритма. \en The version. \~
VERSION GetVersion() const { return version; }
void SetVersion( VERSION ver ) { version = ver; }
VERSION GetVersion() const { return version; }
void SetVersion( VERSION ver ) { version = ver; }
/** \brief \ru Создать копию текущих параметров.
\en Make a copy of current parameters.\~
\details \ru Создать копию текущих параметров.
\en Make a copy of current parameters.\~
\param[in] copyCurves - \ru Создать копии кривых.
\en Create copies of the curves. \~
\param[in] copySurface - \ru Создать копию поверхности.
\en Create a copy of the surface. \~
*/
MbCurvesWrappingParams * Duplicate( bool copyCurves, bool copySurface );
private:
MbCurvesWrappingParams & operator = ( const MbCurvesWrappingParams & other ); // \ru Не реализовано. \en Not implemented.
};
@@ -1162,6 +1232,8 @@ public:
bool _fixFirstPointNoisy; ///< \ru Флаг фиксации сплайна в начальной точке. \en Flag of fixing a spline at the first point.
bool _fixLastPointNoisy; ///< \ru Флаг фиксации сплайна в конечной точке. \en Flag of fixing a spline at the last point.
SArray<size_t> _arrayFixNoisyNum; ///< \ru Номера точек точных значений зашумленных точек. \en Signs of exactly noisy points.
// \ru Диагностика. \en The diagnostics.
MbeFairWarning _warning; ///< \ru Предупреждение о работе. \en The operation warning. \~
MbResultType _error; ///< \ru Ошибка о работе. \en The operation error. \~
@@ -1275,6 +1347,8 @@ public:
bool _fixFirstPointNoisy; ///< \ru Флаг фиксации сплайна в начальной точке. \en Flag of fixing a spline at the first point.
bool _fixLastPointNoisy; ///< \ru Флаг фиксации сплайна в конечной точке. \en Flag of fixing a spline at the last point.
SArray<size_t> _arrayFixNoisyNum; ///< \ru Номера точек точных значений зашумленных точек. \en Signs of exactly noisy points.
MbeFairWarning _warning; ///< \ru Предупреждение о работе. \en The operation warning. \~
MbResultType _error; ///< \ru Ошибка о работе. \en The operation error. \~
+120 -44
View File
@@ -211,8 +211,10 @@ public:
bool SetStopObjectAtEnd( const MbSurface * object, bool byObject = true );
/// \ru Установить вектор нормали к плоскости остановки скругления в начале цепочки. \en Set normal to the bound plane at the begin.
void SetBegVector( const MbVector3D & vect ) { vector1.Init( vect ); }
MbVector3D & SetBegVector() { return vector1; }
/// \ru Установить вектор нормали к плоскости остановки скругления в конце цепочки. \en Set normal to the bound plane at the end.
void SetEndVector( const MbVector3D & vect ) { vector2.Init( vect ); }
MbVector3D & SetEndVector() { return vector2; }
/// \ru Получить вектор нормали к плоскости остановки в начале скругления. \en Get normal vector to the bound plane at the begin of the fillet.
void GetBegVector( MbVector3D & vect ) const { vect.Init( vector1 ); }
/// \ru Получить вектор нормали к плоскости остановки в конце скругления. \en Get normal vector to the bound plane at the end of the fillet.
@@ -926,6 +928,8 @@ public:
virtual void SetMate( MbePatchMatingType newType, const MbSurface * newSurface ) = 0;
/// \ru Установить тип сопряжения сегмента. \en Set conjugation type of segment.
virtual void SetMate( size_t segInd, MbePatchMatingType newType, const MbSurface * newSurface ) = 0;
/// \ru Установить тип сопряжения по кривой на поверхности или контуру из кривых на поверхности. \en Set conjugation type to a curve on a surface or a contour from curves on a surface.
virtual bool SetMateByCurve( MbePatchMatingType newType, const MbCurve3D & curve ) = 0;
/// \ru Выдать тип сопряжения. \en Get the type of conjugation.
virtual MbePatchMatingType GetMatingType() const = 0;
@@ -966,8 +970,8 @@ private:
class MATH_CLASS MbCurveMate: public MbRefItem,
public TapeBase {
protected:
c3d::SpaceCurveSPtr curve; ///< \ru Кривая. \en A curve.
DPtr<MbPatchMating> mating; ///< \ru Сопряжение. \en The conjugation.
c3d::SpaceCurveSPtr _curve; ///< \ru Кривая. \en A curve.
DPtr<MbPatchMating> _mating; ///< \ru Сопряжение. \en The conjugation.
public:
/// \ru Конструктор по кривой. \en Constructor by a curve.
@@ -989,24 +993,26 @@ public:
virtual ~MbCurveMate();
/// \ru Получить кривую. \en Get a curve.
const MbCurve3D & GetCurve() const { return *curve; }
const MbCurve3D & GetCurve() const { return *_curve; }
/// \ru Получить кривую для изменения. \en Get a curve for changing.
MbCurve3D & SetCurve() { return *curve; }
MbCurve3D & SetCurve() { return *_curve; }
/// \ru Выдать тип сопряжения. \en Get the type of conjugation.
MbePatchMatingType GetMatingType() const { return mating->GetMatingType(); }
MbePatchMatingType GetMatingType() const { return _mating->GetMatingType(); }
/// \ru Выдать поверхность сопряжения. \en Get surface of conjugation.
const MbSurface * GetMatingSurface() const { return mating->GetSurface(); }
const MbSurface * GetMatingSurface() const { return _mating->GetSurface(); }
/// \ru Установить сопряжение. \en Set the conjugation.
void SetMating( MbPatchMating & other ) { mating->SetMate( other.GetMatingType(), other.GetSurface() ); }
void SetMating( const MbPatchMating & other ) { _mating->SetMate( other.GetMatingType(), other.GetSurface() ); }
/// \ru Установить сопряжение. \en Set the conjugation.
void SetMating( MbePatchMatingType type, const MbSurface * surface ) { mating->SetMate( type, surface ); }
void SetMating( MbePatchMatingType type, const MbSurface * surface ) { _mating->SetMate( type, surface ); }
/// \ru Установить сопряжение сегмента. \en Set the conjugation of segment.
void SetMating( size_t segInd, MbePatchMatingType type, const MbSurface * surface ) { mating->SetMate( segInd, type, surface ); }
void SetMating( size_t segInd, MbePatchMatingType type, const MbSurface * surface ) { _mating->SetMate( segInd, type, surface ); }
/// \ru Установить тип сопряжения по кривой на поверхности или контуру из кривых на поверхности. \en Set conjugation type to a curve on a surface or a contour from curves on a surface.
bool SetMating( MbePatchMatingType newType, const MbCurve3D & curve ) { return _mating->SetMateByCurve( newType, curve ); }
MbPatchMating & SetMating() { return *mating; } ///< Получить сопряжение. \en Get the conjugation.
const MbPatchMating & GetMating() const { return *mating; } ///< Получить сопряжение. \en Get the conjugation.
MbPatchMating & SetMating() { return *_mating; } ///< Получить сопряжение. \en Get the conjugation.
const MbPatchMating & GetMating() const { return *_mating; } ///< Получить сопряжение. \en Get the conjugation.
MbCurveMate & Duplicate( MbRegDuplicate * iReg ) const; /// \ru Сделать копию элемента. \en Create a copy of the element.
@@ -1064,10 +1070,11 @@ public:
ts_byCurves, ///< \ru Построение задается сопряжениями по каждой кривой. \en The construction is defined by conjugations on curves.
};
private:
SurfaceType type; ///< \ru Тип заплатки. \en Type of patch.
bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods).
bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true).
bool tolerantData; ///< \ru Построить неточную заплатку по неточным входным данным. \en Build an tolerant patch from tolerant input data.
SurfaceType type; ///< \ru Тип заплатки. \en Type of patch.
bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods).
bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true).
bool tolerantData; ///< \ru Построить неточную заплатку по неточным входным данным. \en Build an tolerant patch from tolerant input data.
MbePatchMatingType internalMatingType; ///< \ru Тип сопряжения между частями заплатки. Используется при type = ts_byCurves. \en The type of mating between parts of the patch. Used when type = ts_byCurves. \warning \ru В разработке. \en Under development. \~
public:
/** \brief \ru Конструктор по умолчанию.
@@ -1076,18 +1083,20 @@ public:
\en Constructor of parameters of patch with undefined type and without checking of self-intersection. \~
*/
PatchValues()
: type ( ts_none )
, checkSelfInt( false )
, mergeEdges ( true )
, tolerantData( false )
: type ( ts_none )
, checkSelfInt ( false )
, mergeEdges ( true )
, tolerantData ( false )
, internalMatingType( pmt_None )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
PatchValues( const PatchValues & other )
: type ( other.type )
, checkSelfInt ( other.checkSelfInt )
, mergeEdges ( other.mergeEdges )
, tolerantData ( other.tolerantData )
: type ( other.type )
, checkSelfInt ( other.checkSelfInt )
, mergeEdges ( other.mergeEdges )
, tolerantData ( other.tolerantData )
, internalMatingType( other.internalMatingType )
{}
/// \ru Деструктор. \en Destructor.
@@ -1113,23 +1122,30 @@ public:
/// \ru Установить флаг построения неточной заплатки по неточным входным данным. \en Set the flag for building an tolerant patch from tolerant input data.
void SetTolerantData( bool tolData ) { tolerantData = tolData; }
/// \ru Выдать тип сопряжения между кусками заплатки. \en Get the type of mating between pieces of the patch.
MbePatchMatingType GetInternalMatingType() const { return internalMatingType; }
/// \ru Установить тип сопряжения между кусками заплатки. \en Set the type of mating between pieces of the patch.
void SetInternalMatingType( MbePatchMatingType matingType ) { internalMatingType = matingType; }
reader & Read ( reader & in, std::vector<DPtr<MbPatchMating>> & matings );
writer & Write( writer & out, const std::vector<SPtr<MbCurveMate>> & curves ) const;
/// \ru Оператор присваивания. \en Assignment operator.
void operator = ( const PatchValues & other ) {
type = other.type;
checkSelfInt = other.checkSelfInt;
mergeEdges = other.mergeEdges;
tolerantData = other.tolerantData;
type = other.type;
checkSelfInt = other.checkSelfInt;
mergeEdges = other.mergeEdges;
tolerantData = other.tolerantData;
internalMatingType = other.internalMatingType;
}
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const PatchValues & obj, double ) const {
return ( (obj.type == type) &&
(obj.checkSelfInt == checkSelfInt) &&
(obj.mergeEdges == mergeEdges) &&
(obj.tolerantData == tolerantData) );
return ( (obj.type == type) &&
(obj.checkSelfInt == checkSelfInt) &&
(obj.mergeEdges == mergeEdges) &&
(obj.tolerantData == tolerantData) &&
(obj.internalMatingType == internalMatingType) );
}
KNOWN_OBJECTS_RW_REF_OPERATORS( PatchValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
@@ -2384,10 +2400,10 @@ public:
/// \ru Привести кривые к поверхностной форме (кривые на поверхности) \en Convert curves to the surface form (curves on the surface)
bool TransformCurves( VERSION vers );
/// \ru Привести кривые к поверхностной форме (кривые на поверхности) \en Convert curves to the surface form (curves on the surface)
bool TransformForCompositeSurfaceMating( VERSION vers );
bool TransformForCompositeSurfaceMating( const double mPrec, VERSION vers );
/// \ru Обеспечить непрерывность длины первой производной для кривых семейства dirU.
/// \en Ensure continuity of the length of the first derivative for the curves of the dirU family.
bool SetContinuousDerivativeLength( bool dirU, bool & smooth, VERSION version );
bool SetContinuousDerivativeLength( bool dirU, bool & smooth, const double aEps, VERSION version );
/** \} */
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
@@ -2431,12 +2447,14 @@ private:
const MbSurface & surface,
const RPArray<MbCurve3D> & constrCurves,
MbSurfaceCurve *& resCurve,
const double mPrec,
VERSION vers );
// \ru Привести кривую к типу поверхностной кривой или к контура из SurfaceCurve. \en Convert the curve to type of surface curve or contour from SurfaceCurve.
static bool TransformToSurfaceCurve( const MbCurve3D & initCurve,
const c3d::SurfacesVector & surfaces,
const RPArray<MbCurve3D> & constrCurves,
MbCurve3D *& resCurve,
const double mPrec,
VERSION vers );
public:
KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MeshSurfaceValues, MATH_FUNC_EX )
@@ -2452,7 +2470,7 @@ OBVIOUS_PRIVATE_COPY( MeshSurfaceValues )
\ingroup Shell_Building_Parameters
*/
// ---
class MATH_CLASS MbMeshShellParameters
class MATH_CLASS MbMeshShellParameters : public MbPrecision
{
private:
MeshSurfaceValues _params; ///< \ru Параметры операции. \en The operation parameters.
@@ -6257,16 +6275,17 @@ public:
class MATH_CLASS MbDraftSolidParams: public MbPrecision
{
private:
c3d::FacesSPtrVector _faces; ///< \ru Уклоняемые грани. \en Drafts faces.
c3d::EdgesSPtrVector _edges; ///< \ru Нейтральные ребра. \en Neutral edges.
c3d::FacesSPtrVector _faces; ///< \ru Уклоняемые грани. \en Drafts faces.
c3d::EdgesSPtrVector _edges; ///< \ru Нейтральные ребра. \en Neutral edges.
MbPlacement3D _neutralPlane; ///< \ru Нейтральная плоскость. \en Neutral plane.
MbVector3D _dir; ///< \ru Базовое направление. \en Basic direction.
MbPlacement3D _neutralPlane; ///< \ru Нейтральная плоскость. \en Neutral plane.
MbVector3D _dir; ///< \ru Базовое направление. \en Basic direction.
SPtr<MbSNameMaker> _names; ///< \ru Именователь. \en An object for naming the new objects.
double _angle; ///< \ru Угол уклона. \en Drafts angle.
MbeFacePropagation _faceProp; ///< \ru Признак захвата граней. \en Face propagation.
bool _reverse; ///< \ru Обратить базовое направление. \en Inverse basic direction.
SPtr<MbSNameMaker> _names; ///< \ru Именователь. \en An object for naming the new objects.
double _angle; ///< \ru Угол уклона. \en Drafts angle.
MbeFacePropagation _faceProp; ///< \ru Признак захвата граней. \en Face propagation.
bool _reverse; ///< \ru Обратить базовое направление. \en Inverse basic direction.
bool _rebuildFillets; ///< \ru Перестраивать ли скругления. \en Whether to rebuild the fillets.
private:
@@ -6296,6 +6315,32 @@ public:
double angle,
MbeFacePropagation faceProp,
bool reverse );
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по нейтральной плоскости и именователю операции. \n
\en Constructor by neutral plane and object defining names generation in the operation. \n \~
\param[in] faces - \ru Уклоняемые грани.
\en Drafts faces. \~
\param[in] neutralPlane - \ru Нейтральная плоскость.
\en A neutral plane. \~
\param[in] names - \ru Именователь операции.
\en An object defining names generation in the operation. \~
\param[in] angle - \ru Угол уклона.
\en Draft angle. \~
\param[in] faceProp - \ru Признак захвата граней.
\en Face propagation. \~
\param[in] reverse - \ru Обратить базовое направление.
\en Inverse basic direction. \~
\param[in] rebuildFillets - \ru Перестраивать ли прилежащие скругления.
\en Whether to rebuild the adjacent fillets. \~
*/
MbDraftSolidParams( const c3d::FacesSPtrVector & faces,
const MbPlacement3D & neutralPlane,
const MbSNameMaker & names,
double angle,
MbeFacePropagation faceProp,
bool reverse,
bool rebuildFillets );
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по нейтральной плоскости и именователю. \n
@@ -6345,6 +6390,35 @@ public:
double angle,
MbeFacePropagation faceProp,
bool reverse );
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по набору ребер и именователю. \n
\en Constructor by edges and object defining names generation in the operation. \n \~
\param[in] faces - \ru Уклоняемые грани.
\en Drafts faces. \~
\param[in] edges - \ru Нейтральные ребра.
\en A neutral edges. \~
\param[in] dir - \ru Базовое направление.
\en A basic direction. \~
\param[in] names - \ru Именователь.
\en An object defining names generation in the operation. \~
\param[in] angle - \ru Угол уклона.
\en Draft angle. \~
\param[in] faceProp - \ru Признак захвата граней.
\en Face propagation. \~
\param[in] reverse - \ru Обратить базовое направление.
\en Inverse basic direction. \~
\param[in] rebuildFillets - \ru Перестраивать ли прилежащие скругления.
\en Whether to rebuild the adjacent fillets. \~
*/
MbDraftSolidParams( const c3d::FacesSPtrVector & faces,
const c3d::EdgesSPtrVector & edges,
const MbVector3D & dir,
const MbSNameMaker & names,
double angle,
MbeFacePropagation faceProp,
bool reverse,
bool rebuildFillets );
/// \ru Конструктор копирования. \en Copy constructor.
MbDraftSolidParams( const MbDraftSolidParams & other );
@@ -6362,8 +6436,10 @@ public:
double GetAngle() const { return _angle; }
/// \ru Получить признак захвата граней. \en Get face propagation.
MbeFacePropagation GetFacePropagetion() const { return _faceProp; }
/// \ru Получить обратитное базовое направление. \en Get inverse basic direction.
bool GetReverse() const {return _reverse;}
/// \ru Получить обратное базовое направление. \en Get inverse basic direction.
bool GetReverse() const { return _reverse; }
/// \ru Перестраивать ли прилежащие скругления. \en Whether to rebuild the adjacent fillets.
bool DoRebuildFillets() const { return _rebuildFillets; }
/// \ru Оператор присваивания. \en Assignment operator.
const MbDraftSolidParams & operator = ( const MbDraftSolidParams & );
+3 -1
View File
@@ -1471,7 +1471,9 @@ public :
/// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar'
void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ) override;
void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ) override;
void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ) override;
// \ru Заменить операнд. \en Replace the operand.
BTreeNode * ReplaceSubNode( BTreeNode & newNode, size_t opNum );
virtual BTreeNode * GetSubNode( size_t i );
bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const override;
+4 -4
View File
@@ -2399,10 +2399,10 @@ class MATH_CLASS MbRemoveOperationResultParams: public MbPrecision
MbeSheetOperationName _opType; ///< \ru Тип листовой операции. \en Type of sheet metal operations.
MbSNameMaker _nameMaker; ///< \ru Именователь. \en An object for naming the new objects.
public:
private:
/// \ru Конструктор по умолчанию. Не реализован. \en Default constructor. Not implemented.
MbRemoveOperationResultParams();
public:
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по главному имени удаляемой операции, типу листовой операции
@@ -2463,10 +2463,10 @@ class MATH_CLASS MbCutSolidArrayByBordersParams: public MbPrecision
double _depth; ///< \ru Глубина выдавливания. \en The extrusion depth.
MbSNameMaker _nameMaker; ///< \ru Именователь. \en An object for naming the new objects.
public:
private:
/// \ru Конструктор по умолчанию. Не реализован. \en Default constructor. Not implemented.
MbCutSolidArrayByBordersParams();
public:
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по листовому телу, набору плейсментов и глубине выдавливания. \n
+2 -2
View File
@@ -616,9 +616,9 @@ inline void MbFilletSurface::CheckUParam( double & u ) const {
}
}
else {
if ( poleMin && u<umin )
if ( poleUMin && u < umin )
u = umin;
if ( poleMax && u>umax )
if ( poleUMax && u > umax )
u = umax;
}
}
+6 -4
View File
@@ -47,8 +47,10 @@ protected:
double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v.
double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v.
bool uclosed; ///< \ru Признак замкнутости по параметру u. \en An attribute of closedness in u-parameter direction.
bool poleMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin.
bool poleMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax.
bool poleUMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin.
bool poleUMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax.
bool poleVMin; ///< \ru Наличие полюса при vmin. \en Existence of a pole at vmin.
bool poleVMax; ///< \ru Наличие полюса при vmax. \en Existence of a pole at vmax.
protected:
@@ -365,9 +367,9 @@ inline void MbSmoothSurface::CheckParam( double &u, double &v ) const {
}
}
else {
if ( poleMin && u<umin )
if ( poleUMin && u < umin )
u = umin;
if ( poleMax && u>umax )
if ( poleUMax && u > umax )
u = umax;
}
}
+2 -2
View File
@@ -129,9 +129,9 @@ public: // \ru Стандартные функции контейнерного
using RPArray<Type>::capacity;
using RPArray<Type>::reserve;
/// \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element.
const stored_type * begin () const { return RPArray<Type>::begin(); }
using RPArray<Type>::begin; //const stored_type * begin() const { return RPArray<Type>::begin(); }
///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array.
const stored_type * end() const { return RPArray<Type>::end(); }
using RPArray<Type>::end; //const stored_type * end() const { return RPArray<Type>::end(); }
public: // \ru Доступные методы от RPArray<Type> \en Available methods from RPArray<Type>
+11
View File
@@ -90,6 +90,17 @@ extern "C" MATH_FUNC (bool) IsMathVisionEnable();
extern "C" MATH_FUNC (bool) IsMathBShaperEnable();
//------------------------------------------------------------------------------
/** \brief \ru Проверить контроллер защиты детектора столкновений.
\en Check the controller of the Collision Detection. \~
\details \ru Проверить контроллер защиты детектора столкновений.
\en Check the controller of the Collision Detection. \~
\ingroup Base_Tools
*/
// ---
extern "C" MATH_FUNC (bool) IsMathCollisionEnable();
//------------------------------------------------------------------------------
/** \brief \ru Отпустить контролера работы модулей ядра.
\en Free the controller of the kernel modules work. \~
+117 -91
View File
@@ -24,6 +24,7 @@
#include <topology_item.h>
#include <list>
#include <set>
#include <map>
#include <vector>
#include <surface.h>
#include <op_binding_data.h>
@@ -44,21 +45,25 @@ class MATH_CLASS MbOrientedEdge;
class MATH_CLASS MbLoop;
class MATH_CLASS MbFace;
class MATH_CLASS MbFunction;
struct MATH_CLASS MbItemIndex;
class MbFaceTemp;
struct MATH_CLASS MbItemIndex;
class MbFaceTemp;
namespace c3d // namespace C3D
{
// vertices typedefs
typedef SPtr<MbVertex> VertexSPtr;
typedef SPtr<const MbVertex> ConstVertexSPtr;
typedef SPtr<MbVertex> VertexSPtr;
typedef SPtr<const MbVertex> ConstVertexSPtr;
typedef std::vector<MbVertex *> VerticesVector;
typedef std::vector<const MbVertex *> ConstVerticesVector;
typedef std::pair<MbVertex *, MbVertex *> VerticesPair;
typedef std::pair<const MbVertex *, const MbVertex *> ConstVerticesPair;
typedef std::pair<VertexSPtr, VertexSPtr> VerticesSPtrPair;
typedef std::pair<ConstVertexSPtr, ConstVertexSPtr> ConstVerticesSPtrPair;
typedef std::vector<VertexSPtr> VerticesSPtrVector;
typedef std::vector<ConstVertexSPtr> ConstVerticesSPtrVector;
typedef std::vector<MbVertex *> VerticesVector;
typedef std::vector<const MbVertex *> ConstVerticesVector;
typedef std::vector<VertexSPtr> VerticesSPtrVector;
typedef std::vector<ConstVertexSPtr> ConstVerticesSPtrVector;
typedef std::set<MbVertex *> VerticesSet;
typedef VerticesSet::iterator VerticesSetIt;
@@ -80,56 +85,70 @@ typedef ConstVerticesSPtrSet::iterator ConstVerticesSPtrSetIt;
typedef ConstVerticesSPtrSet::const_iterator ConstVerticesSPtrSetConstIt;
typedef std::pair<ConstVerticesSPtrSetConstIt, bool> ConstVerticesSPtrSetRet;
// edges typedefs
typedef SPtr<MbEdge> WireEdgeSPtr;
typedef SPtr<const MbEdge> ConstWireEdgeSPtr;
typedef std::map<MbVertex *, MbVertex *> VerticesPairMap;
typedef std::map<const MbVertex *, const MbVertex *> ConstVerticesPairMap;
typedef std::map<VertexSPtr, VertexSPtr> VerticesSPtrPairMap;
typedef std::map<ConstVertexSPtr, ConstVertexSPtr> ConstVerticesSPtrPairMap;
typedef std::vector<MbEdge *> WireEdgesVector;
typedef std::vector<const MbEdge *> ConstWireEdgesVector;
typedef std::vector<WireEdgeSPtr> WireEdgesSPtrVector;
typedef std::vector<ConstWireEdgeSPtr> ConstWireEdgesSPtrVector;
// edges typedefs
typedef SPtr<MbCurveEdge> EdgeSPtr;
typedef SPtr<const MbCurveEdge> ConstEdgeSPtr;
typedef SPtr<MbEdge> WireEdgeSPtr;
typedef SPtr<const MbEdge> ConstWireEdgeSPtr;
typedef std::pair<MbCurveEdge *, size_t> EdgeIndex;
typedef std::pair<const MbCurveEdge *, size_t> ConstEdgeIndex;
typedef std::pair<MbEdge *, MbEdge *> WireEdgesPair;
typedef std::pair<const MbEdge *, const MbEdge *> ConstWireEdgesPair;
typedef std::pair<WireEdgeSPtr, WireEdgeSPtr> WireEdgesSPtrPair;
typedef std::pair<ConstWireEdgeSPtr, ConstWireEdgeSPtr> ConstWireEdgesSPtrPair;
typedef std::pair<size_t, MbCurveEdge *> IndexEdge;
typedef std::pair<size_t, const MbCurveEdge *> IndexConstEdge;
typedef std::vector<MbEdge *> WireEdgesVector;
typedef std::vector<const MbEdge *> ConstWireEdgesVector;
typedef std::vector<WireEdgeSPtr> WireEdgesSPtrVector;
typedef std::vector<ConstWireEdgeSPtr> ConstWireEdgesSPtrVector;
typedef std::pair<MbCurveEdge *, MbCurveEdge *> EdgesPair;
typedef std::vector<MbCurveEdge *> EdgesVector;
typedef std::vector<const MbCurveEdge *> ConstEdgesVector;
// edges typedefs
typedef SPtr<MbCurveEdge> EdgeSPtr;
typedef SPtr<const MbCurveEdge> ConstEdgeSPtr;
typedef std::vector<EdgeSPtr> EdgesSPtrVector;
typedef std::vector<ConstEdgeSPtr> ConstEdgesSPtrVector;
typedef std::pair<MbCurveEdge *, size_t> EdgeIndex;
typedef std::pair<const MbCurveEdge *, size_t> ConstEdgeIndex;
typedef std::list<MbCurveEdge *> EdgesList;
typedef std::list<const MbCurveEdge *> ConstEdgesList;
typedef std::pair<size_t, MbCurveEdge *> IndexEdge;
typedef std::pair<size_t, const MbCurveEdge *> IndexConstEdge;
typedef std::set<MbCurveEdge *> EdgesSet;
typedef EdgesSet::iterator EdgesSetIt;
typedef EdgesSet::const_iterator EdgesSetConstIt;
typedef std::pair<EdgesSetConstIt, bool> EdgesSetRet;
typedef std::pair<MbCurveEdge *, MbCurveEdge *> EdgesPair;
typedef std::pair<const MbCurveEdge *, const MbCurveEdge *> ConstEdgesPair;
typedef std::pair<EdgeSPtr, EdgeSPtr> EdgesSPtrPair;
typedef std::pair<ConstEdgeSPtr, ConstEdgeSPtr> ConstEdgesSPtrPair;
typedef std::set<EdgeSPtr> EdgesSPtrSet;
typedef EdgesSPtrSet::iterator EdgesSPtrSetIt;
typedef EdgesSPtrSet::const_iterator EdgesSPtrSetConstIt;
typedef std::pair<EdgesSPtrSetConstIt, bool> EdgesSPtrSetRet;
typedef std::vector<MbCurveEdge *> EdgesVector;
typedef std::vector<const MbCurveEdge *> ConstEdgesVector;
typedef std::vector<EdgeSPtr> EdgesSPtrVector;
typedef std::vector<ConstEdgeSPtr> ConstEdgesSPtrVector;
typedef std::set<const MbCurveEdge *> ConstEdgesSet;
typedef ConstEdgesSet::iterator ConstEdgesSetIt;
typedef ConstEdgesSet::const_iterator ConstEdgesSetConstIt;
typedef std::pair<ConstEdgesSetConstIt, bool> ConstEdgesSetRet;
typedef std::list<MbCurveEdge *> EdgesList;
typedef std::list<const MbCurveEdge *> ConstEdgesList;
typedef std::set<MbCurveEdge *> EdgesSet;
typedef EdgesSet::iterator EdgesSetIt;
typedef EdgesSet::const_iterator EdgesSetConstIt;
typedef std::pair<EdgesSetConstIt, bool> EdgesSetRet;
typedef std::set<EdgeSPtr> EdgesSPtrSet;
typedef EdgesSPtrSet::iterator EdgesSPtrSetIt;
typedef EdgesSPtrSet::const_iterator EdgesSPtrSetConstIt;
typedef std::pair<EdgesSPtrSetConstIt, bool> EdgesSPtrSetRet;
typedef std::set<const MbCurveEdge *> ConstEdgesSet;
typedef ConstEdgesSet::iterator ConstEdgesSetIt;
typedef ConstEdgesSet::const_iterator ConstEdgesSetConstIt;
typedef std::pair<ConstEdgesSetConstIt, bool> ConstEdgesSetRet;
typedef std::set<ConstEdgeSPtr> ConstEdgesSPtrSet;
typedef ConstEdgesSPtrSet::iterator ConstEdgesSPtrSetIt;
typedef ConstEdgesSPtrSet::const_iterator ConstEdgesSPtrSetConstIt;
typedef std::pair<ConstEdgesSPtrSetConstIt, bool> ConstEdgesSPtrSetRet;
typedef std::set<ConstEdgeSPtr> ConstEdgesSPtrSet;
typedef ConstEdgesSPtrSet::iterator ConstEdgesSPtrSetIt;
typedef ConstEdgesSPtrSet::const_iterator ConstEdgesSPtrSetConstIt;
typedef std::pair<ConstEdgesSPtrSetConstIt, bool> ConstEdgesSPtrSetRet;
// oriented edges typedefs
typedef MbOrientedEdge * OrientEdge;
@@ -146,16 +165,15 @@ typedef std::pair<ConstEdgeSPtr, bool> ConstEdgeSPtrOrient;
typedef std::vector<OrientEdge> OrientEdgesVector;
typedef std::vector<ConstOrientEdge> ConstOrientEdgesVector;
typedef std::vector<OrientEdgeSPtr> OrientEdgesSPtrVector;
typedef std::vector<ConstOrientEdgeSPtr> ConstOrientEdgesSPtrVector;
typedef std::vector<EdgeOrient> EdgeOrientVector;
typedef std::vector<ConstEdgeOrient> ConstEdgeOrientVector;
typedef std::vector<EdgeSPtrOrient> EdgeSPtrOrientVector;
typedef std::vector<ConstEdgeSPtrOrient> ConstEdgeSPtrOrientVector;
// loops typedefs
typedef SPtr<MbLoop> LoopSPtr;
typedef SPtr<const MbLoop> ConstLoopSPtr;
@@ -168,48 +186,54 @@ typedef std::vector<LoopNumber> LoopNumberVector;
typedef std::vector<MbLoop *> LoopsVector;
typedef std::vector<const MbLoop *> ConstLoopsVector;
typedef std::vector<LoopSPtr> LoopsSPtrVector;
typedef std::vector<ConstLoopSPtr> ConstLoopsSPtrVector;
// faces typedefs
typedef SPtr<MbFace> FaceSPtr;
typedef SPtr<const MbFace> ConstFaceSPtr;
typedef SPtr<MbFace> FaceSPtr;
typedef SPtr<const MbFace> ConstFaceSPtr;
typedef std::pair<MbFace *, size_t> FaceIndex;
typedef std::pair<const MbFace *, size_t> ConstFaceIndex;
typedef std::pair<MbFace *, size_t> FaceIndex;
typedef std::pair<const MbFace *, size_t> ConstFaceIndex;
typedef std::pair<const MbFace*,const MbFace*> ConstFaceFacePair;
typedef std::vector<MbFace *> FacesVector;
typedef std::vector<const MbFace *> ConstFacesVector;
typedef std::vector<FaceSPtr> FacesSPtrVector;
typedef std::vector<ConstFaceSPtr> ConstFacesSPtrVector;
typedef std::vector<MbFace *> FacesVector;
typedef std::vector<const MbFace *> ConstFacesVector;
typedef std::pair<ConstFacesVector, ConstFacesVector> ConstFacesVectorPair;
typedef std::vector<FaceSPtr> FacesSPtrVector;
typedef std::vector<ConstFaceSPtr> ConstFacesSPtrVector;
typedef std::set<MbFace *> FacesSet;
typedef FacesSet::iterator FacesSetIt;
typedef FacesSet::const_iterator FacesSetConstIt;
typedef std::pair<FacesSetConstIt, bool> FacesSetRet;
typedef std::set<MbFace *> FacesSet;
typedef FacesSet::iterator FacesSetIt;
typedef FacesSet::const_iterator FacesSetConstIt;
typedef std::pair<FacesSetConstIt, bool> FacesSetRet;
typedef std::set<FaceSPtr> FacesSPtrSet;
typedef FacesSPtrSet::iterator FacesSPtrSetIt;
typedef FacesSPtrSet::const_iterator FacesSPtrSetConstIt;
typedef std::pair<FacesSPtrSetConstIt, bool> FacesSPtrSetRet;
typedef std::set<FaceSPtr> FacesSPtrSet;
typedef FacesSPtrSet::iterator FacesSPtrSetIt;
typedef FacesSPtrSet::const_iterator FacesSPtrSetConstIt;
typedef std::pair<FacesSPtrSetConstIt, bool> FacesSPtrSetRet;
typedef std::set<const MbFace *> ConstFacesSet;
typedef ConstFacesSet::iterator ConstFacesSetIt;
typedef ConstFacesSet::const_iterator ConstFacesSetConstIt;
typedef std::pair<ConstFacesSetConstIt, bool> ConstFacesSetRet;
typedef std::set<const MbFace *> ConstFacesSet;
typedef ConstFacesSet::iterator ConstFacesSetIt;
typedef ConstFacesSet::const_iterator ConstFacesSetConstIt;
typedef std::pair<ConstFacesSetConstIt, bool> ConstFacesSetRet;
typedef std::set<ConstFaceSPtr> ConstFacesSPtrSet;
typedef ConstFacesSPtrSet::iterator ConstFacesSPtrSetIt;
typedef ConstFacesSPtrSet::const_iterator ConstFacesSPtrSetConstIt;
typedef std::pair<ConstFacesSPtrSetConstIt, bool> ConstFacesSPtrSetRet;
typedef std::set<ConstFaceSPtr> ConstFacesSPtrSet;
typedef ConstFacesSPtrSet::iterator ConstFacesSPtrSetIt;
typedef ConstFacesSPtrSet::const_iterator ConstFacesSPtrSetConstIt;
typedef std::pair<ConstFacesSPtrSetConstIt, bool> ConstFacesSPtrSetRet;
typedef std::map<MbFace *, size_t> FaceIndexMap;
typedef std::map<const MbFace *, size_t> ConstFaceIndexMap;
typedef std::map<size_t, MbFace *> IndexFaceMap;
typedef std::map<size_t, const MbFace *> IndexConstFaceMap;
typedef std::map<MbFace *, size_t> FaceIndexMap;
typedef std::map<const MbFace *, size_t> ConstFaceIndexMap;
typedef std::map<size_t, MbFace *> IndexFaceMap;
typedef std::map<size_t, const MbFace *> IndexConstFaceMap;
typedef std::map<FaceSPtr *, size_t> FaceSPtrIndexMap;
typedef std::map<ConstFaceSPtr, size_t> ConstFaceSPtrIndexMap;
typedef std::map<size_t, FaceSPtr> IndexFaceSPtrMap;
typedef std::map<size_t, ConstFaceSPtr> IndexConstFaceSPtrMap;
} // namespace C3D
@@ -1445,26 +1469,28 @@ inline int ItemIndexCompare( const MbItemIndex * first, const MbItemIndex * seco
*/
// ---
class MATH_CLASS MbFace : public MbTopologyItem, public MbSyncItem {
public:
//------------------------------------------------------------------------------
/** \brief \ru Вспомогательные данные для грани.
\en Auxiliary data for a face. \~
\details \ru Вспомогательные данные служат для ускорения работы объекта.
\en Auxiliary data are used for fast calculations. \n \~
*/
// ---
struct MATH_CLASS MbFaceAuxiliaryData : public AuxiliaryData
{
MbFaceTemp * _temporal; ///< \ru Объект сопровождения грани (для скорости вычислений). \en An object for maintenance of a face (to improve calculations speed).
MbFaceAuxiliaryData() : AuxiliaryData(), _temporal( nullptr ) {}
MbFaceAuxiliaryData( const MbFaceAuxiliaryData & ) : _temporal( nullptr ) {}
virtual ~MbFaceAuxiliaryData();
};
protected:
MbSurface * surface; ///< \ru Поверхность грани (всегда не nullptr). \en Face surface (always not nullptr).
bool sameSense; ///< \ru Признак совпадения направления нормали грани с нормалью поверхности. \en An attribute of coincidence between the face normal direction and the surface normal direction.
RPArray<MbLoop> loops; ///< \ru Границы грани (первая граница должна быть внешней). \en Face boundaries (the first boundary should be external).
//------------------------------------------------------------------------------
/** \brief \ru Вспомогательные данные.
\en Auxiliary data. \~
\details \ru Вспомогательные данные служат для ускорения работы объекта.
\en Auxiliary data are used for fast calculations. \n \~
*/
// ---
struct MATH_CLASS MbFaceAuxiliaryData : public AuxiliaryData
{
MbFaceTemp * _temporal; ///< \ru Объект сопровождения грани (для скорости). \en An object for maintenance of a face (to improve speed).
MbFaceAuxiliaryData() : AuxiliaryData(), _temporal( nullptr ) {}
virtual ~MbFaceAuxiliaryData();
MbFaceAuxiliaryData( const MbFaceAuxiliaryData & ) : _temporal( nullptr ) {}
};
mutable CacheManager<MbFaceAuxiliaryData> * cache;
mutable CacheManager<MbFaceAuxiliaryData> * cache; ///< \ru Вспомогательные данные для грани. \en Auxiliary data for the face.
public:
/// \ru Конструктор по поверхности и ориентации нормали грани относительно нормали поверхности. \en Constructor by surface and orientation of face normal in relation to surface normal.
+13 -12
View File
@@ -117,18 +117,15 @@ void GetEdges( const FacesVector & faceSet, EdgesVector & edges );
// ---
class MATH_CLASS MbFaceShell : public MbTopItem, public MbSyncItem
{
protected:
RPArray<MbFace> faceSet; ///< \ru Множество граней. \en A set of faces.
bool closed; ///< \ru Признак замкнутости указывает на отсутствие края. \en An attribute of closedness indicates the absence of boundary.
public:
//------------------------------------------------------------------------------
/** \brief \ru Вспомогательные данные.
\en Auxiliary data. \~
\details \ru Вспомогательные данные служат для ускорения работы объекта.
\en Auxiliary data are used for fast calculations. \n \~
*/
// ---
struct MbFaceShellAuxiliaryData : public AuxiliaryData
/** \brief \ru Вспомогательные данные для множества граней.
\en Auxiliary data for a face set. \~
\details \ru Вспомогательные данные служат для ускорения работы объекта.
\en Auxiliary data are used for fast calculations. \n \~
*/
// ---
struct MATH_CLASS MbFaceShellAuxiliaryData : public AuxiliaryData
{
MbFaceSetTemp * _temporal; ///< \ru Объект сопровождения множества граней (для скорости). \en An object for maintenance of a set of faces (to improve speed).
MbFaceShellAuxiliaryData();
@@ -136,7 +133,11 @@ protected:
virtual ~MbFaceShellAuxiliaryData();
};
mutable CacheManager<MbFaceShellAuxiliaryData> * cache;
protected:
RPArray<MbFace> faceSet; ///< \ru Множество граней. \en A set of faces.
bool closed; ///< \ru Признак замкнутости указывает на отсутствие края. \en An attribute of closedness indicates the absence of boundary.
mutable CacheManager<MbFaceShellAuxiliaryData> * cache; ///< \ru Вспомогательные данные для множества граней. \en Auxiliary data for the face set.
public :
/// \ru Конструктор без параметров. \en Constructor without parameters.
+48 -4
View File
@@ -241,8 +241,16 @@ public :
bool MakePlaneCurves( RPArray<MbCurve> & curves, MbPlacement3D & place ) const;
/// \ru Дать кривую на поверхности, если пространственная кривая на поверхности (после использования вызывать DeleteItem на двумерные кривые). \en Get a surface curve if a space curve is on a surface (after the using call DeleteItem for two-dimensional curves)
bool MakeSurfaceCurves( RPArray<MbCurve> & curves, MbSurface *& surface ) const;
/// \ru Построить контуры из копий кривых. \en Construct contours of curves copies.
bool MakeCurves( RPArray<MbCurve3D> & ) const;
/** \brief \ru Построить контуры из копий кривых.
\en Construct contours of curves copies.\~
\details \ru Построить контуры из копий кривых. Новые контуры прицепляются к массиву curves.\n
\en Construct contours of curves copies. New contours are added to the curves array.\n\~
\param[out] curves - \ru Массив, к которуму добавляются построенные контуры.
\en Array, to which created contours are added.\~
\result \ru Возвращает true, если хоть 1 контур был создан.
\en Returns true if at least one contour is created. \~
*/
bool MakeCurves( RPArray<MbCurve3D> & curves ) const;
/// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array.
template <class CurvesVector>
void GetCurves( CurvesVector & ) const;
@@ -250,7 +258,6 @@ public :
bool IsNormalizeWire() const { return normal; }
/// \ru Переставить кривые и переориентировать ребра, создав связные цепочки с общими вершинами. \en Perform curves reposition and edges reorientation by creating connected chains with common vertices.
bool NormalizeWire( double precision = METRIC_REGION );
/** \brief \ru Отделение частей каркаса.
\en Detachment of frame parts \~
\details \ru Отделение частей каркаса с сохранением исходного объекта.
@@ -263,7 +270,44 @@ public :
\en Returns a number of frames in 'parts'. \~
*/
size_t CreateParts( RPArray<MbWireFrame> & parts );
/** \} */
/** \brief \ru Создать связные контуры с учётом толерантностей в вершинах рёбер каркаса.
\en Create connected contours according to vertex tolerances of the wire frame edges. \~
\details \ru Создать связные контуры с учётом толерантностей в вершинах рёбер каркаса
с сохранением исходного объекта. Если исходный каркас распадается на части,
то все части выдаются в качестве результата. Отличается от #MakeCurves тем, что
толерантности разные в вершинах рёбер.\n
\en Create connected contours according to vertex tolerances of the wire frame edges.
The initial object is preserved. If the initial frame is decomposed, all parts
will be given as a result. Difference from #MakeCurves is that tolerances are
different in each edge vertex instead of the global one.\n \~
\param[in] onlySmoothConnected - \ru Сегменты контуров должны быть состыкованы гладко (по G1).
\en Contours segments must be smoothly connected (by G1). \~
\param[out] contours - \ru Каркасы, полученные из frame.
\en Frames obtained from 'frame'. \~
\result \ru Возвращает true, если размер массива контуров увеличился.
\en Returns true if contours array size is increased. \~
*/
bool CreateContours ( c3d::SpaceCurvesSPtrVector & contours, bool onlySmoothConnected ) const;
/** \brief \ru Создать связные контуры с учётом толерантностей в вершинах рёбер каркаса.
\en Create connected contours according to vertex tolerances of the wire frame edges. \~
\details \ru Создать связные контуры с учётом толерантностей в вершинах рёбер каркаса
с сохранением исходного объекта. Если исходный каркас распадается на части,
то все части выдаются в качестве результата. Отличается от #MakeCurves тем, что
толерантности разные в вершинах рёбер.\n
\en Create connected contours according to vertex tolerances of the wire frame edges.
The initial object is preserved. If the initial frame is decomposed, all parts
will be given as a result. Difference from #MakeCurves is that tolerances are
different in each edge vertex instead of the global one.\n \~
\param[in] onlySmoothConnected - \ru Сегменты контуров должны быть состыкованы гладко (по G1).
\en Contours segments must be smoothly connected (by G1). \~
\param[out] contours - \ru Каркасы, полученные из frame.
\en Frames obtained from 'frame'. \~
\result \ru Возвращает true, если размер массива контуров увеличился.
\en Returns true if contours array size is increased. \~
*/
bool CreateContours ( c3d::WireFramesSPtrVector & contours, bool onlySmoothConnected ) const;
/// \ru Установить заданный флаг измененности для всех рёбер и вершин. \en Set flag of changes for all edges and vertices.
void SetOwnChangedThrough( MbeChangedType );
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.