diff --git a/C3d/Include/action_point.h b/C3d/Include/action_point.h index 4dae8eb..d593eef 100644 --- a/C3d/Include/action_point.h +++ b/C3d/Include/action_point.h @@ -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. \~ diff --git a/C3d/Include/action_surface_curve.h b/C3d/Include/action_surface_curve.h index 5fb0ae7..0b31aa8 100644 --- a/C3d/Include/action_surface_curve.h +++ b/C3d/Include/action_surface_curve.h @@ -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 & surfaceCurves ); + RPArray & 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> & 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 & resultCurves ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/alg_dimension.h b/C3d/Include/alg_dimension.h index 86fcc0f..914cb78 100644 --- a/C3d/Include/alg_dimension.h +++ b/C3d/Include/alg_dimension.h @@ -18,16 +18,16 @@ #include #include #include +#include +#include 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 MbItemItemDist { + template + 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 MbCurvCurvDist; +typedef MbItemItemDist MbCurvSurfDist; +typedef MbItemItemDist MbSurfCurvDist; +typedef MbItemItemDist 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 +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 MbMinMaxItemItemDistances { private : - SArray 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 > 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 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 > ); + 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 MbMinMaxCurvCurvDists; +typedef MbMinMaxItemItemDistances MbMinMaxCurvSurfDists; +typedef MbMinMaxItemItemDistances MbMinMaxSurfCurvDists; +typedef MbMinMaxItemItemDistances MbMinMaxSurfSurfDists; +DEPRECATE_DECLARE_REPLACE( MbMinMaxSurfSurfDists ) +typedef MbMinMaxItemItemDistances 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 MbMinMaxGridDistancesResults { +public: + MbMinMaxItemItemDistances allResults; ///< \ru Все результаты. \en All results. \~ + MbMinMaxItemItemDistances minResults; ///< \ru Результаты-минимумы. \en Results-minimums. \~ + MbMinMaxItemItemDistances 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 & results ); #endif // __ALG_DIMENSION_H diff --git a/C3d/Include/attr_color.h b/C3d/Include/attr_color.h index 43ce004..8ee992b 100644 --- a/C3d/Include/attr_color.h +++ b/C3d/Include/attr_color.h @@ -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 ) 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 ) ColorToVisual( const MbColor & cAttr, const MbVisual & vAttr ); + + //------------------------------------------------------------------------------ /** \brief \ru Преобразовать цвет по трём компонентам в uint32. \en Convert a color by 3 components in uint32. \~ diff --git a/C3d/Include/attribute_container.h b/C3d/Include/attribute_container.h index 4fa4517..233f2db 100644 --- a/C3d/Include/attribute_container.h +++ b/C3d/Include/attribute_container.h @@ -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 diff --git a/C3d/Include/cdet_data.h b/C3d/Include/cdet_data.h index 61105f7..683435f 100644 --- a/C3d/Include/cdet_data.h +++ b/C3d/Include/cdet_data.h @@ -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( 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 { diff --git a/C3d/Include/check_geometry.h b/C3d/Include/check_geometry.h index 93e74ca..e47b05b 100644 --- a/C3d/Include/check_geometry.h +++ b/C3d/Include/check_geometry.h @@ -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 diff --git a/C3d/Include/conv_exchange_settings.h b/C3d/Include/conv_exchange_settings.h index 126933b..fc74168 100644 --- a/C3d/Include/conv_exchange_settings.h +++ b/C3d/Include/conv_exchange_settings.h @@ -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 GetUserCharEncodingTransformer() const { return SPtr(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& ioPermissions ) const; + void GetIoPermissions( std::vector& 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 ProductIdentifierGenerator() const { return SPtr( new NameProductIdMaker() ); } /// \ru Получить пользовательский преобразователь строк. \en Get user string transformer. - virtual SPtr GetUserCharEncodingTransformer() const; + SPtr GetUserCharEncodingTransformer() const override; OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D ) }; // IConvertorProperty3D + //------------------------------------------------------------------------------ /** \brief \ru Преобразование строк с использованием установленной локали. \en Transform strings using the set locale. diff --git a/C3d/Include/conv_model_exchange.h b/C3d/Include/conv_model_exchange.h index 6d40597..f4ea4ee 100644 --- a/C3d/Include/conv_model_exchange.h +++ b/C3d/Include/conv_model_exchange.h @@ -384,7 +384,9 @@ namespace c3d { // \ru Очистить. \en Clear. inline void Clear() { - delete[] data; + if( data != nullptr ) + delete[] data; + data = nullptr; count = 0; } diff --git a/C3d/Include/cr_draft_solid.h b/C3d/Include/cr_draft_solid.h index 3ca0921..9d82a87 100644 --- a/C3d/Include/cr_draft_solid.h +++ b/C3d/Include/cr_draft_solid.h @@ -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 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 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 * 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 * 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 & 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 & 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( 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( 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 & 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( 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( partLines ) ) + , reverse ( rev ) + , step ( st ) + , rebuildFillets( _rebuildFillets ) { } @@ -108,17 +117,19 @@ public: const SArray & 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 ) { } diff --git a/C3d/Include/creator.h b/C3d/Include/creator.h index 6a25356..f9d42a3 100644 --- a/C3d/Include/creator.h +++ b/C3d/Include/creator.h @@ -423,7 +423,7 @@ public : \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ - bool CreateWireFrame( SPtr & frame, MbeCopyMode sameShell ); + bool CreateWireFrame( SPtr & 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 & frame, MbeCopyMode sameShell ); + bool CreatePointFrame( SPtr & 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 & mesh, MbeCopyMode sameShell ); + bool CreateMesh( SPtr & 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 diff --git a/C3d/Include/cur_b_spline.h b/C3d/Include/cur_b_spline.h index 0e54402..e002627 100644 --- a/C3d/Include/cur_b_spline.h +++ b/C3d/Include/cur_b_spline.h @@ -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 diff --git a/C3d/Include/cur_contour3d.h b/C3d/Include/cur_contour3d.h index d14f12b..6426d7f 100644 --- a/C3d/Include/cur_contour3d.h +++ b/C3d/Include/cur_contour3d.h @@ -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 void GetSegments( CurvesVector & curves ) const; ///< \ru Получить кривые контура. \en Get contour segments. diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index be8840e..82a2fe3 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -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 diff --git a/C3d/Include/cur_nurbs3d.h b/C3d/Include/cur_nurbs3d.h index 0b7ba28..1c93e64 100644 --- a/C3d/Include/cur_nurbs3d.h +++ b/C3d/Include/cur_nurbs3d.h @@ -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. diff --git a/C3d/Include/dxf_data.h b/C3d/Include/dxf_data.h index 41825a2..b4a45d4 100644 --- a/C3d/Include/dxf_data.h +++ b/C3d/Include/dxf_data.h @@ -95,7 +95,7 @@ private: \en The Loop is declared inside DXFFace. \~ \ingroup DXF_Exchange */ - class CONV_CLASS DXFLoop { + class DXFLoop { public: SArray points; ///< \ru Набор точек. \en Point set. diff --git a/C3d/Include/func_composite_function.h b/C3d/Include/func_composite_function.h new file mode 100644 index 0000000..fff47f7 --- /dev/null +++ b/C3d/Include/func_composite_function.h @@ -0,0 +1,328 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Составная функция. + \en Composite Function. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __FUNC_COMPOSITE_FUNCTION_H +#define __FUNC_COMPOSITE_FUNCTION_H + + +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \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 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 + 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 & 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 + 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 + 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 +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( initSegment ); + MbCompositeFunction * contour = const_cast( 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( &seg->Duplicate() ); + segments.push_back( segment ); + segment->AddRef(); + } + } + } + else { + MbFunction * segment = same ? const_cast( initSegment ) : static_cast( &initSegment->Duplicate() ); + segments.push_back( segment ); + segment->AddRef(); + } + } + } + CalculateParamLengthAndClosed(); + } +} + + +//------------------------------------------------------------------------------ +// \ru Инициализация по набору функций. \en Initialize by functions. +// --- +template +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( initSegment ); + MbCompositeFunction * contour = const_cast( 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( &seg->Duplicate() ); + segments.push_back( segment ); + segment->AddRef(); + } + } + } + else { + MbFunction * segment = sames ? const_cast( initSegment ) : static_cast( &initSegment->Duplicate() ); + segments.push_back( segment ); + segment->AddRef(); + } + } + } + ::DecRefItems( initSegments ); + CalculateParamLength(); + closed = cls; + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +// \ru Получить функции. \en Get segments. +// --- +template +void MbCompositeFunction::GetSegments( CurvesVector & funcs ) const +{ + size_t segmentsCnt = segments.size(); + funcs.reserve( funcs.size() + segmentsCnt ); + SPtr function; + for ( size_t k = 0; k < segmentsCnt; ++k ) { + function = const_cast(segments[k]); + if ( function != nullptr ) { + funcs.push_back( function ); + ::DetachItem( function ); + } + } +} + + +#endif // __FUNC_COMPOSITE_FUNCTION_H diff --git a/C3d/Include/func_const_function.h b/C3d/Include/func_const_function.h index 2df608a..20529c9 100644 --- a/C3d/Include/func_const_function.h +++ b/C3d/Include/func_const_function.h @@ -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 diff --git a/C3d/Include/function.h b/C3d/Include/function.h index 4e0dc47..d1232c5 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -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. diff --git a/C3d/Include/gc_api.h b/C3d/Include/gc_api.h index bc55225..d1fa809 100644 --- a/C3d/Include/gc_api.h +++ b/C3d/Include/gc_api.h @@ -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) */ diff --git a/C3d/Include/gce_api.h b/C3d/Include/gce_api.h index a489f9a..e8e008c 100644 --- a/C3d/Include/gce_api.h +++ b/C3d/Include/gce_api.h @@ -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 Ограничение "Точка на участке кривой по коэффициенту его длины". diff --git a/C3d/Include/gce_types.h b/C3d/Include/gce_types.h index b563efb..8483182 100644 --- a/C3d/Include/gce_types.h +++ b/C3d/Include/gce_types.h @@ -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 diff --git a/C3d/Include/gcm_api.h b/C3d/Include/gcm_api.h index e623b65..a5093f0 100644 --- a/C3d/Include/gcm_api.h +++ b/C3d/Include/gcm_api.h @@ -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. \~ diff --git a/C3d/Include/gcm_constraint.h b/C3d/Include/gcm_constraint.h index 3fea85f..14be7c2 100644 --- a/C3d/Include/gcm_constraint.h +++ b/C3d/Include/gcm_constraint.h @@ -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) ) diff --git a/C3d/Include/gcm_manager.h b/C3d/Include/gcm_manager.h index 0630064..0bbf13b 100644 --- a/C3d/Include/gcm_manager.h +++ b/C3d/Include/gcm_manager.h @@ -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) 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 diff --git a/C3d/Include/gcm_types.h b/C3d/Include/gcm_types.h index 88e27a5..bcb4c05 100644 --- a/C3d/Include/gcm_types.h +++ b/C3d/Include/gcm_types.h @@ -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 } diff --git a/C3d/Include/iges_structure.h b/C3d/Include/iges_structure.h index 3967be8..5f52978 100644 --- a/C3d/Include/iges_structure.h +++ b/C3d/Include/iges_structure.h @@ -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& ); }; diff --git a/C3d/Include/io_tape.h b/C3d/Include/io_tape.h index 912cf3d..603c003 100644 --- a/C3d/Include/io_tape.h +++ b/C3d/Include/io_tape.h @@ -233,8 +233,7 @@ class writer; \details \ru Типы регистрации потоковых объектов. \n \en Types of stream objects registration. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- enum RegistrableRec { noRegistrable, ///< \ru Нерегистрируемый объект. \en Unregistrable object. registrable ///< \ru Регистрируемый объект. \en Registrable object. @@ -247,8 +246,7 @@ enum RegistrableRec { \details \ru Типы регистрации потоковых объектов. \n \en Types of stream objects registration. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- enum TapeInit { tapeInit ///< \ru По умолчанию. \en By default. }; @@ -260,16 +258,14 @@ enum TapeInit { \details \ru Упакованное имя одного класса - для набора массива потоковых классов в TapeClass. \n \en Packed name of one class - for array of stream classes in TapeClass. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS ClassDescriptor { protected: uint16 val; ///< \ru Хэш имени класса. \en The class name hash. MbUuid appID_; ///< \ru Дополнительный идентификатор приложения. \en Additional application identifier. - private: - /// Признак записи appID + /// \ru Признак записи appID. \en AppID record flag. static const uint16 rwIdFlag; public: @@ -291,24 +287,18 @@ public: /// \ru Оператор равенства. \en The equality operator. bool operator == ( const ClassDescriptor & other ) const; - /// \ru Оператор неравенства. \en The inequality operator. - bool operator!=( const ClassDescriptor & other ) const; - + bool operator != ( const ClassDescriptor & other ) const; /// \ru Оператор сравнения. \en Comparison operator. bool operator < (const ClassDescriptor & other ) const; - /// \ru Оператор сравнения. \en Comparison operator. bool operator > ( const ClassDescriptor & other ) const; - #ifdef C3D_DEBUG /// \ru Оператор доступа. \en An access operator. - operator uint16() const { return val; } + operator uint16() const { return val; } #endif - /// \ru Оператор записи. \en Write operator. void Write( writer & out ); - /// \ru Оператор чтения. \en Read operator. bool Read( reader & in ); }; @@ -320,8 +310,7 @@ public: \details \ru Базовый класс для потоковых классов. \n \en Base class for stream classes. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- #ifndef ENABLE_MEMORY_LEAKS_CHECK class MATH_CLASS TapeBase { #else @@ -338,19 +327,18 @@ public: /// \ru Деструктор. \en Destructor. virtual ~TapeBase(); +public: /// \ru Является ли потоковый класс регистрируемым. \en Whether the stream class is registrable. - RegistrableRec GetRegistrable() const; + RegistrableRec GetRegistrable() const; /// \ru Установить состояние регистрации потокового класса. \en Set the state of registration of the stream class. - void SetRegistrable( RegistrableRec regs = registrable ) const; + void SetRegistrable( RegistrableRec regs = registrable ) const; /// \ru Получить дескриптор класса //virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const { return ClassDescriptor( ::pureName(typeid(*this).name()) ); } virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const = 0; - /// \ru Получить имя класса. \en Get the class name. - virtual const char * GetPureName( const VersionContainer & ) const; - + virtual const char * GetPureName( const VersionContainer & ) const; /// \ru Принадлежит ли объект к регистрируемому семейству. \en Whether the object belongs to a registrable family. - virtual bool IsFamilyRegistrable() const; + virtual bool IsFamilyRegistrable() const; private: /// \ru Функция-пустышка для обеспечения полиморфизма данного класса и его наследников. \en Dummy function for providing polymorphism of the given class and its descendants. @@ -371,16 +359,14 @@ typedef TapeBase * (CALL_DECLARATION * BUILD_FUNC) ( void ); \details \ru Шаблон функции преобразования из указателя на TapeBase к указателю на класс. \n \en Template of function of conversion from a pointer to TapeBase to a pointer to the class. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- typedef void * (CALL_DECLARATION * CAST_FUNC) ( const TapeBase * ); //---------------------------------------------------------------------------------------- /**\ru Шаблон функции чтения экземпляра. \en Template of instance reading function. \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- typedef void (CALL_DECLARATION * READ_FUNC) ( reader & in, void * /*obj*/ ); //---------------------------------------------------------------------------------------- @@ -396,8 +382,7 @@ typedef void (CALL_DECLARATION * WRITE_FUNC) ( writer & out, void * /*obj*/ ); \en "Wrapper" for one stream class ( not instance! ). Stores packed class name and addresses of functions necessary while reading/writing. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS TapeClass { protected: ClassDescriptor hashValue; ///< \ru Упакованное имя класса. \en Packed class name. @@ -431,8 +416,7 @@ OBVIOUS_PRIVATE_COPY( TapeClass ) \details \ru Массив для регистрации объектов при чтении/записи. \n \en Array for object registration while reading/writing. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- class MATH_CLASS TapeRegistrator { public: @@ -465,7 +449,6 @@ public: ///< \ru Вставить элемент с определенным индексом. \en Insert an element with defined index. void AddAt( const TapeBase * e, size_t ind ); - /// \ru Добавить объект в массив. \en Add the object to the array. size_t Add( const TapeBase * e ); @@ -500,14 +483,14 @@ public: OBVIOUS_PRIVATE_COPY( TapeRegistrator ) }; + //---------------------------------------------------------------------------------------- -/** \brief \ru Массив для регистрации объектов с сохраненим информации о позиции чтения/записи. +/** \brief \ru Массив для регистрации объектов с сохранениeм информации о позиции чтения/записи. \en Array for registration of objects with information about reading/writing position. \~ - \details \ru Массив для регистрации объектов с сохраненим информации о позиции чтения/записи. \n + \details \ru Массив для регистрации объектов с сохранениeм информации о позиции чтения/записи. \n \en Array for registration of objects with information about reading/writing position. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- class MATH_CLASS TapeRegistratorEx : public TapeRegistrator { public: typedef std::map ClusterIndexMap; @@ -525,15 +508,12 @@ public: TapeRegistratorEx(); /// \ru Выдать указатель на зарегистрированный объект по заданной позиции в кластере. - /// \en Get the pointer ещ the registered object by the position in the cluster. + /// \en Get the pointer of the registered object by the position in the cluster. virtual TapeBase * Get ( const ClusterReference & ref ) const; - /// \ru Выдать позицию в кластере по заданному индексу. \en Get position in the cluster by given index. virtual ClusterReference GetClusterRef ( size_t ind ) const; - /// \ru Добавить позицию объекта в кластере. \en Add the object position in the cluster. virtual void AddClusterRef( size_t ind, const ClusterReference & ref ); - /// \ru Очистить массив зарегистрированных объектов. \en Flush the array of registered objects. virtual void FlushRegistered(); /// \ru Очистить зарегистрированный объект \en Flush the registered object @@ -549,8 +529,7 @@ OBVIOUS_PRIVATE_COPY( TapeRegistratorEx ) \details \ru Cпособы записи указателей. \n \en Methods of writing pointers. \n \~ \ingroup Base_Tools_IO -*/ -//--- +*/ //--- enum TapePointerType { tpt_Null = 0x00, ///< \ru Нулевой указатель. \en Null pointer. tpt_Indexed16 = 0x01, ///< \ru Индекс указателя в массиве регистрации (2 байта). \en Pointer index in the registration array (2 bytes). @@ -570,8 +549,7 @@ enum TapePointerType { \details \ru Базовый класс потока для реализации чтения и записи. \n \en The base class of the stream for implementation of reading and writing. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS tape { protected: iobuf_Seq & buf; ///< \ru Буфер для данных. \en Buffer for data. @@ -579,10 +557,9 @@ protected: uint8 level; ///< \ru Уровень вложенности при чтении/записи. \en Nesting level while reading/writing. TapeRegistrator & registrator; ///< \ru Структура для регистрации записанных/прочитанных адресов. \en Structure for registration of written/read addresses. mutable ProgressBarWrapper * progress; ///< \ru Индикатор прогресса. \en Progress indicator. - private: - uint8 ownBuf; ///< \ru Владеет ли буфером. \en Whether it owns the buffer. - bool ownReg; ///< \ru Признак владения регистратором. + uint8 ownBuf; ///< \ru Владеет ли буфером. \en Whether it owns the buffer. + bool ownReg; ///< \ru Признак владения регистратором. \en Whether it owns of the registrar. public: /// \ru Тип объекта. \en An object type. @@ -601,9 +578,8 @@ public: /// \ru Получить доступ к буферу. \en Get access to the buffer. const iobuf_Seq & GetIOBuffer() const; - /// \ru Получить доступ к буферу. \en Get access to the buffer. - iobuf_Seq & GetIOBuffer(); + iobuf_Seq & GetIOBuffer(); /// \ru Узнать режим работы буфера. \en Get the buffer mode. uint8 mode() const; //AR getMode @@ -622,11 +598,11 @@ public: VERSION AppVersion( size_t ind = -1 ) const; /// \ru Получить доступ к контейнеру версий. \en Get access to the version container. - const VersionContainer & GetVersionsContainer() const; + const VersionContainer & GetVersionsContainer() const; /// \ru Установить версию открытого файла. \en Set the version of open file. - void SetVersionsContainer( const VersionContainer & vers ) const; + void SetVersionsContainer( const VersionContainer & vers ) const; /// \ru Установить версию хранилища. \en Set the storage version. - VERSION SetStorageVersion( VERSION v ); + VERSION SetStorageVersion( VERSION v ); /// \ru Свежий ли буфер? \en Is the buffer fresh? int fresh() const; @@ -652,6 +628,7 @@ public: size_t GetMaxRegisteredCount() const; ///< \ru Зарезервировать память под n объектов. \en Reserve memory for n objects. void ReserveRegistered( size_t n ); + /// \ru Владеем ли буфером? \en Do we own the buffer? bool IsOwnBuffer() const; /// \ru Установить флаг владения буфером. \en Set the flag of buffer ownership. @@ -684,20 +661,18 @@ private: /// \ru Открыть системный файл в соответствующем режиме (чтение или запись). \en Open the system file in the appropriate mode (reading or writing). void init( uint8 om ); -private: - tape ( const tape & ); // \ru запрещено \en forbidden - void operator = ( const tape & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( tape ) }; #pragma pack( pop ) + //---------------------------------------------------------------------------------------- /** \brief \ru Поток для чтения. \en Stream for reading. \~ \details \ru Поток для чтения. \n \en Stream for reading. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS reader : public virtual tape { public: typedef std::unique_ptr reader_ptr; @@ -707,14 +682,12 @@ protected: /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om, TapeRegistrator & reg ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( membuf & sb, bool openSys, uint8 om, TapeRegistrator & reg ); public: /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE reader( iobuf_Seq & buf, uint16 om ); @@ -723,7 +696,6 @@ public: public: /// \ru Создать читатель для последовательного буфера. \en Create reader for iobuf_Seq. static reader_ptr CreateReader ( std::unique_ptr buf, uint16 om ); - /// \ru Создать читатель для буфера в памяти. \en Create reader for membuf. static reader_ptr CreateMemReader ( membuf & sb, uint8 om ); @@ -777,11 +749,10 @@ protected: /// \ru Читаем индекс объекта. \en Read object index. size_t ReadObjectIndex(); -private: - reader ( const reader & ); // \ru запрещено \en forbidden - reader & operator = ( const reader & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( reader ) }; + //---------------------------------------------------------------------------------------- /** \brief \ru Индикатор прогресса в области видимости для reader. \en Scoped progress indicator for reader. \~ @@ -793,8 +764,7 @@ private: When exiting the scope, the current progress indicator is released and the parent progress indicator is set. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS ScopedReadProgress { SPtr _progress; @@ -807,7 +777,7 @@ public: private: ScopedReadProgress(); - void operator = ( const ScopedReadProgress& ); + void operator = ( const ScopedReadProgress & ); }; //---------------------------------------------------------------------------------------- @@ -816,13 +786,12 @@ private: \details \ru Поток для чтения с возможностью чтения из разных FileSpaces по заданным позициям. \n \en Stream for reading from several FileSpace by given positions in clusters. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS reader_ex : public reader { - std::unique_ptr m_tree; - uint32 m_lastError; - bool m_fullRead; + std::unique_ptr m_tree; + uint32 m_lastError; + bool m_fullRead; protected: /// \ru Конструктор. \en Constructor. reader_ex( iobuf_Seq & buf, bool ownbuf, bool openSys, uint16 om ); @@ -876,19 +845,17 @@ protected: /// \ru Зарегистрировать объект. \en Register the object. virtual void RegisterObject( TapeBase * obj, uint8 regId, ClusterReference ref = ClusterReference() ); -private: - reader_ex ( const reader_ex & ); // \ru запрещено \en forbidden - reader_ex & operator = ( const reader_ex & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( reader_ex ) }; + //---------------------------------------------------------------------------------------- /** \brief \ru Поток для записи. \en Stream for writing. \~ \details \ru Поток для записи. \n \en Stream for writing. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS writer : public virtual tape { public: typedef std::unique_ptr writer_ptr; @@ -962,23 +929,20 @@ protected: /// Записать индекс объекта void WriteObjectIndex ( size_t index ); -private: - writer ( const writer & ); // \ru запрещено \en forbidden - writer & operator = ( const writer & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( writer ) }; //---------------------------------------------------------------------------------------- /** \brief \ru Поток для записи в разные FileSpaces. -\en Stream for writing to several FileSpaces. \~ -\details \ru Поток для записи в разные FileSpaces. \n -\en Stream for writing to several FileSpaces. \n \~ -\ingroup Base_Tools_IO -*/ -// --- + \en Stream for writing to several FileSpaces. \~ + \details \ru Поток для записи в разные FileSpaces. \n + \en Stream for writing to several FileSpaces. \n \~ + \ingroup Base_Tools_IO +*/ // --- class MATH_CLASS writer_ex : public writer { - std::unique_ptr m_tree; - ClusterReference m_catalogRef; + std::unique_ptr m_tree; + ClusterReference m_catalogRef; protected: /// \ru Конструктор. \en Constructor. writer_ex ( iobuf_Seq & buf, bool ownBuf, bool openSys, uint16 om ); @@ -986,7 +950,6 @@ protected: public: /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer_ex ( membuf & sb, uint8 om ); - /// \ru Конструктор. \en Constructor. \~ \deprecated \ru Метод устарел. \en The method is deprecated. DEPRECATE_DECLARE writer_ex ( iobuf_Seq & buf, uint16 om ); @@ -995,16 +958,14 @@ public: public: /// \ru Создать писатель для последовательного буфера. \en Create writer for iobuf_Seq. static std::unique_ptr CreateWriterEx( std::unique_ptr buf, uint16 om ); - /// \ru Создать писатель для буфера в памяти. \en Create writer for membuf. static std::unique_ptr CreateMemWriterEx( membuf & sb, uint8 om ); public: /// \ru Записать дерево модели. \en Write the model tree. - virtual void WriteModelCatalog(); + virtual void WriteModelCatalog(); /// \ru Выдать следующую позицию записи. \en Get next writing position. - virtual ClusterReference GetNextWritePosition (); - + virtual ClusterReference GetNextWritePosition (); /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. virtual const c3d::IModelTree * GetModelTree () const; @@ -1020,19 +981,17 @@ protected: /// \ru Является ли объект регистрируемым. \en Whether the object is registrable. virtual bool IsRegistrable( const TapeBase * mem ); -private: - writer_ex ( const writer_ex & ); // \ru запрещено \en forbidden - writer_ex & operator = ( const writer_ex & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( writer_ex ) }; + //---------------------------------------------------------------------------------------- /** \brief \ru Поток для чтения и записи. \en Stream for reading and writing. \~ \details \ru Поток для чтения и записи. \n \en Stream for reading and writing. \n \~ \ingroup Base_Tools_IO -*/ -// --- +*/ // --- class MATH_CLASS rw : public writer, public reader { public: typedef std::unique_ptr rw_ptr; @@ -1052,19 +1011,17 @@ private: /// \ru Конструктор. \en Constructor. rw( iobuf_Seq & sb, bool ownBuf, bool openSys, uint16 om, TapeRegistrator * reg ); - rw ( const rw & ); // \ru запрещено \en forbidden - rw & operator = ( const rw & ); // \ru запрещено \en forbidden +OBVIOUS_PRIVATE_COPY( rw ) }; //---------------------------------------------------------------------------------------- /** \brief \ru Менеджер потоков. -\en Stream manager. \~ -\details \ru Менеджер потоков чтения и записи. \n -\en Reading and writing streams manager. \n \~ -\ingroup Base_Tools_IO -*/ -// --- + \en Stream manager. \~ + \details \ru Менеджер потоков чтения и записи. \n + \en Reading and writing streams manager. \n \~ + \ingroup Base_Tools_IO +*/ // --- class MATH_CLASS TapeManager { private: //static TPointer & StaticTapeManager(); @@ -1109,10 +1066,10 @@ private: //---------------------------------------------------------------------------------------- /** \brief \ru Массив регистрации потоковых классов. -\en Array of stream classes registration. \~ -\details \ru Массив регистрации потоковых классов TapeClass. \n -\en Array of stream TapeClass classes registration. \n \~ -\ingroup Base_Tools_IO + \en Array of stream classes registration. \~ + \details \ru Массив регистрации потоковых классов TapeClass. \n + \en Array of stream TapeClass classes registration. \n \~ + \ingroup Base_Tools_IO */ // --- struct TapeClassContainer @@ -1195,8 +1152,8 @@ void WriteVBase( writer & out, const Base * base ) //---------------------------------------------------------------------------------------- /** - \brief \ru Дружественные операторы чтения и записи указателей и ссылок. - \en Friend operators of reading and writing of pointers and references. \~ + \brief \ru Дружественные операторы чтения и записи указателей и ссылок. + \en Friend operators of reading and writing of pointers and references. \~ \ingroup Base_Tools_IO */ // --- @@ -1345,7 +1302,7 @@ void WriteVBase( writer & out, const Base * base ) by creating variable r ## Class of type TapeClass (and in constructor of TapeClass addition to array of stream classes is performed). - Symbol ## is a directive for preprocessor about the necessity of "glueing" + Symbol ## is a directive for preprocessor about the necessity of "gluing" of the current identifier with the next one. \~ \ingroup Base_Tools_IO */ @@ -1976,7 +1933,8 @@ inline const char * pureName( const char * name ) //---------------------------------------------------------------------------------------- /// \ru Упаковать строку(имя класса) в uint16. \en Pack the string (class name) into uint16. \~ \ingroup Base_Tools_IO // --- -inline uint16 hash( const char * name ) +inline +uint16 hash( const char * name ) { const uint16 * c = (const uint16 *)name; @@ -2001,7 +1959,8 @@ inline uint16 hash( const char * name ) // \ru Длина строки не может превышать SYS_MAX_UINT16 - 1 \en The string length cannot exceed SYS_MAX_UINT16 - 1 // \ru Созданную строку кто-то потом должен уничтожить (через delete[]) \en Created string must be deleted by someone then (using delete[]) // --- -inline reader & __readChar( reader & ps, char *& s ) +inline +reader & __readChar( reader & ps, char *& s ) { s = nullptr; @@ -2049,7 +2008,8 @@ inline reader & __readChar( reader & ps, char *& s ) // \ru Длина строки не может превышать SYS_MAX_UINT32 - 1 \en The string length cannot exceed SYS_MAX_UINT32 - 1 // \ru Созданную строку кто-то потом должен уничтожить \en Created string should be deleted by someone then // --- -inline reader & __readWchar( reader & ps, TCHAR * & s ) +inline +reader & __readWchar( reader & ps, TCHAR * & s ) { s = nullptr; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read if ( ps.good() ) @@ -2104,7 +2064,8 @@ inline reader & __readWchar( reader & ps, TCHAR * & s ) // \ru Длина строки не может превышать SYS_MAX_UINT32 - 1 \en The string length cannot exceed SYS_MAX_UINT32 - 1 // \ru Созданную строку кто-то потом должен уничтожить \en Created string should be deleted by someone then // --- -inline reader & __readWcharT( reader & ps, wchar_t * & s ) +inline +reader & __readWcharT( reader & ps, wchar_t * & s ) { s = nullptr; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read if ( ps.good() ) @@ -2149,7 +2110,8 @@ inline reader & __readWcharT( reader & ps, wchar_t * & s ) // --- #ifndef DISABLE_RWTCHAR #ifdef _UNICODE -inline reader & operator >> ( reader & ps, char *& s ) +inline +reader & operator >> ( reader & ps, char *& s ) { return __readChar( ps, s ); } @@ -2162,7 +2124,8 @@ inline reader & operator >> ( reader & ps, char *& s ) // --- #ifndef DISABLE_RWTCHAR #ifdef _UNICODE -inline writer & operator << ( writer & ps, const char * s ) +inline +writer & operator << ( writer & ps, const char * s ) { return ps.__writeChar( s ); } @@ -2172,10 +2135,11 @@ inline writer & operator << ( writer & ps, const char * s ) //---------------------------------------------------------------------------------------- /// \ru Чтение WCHAR строки из потока. \en Reading of WCHAR string from the stream. \~ \ingroup Base_Tools_IO // \ru И нулевой указатель и пустая строка возвращаются как нулевой указатель! \en Both null pointer and an empty string are returned as null pointer! -// \ru OV длина строки не может превышать SYS_MAX_UINT32 - 1 \en OV length of string can't exceed SYS_MAX_UINT32 - 1 +// \ru длина строки не может превышать SYS_MAX_UINT32 - 1 \en length of string can't exceed SYS_MAX_UINT32 - 1 // --- #ifndef DISABLE_RWTCHAR -inline reader & operator >> ( reader & ps, TCHAR *& s ) +inline +reader & operator >> ( reader & ps, TCHAR *& s ) { return __readWchar( ps, s ); } @@ -2187,7 +2151,8 @@ inline reader & operator >> ( reader & ps, TCHAR *& s ) // \ru длина строки не может превышать SYS_MAX_UINT32 - 1 \en string length can't exceed SYS_MAX_UINT32 - 1 // --- #ifndef DISABLE_RWTCHAR -inline writer & operator << ( writer & ps, const TCHAR * s ) +inline +writer & operator << ( writer & ps, const TCHAR * s ) { return ps.__writeWchar( s ); } @@ -2207,7 +2172,8 @@ inline writer & operator << ( writer & ps, const TCHAR * s ){ return ps.__write //---------------------------------------------------------------------------------------- /// \ru Запись bool в поток. \en Writing bool to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, bool i ) +inline +writer & operator << ( writer & ps, bool i ) { //unsigned char val = i; uint8 val = i ? 1 : 0; @@ -2219,7 +2185,8 @@ inline writer & operator << ( writer & ps, bool i ) //---------------------------------------------------------------------------------------- /// \ru Чтение bool в поток. \en Reading of bool to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, bool & i ) +inline +reader & operator >> ( reader & ps, bool & i ) { if ( IsVersion16bit( ps.MathVersion() ) ) { @@ -2239,7 +2206,8 @@ inline reader & operator >> ( reader & ps, bool & i ) // \ru оператор записи для типов: int (не поддерживает int32, long, LONG - для них есть своя реализация) \en write operator for types: int (doesn't support int32, long, LONG - there is a separate implementation for them) // \ru поддерживает запись в 32 и 16-битный формат файла \en supports writing to 32- and 16-bit format of file // --- -inline writer & operator << ( writer & ps, signed int i ) +inline +writer & operator << ( writer & ps, signed int i ) { #ifdef C3D_WINDOWS //_MSC_VER if ( IsVersion16bit( ps.MathVersion() ) ) @@ -2271,7 +2239,9 @@ inline writer & operator << ( writer & ps, signed int i ) // \ru оператор записи для типов: uint (не поддерживает uint32, ulong - для них есть своя реализация) \en write operator for types: uint (doesn't support uint32, ulong - there is a separate implementation for them) // \ru поддерживает запись в 32 и 16-битный формат файла \en supports writing to 32- and 16-bit format of file // --- -inline writer & operator << ( writer & ps, unsigned int i ) { +inline +writer & operator << ( writer & ps, unsigned int i ) +{ #ifdef C3D_WINDOWS //_MSC_VER if ( IsVersion16bit( ps.MathVersion() ) ) { // \ru чтение из 16-битной версии файла \en reading from 16-bit version of file @@ -2301,7 +2271,8 @@ inline writer & operator << ( writer & ps, unsigned int i ) { // \ru оператор чтения для типов: int (не поддерживает int32, long, LONG - для них есть своя реализация) \en read operator for types: int (doesn't support int32, long, LONG - there is a separate implementation for them) // \ru поддерживает чтение из 32 и 16-битного формата файла \en supports reading from 32- and 16-bit format of file // --- -inline reader & operator >> ( reader & ps, signed int & i ) +inline +reader & operator >> ( reader & ps, signed int & i ) { #ifdef C3D_WINDOWS //_MSC_VER // Linux identical int/uint and int32/uint32 if ( IsVersion16bit( ps.MathVersion() ) ) { @@ -2335,7 +2306,8 @@ inline reader & operator >> ( reader & ps, signed int & i ) // \ru оператор чтения для типов: uint (не поддерживает uint32, ulong - для них есть своя реализация) \en read operator for types: uint (doesn't support uint32, ulong - there is a separate implementation for them) // \ru поддерживает чтение из 32 и 16-битного формата файла \en supports reading from 32- and 16-bit format of file // --- -inline reader & operator >> ( reader & ps, unsigned int & i ) +inline +reader & operator >> ( reader & ps, unsigned int & i ) { #ifdef C3D_WINDOWS //_MSC_VER // Linux identical int/uint and int32/uint32 if ( IsVersion16bit( ps.MathVersion() ) ) @@ -2373,7 +2345,8 @@ inline reader & operator >> ( reader & ps, unsigned int & i ) #ifdef C3D_WINDOWS //_MSC_VER // Linux identical int/uint and int32/uint32 // \ru ВНИМАНИЕ!!! В целях совместимости данных для задач скомпилированных под Windows и Linux \en NOTE!!! To provide data compatibility for tasks compiled for Windows and Linux // \ru ЗАПРЕЩАЕТСЯ использовать тип данных long и unsigned long. Используйте int32 и uint32 \en IT IS FORBIDDEN to use long and unsigned long data types. Use int32 and uint32 -inline writer & operator << ( writer & ps, int32 l ) +inline +writer & operator << ( writer & ps, int32 l ) { ps.writeBytes( &l, sizeof(l) ); return ps; @@ -2389,7 +2362,8 @@ inline writer & operator << ( writer & ps, int32 l ) #ifdef C3D_WINDOWS // Linux identical int/uint and int32/uint32 // \ru ВНИМАНИЕ!!! В целях совместимости данных для задач скомпилированных под Windows и Linux \en NOTE!!! To provide data compatibility for tasks compiled for Windows and Linux // \ru ЗАПРЕЩАЕТСЯ использовать тип данных long и unsigned long. Используйте int32 и uint32 \en IT IS FORBIDDEN to use long and unsigned long data types. Use int32 and uint32 -inline writer& operator << ( writer& ps, uint32 l ) +inline +writer & operator << ( writer & ps, uint32 l ) { ps.writeBytes( &l, sizeof(l) ); return ps; @@ -2405,7 +2379,8 @@ inline writer& operator << ( writer& ps, uint32 l ) #ifdef C3D_WINDOWS //_MSC_VER // Linux identical int/uint and int32/uint32 // \ru ВНИМАНИЕ!!! В целях совместимости данных для задач скомпилированных под Windows и Linux \en NOTE!!! To provide data compatibility for tasks compiled for Windows and Linux // \ru ЗАПРЕЩАЕТСЯ использовать тип данных long и unsigned long. Используйте int32 и uint32 \en IT IS FORBIDDEN to use long and unsigned long data types. Use int32 and uint32 -inline reader& operator >> ( reader& ps, int32 & l ) +inline +reader & operator >> ( reader & ps, int32 & l ) { size_t size = sizeof(int32); if ( !ps.readBytes(&l, size) ) @@ -2424,7 +2399,8 @@ inline reader& operator >> ( reader& ps, int32 & l ) #ifdef C3D_WINDOWS //_MSC_VER // Linux identical int/uint and int32/uint32 // \ru ВНИМАНИЕ!!! В целях совместимости данных для задач скомпилированных под Windows и Linux \en NOTE!!! To provide data compatibility for tasks compiled for Windows and Linux // \ru ЗАПРЕЩАЕТСЯ использовать тип данных long и unsigned long. Используйте int32 и uint32 \en IT IS FORBIDDEN to use long and unsigned long data types. Use int32 and uint32 -inline reader& operator >> ( reader& ps, uint32 & l ) +inline +reader & operator >> ( reader & ps, uint32 & l ) { size_t size = sizeof(uint32); if ( !ps.readBytes(&l, size) ) @@ -2438,7 +2414,8 @@ inline reader& operator >> ( reader& ps, uint32 & l ) //---------------------------------------------------------------------------------------- /// \ru Запись int64 в поток. \en Writing int64 to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, int64 val ) +inline +writer & operator << ( writer & ps, int64 val ) { ps.writeInt64( val ); return ps; @@ -2448,7 +2425,8 @@ inline writer & operator << ( writer & ps, int64 val ) //---------------------------------------------------------------------------------------- /// \ru Чтение int64 в поток. \en Reading int64 to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, int64 & val ) +inline +reader & operator >> ( reader & ps, int64 & val ) { ps.readInt64( val ); return ps; @@ -2458,7 +2436,8 @@ inline reader & operator >> ( reader & ps, int64 & val ) //---------------------------------------------------------------------------------------- /// \ru Чтение signed char в поток. \en Reading signed char to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, signed char & ch ) +inline +reader & operator >> ( reader & ps, signed char & ch ) { ch = (signed char)ps.readByte(); return ps; @@ -2468,7 +2447,8 @@ inline reader & operator >> ( reader & ps, signed char & ch ) //---------------------------------------------------------------------------------------- /// \ru Чтение unsigned char в поток. \en Reading unsigned char to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, unsigned char & ch ) +inline +reader & operator >> ( reader & ps, unsigned char & ch ) { ch = (unsigned char)ps.readByte(); return ps; @@ -2478,7 +2458,9 @@ inline reader & operator >> ( reader & ps, unsigned char & ch ) //---------------------------------------------------------------------------------------- /// \ru Чтение char в поток. \en Reading char to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, char & ch ) { +inline +reader & operator >> ( reader & ps, char & ch ) +{ ch = (char)ps.readByte(); return ps; } @@ -2487,7 +2469,9 @@ inline reader & operator >> ( reader & ps, char & ch ) { //---------------------------------------------------------------------------------------- /// \ru Чтение signed short в поток. \en Reading signed short to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, signed short & sh ) { +inline +reader & operator >> ( reader & ps, signed short & sh ) +{ const size_t size = sizeof(sh); if ( !ps.readBytes(&sh, size) ) @@ -2499,7 +2483,8 @@ inline reader & operator >> ( reader & ps, signed short & sh ) { //---------------------------------------------------------------------------------------- /// \ru Чтение unsigned short в поток. \en Reading unsigned short to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, unsigned short & sh ) +inline +reader & operator >> ( reader & ps, unsigned short & sh ) { const size_t size = sizeof(sh); @@ -2509,12 +2494,13 @@ inline reader & operator >> ( reader & ps, unsigned short & sh ) return ps; } -//#ifdef __MOBILE_VERSION__ + #ifndef __ATS_BUILD__ // Нужно для сборки решения Tools\ATS... //---------------------------------------------------------------------------------------- /// \ru Чтение wchar_t в поток. \en Reading wchar_t to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, wchar_t & sh ) +inline +reader & operator >> ( reader & ps, wchar_t & sh ) { sh = 0; //Обнулить, т.к. размер 4 байта, а читаются только 2 //size_t size = sizeof(sh); @@ -2527,13 +2513,14 @@ inline reader & operator >> ( reader & ps, wchar_t & sh ) return ps; } #endif // __ATS_BUILD__ -//#endif // __MOBILE_VERSION__ //---------------------------------------------------------------------------------------- /// \ru Чтение float в поток. \en Reading float to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, float & f ) { +inline +reader & operator >> ( reader & ps, float & f ) +{ size_t size = sizeof(f); if ( !ps.readBytes(&f, size) ) @@ -2546,7 +2533,8 @@ inline reader & operator >> ( reader & ps, float & f ) { //---------------------------------------------------------------------------------------- /// \ru Чтение double в поток. \en Reading double to the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, double & d ) +inline +reader & operator >> ( reader & ps, double & d ) { size_t size = sizeof(d); @@ -2564,7 +2552,9 @@ inline reader & operator >> ( reader & ps, double & d ) //---------------------------------------------------------------------------------------- /// \ru Чтение long double из потока. \en Reading long double from the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, long double & l ) { +inline +reader & operator >> ( reader & ps, long double & l ) +{ size_t size = sizeof(l); if ( !ps.readBytes(&l, size) ) @@ -2577,7 +2567,8 @@ inline reader & operator >> ( reader & ps, long double & l ) { /// \ru Чтение smart-указателя из потока. \en Reading a smart pointer from the stream. \~ \ingroup Base_Tools_IO // --- template -inline reader & operator >> ( reader & ps, SPtr<_Class> & sPtr ) +inline +reader & operator >> ( reader & ps, SPtr<_Class> & sPtr ) { _Class * ptr = nullptr; ps >> ptr; @@ -2589,7 +2580,8 @@ inline reader & operator >> ( reader & ps, SPtr<_Class> & sPtr ) /// \ru Запись smart-указателя в поток. \en Writing a smart pointer to the stream. \~ \ingroup Base_Tools_IO // --- template -inline writer & operator << ( writer & ps, const SPtr<_Class> & sPtr ) +inline +writer & operator << ( writer & ps, const SPtr<_Class> & sPtr ) { ps << sPtr.get(); return ps; @@ -2599,7 +2591,8 @@ inline writer & operator << ( writer & ps, const SPtr<_Class> & sPtr ) //---------------------------------------------------------------------------------------- /// \ru Запись signed char в поток. \en Write signed char to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer & ps, signed char ch ) +inline +writer & operator << ( writer & ps, signed char ch ) { ps.writeByte( ch ); // \ru байт \en byte return ps; @@ -2609,7 +2602,8 @@ inline writer& operator << ( writer & ps, signed char ch ) //---------------------------------------------------------------------------------------- /// \ru Запись unsigned char в поток. \en Write unsigned char to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer & ps, unsigned char ch ) +inline +writer & operator << ( writer & ps, unsigned char ch ) { ps.writeByte( ch ); // \ru байт \en byte return ps; @@ -2619,7 +2613,8 @@ inline writer& operator << ( writer & ps, unsigned char ch ) //---------------------------------------------------------------------------------------- /// \ru Запись char в поток. \en Write char to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer & ps, char ch ) +inline +writer & operator << ( writer & ps, char ch ) { ps.writeByte( ch ); // \ru байт \en byte return ps; @@ -2629,7 +2624,8 @@ inline writer& operator << ( writer & ps, char ch ) //---------------------------------------------------------------------------------------- /// \ru Запись signed short в поток. \en Write signed short to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer & ps, signed short sh ) +inline +writer & operator << ( writer & ps, signed short sh ) { ps.writeBytes( &sh, sizeof(sh) ); return ps; @@ -2639,31 +2635,33 @@ inline writer& operator << ( writer & ps, signed short sh ) //---------------------------------------------------------------------------------------- /// \ru Запись unsigned short в поток. \en Write unsigned short to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer& ps, unsigned short sh ) +inline +writer & operator << ( writer & ps, unsigned short sh ) { ps.writeBytes( &sh, sizeof(sh) ); return ps; } -//#ifdef __MOBILE_VERSION__ + #ifndef __ATS_BUILD__ // Нужно для сборки решения Tools\ATS... //---------------------------------------------------------------------------------------- /// \ru Запись wchar_t в поток. \en Write wchar_t to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, wchar_t sh ) +inline +writer & operator << ( writer & ps, wchar_t sh ) { size_t size = 2; //В windows sizeof(wchar_t) = 2, в Android sizeof(wchar_t) = 4 ps.writeBytes( &sh, size ); return ps; } #endif // __ATS_BUILD__ -//#endif // __MOBILE_VERSION__ //---------------------------------------------------------------------------------------- /// \ru Запись float в поток. \en Write float to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, float f ) +inline +writer & operator << ( writer & ps, float f ) { ps.writeBytes( &f, sizeof(f) ); return ps; @@ -2673,7 +2671,8 @@ inline writer & operator << ( writer & ps, float f ) //---------------------------------------------------------------------------------------- /// \ru Запись double в поток. \en Write double to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer& operator << ( writer & ps, const double & d ) +inline +writer & operator << ( writer & ps, const double & d ) { ps.writeBytes( &d, sizeof(d) ); return ps; @@ -2683,7 +2682,8 @@ inline writer& operator << ( writer & ps, const double & d ) //---------------------------------------------------------------------------------------- /// \ru Запись long double в поток. \en Write long double to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, const long double & l ) +inline +writer & operator << ( writer & ps, const long double & l ) { ps.writeBytes( &l, sizeof(l) ); return ps; @@ -2692,7 +2692,8 @@ inline writer & operator << ( writer & ps, const long double & l ) //---------------------------------------------------------------------------------------- /// \ru Записать TCHAR строку в поток. \en Write TCHAR string to the stream. \~ \ingroup Base_Tools_IO // --- -inline void WriteTCHAR( writer & out, const TCHAR * ts, bool directSingleByte = false ) +inline +void WriteTCHAR( writer & out, const TCHAR * ts, bool directSingleByte = false ) { if ( directSingleByte || out.MathVersion() < UNICODE_VERSION ) { @@ -2711,7 +2712,8 @@ inline void WriteTCHAR( writer & out, const TCHAR * ts, bool directSingleByte = //---------------------------------------------------------------------------------------- /// \ru Прочитать TCHAR строку из потока. \en Read TCHAR string from the stream. \~ \ingroup Base_Tools_IO //--- -inline void ReadTCHAR( reader & in, TCHAR *& ts, bool directSingleByte = false ) +inline +void ReadTCHAR( reader & in, TCHAR *& ts, bool directSingleByte = false ) { if ( directSingleByte || in.MathVersion() < UNICODE_VERSION ) { @@ -2732,7 +2734,8 @@ inline void ReadTCHAR( reader & in, TCHAR *& ts, bool directSingleByte = false ) //---------------------------------------------------------------------------------------- /// \ru Записать wchar_t строку в поток. \en Write wchar_t string to the stream. \~ \ingroup Base_Tools_IO // --- -inline void WriteWcharT( writer & out, const wchar_t* ts ) +inline +void WriteWcharT( writer & out, const wchar_t * ts ) { out.__writeWcharT( ts ); } @@ -2740,7 +2743,8 @@ inline void WriteWcharT( writer & out, const wchar_t* ts ) //---------------------------------------------------------------------------------------- /// \ru Прочитать TCHAR строку из потока. \en Read TCHAR string from the stream. \~ \ingroup Base_Tools_IO //--- -inline void ReadWcharT( reader& in, wchar_t* & ts ) +inline +void ReadWcharT( reader& in, wchar_t *& ts ) { __readWcharT( in, ts ); } @@ -2749,7 +2753,8 @@ inline void ReadWcharT( reader& in, wchar_t* & ts ) //---------------------------------------------------------------------------------------- /// \ru Запись size_t в зависимости от версии потока. \en Write size_t subject to the stream version. \~ \ingroup Base_Tools_IO // --- -inline void WriteCOUNT( writer & out, size_t count ) +inline +void WriteCOUNT( writer & out, size_t count ) { if ( IsVersion64bit( out.MathVersion() ) ) { @@ -2776,7 +2781,8 @@ inline void WriteCOUNT( writer & out, size_t count ) //---------------------------------------------------------------------------------------- /// \ru Запись ptrdiff_t в зависимости от версии потока. \en Writing ptrdiff_t subject to the stream version. \~ \ingroup Base_Tools_IO // --- -inline void WriteINT_T( writer & out, ptrdiff_t count ) +inline +void WriteINT_T( writer & out, ptrdiff_t count ) { if ( IsVersion64bit( out.MathVersion() ) ) { @@ -2800,7 +2806,8 @@ inline void WriteINT_T( writer & out, ptrdiff_t count ) // \ru уметь читать оба, в зависимости от места где вызывается. \en there should be capability for reading both of them subject to the place where it is called. // \ru Решено запись не менять, т.к. в 16 битовую задачу не записываем. \en Decided not to modify writing since we do not write to 16-bit task. // --- -inline size_t ReadCOUNT ( reader & in, bool uint_val = true ) +inline +size_t ReadCOUNT ( reader & in, bool uint_val = true ) { size_t count = 0; if ( IsVersion64bit( in.MathVersion() ) ) @@ -2857,7 +2864,8 @@ inline size_t ReadCOUNT ( reader & in, bool uint_val = true ) // --- // \ru САА K13 31.8.2010 Исправление BUG 52091 \en CAA K13 31.8.2010 Fix for BUG 52091 // \ru 77 вызовов и из них только 2 с false!!! - поэтому по умолчанию для всех \en 77 calls and only 2 of them with false!!! - so it is default for all -inline ptrdiff_t ReadINT_T( reader & in, bool uint_val = true ) +inline +ptrdiff_t ReadINT_T( reader & in, bool uint_val = true ) { ptrdiff_t count = 0; if ( IsVersion64bit( in.MathVersion() ) ) @@ -2890,22 +2898,12 @@ inline ptrdiff_t ReadINT_T( reader & in, bool uint_val = true ) return count; } -//OV_LNX \ru Перенесено в Asset\Tape\io_buffer.h \en Moved to Asset\Tape\io_buffer.h -//OV_LNX //---------------------------------------------------------------------------------------- -//OV_LNX /// \ru Длина данных size_t в потоке. \en Length of size_t data in the stream. \~ \ingroup Base_Tools_IO -//OV_LNX // --- -//OV_LNX inline size_t LenCOUNT( VERSION version ) -//OV_LNX { -//OV_LNX if ( IsVersion64bit(version) ) -//OV_LNX return sizeof(uint64); -//OV_LNX else -//OV_LNX return sizeof(uint32); -//OV_LNX } //---------------------------------------------------------------------------------------- /// \ru Запись size_t в память в зависимости от версии потока. \en Writing size_t to the memory subject to the stream version. \~ \ingroup Base_Tools_IO // --- -inline void WriteCOUNT( void * out, VERSION version, size_t count ) +inline +void WriteCOUNT( void * out, VERSION version, size_t count ) { if ( IsVersion64bit(version) ) { @@ -2928,7 +2926,8 @@ inline void WriteCOUNT( void * out, VERSION version, size_t count ) //---------------------------------------------------------------------------------------- /// \ru Запись ptrdiff_t в память в зависимости от версии потока. \en Writing ptrdiff_t to the memory subject to the stream version. \~ \ingroup Base_Tools_IO // --- -inline void WriteCOUNT( void * out, VERSION version, ptrdiff_t count ) +inline +void WriteCOUNT( void * out, VERSION version, ptrdiff_t count ) { if ( IsVersion64bit(version) ) { @@ -2951,7 +2950,8 @@ inline void WriteCOUNT( void * out, VERSION version, ptrdiff_t count ) //---------------------------------------------------------------------------------------- /// \ru Чтение size_t в память в зависимости от версии потока. \en Reading of size_t to the memory subject to the stream version. \~ \ingroup Base_Tools_IO // --- -inline size_t ReadCOUNT ( void * in, VERSION version ) +inline +size_t ReadCOUNT ( void * in, VERSION version ) { size_t count = 0; @@ -2979,41 +2979,56 @@ inline size_t ReadCOUNT ( void * in, VERSION version ) //---------------------------------------------------------------------------------------- -/** Получить упакованное имя класса по значению хэша записанному в поток - - \param[in] hash - Значение хэша. - \param[in] ver - Версия потока в котором записан хэш. - - \result Возвращает упакованное имя класса. -*/ -// --- -MATH_FUNC (ClassDescriptor) GetPackedClassName( const ClassDescriptor &, const VersionContainer & ver ); +/** \brief \ru Получить упакованное имя класса по значению хэша записанному в поток. + \en Get the packed class name from the hash value written to the stream. \~ + \details \ru Получить упакованное имя класса по значению хэша записанному в поток. \n + \en Get the packed class name from the hash value written to the stream. \n \~ + \param[in] classDescr - \ru Обертка хэша. + \en Hash value wrapper. \~ + \param[in] ver - \ru Версия потока в котором записан хэш. + \en The version of the stream in which the hash is written. \~ + \result \ru Возвращает упакованное имя класса. + \en Returns the packed class name. \~ + \ingroup Base_Tools_IO +*/ // --- +MATH_FUNC (ClassDescriptor) GetPackedClassName( const ClassDescriptor & classDescr, const VersionContainer & ver ); //---------------------------------------------------------------------------------------- -/** Добавить новое соответствие значения хэша записанного в поток упакованному имени класса - - \param[in] сlassName - Упакованное имя класса. - \param[in] hash - Значение хэша. - \param[in] appIndex - Индекс приложения, которому принадлежит класс. - \param[in] lowVersion - Нижняя граница верссии. - \param[in] highVersion - Верхняя граница верссии. -*/ -// --- -MATH_FUNC (void) AddPackedClassNameForVersion( const ClassDescriptor & newClassName, const ClassDescriptor & oldClassName, uint appIndex, VERSION lowVersion, VERSION highVersion ); +/** \brief \ru Добавить новое соответствие значения хэша записанного в поток упакованному имени класса. + \en Add a new mapping of the hash value written to the stream to the packed class name. \~ + \details \ru Добавить новое соответствие значения хэша записанного в поток упакованному имени класса. \n + \en Add a new mapping of the hash value written to the stream to the packed class name. \n \~ + \param[in] newClassName - \ru Новое имя класса. + \en New class name. \~ + \param[in] oldClassName - \ru Старое имя класса. + \en Old class name. \~ + \param[in] appIndex - \ru Индекс приложения, которому принадлежит класс. + \en The index of the application that the class belongs to. \~ + \param[in] lowVersion - \ru Нижняя граница версии. + \en Version lower bound. \~ + \param[in] highVersion - \ru Верхняя граница версии. + \en Version upper bound. \~ + \ingroup Base_Tools_IO +*/ // --- +MATH_FUNC (void) AddPackedClassNameForVersion( const ClassDescriptor & newClassName, + const ClassDescriptor & oldClassName, + uint appIndex, + VERSION lowVersion, + VERSION highVersion ); //---------------------------------------------------------------------------------------- -/** - \brief \ru Диагностика коллизий имени нового класса с зарегистрированными классами. - \en Diagnostics of collisions of new class name with registered classes. \~ - \param[in] className - \ru Имя класса. \en The class name. ~ - \param[in] appID - \ru Идентификатор приложения. \en The application id. +/** \brief \ru Диагностика коллизий имени нового класса с зарегистрированными классами. + \en Diagnostics of collisions of new class name with registered classes. \~ + \details \ru Диагностика коллизий имени нового класса с зарегистрированными классами. \n + \en Diagnostics of collisions of new class name with registered classes. \n \~ + \param[in] className - \ru Имя класса. \en The class name. \~ + \param[in] appID - \ru Идентификатор приложения. \en The application id. \~ \return \ru Признак уникальности класса с заданным именем при регистрации с указанным идентификатором приложения. - \en Whether the class with the specified name is unique if registered with specified application id. -\ingroup Base_Tools_IO -*/ -// --- + \en Whether the class with the specified name is unique if registered with specified application id. \~ + \ingroup Base_Tools_IO +*/ // --- MATH_FUNC( bool ) IsValidStreamClassName( const char * className, const MbUuid & appID ); @@ -3059,7 +3074,8 @@ namespace c3d // namespace C3D //---------------------------------------------------------------------------------------- /// \ru Оператор записи хэша. \en Operator of writing hash. \~ \ingroup Base_Tools_IO //--- -inline writer & operator << ( writer & out, const StrHash & strHash ) +inline +writer & operator << ( writer & out, const StrHash & strHash ) { // \ru Нельзя допускать хеш с неопределенным типом и с определенным значением \en Hash with undefined type and with specified value cannot be allowed PRECONDITION( !(IsGoodSimpleName(strHash.m_val) && strHash.m_type == c3d::StrHash::htp_undef) ); @@ -3074,7 +3090,8 @@ inline writer & operator << ( writer & out, const StrHash & strHash ) //---------------------------------------------------------------------------------------- /// \ru Оператор чтения хэша. \en Operator of hash reading. \~ \ingroup Base_Tools_IO //--- -inline reader & operator >> ( reader & in, c3d::StrHash & strHash ) +inline +reader & operator >> ( reader & in, c3d::StrHash & strHash ) { strHash.m_val = ReadSimpleName( in ); @@ -3098,7 +3115,8 @@ inline reader & operator >> ( reader & in, c3d::StrHash & strHash ) //---------------------------------------------------------------------------------------- /// \ru Запись строки в поток. \en Writing a string to the stream. \~ \ingroup Base_Tools_IO //--- -inline writer & operator << ( writer & ps, const std::string & s ) +inline +writer & operator << ( writer & ps, const std::string & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { @@ -3116,7 +3134,8 @@ inline writer & operator << ( writer & ps, const std::string & s ) //---------------------------------------------------------------------------------------- /// \ru Чтение строки из потока. \en Reading a string from the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, std::string & s ) +inline +reader & operator >> ( reader & ps, std::string & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { @@ -3149,7 +3168,8 @@ inline reader & operator >> ( reader & ps, std::string & s ) //---------------------------------------------------------------------------------------- /// \ru Запись строки в поток. \en Writing a string to the stream. \~ \ingroup Base_Tools_IO // --- -inline writer & operator << ( writer & ps, const std::wstring & s ) +inline +writer & operator << ( writer & ps, const std::wstring & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { @@ -3167,7 +3187,8 @@ inline writer & operator << ( writer & ps, const std::wstring & s ) //---------------------------------------------------------------------------------------- /// \ru Чтение строки из потока. \en Reading a string from the stream. \~ \ingroup Base_Tools_IO // --- -inline reader & operator >> ( reader & ps, std::wstring & s ) +inline +reader & operator >> ( reader & ps, std::wstring & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { @@ -3196,7 +3217,8 @@ inline reader & operator >> ( reader & ps, std::wstring & s ) //---------------------------------------------------------------------------------------- /// \ru Запись строки в поток. \en Writing a string to the stream. \~ \ingroup Base_Tools_IO //--- -inline writer & operator << ( writer & ps, const std::wstring * s ) +inline +writer & operator << ( writer & ps, const std::wstring * s ) { WriteWcharT( ps, (s ? s->c_str() : nullptr) ); // \ru в зависимости от версии потока \en subject to the stream version return ps; @@ -3205,7 +3227,8 @@ inline writer & operator << ( writer & ps, const std::wstring * s ) //---------------------------------------------------------------------------------------- /// \ru Прочитать кластер. \en Read the cluster. \~ \ingroup Base_Tools_IO // --- -inline void ReadCluster( reader & in, uint16 clusterSize, Cluster & cl ) +inline +void ReadCluster( reader & in, uint16 clusterSize, Cluster & cl ) { // \ru очистить поле указателя, т.к. в AllocMem есть проверка на 0 \en clear the pointer field since there is a check for 0 in AllocMem cl.SetClusterOffset( 0 ); @@ -3227,9 +3250,11 @@ inline void ReadCluster( reader & in, uint16 clusterSize, Cluster & cl ) // \~ \ingroup Base_Tools_IO // --- #ifdef C3D_DEBUG -inline void WriteCluster( writer & out, const Cluster & cl, uint16 clusterSize ) +inline +void WriteCluster( writer & out, const Cluster & cl, uint16 clusterSize ) #else -inline void WriteCluster( writer & out, const Cluster & cl, uint16 /*clusterSize*/ ) +inline +void WriteCluster( writer & out, const Cluster & cl, uint16 /*clusterSize*/ ) #endif { uint16 len = cl.m_l; @@ -3241,7 +3266,8 @@ inline void WriteCluster( writer & out, const Cluster & cl, uint16 /*clusterSize //---------------------------------------------------------------------------------------- /// \ru Записать информацию о кластере. \en Write the information about the cluster. \~ \ingroup Base_Tools_IO // --- -inline size_t WriteClusterInfo( void * out, VERSION version, const Cluster & obj ) +inline +size_t WriteClusterInfo( void * out, VERSION version, const Cluster & obj ) { WriteCOUNT( out, version, obj.m_f ); @@ -3254,7 +3280,8 @@ inline size_t WriteClusterInfo( void * out, VERSION version, const Cluster & obj //---------------------------------------------------------------------------------------- /// \ru Прочитать информацию о кластере. \en Read the information about the cluster. \~ \ingroup Base_Tools_IO // --- -inline size_t ReadClusterInfo( void * in, VERSION version, Cluster & obj ) +inline +size_t ReadClusterInfo( void * in, VERSION version, Cluster & obj ) { size_t off = ReadCOUNT( in, version ); @@ -3270,7 +3297,8 @@ inline size_t ReadClusterInfo( void * in, VERSION version, Cluster & obj ) // \ru Записать содержимое кластера. Возвращает размер данных кластера или -1, если длина кластера больше заявленной. // \en Write the cluster's contents. Return size of cluster's data or -1, if the cluster length is greater than the defined one. // --- -inline size_t WriteClusterBody( void * out, VERSION version, const Cluster & obj, uint16 clusterSize ) +inline +size_t WriteClusterBody( void * out, VERSION version, const Cluster & obj, uint16 clusterSize ) { uint8 * m = (uint8 *)out; @@ -3295,7 +3323,8 @@ inline size_t WriteClusterBody( void * out, VERSION version, const Cluster & obj // \ru Прочитать содержимое кластера. Возвращает размер данных кластера или -1, если длина кластера больше заявленной. // \en Read the cluster's contents. Return size of cluster's data or -1, if the cluster length is greater than the defined one. // --- -inline size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 clusterSize ) +inline +size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 clusterSize ) { uint8 * m = (uint8 *)in; diff --git a/C3d/Include/mb_data.h b/C3d/Include/mb_data.h index b386d40..951b000 100644 --- a/C3d/Include/mb_data.h +++ b/C3d/Include/mb_data.h @@ -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 arrayFixPntTngSign; ///< \ru Признаки учета касательных на точках / точек на касательных. \en Signs of points on tangents / tangents on points. + + SArray 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 ), diff --git a/C3d/Include/mb_dimension.h b/C3d/Include/mb_dimension.h index fea872b..cff7558 100644 --- a/C3d/Include/mb_dimension.h +++ b/C3d/Include/mb_dimension.h @@ -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) }; diff --git a/C3d/Include/mb_operation_result.h b/C3d/Include/mb_operation_result.h index 09f5de6..634c99b 100644 --- a/C3d/Include/mb_operation_result.h +++ b/C3d/Include/mb_operation_result.h @@ -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! }; diff --git a/C3d/Include/mb_point_mating.h b/C3d/Include/mb_point_mating.h index 9e57d27..271f450 100644 --- a/C3d/Include/mb_point_mating.h +++ b/C3d/Include/mb_point_mating.h @@ -292,7 +292,7 @@ bool MbPntMatingData::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; diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index 903dad6..6462fbe 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -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 diff --git a/C3d/Include/mb_smooth_nurbs_fit_curve.h b/C3d/Include/mb_smooth_nurbs_fit_curve.h index 5a58658..61d82a7 100644 --- a/C3d/Include/mb_smooth_nurbs_fit_curve.h +++ b/C3d/Include/mb_smooth_nurbs_fit_curve.h @@ -161,7 +161,7 @@ enum MbeSmoothingMethod \ingroup Data_Structures */ // --- -template +template class MbApproxNurbsParameters { private: @@ -174,6 +174,7 @@ private: std::vector _approxPoints; ///< \ru Аппроксимируемая полилиния. \en Polyline to be approximated. c3d::DoubleVector _approxParams; ///< \ru Параметры точек полилинии. \en Points parameters. std::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> & 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 & 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 & param, - MbApproxNurbsCurveResult & result ); +MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters & param, + MbApproxNurbsCurveResult & result ); //------------------------------------------------------------------------------- @@ -630,7 +661,7 @@ MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParamet \en Under development. \~ */ // --- -MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters & param, - MbApproxNurbsCurveResult & result ); +MATH_FUNC( MbResultType ) ApproximatePolylineByNurbs( const MbApproxNurbsParameters & param, + MbApproxNurbsCurveResult & result ); #endif // __MB_SMOOTH_NURBS_FIT_CURVE_H diff --git a/C3d/Include/model_tree.h b/C3d/Include/model_tree.h index 10296a9..2584772 100644 --- a/C3d/Include/model_tree.h +++ b/C3d/Include/model_tree.h @@ -148,6 +148,7 @@ public: private: MbEmbodimentNode(); + MbEmbodimentNode( const MbEmbodimentNode * emb ); }; //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/op_binding_data.h b/C3d/Include/op_binding_data.h index 18527fb..e34e1d0 100644 --- a/C3d/Include/op_binding_data.h +++ b/C3d/Include/op_binding_data.h @@ -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 ) { diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h index 9a24c83..2644261 100644 --- a/C3d/Include/op_curve_parameter.h +++ b/C3d/Include/op_curve_parameter.h @@ -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 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 & 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 & 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(&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 _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 _arrayFixNoisyNum; ///< \ru Номера точек точных значений зашумленных точек. \en Signs of exactly noisy points. + MbeFairWarning _warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ MbResultType _error; ///< \ru Ошибка о работе. \en The operation error. \~ diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index 3b58f6f..9d7036a 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -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 mating; ///< \ru Сопряжение. \en The conjugation. + c3d::SpaceCurveSPtr _curve; ///< \ru Кривая. \en A curve. + DPtr _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> & matings ); writer & Write( writer & out, const std::vector> & 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 & 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 & 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 _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 _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 & ); diff --git a/C3d/Include/pars_equation_tree.h b/C3d/Include/pars_equation_tree.h index 3d2c7b3..29b8ad2 100644 --- a/C3d/Include/pars_equation_tree.h +++ b/C3d/Include/pars_equation_tree.h @@ -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; diff --git a/C3d/Include/sheet_metal_param.h b/C3d/Include/sheet_metal_param.h index 16b4038..72bf195 100644 --- a/C3d/Include/sheet_metal_param.h +++ b/C3d/Include/sheet_metal_param.h @@ -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 diff --git a/C3d/Include/surf_fillet_surface.h b/C3d/Include/surf_fillet_surface.h index f519d18..44e2052 100644 --- a/C3d/Include/surf_fillet_surface.h +++ b/C3d/Include/surf_fillet_surface.h @@ -616,9 +616,9 @@ inline void MbFilletSurface::CheckUParam( double & u ) const { } } else { - if ( poleMin && uumax ) + if ( poleUMax && u > umax ) u = umax; } } diff --git a/C3d/Include/surf_smooth_surface.h b/C3d/Include/surf_smooth_surface.h index a8aefe6..e5b4deb 100644 --- a/C3d/Include/surf_smooth_surface.h +++ b/C3d/Include/surf_smooth_surface.h @@ -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 && uumax ) + if ( poleUMax && u > umax ) u = umax; } } diff --git a/C3d/Include/templ_ifc_array.h b/C3d/Include/templ_ifc_array.h index e0bdca0..576dd4d 100644 --- a/C3d/Include/templ_ifc_array.h +++ b/C3d/Include/templ_ifc_array.h @@ -129,9 +129,9 @@ public: // \ru Стандартные функции контейнерного using RPArray::capacity; using RPArray::reserve; /// \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. - const stored_type * begin () const { return RPArray::begin(); } + using RPArray::begin; //const stored_type * begin() const { return RPArray::begin(); } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. - const stored_type * end() const { return RPArray::end(); } + using RPArray::end; //const stored_type * end() const { return RPArray::end(); } public: // \ru Доступные методы от RPArray \en Available methods from RPArray diff --git a/C3d/Include/tool_enabler.h b/C3d/Include/tool_enabler.h index 6baae0d..2b6bf3a 100644 --- a/C3d/Include/tool_enabler.h +++ b/C3d/Include/tool_enabler.h @@ -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. \~ diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 3df571e..ebff1e7 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -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 VertexSPtr; -typedef SPtr ConstVertexSPtr; +typedef SPtr VertexSPtr; +typedef SPtr ConstVertexSPtr; -typedef std::vector VerticesVector; -typedef std::vector ConstVerticesVector; +typedef std::pair VerticesPair; +typedef std::pair ConstVerticesPair; +typedef std::pair VerticesSPtrPair; +typedef std::pair ConstVerticesSPtrPair; -typedef std::vector VerticesSPtrVector; -typedef std::vector ConstVerticesSPtrVector; +typedef std::vector VerticesVector; +typedef std::vector ConstVerticesVector; +typedef std::vector VerticesSPtrVector; +typedef std::vector ConstVerticesSPtrVector; typedef std::set VerticesSet; typedef VerticesSet::iterator VerticesSetIt; @@ -80,56 +85,70 @@ typedef ConstVerticesSPtrSet::iterator ConstVerticesSPtrSetIt; typedef ConstVerticesSPtrSet::const_iterator ConstVerticesSPtrSetConstIt; typedef std::pair ConstVerticesSPtrSetRet; -// edges typedefs -typedef SPtr WireEdgeSPtr; -typedef SPtr ConstWireEdgeSPtr; +typedef std::map VerticesPairMap; +typedef std::map ConstVerticesPairMap; +typedef std::map VerticesSPtrPairMap; +typedef std::map ConstVerticesSPtrPairMap; -typedef std::vector WireEdgesVector; -typedef std::vector ConstWireEdgesVector; - -typedef std::vector WireEdgesSPtrVector; -typedef std::vector ConstWireEdgesSPtrVector; // edges typedefs -typedef SPtr EdgeSPtr; -typedef SPtr ConstEdgeSPtr; +typedef SPtr WireEdgeSPtr; +typedef SPtr ConstWireEdgeSPtr; -typedef std::pair EdgeIndex; -typedef std::pair ConstEdgeIndex; +typedef std::pair WireEdgesPair; +typedef std::pair ConstWireEdgesPair; +typedef std::pair WireEdgesSPtrPair; +typedef std::pair ConstWireEdgesSPtrPair; -typedef std::pair IndexEdge; -typedef std::pair IndexConstEdge; +typedef std::vector WireEdgesVector; +typedef std::vector ConstWireEdgesVector; +typedef std::vector WireEdgesSPtrVector; +typedef std::vector ConstWireEdgesSPtrVector; -typedef std::pair EdgesPair; -typedef std::vector EdgesVector; -typedef std::vector ConstEdgesVector; +// edges typedefs +typedef SPtr EdgeSPtr; +typedef SPtr ConstEdgeSPtr; -typedef std::vector EdgesSPtrVector; -typedef std::vector ConstEdgesSPtrVector; +typedef std::pair EdgeIndex; +typedef std::pair ConstEdgeIndex; -typedef std::list EdgesList; -typedef std::list ConstEdgesList; +typedef std::pair IndexEdge; +typedef std::pair IndexConstEdge; -typedef std::set EdgesSet; -typedef EdgesSet::iterator EdgesSetIt; -typedef EdgesSet::const_iterator EdgesSetConstIt; -typedef std::pair EdgesSetRet; +typedef std::pair EdgesPair; +typedef std::pair ConstEdgesPair; +typedef std::pair EdgesSPtrPair; +typedef std::pair ConstEdgesSPtrPair; -typedef std::set EdgesSPtrSet; -typedef EdgesSPtrSet::iterator EdgesSPtrSetIt; -typedef EdgesSPtrSet::const_iterator EdgesSPtrSetConstIt; -typedef std::pair EdgesSPtrSetRet; +typedef std::vector EdgesVector; +typedef std::vector ConstEdgesVector; +typedef std::vector EdgesSPtrVector; +typedef std::vector ConstEdgesSPtrVector; -typedef std::set ConstEdgesSet; -typedef ConstEdgesSet::iterator ConstEdgesSetIt; -typedef ConstEdgesSet::const_iterator ConstEdgesSetConstIt; -typedef std::pair ConstEdgesSetRet; +typedef std::list EdgesList; +typedef std::list ConstEdgesList; + +typedef std::set EdgesSet; +typedef EdgesSet::iterator EdgesSetIt; +typedef EdgesSet::const_iterator EdgesSetConstIt; +typedef std::pair EdgesSetRet; + +typedef std::set EdgesSPtrSet; +typedef EdgesSPtrSet::iterator EdgesSPtrSetIt; +typedef EdgesSPtrSet::const_iterator EdgesSPtrSetConstIt; +typedef std::pair EdgesSPtrSetRet; + +typedef std::set ConstEdgesSet; +typedef ConstEdgesSet::iterator ConstEdgesSetIt; +typedef ConstEdgesSet::const_iterator ConstEdgesSetConstIt; +typedef std::pair ConstEdgesSetRet; + +typedef std::set ConstEdgesSPtrSet; +typedef ConstEdgesSPtrSet::iterator ConstEdgesSPtrSetIt; +typedef ConstEdgesSPtrSet::const_iterator ConstEdgesSPtrSetConstIt; +typedef std::pair ConstEdgesSPtrSetRet; -typedef std::set ConstEdgesSPtrSet; -typedef ConstEdgesSPtrSet::iterator ConstEdgesSPtrSetIt; -typedef ConstEdgesSPtrSet::const_iterator ConstEdgesSPtrSetConstIt; -typedef std::pair ConstEdgesSPtrSetRet; // oriented edges typedefs typedef MbOrientedEdge * OrientEdge; @@ -146,16 +165,15 @@ typedef std::pair ConstEdgeSPtrOrient; typedef std::vector OrientEdgesVector; typedef std::vector ConstOrientEdgesVector; - typedef std::vector OrientEdgesSPtrVector; typedef std::vector ConstOrientEdgesSPtrVector; typedef std::vector EdgeOrientVector; typedef std::vector ConstEdgeOrientVector; - typedef std::vector EdgeSPtrOrientVector; typedef std::vector ConstEdgeSPtrOrientVector; + // loops typedefs typedef SPtr LoopSPtr; typedef SPtr ConstLoopSPtr; @@ -168,48 +186,54 @@ typedef std::vector LoopNumberVector; typedef std::vector LoopsVector; typedef std::vector ConstLoopsVector; - typedef std::vector LoopsSPtrVector; typedef std::vector ConstLoopsSPtrVector; + // faces typedefs -typedef SPtr FaceSPtr; -typedef SPtr ConstFaceSPtr; +typedef SPtr FaceSPtr; +typedef SPtr ConstFaceSPtr; -typedef std::pair FaceIndex; -typedef std::pair ConstFaceIndex; +typedef std::pair FaceIndex; +typedef std::pair ConstFaceIndex; +typedef std::pair ConstFaceFacePair; + +typedef std::vector FacesVector; +typedef std::vector ConstFacesVector; +typedef std::vector FacesSPtrVector; +typedef std::vector ConstFacesSPtrVector; -typedef std::vector FacesVector; -typedef std::vector ConstFacesVector; typedef std::pair ConstFacesVectorPair; -typedef std::vector FacesSPtrVector; -typedef std::vector ConstFacesSPtrVector; +typedef std::set FacesSet; +typedef FacesSet::iterator FacesSetIt; +typedef FacesSet::const_iterator FacesSetConstIt; +typedef std::pair FacesSetRet; -typedef std::set FacesSet; -typedef FacesSet::iterator FacesSetIt; -typedef FacesSet::const_iterator FacesSetConstIt; -typedef std::pair FacesSetRet; +typedef std::set FacesSPtrSet; +typedef FacesSPtrSet::iterator FacesSPtrSetIt; +typedef FacesSPtrSet::const_iterator FacesSPtrSetConstIt; +typedef std::pair FacesSPtrSetRet; -typedef std::set FacesSPtrSet; -typedef FacesSPtrSet::iterator FacesSPtrSetIt; -typedef FacesSPtrSet::const_iterator FacesSPtrSetConstIt; -typedef std::pair FacesSPtrSetRet; +typedef std::set ConstFacesSet; +typedef ConstFacesSet::iterator ConstFacesSetIt; +typedef ConstFacesSet::const_iterator ConstFacesSetConstIt; +typedef std::pair ConstFacesSetRet; -typedef std::set ConstFacesSet; -typedef ConstFacesSet::iterator ConstFacesSetIt; -typedef ConstFacesSet::const_iterator ConstFacesSetConstIt; -typedef std::pair ConstFacesSetRet; +typedef std::set ConstFacesSPtrSet; +typedef ConstFacesSPtrSet::iterator ConstFacesSPtrSetIt; +typedef ConstFacesSPtrSet::const_iterator ConstFacesSPtrSetConstIt; +typedef std::pair ConstFacesSPtrSetRet; -typedef std::set ConstFacesSPtrSet; -typedef ConstFacesSPtrSet::iterator ConstFacesSPtrSetIt; -typedef ConstFacesSPtrSet::const_iterator ConstFacesSPtrSetConstIt; -typedef std::pair ConstFacesSPtrSetRet; +typedef std::map FaceIndexMap; +typedef std::map ConstFaceIndexMap; +typedef std::map IndexFaceMap; +typedef std::map IndexConstFaceMap; -typedef std::map FaceIndexMap; -typedef std::map ConstFaceIndexMap; -typedef std::map IndexFaceMap; -typedef std::map IndexConstFaceMap; +typedef std::map FaceSPtrIndexMap; +typedef std::map ConstFaceSPtrIndexMap; +typedef std::map IndexFaceSPtrMap; +typedef std::map 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 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 * cache; + mutable CacheManager * cache; ///< \ru Вспомогательные данные для грани. \en Auxiliary data for the face. public: /// \ru Конструктор по поверхности и ориентации нормали грани относительно нормали поверхности. \en Constructor by surface and orientation of face normal in relation to surface normal. diff --git a/C3d/Include/topology_faceset.h b/C3d/Include/topology_faceset.h index fdec92d..d1c3ea0 100644 --- a/C3d/Include/topology_faceset.h +++ b/C3d/Include/topology_faceset.h @@ -117,18 +117,15 @@ void GetEdges( const FacesVector & faceSet, EdgesVector & edges ); // --- class MATH_CLASS MbFaceShell : public MbTopItem, public MbSyncItem { -protected: - RPArray 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 * cache; +protected: + RPArray faceSet; ///< \ru Множество граней. \en A set of faces. + bool closed; ///< \ru Признак замкнутости указывает на отсутствие края. \en An attribute of closedness indicates the absence of boundary. + + mutable CacheManager * cache; ///< \ru Вспомогательные данные для множества граней. \en Auxiliary data for the face set. public : /// \ru Конструктор без параметров. \en Constructor without parameters. diff --git a/C3d/Include/wire_frame.h b/C3d/Include/wire_frame.h index da0c343..0d54c5f 100644 --- a/C3d/Include/wire_frame.h +++ b/C3d/Include/wire_frame.h @@ -241,8 +241,16 @@ public : bool MakePlaneCurves( RPArray & 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 & curves, MbSurface *& surface ) const; - /// \ru Построить контуры из копий кривых. \en Construct contours of curves copies. - bool MakeCurves( RPArray & ) 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 & curves ) const; /// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. template 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 & 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 ); diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index bfc1eb4..84be42b 100644 Binary files a/C3d/Lib/x32/Debug/c3d.lib and b/C3d/Lib/x32/Debug/c3d.lib differ diff --git a/C3d/Lib/x32/Release/c3d.lib b/C3d/Lib/x32/Release/c3d.lib index 7b3b4b3..7865beb 100644 Binary files a/C3d/Lib/x32/Release/c3d.lib and b/C3d/Lib/x32/Release/c3d.lib differ diff --git a/C3d/Lib/x64/Debug/c3d.lib b/C3d/Lib/x64/Debug/c3d.lib index f028d28..c3f64be 100644 Binary files a/C3d/Lib/x64/Debug/c3d.lib and b/C3d/Lib/x64/Debug/c3d.lib differ diff --git a/C3d/Lib/x64/Release/c3d.lib b/C3d/Lib/x64/Release/c3d.lib index 0aa946b..1364cb2 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ