diff --git a/C3d/Include/action.h b/C3d/Include/action.h index 6d499c1..3efbb30 100644 --- a/C3d/Include/action.h +++ b/C3d/Include/action.h @@ -77,7 +77,7 @@ MATH_FUNC (bool) IsMultiShell( const MbFaceShell * shell, bool checkNesting = tr \ingroup Algorithms_3D */ // --- -MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, RPArray & parts, bool sort, c3d::IndicesVector * partIndices = C3D_NULL_PTR ); +MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, RPArray & parts, bool sort, c3d::IndicesVector * partIndices = c3d_null ); //------------------------------------------------------------------------------ @@ -102,7 +102,7 @@ MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, RPArray & par \ingroup Algorithms_3D */ // --- -MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsVector & parts, bool sort, c3d::IndicesVector * partIndices = C3D_NULL_PTR ); +MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsVector & parts, bool sort, c3d::IndicesVector * partIndices = c3d_null ); //------------------------------------------------------------------------------ @@ -127,7 +127,7 @@ MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsVector & parts, \ingroup Algorithms_3D */ // --- -MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsSPtrVector & parts, bool sort, c3d::IndicesVector * partIndices = C3D_NULL_PTR ); +MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsSPtrVector & parts, bool sort, c3d::IndicesVector * partIndices = c3d_null ); //------------------------------------------------------------------------------ @@ -151,15 +151,15 @@ MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, c3d::ShellsSPtrVector & pa template size_t CreateShells( const MbFaceShell & shell, ShellsVector & parts, bool sort = true ) { - c3d::ShellSPtr outer( new MbFaceShell( shell ) ); // new shell on the same faces (новая оболочка с теми же гранями) - - c3d::IndicesVector * partIndices = C3D_NULL_PTR; - - if ( ::DetachShells( *outer, parts, sort, partIndices ) > 0 ) { - parts.push_back( outer ); - ::DetachItem( outer ); - } - + c3d::ShellSPtr outer( new MbFaceShell( shell ) ); // new shell on the same faces (новая оболочка с теми же гранями) + + c3d::IndicesVector * partIndices = c3d_null; + + if ( ::DetachShells( *outer, parts, sort, partIndices ) > 0 ) { + parts.push_back( outer ); + ::DetachItem( outer ); + } + return parts.size(); } @@ -251,21 +251,6 @@ MATH_FUNC (bool) UnifyOwnComplanarFaces( MbFaceShell & shell, bool checkBaseSurfaces ); -//------------------------------------------------------------------------------ -/** \brief \ru Найти и устранить общие поверхности-подложки в гранях. - \en Find and eliminate common underlying surfaces of faces \~ - \details \ru Найти и устранить общие поверхности-подложки в гранях оболочки. \n - \en Find and eliminate common underlying surfaces of a shell faces. \n \~ - \param[in] shell - \ru Модифицируемая оболочка. - \en A shell to be modified. \~ - \return \ru Возвращает true, если оболочка была изменена. - \en Returns 'true' if the shell has been modified. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) CheckIdenticalBaseSufaces( MbFaceShell & shell ); - - //------------------------------------------------------------------------------ /** \brief \ru Захватить грани одним из способов. \en Capture the faces in one of proposed methods. \~ @@ -1254,9 +1239,9 @@ MATH_FUNC (bool) FindTouchedFaces( const MbSolid & solid1, \en To find contacted faces of bodies. \~ \details \ru Разбить контактирующие грани тел, выделив общие области с конечной площадью перекрытия в отдельные грани. \~ \en To find contacted faces of bodies and build a finite overlap contacted area as faces. \~ - \param[in/out] solid1 - \ru Первое тело. + \param[in,out] solid1 - \ru Первое тело. \en The first solid. \~ - \param[in/out] solid2 - \ru Второе тело. + \param[in,out] solid2 - \ru Второе тело. \en The second solid. \~ \param[in] precision - \ru Точность операции. \en The precision of operation. \~ @@ -1344,13 +1329,13 @@ c3d::SolidSPtr GetTransformedSolid( c3d::SolidSPtr & solid, MbeCopyMode & copyMo { c3d::SolidSPtr resSolid( solid ); - if ( (resSolid != NULL) && !matr.IsSingle() ) { + if ( (resSolid != c3d_null) && !matr.IsSingle() ) { MbSNameMaker n( transformedMainName, MbSNameMaker::i_SideNone, 0 ); - MbSolid * resSolidPtr = NULL; + MbSolid * resSolidPtr = c3d_null; TransformValues tv( matr ); ::TransformedSolid( *solid, cm_Copy, tv, n, resSolidPtr ); - if ( resSolidPtr != NULL ) { + if ( resSolidPtr != c3d_null ) { resSolid = resSolidPtr; copyMode = cm_Same; } @@ -1374,10 +1359,10 @@ c3d::SolidSPtr GetTransformedSolid( c3d::SolidSPtr & solid, MbeCopyMode & copyMo */ // --- template -SPtr GetTransformedItem( SPtr & item, const MbMatrix3D & matr, MbRegDuplicate * iDupReg = NULL, MbRegTransform * iTransReg = NULL ) +SPtr GetTransformedItem( SPtr & item, const MbMatrix3D & matr, MbRegDuplicate * iDupReg = c3d_null, MbRegTransform * iTransReg = c3d_null ) { SPtr resItem( item ); - if ( (resItem != NULL) && !matr.IsSingle() ) { + if ( (resItem != c3d_null) && !matr.IsSingle() ) { resItem = static_cast( &item->Duplicate( iDupReg ) ); resItem->Transform( matr, iTransReg ); } diff --git a/C3d/Include/action_analysis.h b/C3d/Include/action_analysis.h index 068ba44..856c287 100644 --- a/C3d/Include/action_analysis.h +++ b/C3d/Include/action_analysis.h @@ -59,7 +59,7 @@ typedef void( *SurfaceFunction )( const MbSurface & surf, // Поверхно MATH_FUNC( void ) MinSurfaceCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -80,7 +80,7 @@ MATH_FUNC( void ) MinSurfaceCurvature( const MbSurface & surf, MATH_FUNC( void ) MaxSurfaceCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -101,7 +101,7 @@ MATH_FUNC( void ) MaxSurfaceCurvature( const MbSurface & surf, MATH_FUNC( void ) GaussCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -122,7 +122,7 @@ MATH_FUNC( void ) GaussCurvature( const MbSurface & surf, MATH_FUNC( void ) MeanCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -143,7 +143,7 @@ MATH_FUNC( void ) MeanCurvature( const MbSurface & surf, MATH_FUNC( void ) UNormalCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -164,7 +164,7 @@ MATH_FUNC( void ) UNormalCurvature( const MbSurface & surf, MATH_FUNC( void ) VNormalCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, - MbVector * der = NULL ); + MbVector * der = c3d_null ); //------------------------------------------------------------------------------ @@ -172,8 +172,8 @@ MATH_FUNC( void ) VNormalCurvature( const MbSurface & surf, \en Find the points of the surface at which the selected curvature takes the largest in modulus values. \~ \details \ru Ищутся точки, в которых выбранная кривизна принимает на поверхности наибольшее положительное и наименьшее отрицательное значение. \en Looks for points at which the selected curvature takes on the surface the greatest positive and least negative value. \~ - \param[in] surf - \ru Исследуемая поверхность. - \en Test surface. \~ + \param[in] surface - \ru Исследуемая поверхность. + \en Test surface. \~ \param[in] func - \ru Функция расчета кривизны в точке. \en The function of calculating the curvature at a point. \~ \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). @@ -241,8 +241,8 @@ MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, \en Find the points on the surface at which the major normal curvatures take the largest values in the module. \~ \details \ru Ищутся точки на поверхности, в которых главные нормальные кривизны принимают наибольшее положительное и наименьшее отрицательное значение. \en Looks for points on the surface at which the major normal curvatures take the largest positive and smallest negative values. \~ - \param[in] surf - \ru Исследуемая поверхность. - \en Test surface. \~ + \param[in] surface - \ru Исследуемая поверхность. + \en Test surface. \~ \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). \en The largest in modulus value negative curvature (0, if there is no such). \~ \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. @@ -321,7 +321,7 @@ MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, */ MATH_FUNC( double ) CurveOrientedCurvature( const MbCurve3D & curve, double & param, - const MbVector3D * planeNorm = NULL ); + const MbVector3D * planeNorm = c3d_null ); //------------------------------------------------------------------------------ @@ -358,10 +358,10 @@ MATH_FUNC( void ) CurveMinMaxCurvature( const MbCurve3D & curve, double & maxParam, double & minCurv, double & minParam, - c3d::DoubleVector * bendPoints = NULL, - c3d::DoubleVector * maxPoints = NULL, - c3d::DoubleVector * minPoints = NULL, - c3d::DoublePairsVector * rapPoints = NULL ); + c3d::DoubleVector * bendPoints = c3d_null, + c3d::DoubleVector * maxPoints = c3d_null, + c3d::DoubleVector * minPoints = c3d_null, + c3d::DoublePairsVector * rapPoints = c3d_null ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/action_b_shaper.h b/C3d/Include/action_b_shaper.h index 42be300..98bb480 100644 --- a/C3d/Include/action_b_shaper.h +++ b/C3d/Include/action_b_shaper.h @@ -341,8 +341,8 @@ public: To fit surface use corresponding methods SegmentMesh or FitSurfaceToSegment. \n \~ \param[in] idxSegment - \ru Индекс сегмента полигональной сетки. \en Index of a mesh segment. \~ - \return \ru Возвращает указатель на поверхность для сегмента, если поверхность определена, иначе - NULL. - \en Returns pointer to segment surface if it exists, else - NULL. \~ + \return \ru Возвращает указатель на поверхность для сегмента, если поверхность определена, иначе - c3d_null. + \en Returns pointer to segment surface if it exists, else - c3d_null. \~ \ingroup Polygonal_Objects */ virtual const MbSurface * GetSegmentSurface( size_t idxSegment ) const = 0; diff --git a/C3d/Include/action_curve.h b/C3d/Include/action_curve.h index 2e86ae0..3976d69 100644 --- a/C3d/Include/action_curve.h +++ b/C3d/Include/action_curve.h @@ -171,12 +171,14 @@ MATH_FUNC (MbResultType) Segment( const MbCartPoint & point1, */ //--- -MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, - const MbCartPoint & center, - const std::vector & points, - double & a, double & b, double & c, - bool option, - MbCurve *& result ); +MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, + const MbCartPoint & center, + const c3d::ParamPointsVector & points, + double & a, + double & b, + double & c, + bool option, + MbCurve *& result ); //------------------------------------------------------------------------------ /**\attention \ru Функция устарела. Вместо неё применять #Arc. @@ -185,11 +187,13 @@ MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, */ // 2018 //--- -MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, +MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, const SArray & points, - bool curveClosed, double angle, - double & a, double & b, - MbCurve *& result ); + bool curveClosed, + double angle, + double & a, + double & b, + MbCurve *& result ); //------------------------------------------------------------------------------ @@ -225,8 +229,9 @@ MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, */ // --- MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, - bool curveClosed, MbePlaneType curveType, - MbCurve *& result ); + bool curveClosed, + MbePlaneType curveType, + MbCurve *& result ); //------------------------------------------------------------------------------ @@ -256,9 +261,11 @@ MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, */ //--- MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, - const SArray & weightList, size_t degree, - const SArray & knotList, bool curveClosed, - MbCurve *& result ); + const SArray & weightList, + size_t degree, + const SArray & knotList, + bool curveClosed, + MbCurve *& result ); //------------------------------------------------------------------------------ @@ -430,7 +437,7 @@ MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); // --- MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr, bool modifySegments, - MbSNameMaker * names = NULL ); + MbSNameMaker * names = c3d_null ); //------------------------------------------------------------------------------ @@ -694,12 +701,12 @@ MATH_FUNC (MbResultType) SurfaceBoundContour( const MbSurface & surface, or for contour pt_Contour if its first segment is of one of the listed types. \~ \param[in] segment - \ru Изменяемая кривая. \en The modified curve. \~ - \param[in] p1 - \ru Новая начальная точка. - \en A new start point. \~ + \param[in] p - \ru Новая начальная точка. + \en A new start point. \~ \ingroup Algorithms_2D */ // --- -MATH_FUNC (bool) ChangeFirstPoint( MbCurve * segment, const MbCartPoint & p1 ); +MATH_FUNC (bool) ChangeFirstPoint( MbCurve * segment, const MbCartPoint & p ); //------------------------------------------------------------------------------ @@ -717,23 +724,25 @@ MATH_FUNC (bool) ChangeFirstPoint( MbCurve * segment, const MbCartPoint & p1 ); or for contour pt_Contour if its last segment is of one of the listed types. \~ \param[in] segment - \ru Изменяемая кривая. \en The modified curve. \~ - \param[in] p1 - \ru Новая начальная точка. - \en A new start point. \~ + \param[in] p - \ru Новая начальная точка. + \en A new start point. \~ \ingroup Algorithms_2D */ // --- -MATH_FUNC (bool) ChangeLastPoint( MbCurve * segment, const MbCartPoint & p2 ); +MATH_FUNC (bool) ChangeLastPoint( MbCurve * segment, const MbCartPoint & p ); //------------------------------------------------------------------------------ /** \brief \ru Является ли кривая прямолинейной независимо от ее параметризации. - \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \en Whether the curve is like straight-line regardless of its parameterization. \~ \details \ru Является ли кривая прямолинейной независимо от ее параметризации.\n - \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \en Whether the curve is like straight-line regardless of its parameterization. \~ \param[in] curve - \ru Кривая. \en Curve. \~ \param[in] eps - \ru Точность. \en Accuracy. \~ + \return \ru Возвращает true, если кривая геометрически прямолинейна. + \en Returns true, if a curve is geometrically straight. \~ \ingroup Curve_Modeling */ // --- @@ -758,7 +767,7 @@ MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); // --- MATH_FUNC( MbContour * ) DeleteDegenerateSegments( const MbContour & cntr, bool modifySegments, - MbSNameMaker * names = NULL ); + MbSNameMaker * names = c3d_null ); #endif // __ACTION_CURVE_H diff --git a/C3d/Include/action_curve3d.h b/C3d/Include/action_curve3d.h index fb759d4..39b4f53 100644 --- a/C3d/Include/action_curve3d.h +++ b/C3d/Include/action_curve3d.h @@ -56,7 +56,7 @@ struct MATH_CLASS EvolutionValues; // --- MATH_FUNC (MbResultType) Line( const MbCartPoint3D & point1, const MbCartPoint3D & point2, - MbCurve3D *& result ); + MbCurve3D *& result ); //------------------------------------------------------------------------------ @@ -77,7 +77,7 @@ MATH_FUNC (MbResultType) Line( const MbCartPoint3D & point1, // --- MATH_FUNC (MbResultType) Segment( const MbCartPoint3D & point1, const MbCartPoint3D & point2, - MbCurve3D *& result ); + MbCurve3D *& result ); //------------------------------------------------------------------------------ @@ -106,11 +106,13 @@ MATH_FUNC (MbResultType) Segment( const MbCartPoint3D & point1, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) Arc( const MbCartPoint3D & centre, +MATH_FUNC (MbResultType) Arc( const MbCartPoint3D & centre, const SArray & points, - bool curveClosed, double angle, - double & a, double & b, - MbCurve3D *& result ); + bool curveClosed, + double angle, + double & a, + double & b, + MbCurve3D *& result ); //------------------------------------------------------------------------------ @@ -146,9 +148,9 @@ MATH_FUNC (MbResultType) Arc( const MbCartPoint3D & centre, */ // --- MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, - bool curveClosed, - MbeSpaceType curveType, - MbCurve3D *& result ); + bool curveClosed, + MbeSpaceType curveType, + MbCurve3D *& result ); //------------------------------------------------------------------------------ @@ -178,9 +180,11 @@ MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, */ //--- MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, - const SArray & weightList, size_t degree, - const SArray & knotList, bool curveClosed, - MbCurve3D *& result ); + const SArray & weightList, + size_t degree, + const SArray & knotList, + bool curveClosed, + MbCurve3D *& result ); //------------------------------------------------------------------------------ @@ -279,11 +283,11 @@ MATH_FUNC (MbResultType) SpiralCurve( const MbPlacement3D & place, \details \ru Создать спираль. \n Если spiralAxis == true, то lawCurve - определяет плоскую ось спирали. \n Если spiralAxis == false, то lawCurve - определяет закон изменения радиуса спирали. \n - Если lawCurve == NULL, то строится коническая спираль с углом конусности angle. \n + Если lawCurve == c3d_null, то строится коническая спираль с углом конусности angle. \n \en Create a spiral. \n If 'spiralAxis' == true, 'lawCurve' determines the axis of a spiral. \n If spiralAxis == false, then 'lawCurve' - determines a radius law. \n - If lawCurve == NULL, a conical spiral is created with the specified taper angle. \n \~ + If lawCurve == c3d_null, a conical spiral is created with the specified taper angle. \n \~ \param[in] point0 - \ru Начало локальной системы координат (ЛСК). \en The origin of local coordinate system (LCS). \~ \param[in] point1 - \ru Точка на оси Z ЛСК. @@ -640,7 +644,7 @@ MATH_FUNC (MbResultType) CreatePolyArcCurve3D( const MbCurve3D & curve, MATH_FUNC (bool) GetSpaceCurve( const MbItem & item, bool keepPlacement, SPtr & curve0, - std::vector< SPtr > * curves = NULL ); + std::vector< SPtr > * curves = c3d_null ); //------------------------------------------------------------------------------- @@ -662,9 +666,9 @@ MATH_FUNC (bool) GetSpaceCurve( const MbItem & item, \param[in] deviationAngle - \ru Параметру точности. \en The parameter of accuracy. \~ \return \ru Возвращает указатель на построенную кривую с нулевум счетчиком ссылок \n - или NULL, если не удалось построить развертку для заданных параметров. + или c3d_null, если не удалось построить развертку для заданных параметров. \en The pointer to the constructed curve with zero counter of references\n - return NULL, if unwrap curve can't be construvted for this parameters + return c3d_null, if unwrap curve can't be construvted for this parameters \ingroup Curve3D_Modeling */ // --- @@ -719,6 +723,8 @@ MATH_FUNC (MbResultType) EvolutionSection( const MbSweptData & generCurves, \en Curve. \~ \param[in] eps - \ru Точность. \en Accuracy. \~ + \return \ru Возвращает true, если кривая геометрически прямолинейна. + \en Returns true, if a curve is geometrically straight. \~ \ingroup Curve3D_Modeling */ // --- @@ -1256,11 +1262,14 @@ MATH_FUNC( MbResultType ) AddKnotNurbs( MbNurbs3D * curve, \en Insert a knot into the onesegmented NURBS curve.\n The output parameter of the method is a NURBS curve of first segment. \~ - \param[in] curve - \ru NURBS кривая в произвольном формате. \en NURBS curve in any format. \~ - \param[in] data - \ru Данные построения кривой. \en The curve construction data. \~ - \param[out] result - \ru NURBS Кривая. \en NURBS curve. \~ - \return \ru Возвращает значение результата операции. \en Returns operation result value. - + \param[in] curve - \ru NURBS кривая в произвольном формате. + \en NURBS curve in any format. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] resCurve - \ru NURBS Кривая. + \en NURBS curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. \ingroup Curve3D_Modeling */ MATH_FUNC( MbResultType ) ExtractExtrapolFromSegment( MbNurbs3D * curve, @@ -1310,7 +1319,7 @@ MATH_FUNC(MbResultType) ConicNurbs( MbNurbs3D * curve, \en The curve length evaluation. \~ \param[in] accuracy - \ru Относительная точность рассчёта длины кривой. \en Relative accuracy calculate the length of a curve. \~ - \param[in/out] maxCurvatre - \ru Максимально допустимая кривизна кривой. + \param[in,out] maxCurvatre - \ru Максимально допустимая кривизна кривой. \en The maximum curvature of the resulting curve. \~ \param[out] result - \ru Построенная кривая. \en The resulting curve. \~ diff --git a/C3d/Include/action_mesh.h b/C3d/Include/action_mesh.h index 9f75df8..f35afad 100644 --- a/C3d/Include/action_mesh.h +++ b/C3d/Include/action_mesh.h @@ -61,8 +61,8 @@ MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, локальной системы координат. \en Create a polygonal object for two-dimensional object in the XOY-plane of the local coordinate system. \~ - \param[in] obj - \ru Двумерный объект (если NULL, то объект не создаётся). - \en Two-dimensional object (if NULL, object isn't created). \~ + \param[in] obj - \ru Двумерный объект (если c3d_null, то объект не создаётся). + \en Two-dimensional object (if c3d_null, object isn't created). \~ \param[in] plane - \ru Локальная система координат. \en A local coordinate system. \~ \param[in] sag - \ru Максимальное отклонение полигонального объекта от оригинала по прогибу. diff --git a/C3d/Include/action_phantom.h b/C3d/Include/action_phantom.h index c26309b..b5cc68b 100644 --- a/C3d/Include/action_phantom.h +++ b/C3d/Include/action_phantom.h @@ -184,7 +184,7 @@ MATH_FUNC (MbResultType) OffsetPhantom( const MbSolid & solid, const SweptValues & params, const MbSNameMaker & operNames, MbFaceShell *& result, - size_t * hpShellFaceInd = NULL ); // \ru Номер грани в исходной оболочки для построения хот-точки); \en The face number in the initial shell for a hot-point creation); + size_t * hpShellFaceInd = c3d_null ); // \ru Номер грани в исходной оболочки для построения хот-точки); \en The face number in the initial shell for a hot-point creation); //------------------------------------------------------------------------------ @@ -261,7 +261,7 @@ MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & sol const SmoothValues & params, RPArray & result, double edgeParam = 0.5, - const MbCurveEdge * dimensionEdge = NULL ); + const MbCurveEdge * dimensionEdge = c3d_null ); //------------------------------------------------------------------------------ @@ -293,7 +293,7 @@ MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & sol const SmoothValues & params, RPArray & result, double edgeParam = 0.5, - const MbCurveEdge * dimensionEdge = NULL ); + const MbCurveEdge * dimensionEdge = c3d_null ); //------------------------------------------------------------------------------ @@ -303,15 +303,18 @@ MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & sol \en A function creation for behavior of selected curve coordinate with curve parameter. \n \param[in] curve - \ru Кривая. \en The curve. \~ - \param[in] coordinate - \ru Номер координаты пространства. - \en The number of curve coordinate. \~ + \param[in] place - \ru Локальная система координат, в которой используется кривая. + \en The local coordinate system that uses the curve. \~ + \param[in] coordinate - \ru Номер (0,1,2) координаты кривой в локальной системе координат для построения функции. + \en The number (0,1,2) of the curve coordinate in the local coordinate system for constructing the function. \~ \return \ru Возвращает построенную функцию. \en Returns the created function. \~ \ingroup Algorithms_3D */ // --- MATH_FUNC (MbFunction *) CreateFunction( const MbCurve3D & curve, - size_t coordinate ); + const MbPlacement3D & place, + size_t coordinate ); #endif // __ACTION_PHANTOM_H diff --git a/C3d/Include/action_point.h b/C3d/Include/action_point.h index 43c3a97..70ce11b 100644 --- a/C3d/Include/action_point.h +++ b/C3d/Include/action_point.h @@ -39,8 +39,8 @@ class MATH_CLASS MbFaceShell; \en Number of elements in the array. \~ \param[out] res - \ru Результат операции. \en The operation result. \~ - \return \ru Возвращает массив элементов, если он создан, или NULL в противном случае. - \en Returns an array of elements if it has been created, otherwise returns NULL. \~ + \return \ru Возвращает массив элементов, если он создан, или c3d_null в противном случае. + \en Returns an array of elements if it has been created, otherwise returns c3d_null. \~ \ingroup Algorithms_3D */ // --- @@ -48,11 +48,11 @@ template inline SArray * CreateArray( size_t cnt, MbResultType & res ) { SArray * arr = new SArray ( cnt, 1 ); - if ( arr != NULL && arr->GetAddr() == NULL ) { + if ( arr != c3d_null && arr->GetAddr() == c3d_null ) { delete arr; - arr = NULL; + arr = c3d_null; } - if ( arr == NULL ) + if ( arr == c3d_null ) res = rt_TooManyPoints; return arr; @@ -79,7 +79,7 @@ template inline bool ReserveArray( SArray & arr, size_t n, MbResultType & res ) { arr.Reserve( n ); - if ( arr.GetAddr() == NULL ) { + if ( arr.GetAddr() == c3d_null ) { res = rt_TooManyPoints; return false; } @@ -107,7 +107,7 @@ template inline bool AddItem( SArray & arr, const Type & item, MbResultType & res ) { arr.Add( item ); - if ( arr.GetAddr() == NULL ) { + if ( arr.GetAddr() == c3d_null ) { res = rt_TooManyPoints; return false; } diff --git a/C3d/Include/action_sheet.h b/C3d/Include/action_sheet.h index 92f3f33..d277aee 100644 --- a/C3d/Include/action_sheet.h +++ b/C3d/Include/action_sheet.h @@ -613,7 +613,7 @@ MATH_FUNC (MbResultType) UnbendSheetSolid( MbSolid & sol const MbCartPoint & fixedPoint, const MbSNameMaker & nameMaker, MbSolid *& result, - RPArray * ribContours = NULL ); + RPArray * ribContours = c3d_null ); //------------------------------------------------------------------------------ @@ -958,6 +958,51 @@ MATH_FUNC (MbResultType) CreateStampParts( const MbPlacement3D & placement, MbSolid *& partToSubtract ); +//------------------------------------------------------------------------------ +/** \brief \ru Создание составляющих частей штамповки одного тела другим телом. + \en Stamping with a tool solid (punch or die). \~ + \details \ru Штамповка строится на основе произвольного тела-инструмента и заданной плоской листовой грани. + Штамповка подрезается границами листовой грани, которую пересекает тело.\n + \en The stamping is created based on a tool body and a flat sheet face. + The stamping is trimmed by the boundary of the sheet face which contains the sketch.\n \~ + \param[in] solid - \ru Исходное листовое тело. + \en The source sheet solid. \~ + \param[in] sameShell - \ru Флаг удаления оболочки исходного тела. + \en Whether to delete the shell of the source solid. \~ + \param[in] targetFace - \ru Грань штамповки. + \en The face for stamping. \~ + \param[in] toolSolid - \ru Оболочка тела-инструмента. + \en A shell of tool solid. \~ + \param[in] sameShellTool - \ru Флаг удаления оболочки тела-инструмента. + \en Whether to delete the shell of the tool solid. \~ + \param[in] punch - \ru Является тело-инструмент пуансоном или матрицей. + \en Is tool body a punch or a die. \~ + \param[in] pierceFaces - \ru Вскрываемые для вырубки грани инструмента, + \en Pierce faces of tool body. \~ + \param[in] params - \ru Параметры штамповки. + \en The parameters of stamping. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] partToAdd - \ru Добавляемая часть штамповки. + \en Added part of the stamp. \~ + \param[out] partToSubtract - \ru Вычитаемая часть штамповки. + \en Deductible part of the stamp. \~ + \ingroup Sheet_Metal_Modeling +*/ +// --- +MATH_FUNC(MbResultType) CreateStampWithToolSolidParts( MbSolid & solid, + MbeCopyMode sameShell, + const MbFace & targetFace, + MbSolid & toolSolid, + MbeCopyMode sameShellTool, + bool punch, + const RPArray& pierceFaces, + const MbToolStampingValues & params, + const MbSNameMaker & nameMaker, + MbSolid * & partsToAdd, + MbSolid * & partsToSubtract ); + + //------------------------------------------------------------------------------ /** \brief \ru Штамповка. \en Stamping. \~ @@ -1176,6 +1221,7 @@ MATH_FUNC (MbResultType) CreateBeadParts( const MbFace * face, //------------------------------------------------------------------------------ // устаревшая // --- +DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateBeadParts( const MbPlacement3D & placement, const RPArray & contours, const SArray & centers, @@ -1230,6 +1276,7 @@ MATH_FUNC (MbResultType) CreateBead( MbSolid & solid, // устаревшая +DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateBead( MbSolid & solid, MbeCopyMode sameShell, const MbFace & face, @@ -1281,6 +1328,7 @@ MATH_FUNC (MbResultType) CreateJalousieParts( const MbFace * fac //------------------------------------------------------------------------------ // устаревшая // --- +DEPRECATE_DECLARE MATH_FUNC (MbResultType) CreateJalousieParts( const MbPlacement3D & placement, const RPArray & segments, const MbJalousieValues & params, @@ -1785,6 +1833,24 @@ MATH_FUNC (bool) BuildBends3DAxisLines( const RPArray & bendFac RPArray & axisLineSegments ); +//------------------------------------------------------------------------------ +/** \brief \ru Рассчитать осевые линии разогнутых сгибов. + \en Calculate the centerlines of unfolded bends. \~ + \details \ru Возвращает трёхмерные осевые линии, лежащие на разогнутых гранях сгибов.\n + \en Returns the 3D centerlines that lies on the unbent faces of the bends.\n \~ + \param[in] bendFaces - \ru Грани разогнутых сгибов, для которых строить линии сгиба. + \en Sheet faces of unfolded bends, that need constraction of the axis lines. \~ + \param[out] centerlines - \ru Искомые осевые линии. + \en The required centerlines. \~ + \return \ru true - в случае успеха операции, false - в противном случае. + \en True if the operation succeeded, otherwise false. \~ + \ingroup Sheet_Metal_Modeling +*/ +// --- +MATH_FUNC (bool) BuildBends3DCenterlines( const RPArray & bendFaces, + RPArray & centerlines ); + + //------------------------------------------------------------------------------ /** \brief \ru Рассчитать параметры для замыкания угла. \en Calculate the parameters for the corner closure. \~ @@ -2369,7 +2435,7 @@ MATH_FUNC (MbResultType) RemoveOperationResult( MbSolid & solid, \en The initial face for sheet metall solid building. \~ \param[in] sense - \ru Направление придания толщины относительно нормали исходной грани. \en Direction of sheet metal building relative to initial face normal. \~ - \param[in/out] parameters - \ru Параметры операции. + \param[in,out] parameters - \ru Параметры операции. \en Operation parameters. \~ \param[in] nameMaker - \ru Именователь. \en An object for naming the new objects. \~ diff --git a/C3d/Include/action_shell.h b/C3d/Include/action_shell.h index 9c6487a..524385f 100644 --- a/C3d/Include/action_shell.h +++ b/C3d/Include/action_shell.h @@ -263,17 +263,17 @@ MATH_FUNC (MbResultType) MeshShell( MeshSurfaceValues & pars, \ingroup Shell_Modeling */ // --- -MATH_FUNC (MbResultType) TruncateShell( MbSolid & initSolid, - SArray & selIndices, +MATH_FUNC (MbResultType) TruncateShell( MbSolid & initSolid, + SArray & selIndices, MbeCopyMode initCopyMode, - const MbSNameMaker & operNames, + const MbSNameMaker & operNames, RPArray & truncatingItems, - SArray & truncatingOrients, + SArray & truncatingOrients, bool truncatingSplitMode, MbeCopyMode truncatingCopyMode, - const MbMergingFlags & mergeFlags, - MbSolid *& result, - MbPlacement3D *& resultPlace ); + const MbMergingFlags & mergeFlags, + MbSolid *& result, + MbPlacement3D *& resultPlace ); //------------------------------------------------------------------------------ @@ -652,11 +652,11 @@ MATH_FUNC (MbResultType) SurfaceShell( const MbSurface & surface, /** \brief \ru Разрезать тело силуэтным контуром. \en Cut a solid by a silhouette contour. \~ \details \ru Построить оболочки, полученные в результате разрезания тела его силуэтным контуром. \n - \en Create solids as a result of cutting a solids by its silhouette contour.\n\~ - \param[in] shell - \ru Исходное тело. - \en The solid\~ + \en Create solids as a result of cutting a solids by its silhouette contour. \n \~ + \param[in] solid - \ru Исходное тело. + \en The solid. \~ \param[in] sameShell - \ru Способ передачи данных при копировании оболочек. - \en Methods of transferring data while copying shells \~ + \en Methods of transferring data while copying shells. \~ \param[in] eye - \ru Направление взгляда. \en Eye's direction. \~ \param[in] operNames - \ru Именователь с версией. @@ -859,9 +859,9 @@ MATH_FUNC (MbResultType) RectifyFace( const MbFace & face, \ingroup Shell_Modeling */ // --- -MATH_FUNC (MbResultType) OctaLattice( const MbCartPoint3D & point_0, - const MbCartPoint3D & point_1, - const MbCartPoint3D & point_2, +MATH_FUNC (MbResultType) OctaLattice( const MbCartPoint3D & point0, + const MbCartPoint3D & point1, + const MbCartPoint3D & point2, double xRadius, double yRadius, double zRadius, diff --git a/C3d/Include/action_solid.h b/C3d/Include/action_solid.h index cf77770..99e2a4a 100644 --- a/C3d/Include/action_solid.h +++ b/C3d/Include/action_solid.h @@ -180,7 +180,7 @@ MATH_FUNC (MbResultType) MeshSolid( const MbMesh & mesh, const GridsToShellValues & params, const MbSNameMaker & names, MbSolid *& result, - IProgressIndicator * prog = NULL ); + IProgressIndicator * prog = c3d_null ); //------------------------------------------------------------------------------ @@ -202,7 +202,7 @@ MATH_FUNC (MbResultType) MeshSolid( const MbMesh & mesh, MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, const MbSNameMaker & names, MbSolid *& result, - IProgressIndicator * prog = NULL ); + IProgressIndicator * prog = c3d_null ); //------------------------------------------------------------------------------ @@ -224,7 +224,7 @@ MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, MATH_FUNC (MbResultType) CollectionSolid( const MbCollection & grid, const MbSNameMaker & names, MbSolid *& result, - IProgressIndicator * progBar = NULL ); + IProgressIndicator * progBar = c3d_null ); //------------------------------------------------------------------------------ @@ -611,8 +611,8 @@ MATH_FUNC (MbResultType) EvolutionSolid( const MbSweptData & sweptData \en An array of generating contours coordinate systems. \~ \param[in] c - \ru Множество образующих контуров. \en An array of generating contours. \~ - \param[in] spine - \ru Направляющая кривая (может быть NULL). - \en A guide curve (can be NULL). \~ + \param[in] spine - \ru Направляющая кривая (может быть c3d_null). + \en A guide curve (can be c3d_null). \~ \param[in] params - \ru Параметры операции. \en The operation parameters. \~ \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. @@ -647,8 +647,8 @@ MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, \en An array of generating contours coordinate systems. \~ \param[in] c - \ru Множество образующих контуров. \en An array of generating contours. \~ - \param[in] spine - \ru Осевая кривая (может быть NULL). - \en A guide curve (can be NULL). \~ + \param[in] spine - \ru Осевая кривая (может быть c3d_null). + \en A guide curve (can be c3d_null). \~ \param[in] params - \ru Параметры операции. \en The operation parameters. \~ \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. @@ -668,7 +668,7 @@ MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, // --- MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, RPArray & c, - const MbCurve3D * spine, // осевая линия может быть NULL + const MbCurve3D * spine, // осевая линия может быть c3d_null const LoftedValues & params, RPArray * guideCurves, SArray * ps, @@ -686,8 +686,8 @@ MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, \en An array of surfaces of generating contours. \~ \param[in] c - \ru Множество образующих контуров. \en An array of generating contours. \~ - \param[in] spine - \ru Осевая кривая (может быть NULL). - \en A guide curve (can be NULL). \~ + \param[in] spine - \ru Осевая кривая (может быть c3d_null). + \en A guide curve (can be c3d_null). \~ \param[in] params - \ru Параметры операции. \en The operation parameters. \~ \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. @@ -707,7 +707,7 @@ MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, // --- MATH_FUNC (MbResultType) LoftedSolid( RPArray & surfs, RPArray & c, - const MbCurve3D * spine, // осевая линия может быть NULL + const MbCurve3D * spine, // осевая линия может быть c3d_null const LoftedValues & params, RPArray * guideCurves, SArray * ps, @@ -942,8 +942,8 @@ MATH_FUNC(MbResultType) EvolutionResult( MbSolid & solid, \en An array of generating contours coordinate systems. \~ \param[in] c - \ru Множество образующих контуров. \en An array of generating contours. \~ - \param[in] spine - \ru Направляющая кривая (может быть NULL). - \en A guide curve (can be NULL). \~ + \param[in] spine - \ru Направляющая кривая (может быть c3d_null). + \en A guide curve (can be c3d_null). \~ \param[in] params - \ru Параметры операции. \en The operation parameters. \~ \param[in] oType - \ru Тип булевой операции. @@ -995,8 +995,8 @@ MATH_FUNC(MbResultType) LoftedResult( MbSolid & solid, \en An array of generating contours surfaces. \~ \param[in] c - \ru Множество образующих контуров. \en An array of generating contours. \~ - \param[in] spine - \ru Осевая кривая (может быть NULL). - \en A guide curve (can be NULL). \~ + \param[in] spine - \ru Осевая кривая (может быть c3d_null). + \en A guide curve (can be c3d_null). \~ \param[in] params - \ru Параметры операции. \en The operation parameters. \~ \param[in] oType - \ru Тип булевой операции. @@ -1962,7 +1962,7 @@ MATH_FUNC (MbResultType) UnionResult( MbSolid * solid, const MbSNameMaker & names, bool isArray, MbSolid *& result, - RPArray * notGluedSolids = NULL ); + RPArray * notGluedSolids = c3d_null ); //------------------------------------------------------------------------------ @@ -2005,7 +2005,7 @@ MATH_FUNC (MbResultType) UnionSolid( RPArray & solids, const MbSNameMaker & names, bool isArray, MbSolid *& result, - RPArray * notGluedSolids = NULL ); + RPArray * notGluedSolids = c3d_null ); //------------------------------------------------------------------------------ @@ -2365,8 +2365,8 @@ MATH_FUNC (MbResultType) ThinSolid( const MbSurface & surface, //------------------------------------------------------------------------------ /** \brief \ru Создать отверстие, карман, фигурный паз в теле. \en Create a hole, a pocket, a groove in the solid. \~ - \details \ru Cоздать отверстие, карман, фигурный паз в теле или создать cверло, бобышку, если solid==NULL. \n - \en Create a hole, a pocket, a groove in the solid or create a drill, a boss if 'solid' == NULL. \n \~ + \details \ru Cоздать отверстие, карман, фигурный паз в теле или создать cверло, бобышку, если solid==c3d_null. \n + \en Create a hole, a pocket, a groove in the solid or create a drill, a boss if 'solid' == c3d_null. \n \~ \param[in] solid - \ru Исходное тело. \en The source solid. \~ \param[in] sameShell - \ru Режим копирования тела. diff --git a/C3d/Include/action_surface.h b/C3d/Include/action_surface.h index b216fc8..16a41f1 100644 --- a/C3d/Include/action_surface.h +++ b/C3d/Include/action_surface.h @@ -784,8 +784,8 @@ MATH_FUNC (MbResultType) MiddlePlaces( const MbCurve3D & curve1 \en The first guide curve. \~ \param[in] g2 - \ru Вторая направляющая кривая (g1==g2 совпадает с первой при cs_Round). \en The second guide curve (g1==g2 the same first guide for st_Round). \~ - \param[in] c0 - \ru Дополнительная направляющая кривая (может быть NULL). - \en The additional guide curve (may be NULL). \~ + \param[in] c0 - \ru Дополнительная направляющая кривая (может быть c3d_null). + \en The additional guide curve (may be c3d_null). \~ \param[in] form - \ru Форма сечения поверхности (0, 1, 2, 3). \en The form of the surface section (0, 1, 2, 3). \~ \param[in] sense - \ru Направление нормали поверхности направляющей кривой (для guide1==guide2). diff --git a/C3d/Include/action_surface_curve.h b/C3d/Include/action_surface_curve.h index 2d3dc64..7ad3f83 100644 --- a/C3d/Include/action_surface_curve.h +++ b/C3d/Include/action_surface_curve.h @@ -21,9 +21,11 @@ #include #include #include +#include #include #include #include +#include class MATH_CLASS MbAxis3D; @@ -74,12 +76,15 @@ class MATH_CLASS MbSNameMaker; */ // --- MATH_FUNC (MbResultType) CalculatePipePoints( const MbCartPoint3D & origin1, - const MbVector3D & direction1, - double length1, double radius1, + const MbVector3D & direction1, + double length1, + double radius1, const MbCartPoint3D & origin2, - const MbVector3D & direction2, - double length2, double radius2, - MbCartPoint3D & result1, MbCartPoint3D & result2 ); + const MbVector3D & direction2, + double length2, + double radius2, + MbCartPoint3D & result1, + MbCartPoint3D & result2 ); //------------------------------------------------------------------------------ @@ -89,8 +94,8 @@ MATH_FUNC (MbResultType) CalculatePipePoints( const MbCartPoint3D & origin1, \en Create an offset curve from a planar curve. \n \~ \param[in] curve - \ru Исходная кривая. \en The initial curve. \~ - \param[in] d - \ru Величина эквидистанты. - \en The offset distance. \~ + \param[in] dist - \ru Величина эквидистанты. + \en The offset distance. \~ \param[out] result - \ru Эквидистантная кривая. \en The offset curve. \~ \return \ru Возвращает код результата операции. @@ -98,17 +103,17 @@ MATH_FUNC (MbResultType) CalculatePipePoints( const MbCartPoint3D & origin1, \ingroup Curve3D_Modeling */ // --- -MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, - double d, - MbCurve3D *& result ); +MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, + double dist, + MbCurve3D *& result ); //------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантную кривую. - \en Create an offset curve. \~ - \details \ru Создать эквидистантную кривую по трехмерной кривой и вектору направления. \n - \en Create an offset curve from a three-dimensional curve and a direction vector. \n \~ - \param[in] initCurve - \ru Постранственная кривая, к которой строится эквидистантная. +/** \brief \ru Создать эквидистантную кривую в пространстве. + \en Create an offset curve in space. \~ + \details \ru Создать эквидистантную кривую в пространстве по трехмерной кривой и вектору направления. \n + \en Create an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \param[in] initCurve - \ru Пространственная кривая, к которой строится эквидистантная. \en A space curve for which to construct the offset curve. \~ \param[in] offsetVect - \ru Вектор, задающий смещение в точке кривой. \en The displacement vector at a point of the curve. \~ @@ -129,6 +134,7 @@ MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, \ingroup Curve3D_Modeling */ //--- +DEPRECATE_DECLARE MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & initCurve, const MbVector3D & offsetVect, const bool useFillet, @@ -140,20 +146,41 @@ MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & initCurve, //------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантную кривую. - \en Create an offset curve. \~ - \details \ru Создать эквидистантную кривую по поверхностной кривой и значению смещения. \n - \en Create an offset curve from a curve on a surface and a shift value. \n \~ +/** \brief \ru Создать эквидистантную кривую в пространстве. + \en Create an offset curve in space. \~ + \details \ru Создать эквидистантную кривую в пространстве по трехмерной кривой и вектору направления. \n + \en Create an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \param[in] initCurve - \ru Пространственная кривая, к которой строится эквидистантная. + \en A space curve for which to construct the offset curve. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & initCurve, + const MbSpatialOffsetCurveParams & params, + c3d::WireFrameSPtr & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную кривую на поверхности. + \en Create an offset curve on a surface. \~ + \details \ru Создать эквидистантную кривую на поверхности по поверхностной кривой и значению смещения. \n + \en Create an offset curve on a surface from a curve on the surface and a shift value. \n \~ \param[in] curve - \ru Кривая на поверхности грани face. \en A curve on face 'face' surface. \~ - \param[in] face - \ru Грань, на которой строится эквидистанта. - \en The edge on which to build the offset curve. \~ + \param[in] face - \ru Грань, на которой строится эквидистанта. + \en The face on which to build the offset curve. \~ \param[in] dirAxis - \ru Направление смещения с точкой приложения. - \en The offset direction with a point of application. \~ - \param[in] dist - \ru Величина смещения. - \en The offset distance. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ + \en The offset direction with a reference point. \~ + \param[in] dist - \ru Величина смещения. + \en The offset distance. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ \param[out] result - \ru Каркас с построенными кривыми. \en The frame with the constructed curves. \~ \return \ru Возвращает код результата операции. @@ -161,6 +188,7 @@ MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & initCurve, \ingroup Curve3D_Modeling */ //--- +DEPRECATE_DECLARE MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & curve, const MbFace & face, const MbAxis3D & dirAxis, @@ -169,11 +197,32 @@ MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & curve, MbWireFrame *& result ); +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную кривую на поверхности. + \en Create an offset curve on a surface. \~ + \details \ru Создать эквидистантную кривую на поверхности по поверхностной кривой и значению смещения. \n + \en Create an offset curve on a surface from a curve on the surface and a shift value. \n \~ + \param[in] curve - \ru Кривая на поверхности грани face. + \en A curve on face 'face' surface. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & curve, + const MbSurfaceOffsetCurveParams & params, + c3d::WireFrameSPtr & result ); + + //------------------------------------------------------------------------------ /** \brief \ru Создать проекцию кривой на поверхность. \en Create a curve projection onto the surface. \~ - \details \ru Создать проекцию кривой curve на поверхность surface (направление проецирования direction может быть NULL). \n - \en Create the projection of a curve onto surface 'surface' (the projection direction 'direction' can be NULL). \n \~ + \details \ru Создать проекцию кривой curve на поверхность surface (направление проецирования direction может быть c3d_null). \n + \en Create the projection of a curve onto surface 'surface' (the projection direction 'direction' can be c3d_null). \n \~ \param[in] surface - \ru Поверхность для проецирования. \en The surface to project onto. \~ \param[in] curve - \ru Проецируемая кривая. @@ -193,13 +242,13 @@ MATH_FUNC (MbResultType) OffsetCurve( const MbCurve3D & curve, \ingroup Curve3D_Modeling */ // --- -MATH_FUNC (MbResultType) CurveProjection( const MbSurface & surface, - const MbCurve3D & curve, - MbVector3D * direction, - bool createExact, - bool truncateByBounds, - RPArray & result, - VERSION version = Math::DefaultMathVersion() ); +MATH_FUNC (MbResultType) CurveProjection( const MbSurface & surface, + const MbCurve3D & curve, + MbVector3D * direction, + bool createExact, + bool truncateByBounds, + RPArray & result, + VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ @@ -222,12 +271,12 @@ MATH_FUNC (MbResultType) CurveProjection( const MbSurface & surface, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) CurveByTwoProjections( const MbPlacement3D & place1, - const MbCurve & curve1, - const MbPlacement3D & place2, - const MbCurve & curve2, - RPArray & result, - VERSION version = Math::DefaultMathVersion() ); +MATH_FUNC (MbResultType) CurveByTwoProjections( const MbPlacement3D & place1, + const MbCurve & curve1, + const MbPlacement3D & place2, + const MbCurve & curve2, + RPArray & result, + VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ @@ -260,14 +309,14 @@ MATH_FUNC (MbResultType) CurveByTwoProjections( const MbPlacement3D & place1, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) ProjectionCurve( const MbCurve3D & curve, - const RPArray & faces, - const MbVector3D * dir, - const bool createExact, - const bool truncateByBounds, - const MbSNameMaker & snMaker, - RPArray & result, - SArray * resultIndices ); +MATH_FUNC (MbResultType) ProjectionCurve( const MbCurve3D & curve, + const RPArray & faces, + const MbVector3D * dir, + const bool createExact, + const bool truncateByBounds, + const MbSNameMaker & snMaker, + RPArray & result, + SArray * resultIndices ); //------------------------------------------------------------------------------ @@ -304,16 +353,16 @@ MATH_FUNC (MbResultType) ProjectionCurve( const MbCurve3D & curve, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) ProjectionCurve( const MbWireFrame & wireFrame, - const bool sameWireFrame, - const MbSolid & solid, - const bool same, - const SArray & faceIndices, - const MbVector3D * dir, - const bool createExact, - const bool truncateByBounds, - const MbSNameMaker & snMaker, - MbWireFrame *& resFrame ); +MATH_FUNC (MbResultType) ProjectionCurve( const MbWireFrame & wireFrame, + const bool sameWireFrame, + const MbSolid & solid, + const bool same, + const SArray & faceIndices, + const MbVector3D * dir, + const bool createExact, + const bool truncateByBounds, + const MbSNameMaker & snMaker, + MbWireFrame *& resFrame ); //------------------------------------------------------------------------------ @@ -330,8 +379,7 @@ MATH_FUNC (MbResultType) ProjectionCurve( const MbWireFrame & wireFrame, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (bool) EliminateProjectionCurveOverlay( RPArray & curves, - SArray * indices ); +MATH_FUNC (bool) EliminateProjectionCurveOverlay( RPArray & curves, SArray * indices ); //------------------------------------------------------------------------------ @@ -402,7 +450,7 @@ MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, \en The axis of lathe section. \~ \param[in] removeOnSurfaceBounds - \ru Удалить линии очерка, совпадающие с границами поверхности. \en Remove the isocline curves coincident with the surface bounds. \~ - \param[out] result - \ru Выходной массив линий очерка. + \param[out] curves - \ru Выходной массив линий очерка. \en The output array of isocline curves. \~ \param[in] version - \ru Версия построения. \en The version. \~ @@ -686,13 +734,13 @@ MATH_FUNC( MbResultType ) IntersectionCurve( const MbSurface & surf1, bool ext1, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) SpaceSplineThrough( const SArray & points, - MbeSplineParamType paramType, - size_t degree, - bool closed, - RPArray< MbPntMatingData > & transitions, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); +MATH_FUNC (MbResultType) SpaceSplineThrough( const SArray & points, + MbeSplineParamType paramType, + size_t degree, + bool closed, + RPArray & transitions, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -724,14 +772,14 @@ MATH_FUNC (MbResultType) SpaceSplineThrough( const SArray & point */ //--- MATH_FUNC (MbResultType) SpaceSplineBy( const SArray & points, - size_t degree, - bool closed, + size_t degree, + bool closed, const SArray * weights, const SArray * knots, - MbPntMatingData * begData, - MbPntMatingData * endData, + c3d::PntMatingData3D * begData, + c3d::PntMatingData3D * endData, const MbSNameMaker & snMaker, - MbWireFrame *& result ); + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -776,14 +824,14 @@ MATH_FUNC (MbResultType) SpaceSplineBy( const SArray & points, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbResultType) SurfaceSpline( const MbSurface & surface, - bool throughPoints, - SArray & paramPnts, - SArray & paramWts, - bool paramClosed, - RPArray< MbPntMatingData > & spaceTransitions, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); +MATH_FUNC (MbResultType) SurfaceSpline( const MbSurface & surface, + bool throughPoints, + SArray & paramPnts, + SArray & paramWts, + bool paramClosed, + RPArray & spaceTransitions, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); //------------------------------------------------------------------------------ @@ -936,7 +984,7 @@ MATH_FUNC (MbResultType) ConnectingSpline( const MbCurve3D & curve1, double t1, что начало кривой сопряжения будет находится в точке с параметором t1, t1 и t2 - параметры кривых curve1 и curve2, в соответствующих точках которых начинается и заканчивается скругление. \n Параметр sense - прямое или обратное направление кривой скругления. \n - Кривая filletCurve - это кривая сопряжения, дуга (когда surface == NULL) или кривая на поверхности цилиндра surface. \n + Кривая filletCurve - это кривая сопряжения, дуга (когда surface == c3d_null) или кривая на поверхности цилиндра surface. \n Поверхность surface - это цилиндрическая поверхность, на которой строится кривая сопряжения в общем случае. Для управления жизненным циклом поверхномти следует миспользовать методы ::AddRefItem(surface) и ::ReleaseItem(surface). \n \en Create a fillet curve for curves. \n @@ -952,22 +1000,22 @@ MATH_FUNC (MbResultType) ConnectingSpline( const MbCurve3D & curve1, double t1, that the fillet curve start is at the point with parameter t1, t1 and t2 are parameters of curves 'curve1' and 'curve2' which correspond to the start point and the end point of the fillet. \n Parameter 'sense' determines forward or backward orientation of the fillet curve. \n - Curve filletCurve is a fillet curve, an arc (when 'surface' == NULL) or a curve on a cylindric surface 'surface'. \n + Curve filletCurve is a fillet curve, an arc (when 'surface' == c3d_null) or a curve on a cylindric surface 'surface'. \n Surface 'surface' is a cylindric surface on which the fillet curve is constructed in general case. Use ::AddRefItem(surface) and ::ReleaseItem(surface) methods to manage the surface lifecycle. \n \~ \param[in] curve1 - \ru Соединяемая кривая 1. \en A curve 1 to be connected. \~ - \param[in/out] t1 - \ru Параметр точки на кривой 1 соединения с кривой соединения. + \param[in,out] t1 - \ru Параметр точки на кривой 1 соединения с кривой соединения. \en A point parameter on curve 1 of connection with fillet curve. \~ \param[out] w1 - \ru Параметр края на кривой 1. \en The parameter of curve 1 end point. \~ \param[in] curve2 - \ru Соединяемая кривая 2. \en A curve 2 to be connected. \~ - \param[in/out] t2 - \ru Параметр точки на кривой 2 соединения с кривой соединения. + \param[in,out] t2 - \ru Параметр точки на кривой 2 соединения с кривой соединения. \en A point parameter on curve 2 of connection with fillet curve. \~ \param[out] w2 - \ru Параметр края на кривой 2. \en The parameter of curve 2 end point. \~ - \param[in/out] radius - \ru Радиус дуги или цилиндра. + \param[in,out] radius - \ru Радиус дуги или цилиндра. \en The radius of an arc or a cylinder. \~ \param[in] sense - \ru Прямое (true) или обратное (false) направление кривой скругления. \en The forward (true) or the backward (false) direction of the fillet curve. \~ @@ -977,8 +1025,8 @@ MATH_FUNC (MbResultType) ConnectingSpline( const MbCurve3D & curve1, double t1, \en The fillet type. \~ \param[in] names - \ru Именователь кривых каркаса. \en An object defining the frame curves names. \~ - \param[out] surface - \ru Поверхность, которая будет создана и на которой базируется соединительная кривая, (может быть возращён NULL). - \en A surface on which the fillet curve is based on, it will be created by the method (can be NULL). \~ + \param[out] surface - \ru Поверхность, которая будет создана и на которой базируется соединительная кривая, (может быть возращён c3d_null). + \en A surface on which the fillet curve is based on, it will be created by the method (can be c3d_null). \~ \param[out] result - \ru Каркас с построенными кривыми. \en The frame with the constructed curves. \~ \return \ru Возвращает код результата операции. diff --git a/C3d/Include/alg_base.h b/C3d/Include/alg_base.h index 3f9ef51..39b329e 100644 --- a/C3d/Include/alg_base.h +++ b/C3d/Include/alg_base.h @@ -464,7 +464,7 @@ bool IsMonotonic( const TypeVector & items, bool isAscending, bool allowEqual = isOk = true; if ( allowEqual ) { - for ( size_t k = 1; k < cnt; k++ ) { + for ( size_t k = 1; k < cnt; ++k ) { if ( isAscending && items[k] < items[k-1] ) { isOk = false; break; @@ -476,7 +476,7 @@ bool IsMonotonic( const TypeVector & items, bool isAscending, bool allowEqual = } } else { - for ( size_t k = 1; k < cnt; k++ ) { + for ( size_t k = 1; k < cnt; ++k ) { if ( isAscending && items[k] <= items[k-1] ) { isOk = false; break; @@ -614,7 +614,7 @@ bool IsPlanar( const SpacePointsVector & pnts, MbPlacement3D * place, double mEp } } } - if ( isPlanar && place != NULL ) + if ( isPlanar && place != c3d_null ) place->Init( wrkPlace ); } } diff --git a/C3d/Include/alg_curve_delete_part.h b/C3d/Include/alg_curve_delete_part.h index d141186..3e8d763 100644 --- a/C3d/Include/alg_curve_delete_part.h +++ b/C3d/Include/alg_curve_delete_part.h @@ -92,8 +92,8 @@ MATH_FUNC (MbeState) DeleteCurvePart( const MbCartPoint & p1, \en The point indicating the piece of a curve to be kept. \~ \param[in, out] curve - \ru Изменяемая кривая. \en The curve to be modified. \~ - \param[in, out] part2 - \ru Всегда NULL. - \en This value is always NULL. \~ + \param[in, out] part2 - \ru Всегда c3d_null. + \en This value is always c3d_null. \~ \return \ru Состояние кривой после ее модификации. \en The state of a curve after its modification. \~ \warning \ru Для внутреннего использования. @@ -124,8 +124,8 @@ MATH_FUNC (MbeState) TrimmCurvePart( List & curveList, \en The point indicating the piece of a closed curve to be kept \~ \param[in, out] curve - \ru Изменяемая кривая. \en The curve to be modified. \~ - \param[in, out] part2 - \ru Всегда NULL. - \en This value is always NULL. \~ + \param[in, out] part2 - \ru Всегда c3d_null. + \en This value is always c3d_null. \~ \return \ru Состояние кривой после ее модификации. \en The state of a curve after its modification. \~ \warning \ru Для внутреннего использования. @@ -155,8 +155,8 @@ MATH_FUNC (MbeState) TrimmCurvePart( const MbCartPoint & p1, \en Boundary curve for justification. \~ \param[in] pnt - \ru Точка для выбора нужной части кривой. \en The point for selecting the piece of a curve. \~ - \param[in, out] part2 - \ru Всегда NULL. - \en This value is always NULL. \~ + \param[in, out] part2 - \ru Всегда c3d_null. + \en This value is always c3d_null. \~ \return \ru Состояние кривой после ее модификации. \en The state of a curve after modification. \~ \warning \ru Для внутреннего использования. @@ -222,8 +222,8 @@ MATH_FUNC (MbeState) BreakByClosedCurves( MbCurve & curve, const RPArray & limits, bool inside, PArray & part2, - SArray * cross = NULL, - bool * isEqualCurve = NULL, + SArray * cross = c3d_null, + bool * isEqualCurve = c3d_null, bool cutOnCurve = false ); diff --git a/C3d/Include/alg_dimension.h b/C3d/Include/alg_dimension.h index 3b69601..11ab760 100644 --- a/C3d/Include/alg_dimension.h +++ b/C3d/Include/alg_dimension.h @@ -440,7 +440,7 @@ MATH_FUNC (MbeProcessState) MinMaxDistances( const MbSurface & surface1, MbMinMaxSurfDists & allResults, MbMinMaxSurfDists & minResults, MbMinMaxSurfDists & maxResults, - IProgressIndicator * indicator = NULL ); + IProgressIndicator * indicator = c3d_null ); #endif // __ALG_DIMENSION_H diff --git a/C3d/Include/alg_draw.h b/C3d/Include/alg_draw.h index 8d077cb..538675f 100644 --- a/C3d/Include/alg_draw.h +++ b/C3d/Include/alg_draw.h @@ -95,7 +95,7 @@ public: public: /// \ru Отрисовать объект. \en Draw an any object. - virtual void DrawItem( const MbRefItem * ri, int R, int G, int B, int width = 1 ) = 0; + virtual void DrawItem( const MbRefItem * ri, int R, int G, int B, const MbMatrix3D & from = MbMatrix3D::identity, int width = 1 ) = 0; /// \ru Отрисовать трехмерный геометрический объект. \en Draw a three-dimensional geometric object. virtual void DrawItem( const MbSpaceItem * gi, int R, int G, int B, int width = 1 ) = 0; // Отрисовать трехмерный геометрический объект с размещением по матрице. @@ -1028,7 +1028,7 @@ void DrawVertexEdges( const Vertex * vertex, int vR, int vG, int vB, MbStepData stepData( ist_SpaceStep, Math::visualSag ); MbFormNote note(true, false); for ( size_t k = 0, cnt = edges.size(); k < cnt; ++k ) { - if ( edges[k] != NULL ) { + if ( edges[k] != c3d_null ) { edges[k]->GetCurve().CalculateMesh( stepData, note, edgeMesh ); DrawGI::DrawMesh( &edgeMesh, TRGB_WHITE ); DrawGI::DrawMesh( &edgeMesh, eR, eG, eB ); diff --git a/C3d/Include/alg_indicator.h b/C3d/Include/alg_indicator.h index a6f46ad..658a593 100644 --- a/C3d/Include/alg_indicator.h +++ b/C3d/Include/alg_indicator.h @@ -124,7 +124,7 @@ public: }; -#define EMPTY_STR StrData( NULL ) ///< \ru Создание пустой строки \en Creation of an empty string +#define EMPTY_STR StrData( c3d_null ) ///< \ru Создание пустой строки \en Creation of an empty string //------------------------------------------------------------------------------ @@ -279,14 +279,14 @@ MATH_FUNC (ProgressBarWrapper *) CreateProgressBar( IProgressIndicator * progInd \en The wrapper of the execution progress indicator. \~ \param[in] msg - \ru Данные о строке. \en Data of a string \~ - \return \ru true, если progBar != NULL и удалось задать имя процесса. + \return \ru true, если progBar != c3d_null и удалось задать имя процесса. \en true if 'progBar' is not null and the process name is successfully set. \~ \ingroup Base_Items */ // --- inline bool SetProgressBarName( ProgressBarWrapper * progBar, IStrData & msg ) { - if ( progBar != NULL ) + if ( progBar != c3d_null ) return progBar->SetName( msg ); return false; } @@ -308,7 +308,7 @@ inline bool SetProgressBarName( ProgressBarWrapper * progBar, IStrData & msg ) // --- inline bool SetProgressBarValue( ProgressBarWrapper * progBar, size_t v ) { - if ( progBar != NULL && !progBar->IsCancel() ) + if ( progBar != c3d_null && !progBar->IsCancel() ) return progBar->SetProgress( v ); return false; } @@ -328,7 +328,7 @@ inline bool SetProgressBarValue( ProgressBarWrapper * progBar, size_t v ) // --- inline void FinishProgressBar( ProgressBarWrapper * progBar ) { - if ( progBar != NULL ) { + if ( progBar != c3d_null ) { if ( progBar->IsCancel() ) progBar->Stop(); else progBar->Success(); } @@ -347,7 +347,7 @@ inline void FinishProgressBar( ProgressBarWrapper * progBar ) // --- inline bool StopProgressBar( ProgressBarWrapper * progBar ) { - if ( progBar != NULL && progBar->IsCancel() ) { + if ( progBar != c3d_null && progBar->IsCancel() ) { progBar->Stop(); return true; } @@ -362,14 +362,14 @@ inline bool StopProgressBar( ProgressBarWrapper * progBar ) \en The wrapper of the execution progress indicator. \~ \param[in] useParentName - \ru Флаг использования имени родителя. \en The flag of using the parent name. \~ - \return \ru true, если progBar != NULL. + \return \ru true, если progBar != c3d_null. \en true if 'progBar' is not null. \~ \ingroup Base_Items */ // --- inline bool UseParentName( ProgressBarWrapper * progBar, bool useParentName ) { - if ( progBar != NULL ) { + if ( progBar != c3d_null ) { progBar->UseParentName( useParentName ); return true; } @@ -389,7 +389,7 @@ inline bool UseParentName( ProgressBarWrapper * progBar, bool useParentName ) // --- inline bool IsParentNameUsed( const ProgressBarWrapper * progBar ) { - if ( progBar != NULL ) + if ( progBar != c3d_null ) return progBar->IsParentNameUsed(); return false; diff --git a/C3d/Include/alg_mesh_to_brep.h b/C3d/Include/alg_mesh_to_brep.h index d19605d..fec6646 100644 --- a/C3d/Include/alg_mesh_to_brep.h +++ b/C3d/Include/alg_mesh_to_brep.h @@ -76,7 +76,7 @@ MbFaceShell * ConvertGridToShell( const MbGrid & grid, const GridsToShellValues & params, const MbSNameMaker & snMaker, MbResultType & res, - IProgressIndicator * progBar = NULL ); + IProgressIndicator * progBar = c3d_null ); //------------------------------------------------------------------------------ @@ -86,7 +86,7 @@ MbFaceShell * ConvertMeshToShell( const MbMesh & mesh, const GridsToShellValues & params, const MbSNameMaker & snMaker, MbResultType & res, - IProgressIndicator * progBar = NULL ); + IProgressIndicator * progBar = c3d_null ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/alg_nurbs_conic.h b/C3d/Include/alg_nurbs_conic.h index 637741f..d93d98f 100644 --- a/C3d/Include/alg_nurbs_conic.h +++ b/C3d/Include/alg_nurbs_conic.h @@ -57,9 +57,9 @@ class MbVector3D; \en The discriminant is less than 1. Otherwise it will be set to 0.99999999 automatically. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. + c3d_null, если не удалось построить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for a given parameters has failed. \~ + is c3d_null if a try to construct a conic for a given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -87,9 +87,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_1( const MbCartPoint3D & mbPoint0, const Mb \en The discriminant is less than 1. Otherwise it will be set to 0.99999999 automatically. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. + c3d_null, если не удалось построить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for a given parameters has failed. \~ + is c3d_null if a try to construct a conic for a given parameters has failed. \~ \ingroup Curve_Modeling */ // --- @@ -113,9 +113,9 @@ MATH_FUNC ( MbCurve * ) NurbsConic_1( const MbCartPoint & mbPoint0, const MbCart \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -138,9 +138,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_2( std::vector & vmbConicPoi \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve_Modeling */ // --- @@ -165,9 +165,9 @@ MATH_FUNC ( MbCurve * ) NurbsConic_2( std::vector & vmbConicPoints, \param[in] mbTangent2 - \ru Наклон в конце кривой. \en Inclination at end of a curve. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -193,9 +193,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_3( const std::vector & vmbCo \param[in] mbTangent2 - \ru Наклон в конце кривой. \en Inclination at end of a curve. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve_Modeling */ // --- @@ -224,9 +224,9 @@ MATH_FUNC ( MbCurve * ) NurbsConic_3( const std::vector & vmbConicP \en The discriminant is less than 1. Otherwise it will be set to 0.99999999 automatically. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. + c3d_null, если не удалось построить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -256,9 +256,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_4( const MbCartPoint3D & mbPoint1, const Mb \en The discriminant is less than 1. Otherwise it will be set to 0.99999999 automatically. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. + c3d_null, если не удалось построить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve_Modeling */ // --- @@ -288,9 +288,9 @@ MATH_FUNC ( MbCurve * ) NurbsConic_4( const MbCartPoint & mbPoint1, const MbCart \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. \en Point number at which the inclination is specified. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -319,9 +319,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_5( const std::vector & vmbCo \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. \en Point number at which the inclination is specified. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve_Modeling */ // --- @@ -342,9 +342,9 @@ MATH_FUNC ( MbCurve * ) NurbsConic_5( const std::vector & vmbConicP \en The container for points of a conic: the first point is start point, the last point is end point. there should be exactly 5 points. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve3D_Modeling */ // --- @@ -365,9 +365,9 @@ MATH_FUNC ( MbCurve3D * ) NurbsConic_6( const std::vector & vmbCo \en The container for points of a conic: the first point is start point, the last point is end point. there should be exactly 5 points. \~ \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. + c3d_null, если не удалось постороить конику для заданных параметров. \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ + is c3d_null if a try to construct a conic for given parameters has failed. \~ \ingroup Curve_Modeling */ // --- diff --git a/C3d/Include/alg_polyline.h b/C3d/Include/alg_polyline.h index 2fd6656..b6732f8 100644 --- a/C3d/Include/alg_polyline.h +++ b/C3d/Include/alg_polyline.h @@ -43,14 +43,14 @@ class MATH_CLASS MbCubicSpline3D; радиус скругления в этой точке. При создании заполняются поля m_lineSeg и m_arcSeg. m_lineSeg - это прямолинейный сегмент из этой точки в следующую. Для последней точки и замкнутой ломаной - из последней в первую. m_arcSeg - дуга скругления в данной точке. - Если какой-то сегмент был полностью удален или не создан, то его указатель должен быть NULL. + Если какой-то сегмент был полностью удален или не создан, то его указатель должен быть c3d_null. Объектами m_lineSeg и m_arcSeg не владеет, поэтому и не удаляет их. Объекты из полилинии. \en Some points may be deleted while the construction, therefore the old index is entered, it is filled and used in a model. Parameters of a point are its coordinates and fillet radius in this point. In a time of creation the fields 'm_lineSeg' and 'm_lineSeg' are being filled. 'm_lineSeg' is the straight-line segment from this point to the next point. For the last point and a closed polyline - from the last point to the first point. 'm_arcSeg'is the arc of a fillet in the given point. - If a segment has been fully deleted or it was not created then the pointer should be NULL. + If a segment has been fully deleted or it was not created then the pointer should be c3d_null. Object 'm_lineSeg' and 'm_arcSeg' are not owned, therefore they are not deleted. Objects from a polyline. \~ \ingroup Data_Structures */ @@ -69,8 +69,8 @@ public: : m_oldIndex( SYS_MAX_T ) , m_point () , m_radius ( 0.0 ) - , m_lineSeg ( NULL ) - , m_arcSeg ( NULL ) + , m_lineSeg ( c3d_null ) + , m_arcSeg ( c3d_null ) {} /// \ru Конструктор копирования. \en Copy constructor. Polyline3DPoint( const Polyline3DPoint & other ) @@ -250,9 +250,9 @@ MATH_FUNC (void) CreateSmoothFromBezier( const MbBezier & bez, RPArray /** \brief \ru Создать кривую заданного типа базе NURBS-кривой. \en Create a curve of a given type as NURBS-curve. \~ \details \ru Работает для двух типов: pt_LineSegment и pt_Arc. Если не удалось - аппроксимировать с заданной точностью функция вернет NULL. + аппроксимировать с заданной точностью функция вернет c3d_null. \en It works for the two types: 'pt_LineSegment' and 'pt_Arc'. If approximation with the given tolerance has failed - then the function returns NULL. \~ + then the function returns c3d_null. \~ \param[in] nurbs - \ru Исходная NURBS-кривая. \en The initial NURBS-curve. \~ \param[in] type - \ru Тип кривой, которую требуется создать. @@ -288,7 +288,7 @@ MATH_FUNC (MbCurve *) ConvertNurbsToCurveOfType( const MbNurbs & nurbs, MbePlane */ // --- MATH_FUNC (MbCurve *) GetFlatCurve( const MbCurve3D & curve3D, const MbMatrix3D & into, - MbRect1D * pRgn = NULL, VERSION version = Math::DefaultMathVersion() ); + MbRect1D * pRgn = c3d_null, VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/assembly.h b/C3d/Include/assembly.h index 971b4c9..62c8ef4 100644 --- a/C3d/Include/assembly.h +++ b/C3d/Include/assembly.h @@ -94,10 +94,10 @@ public: // \ru Общие функции геометрического объекта \en Common functions of a geometric object virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en An object type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move( const MbVector3D &, MbRegTransform * iReg = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move( const MbVector3D &, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равным \en Make the objects equal @@ -151,11 +151,11 @@ public: virtual const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; // \ru Преобразовать согласно матрице c использованием регистратора селектированные содержимые объекты. \en Transform selected objects according to the matrix using the registrator. - virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); + virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора с использованием регистратора селектированные содержимые объекты. \en Move selected objects along the vector using the registrator. - virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = NULL ); + virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси на заданный угол с использованием регистратора селектированные содержимые объекты. \en Rotate selected objects about the axis by the given angle using the registrator. - virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); + virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); /// \ru Отдать селектированные содержимые объекты. \en Get selected objects. bool DetachSelected( RPArray & items, SArray & matrs, bool selected = true ); /// \ru Отцепить все видимые или невидимые объекты. \en Detach all visible or invisible objects. \~ @@ -310,8 +310,8 @@ template MbAssembly::MbAssembly( const ItemsVector & items ) : MbItem() , assemblyItems() - , constraintSystem( NULL ) - , m_reactor( NULL ) + , constraintSystem( c3d_null ) + , m_reactor( c3d_null ) { #ifdef C3D_DEBUG // Check a condition of the single owner. @@ -336,7 +336,7 @@ MbAssembly::MbAssembly( const ItemsVector & items ) template void MbAssembly::_Init( const ItemsVector & items ) { - C3D_ASSERT( assemblyItems.empty() && (constraintSystem == NULL) ); + C3D_ASSERT( assemblyItems.empty() && (constraintSystem == c3d_null) ); SimpleName idCounter = 0; for ( size_t i = 0, iCount = items.size(); i < iCount; ++i ) @@ -383,7 +383,7 @@ void MbAssembly::GetFacesSet( FacesVector & faces ) const template void MbInstance::GetFacesSet( FacesVector & faces ) const { - if ( item != NULL ) { + if ( item != c3d_null ) { if ( item->IsA() == st_Solid ) static_cast( *item ).GetFacesSet( faces ); else if ( item->IsA() == st_Assembly ) diff --git a/C3d/Include/assisting_item.h b/C3d/Include/assisting_item.h index 73fa9df..06a7861 100644 --- a/C3d/Include/assisting_item.h +++ b/C3d/Include/assisting_item.h @@ -51,10 +51,10 @@ public : // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en An object type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Whether the objects are equal? virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными? \en Whether the objects are similar? virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равным. \en Make the objects equal. diff --git a/C3d/Include/attr_color.h b/C3d/Include/attr_color.h index 3d9c8f4..6516b24 100644 --- a/C3d/Include/attr_color.h +++ b/C3d/Include/attr_color.h @@ -1,436 +1,439 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибуты. Цвет. Толщина линий отрисовки. Стиль линий отрисовки. Свойства для OpenGL. - \en Attributes. Color. Thickness of drawing lines. Style of drawing lines. Properties for OpenGL. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_COLOR_H -#define __ATTR_COLOR_H - - -#include -#include - - -c3d_constexpr uint __RGB__ = 3; - - -//------------------------------------------------------------------------------ -/** \brief \ru Преобразовать цвет по трём компонентам в uint32. - \en Convert a color by 3 components in uint32. \~ - \details - \warning \ru Значения компонент цвета должны лежать в диапазоне [ 0; 1 ]. - \en Values of color components should belong to the range [ 0; 1 ]. \~ - \ingroup Model_Attributes -*/ -// --- -inline uint32 RGB2uint32( double r, double g, double b ) -{ - const double f1 = 255.0 / 256.0; - uint32 uinturgb[3]; - const uint32 bt = 256; - uinturgb[0] = uint32 ( 256.0 * r * f1 ); - uinturgb[1] = uint32 ( 256.0 * g * f1 ); - uinturgb[2] = uint32 ( 256.0 * b * f1 ); - for ( int n = 0; n < 3; n++ ) - if ( uinturgb[n] >= bt ) { - uinturgb[n] = bt - 1; - C3D_ASSERT_UNCONDITIONAL( false ); - } - return uinturgb[0] + bt * ( uinturgb[1] + bt * uinturgb[2] ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Преобразовать цвет по трём компонентам в uint32. - \en Convert a color by 3 components in uint32. \~ - \details - \warning \ru Значения компонент цвета должны лежать в диапазоне [ 0; 1 ]. - \en Values of color components should belong to the range [ 0; 1 ]. \~ - \ingroup Model_Attributes -*/ -// --- -inline uint32 RGB2uint32( float r, float g, float b, float a ) -{ - const float f1 = 255.0 / 256.0; - uint32 uinturgb[4]; - const uint32 bt = 256; - uinturgb[0] = uint32 ( 256.0 * r * f1 ); - uinturgb[1] = uint32 ( 256.0 * g * f1 ); - uinturgb[2] = uint32 ( 256.0 * b * f1 ); - uinturgb[3] = uint32 ( 256.0 * a * f1 ); - for ( int n = 0; n < 4; n++ ) - if ( uinturgb[n] >= bt ) { - uinturgb[n] = bt - 1; - //C3D_ASSERT_UNCONDITIONAL( false ); - } - return uinturgb[0] + bt * ( uinturgb[1] + bt * ( uinturgb[2] + bt * uinturgb[3] ) ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Преобразовать unit32 в три компоненты цвета. - \en Convert unit32 to 3 components of color. \~ - \details - \warning \ru Компоненты цветов лежат в диапазоне [ 0; 1 ]. - \en Color components belong to the range [ 0; 1 ]. \~ - \ingroup Model_Attributes -*/ -// --- -template -void uint322RGB( uint32 color, float_t& r, float_t& g, float_t& b ) { - const float_t r255 = float_t(1.0 / 255.0); - const uint32 u256 = (uint32)SYS_MAX_UINT8 + 1; - r = float_t ( color % u256); - g = float_t ( (color / 256) % u256); - b = float_t ( (color / 65536) % u256); - r *= r255; g *= r255; b *= r255; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Преобразовать цвет из модели HSV в uint32. - \en Convert a color from HSV model in uint32. \~ - \details \ru Преобразовать цвет из модели HSV в uint32. \n - \en Convert a color from HSV model in uint32. \n \~ - \ingroup Model_Attributes -*/ -// --- -inline -uint32 HSV2uint32( double h, double s, double v ) -{ - double hh, p, q, t, ff; - long i; - double r, g, b; - if ( s <= 0.0 ) { - r = v; - g = v; - b = v; - return ::RGB2uint32( r, g, b ); - } - hh = h; - if ( hh >= 360.0 ) - hh = 0.0; - hh /= 60.0; - i = (long)hh; - ff = hh - i; - p = v * (1.0 - s); - q = v * (1.0 - (s * ff)); - t = v * (1.0 - (s * (1.0 - ff))); - - switch ( i ) { - case 0 : { - r = v; - g = t; - b = p; - } break; - case 1 : { - r = q; - g = v; - b = p; - } break; - case 2 : { - r = p; - g = v; - b = t; - } break; - case 3 : { - r = p; - g = q; - b = v; - } break; - case 4 : { - r = t; - g = p; - b = v; - } break; - default : { - r = v; - g = p; - b = q; - } break; - } - return ::RGB2uint32( r, g, b ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Цвет. - \en Color. \~ - \details \ru Цвет. \n - \en Color. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbColor : public MbElementaryAttribute { -protected : - uint32 color; ///< \ru Цвет. \en Color. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbColor( const MbColor & init ); -public : - /// \ru Конструктор. \en Constructor. - MbColor( uint32 init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbColor(); - - // \ru Общие функции объекта \en Common functions of object. - - virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. - - /// \ru Установить цвет. \en Set a color. - void Init( uint32 init ) { color = init; } - /// \ru Дать цвет. \en Get a color. - uint32 Color() const { return color; } -//int R() const { return red; } // \ru Красный цвет \en Red color -//int G() const { return green; } // \ru Зеленый цвет \en Green color -//int B() const { return blue; } // \ru Синий цвет \en Blue color - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbColor & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbColor ) -}; // MbColor - -IMPL_PERSISTENT_OPS( MbColor ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Толщина линий отрисовки. - \en Thickness of drawing lines. \~ - \details \ru Толщина линий отрисовки. \n - \en Thickness of drawing lines. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbWidth : public MbElementaryAttribute { -protected : - int width; ///< \ru Толщина линий отрисовки. \enThickness of drawing lines. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbWidth( const MbWidth & init ); -public : - /// \ru Конструктор. \en Constructor. - MbWidth( int init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbWidth(); - - // \ru Общие функции объекта \en Common functions of object. - - virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. - - /// \ru Установить толщину. \en Set a thickness. - void Init( int init ) { width = init; } - /// \ru Дать толщину. \en Get a thickness. - int Width() const { return width; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbWidth & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWidth ) -}; // MbWidth - -IMPL_PERSISTENT_OPS( MbWidth ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Стиль линий отрисовки. - \en Style of drawing lines. \~ - \details \ru Стиль линий отрисовки. \n - \en Style of drawing lines. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbStyle : public MbElementaryAttribute { -protected : - int style; ///< \ru Стиль линий отрисовки. \en Style of drawing lines. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbStyle( const MbStyle & init ); -public : - /// \ru Конструктор. \en Constructor. - MbStyle( int init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbStyle(); - - // \ru Общие функции объекта \en Common functions of object. - - virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. - - /// \ru Установить стиль линий отрисовки. \en Set style of drawing lines. - void Init( int init ) { style = init; } - /// \ru Дать стиль линий отрисовки. \en Get style of drawing lines. - int Style() const { return style; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbStyle & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStyle ) -}; // MbStyle - -IMPL_PERSISTENT_OPS( MbStyle ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойства для OpenGL. - \en Properties for OpenGL. \~ - \details \ru Свойства для OpenGL для трех цветов: RED, GREEN, BLUE. \n - \en Properties for OpenGL for colors: RED, GREEN, BLUE. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbVisual : public MbElementaryAttribute { -protected : - float ambient[__RGB__]; ///< \ru Коэффициент общего фона для трех цветов: RED, GREEN, BLUE. \en Coefficient of ambient background for colors: RED, GREEN, BLUE, range 0.0 - 1.0. - float diffuse[__RGB__]; ///< \ru Коэффициент диффузного отражения для трех цветов: RED, GREEN, BLUE. \en Coefficient of diffuse reflection for colors: RED, GREEN, BLUE, range 0.0 - 1.0. - float specularity[__RGB__]; ///< \ru Коэффициент зеркального отражения света трех цветов: RED, GREEN, BLUE. \en Coefficient of specular reflection for light colors: RED, GREEN, BLUE, range 0.0 - 1.0. - float shininess; ///< \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection), range 0 - 128. - float opacity; ///< \ru Коэффициент непрозрачности (коэффициент суммарного отражения). \en Opacity coefficient (coefficient of total reflection), range 0.0 (transparent) - 1.0(opaque). - float emission; ///< \ru Коэффициент излучения. \en Emissivity coefficient, range 0.0 - 1.0. - float chrom; ///< \ru Коэффициент зеркального отражения объектов. \en Coefficient of specular reflection for objects, range 0.0 - 1.0. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbVisual( const MbVisual & init ); -public : - /// \ru Конструктор. \en Constructor. - MbVisual( float a = MB_AMBIENT, float d = MB_DIFFUSE, float s = MB_SPECULARITY, - float h = MB_SHININESS, float t = MB_OPACITY, float e = MB_EMISSION ); - /// \ru Деструктор. \en Destructor. - virtual ~MbVisual(); - - // \ru Общие функции объекта \en Common functions of object. - - virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. - - /// \ru Установить свойства для OpenGL. \en Set properties for OpenGL. - void Init( float a = MB_AMBIENT, float d = MB_DIFFUSE, float s = MB_SPECULARITY, - float h = MB_SHININESS, float t = MB_OPACITY, float e = MB_EMISSION, uint rgb = 0 ) { - ambient[rgb%__RGB__] = a; // \ru Коэффициент общего фона. \en Coefficient of ambient background. - diffuse[rgb%__RGB__] = d; // \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. - specularity[rgb%__RGB__] = s; // \ru Коэффициент зеркального отражения света. \en Coefficient of specular reflection for light. - shininess = h; // \ru Блеск (показатель степени. в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). - opacity = t; // \ru Коэффициент непрозрачности. \en Opacity coefficient. - emission = e; // \ru Коэффициент излучения. \en Emissivity coefficient. - chrom = s; // \ru Коэффициент зеркального отражения объектов. \en Coefficient of specular reflection for objects. - } - /// \ru Дать свойства для OpenGL. \en Get properties for OpenGL. - void Get( float & a, float & d, float & s, float & h, float & t, float & e, uint rgb = 0 ) const { - a = ambient[rgb%__RGB__]; // \ru Коэффициент общего фона. \en Coefficient of ambient background. - d = diffuse[rgb%__RGB__]; // \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. - s = specularity[rgb%__RGB__]; // \ru Коэффициент зеркального отражения света. \en Coefficient of Specular reflection for light. - h = shininess; // \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). - t = opacity; // \ru Коэффициент непрозрачности. \en Opacity coefficient. - e = emission; // \ru Коэффициент излучения. \en Emissivity coefficient. - } - float Ambient ( uint rgb = 0 ) const { return ambient[rgb%__RGB__]; } // \ru Дать коэффициент общего фона. \en Get a coefficient of ambient background. - float Diffuse ( uint rgb = 0 ) const { return diffuse[rgb%__RGB__]; } // \ru Дать коэффициент диффузного отражения. \en Get a coefficient of diffuse reflection. - float Specularity ( uint rgb = 0 ) const { return specularity[rgb%__RGB__]; } // \ru Дать коэффициент зеркального отражения света. \en Get a coefficient of specular reflection for light. - float Shininess () const { return shininess; } // \ru Дать блеск (показатель степени в законе зеркального отражения). \en Get shininess (index according to the law of specular reflection). - float Opacity () const { return opacity; } // \ru Дать коэффициент непрозрачности. \en Get an opacity coefficient. - float Emission () const { return emission; } // \ru Дать коэффициент излучения. \en Get a coefficient of emissivity. - float Chrom () const { return chrom; } // \ru Дать коэффициент зеркального отражения объектов. \en Get a coefficient of specular reflection for objects. - const float * Ambients () const { return ambient; } // \ru Дать коэффициенты общего фона. \en Get all coefficients of ambient background. - const float * Diffuses () const { return diffuse; } // \ru Дать коэффициенты диффузного отражения. \en Get all coefficients of diffuse reflection. - const float * Specularitys() const { return specularity; } // \ru Дать коэффициенты зеркального отражения света. \en Get all coefficients of specular reflection for light. - - void SetAmbient ( float v, uint rgb = 0 ) { ambient[rgb%__RGB__] = v; } // \ru Установить коэффициент общего фона. \en Set a coefficient of ambient background. - void SetDiffuse ( float v, uint rgb = 0 ) { diffuse[rgb%__RGB__] = v ; } // \ru Установить коэффициент диффузного отражения. \en Set a coefficient of diffuse reflection. - void SetSpecularity ( float v, uint rgb = 0 ) { specularity[rgb%__RGB__] = v; } // \ru Установить коэффициент зеркального отражения света. \en Set a coefficient of specular reflection for light. - void SetShininess ( float v ) { shininess = v; } // \ru Установить блеск (показатель степени в законе зеркального отражения). \en Set shininess (index according to the law of specular reflection). - void SetOpacity ( float v ) { opacity = v; } // \ru Установить коэффициент непрозрачности. \en Set an opacity coefficient. - void SetEmission ( float v ) { emission = v; } // \ru Установить коэффициент излучения. \en Set a coefficient of emissivity. - void SetChrom ( float v ) { chrom = v; } // \ru Установить коэффициент зеркального отражения объектов. \en Set a coefficient of specular reflection for objects. - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbVisual & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVisual ) -}; // MbVisual - -IMPL_PERSISTENT_OPS( MbVisual ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Количество u-линий и v-линий отрисовочной сетки. - \en The number of u-mesh and v-mesh drawing lines. \~ - \details \ru Количество u-линий и v-линий отрисовочной сетки. \n - \en The number of u-mesh and v-mesh drawing lines. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbWireCount : public MbElementaryAttribute { -protected : - size_t uMeshCount; ///< \ru Количество u-линий отрисовочной сетки. \en The number of u-mesh lines. - size_t vMeshCount; ///< \ru Количество v-линий отрисовочной сетки. \en The number of v-mesh lines. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbWireCount( const MbWireCount & init ); -public : - /// \ru Конструктор. \en Constructor. - MbWireCount( size_t uCount, size_t vCount ); - /// \ru Деструктор. \en Destructor. - virtual ~MbWireCount(); - - // \ru Общие функции объекта \en Common functions of object. - - virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. - - /// \ru Установить количество линий отрисовки. \en Set count of drawing lines. - void Init( size_t uCount, size_t vCount ) { uMeshCount = uCount, vMeshCount = vCount; } - /// \ru Выдать количество разбиений по u и v. \en The the number of splittings in u-direction and v-direction. - void Get( size_t & uCount, size_t & vCount ) const { uCount = uMeshCount; vCount = vMeshCount; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbWireCount & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireCount ) -}; // MbWireCount - -IMPL_PERSISTENT_OPS( MbWireCount ) - - -#endif // __ATTR_COLOR_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибуты. Цвет. Толщина линий отрисовки. Стиль линий отрисовки. Свойства для OpenGL. + \en Attributes. Color. Thickness of drawing lines. Style of drawing lines. Properties for OpenGL. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_COLOR_H +#define __ATTR_COLOR_H + + +#include +#include + + +c3d_constexpr uint __RGB__ = 3; + + +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать цвет по трём компонентам в uint32. + \en Convert a color by 3 components in uint32. \~ + \details + \warning \ru Значения компонент цвета должны лежать в диапазоне [ 0; 1 ]. + \en Values of color components should belong to the range [ 0; 1 ]. \~ + \ingroup Model_Attributes +*/ +// --- +inline +uint32 RGB2uint32( double r, double g, double b ) +{ + const double f1 = 255.0 / 256.0; + uint32 uinturgb[3]; + const uint32 bt = 256; + uinturgb[0] = uint32 ( 256.0 * r * f1 ); + uinturgb[1] = uint32 ( 256.0 * g * f1 ); + uinturgb[2] = uint32 ( 256.0 * b * f1 ); + for ( int n = 0; n < 3; n++ ) + if ( uinturgb[n] >= bt ) { + uinturgb[n] = bt - 1; + C3D_ASSERT_UNCONDITIONAL( false ); + } + return uinturgb[0] + bt * ( uinturgb[1] + bt * uinturgb[2] ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать цвет по трём компонентам в uint32. + \en Convert a color by 3 components in uint32. \~ + \details + \warning \ru Значения компонент цвета должны лежать в диапазоне [ 0; 1 ]. + \en Values of color components should belong to the range [ 0; 1 ]. \~ + \ingroup Model_Attributes +*/ +// --- +inline +uint32 RGB2uint32( float r, float g, float b, float a ) +{ + const float f1 = 255.0 / 256.0; + uint32 uinturgb[4]; + const uint32 bt = 256; + uinturgb[0] = uint32 ( 256.0 * r * f1 ); + uinturgb[1] = uint32 ( 256.0 * g * f1 ); + uinturgb[2] = uint32 ( 256.0 * b * f1 ); + uinturgb[3] = uint32 ( 256.0 * a * f1 ); + for ( int n = 0; n < 4; n++ ) + if ( uinturgb[n] >= bt ) { + uinturgb[n] = bt - 1; + //C3D_ASSERT_UNCONDITIONAL( false ); + } + return uinturgb[0] + bt * ( uinturgb[1] + bt * ( uinturgb[2] + bt * uinturgb[3] ) ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать unit32 в три компоненты цвета. + \en Convert unit32 to 3 components of color. \~ + \details + \warning \ru Компоненты цветов лежат в диапазоне [ 0; 1 ]. + \en Color components belong to the range [ 0; 1 ]. \~ + \ingroup Model_Attributes +*/ +// --- +template +void uint322RGB( uint32 color, float_t & r, float_t & g, float_t & b ) +{ + const float_t r255 = float_t(1.0 / 255.0); + const uint32 u256 = (uint32)SYS_MAX_UINT8 + 1; + r = float_t ( color % u256); + g = float_t ( (color / 256) % u256); + b = float_t ( (color / 65536) % u256); + r *= r255; g *= r255; b *= r255; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать цвет из модели HSV в uint32. + \en Convert a color from HSV model in uint32. \~ + \details \ru Преобразовать цвет из модели HSV в uint32. \n + \en Convert a color from HSV model in uint32. \n \~ + \ingroup Model_Attributes +*/ +// --- +inline +uint32 HSV2uint32( double h, double s, double v ) +{ + double hh, p, q, t, ff; + long i; + double r, g, b; + if ( s <= 0.0 ) { + r = v; + g = v; + b = v; + return ::RGB2uint32( r, g, b ); + } + hh = h; + if ( hh >= 360.0 ) + hh = 0.0; + hh /= 60.0; + i = (long)hh; + ff = hh - i; + p = v * (1.0 - s); + q = v * (1.0 - (s * ff)); + t = v * (1.0 - (s * (1.0 - ff))); + + switch ( i ) { + case 0 : { + r = v; + g = t; + b = p; + } break; + case 1 : { + r = q; + g = v; + b = p; + } break; + case 2 : { + r = p; + g = v; + b = t; + } break; + case 3 : { + r = p; + g = q; + b = v; + } break; + case 4 : { + r = t; + g = p; + b = v; + } break; + default : { + r = v; + g = p; + b = q; + } break; + } + return ::RGB2uint32( r, g, b ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Цвет. + \en Color. \~ + \details \ru Цвет. \n + \en Color. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbColor : public MbElementaryAttribute { +protected : + uint32 color; ///< \ru Цвет. \en Color. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbColor( const MbColor & init ); +public : + /// \ru Конструктор. \en Constructor. + MbColor( uint32 init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbColor(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить цвет. \en Set a color. + void Init( uint32 init ) { color = init; } + /// \ru Дать цвет. \en Get a color. + uint32 Color() const { return color; } +//int R() const { return red; } // \ru Красный цвет \en Red color +//int G() const { return green; } // \ru Зеленый цвет \en Green color +//int B() const { return blue; } // \ru Синий цвет \en Blue color + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbColor & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbColor ) +}; // MbColor + +IMPL_PERSISTENT_OPS( MbColor ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Толщина линий отрисовки. + \en Thickness of drawing lines. \~ + \details \ru Толщина линий отрисовки. \n + \en Thickness of drawing lines. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbWidth : public MbElementaryAttribute { +protected : + int width; ///< \ru Толщина линий отрисовки. \enThickness of drawing lines. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbWidth( const MbWidth & init ); +public : + /// \ru Конструктор. \en Constructor. + MbWidth( int init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbWidth(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить толщину. \en Set a thickness. + void Init( int init ) { width = init; } + /// \ru Дать толщину. \en Get a thickness. + int Width() const { return width; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbWidth & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWidth ) +}; // MbWidth + +IMPL_PERSISTENT_OPS( MbWidth ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Стиль линий отрисовки. + \en Style of drawing lines. \~ + \details \ru Стиль линий отрисовки. \n + \en Style of drawing lines. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbStyle : public MbElementaryAttribute { +protected : + int style; ///< \ru Стиль линий отрисовки. \en Style of drawing lines. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbStyle( const MbStyle & init ); +public : + /// \ru Конструктор. \en Constructor. + MbStyle( int init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbStyle(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить стиль линий отрисовки. \en Set style of drawing lines. + void Init( int init ) { style = init; } + /// \ru Дать стиль линий отрисовки. \en Get style of drawing lines. + int Style() const { return style; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbStyle & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStyle ) +}; // MbStyle + +IMPL_PERSISTENT_OPS( MbStyle ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойства для OpenGL. + \en Properties for OpenGL. \~ + \details \ru Свойства для OpenGL для трех цветов: RED, GREEN, BLUE. \n + \en Properties for OpenGL for colors: RED, GREEN, BLUE. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbVisual : public MbElementaryAttribute { +protected : + float ambient[__RGB__]; ///< \ru Коэффициент общего фона для трех цветов: RED, GREEN, BLUE. \en Coefficient of ambient background for colors: RED, GREEN, BLUE, range 0.0 - 1.0. + float diffuse[__RGB__]; ///< \ru Коэффициент диффузного отражения для трех цветов: RED, GREEN, BLUE. \en Coefficient of diffuse reflection for colors: RED, GREEN, BLUE, range 0.0 - 1.0. + float specularity[__RGB__]; ///< \ru Коэффициент зеркального отражения света трех цветов: RED, GREEN, BLUE. \en Coefficient of specular reflection for light colors: RED, GREEN, BLUE, range 0.0 - 1.0. + float shininess; ///< \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection), range 0 - 128. + float opacity; ///< \ru Коэффициент непрозрачности (коэффициент суммарного отражения). \en Opacity coefficient (coefficient of total reflection), range 0.0 (transparent) - 1.0(opaque). + float emission; ///< \ru Коэффициент излучения. \en Emissivity coefficient, range 0.0 - 1.0. + float chrom; ///< \ru Коэффициент зеркального отражения объектов. \en Coefficient of specular reflection for objects, range 0.0 - 1.0. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbVisual( const MbVisual & init ); +public : + /// \ru Конструктор. \en Constructor. + MbVisual( float a = MB_AMBIENT, float d = MB_DIFFUSE, float s = MB_SPECULARITY, + float h = MB_SHININESS, float t = MB_OPACITY, float e = MB_EMISSION ); + /// \ru Деструктор. \en Destructor. + virtual ~MbVisual(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить свойства для OpenGL. \en Set properties for OpenGL. + void Init( float a = MB_AMBIENT, float d = MB_DIFFUSE, float s = MB_SPECULARITY, + float h = MB_SHININESS, float t = MB_OPACITY, float e = MB_EMISSION, uint rgb = 0 ) { + ambient[rgb%__RGB__] = a; // \ru Коэффициент общего фона. \en Coefficient of ambient background. + diffuse[rgb%__RGB__] = d; // \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. + specularity[rgb%__RGB__] = s; // \ru Коэффициент зеркального отражения света. \en Coefficient of specular reflection for light. + shininess = h; // \ru Блеск (показатель степени. в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). + opacity = t; // \ru Коэффициент непрозрачности. \en Opacity coefficient. + emission = e; // \ru Коэффициент излучения. \en Emissivity coefficient. + chrom = s; // \ru Коэффициент зеркального отражения объектов. \en Coefficient of specular reflection for objects. + } + /// \ru Дать свойства для OpenGL. \en Get properties for OpenGL. + void Get( float & a, float & d, float & s, float & h, float & t, float & e, uint rgb = 0 ) const { + a = ambient[rgb%__RGB__]; // \ru Коэффициент общего фона. \en Coefficient of ambient background. + d = diffuse[rgb%__RGB__]; // \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. + s = specularity[rgb%__RGB__]; // \ru Коэффициент зеркального отражения света. \en Coefficient of Specular reflection for light. + h = shininess; // \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). + t = opacity; // \ru Коэффициент непрозрачности. \en Opacity coefficient. + e = emission; // \ru Коэффициент излучения. \en Emissivity coefficient. + } + float Ambient ( uint rgb = 0 ) const { return ambient[rgb%__RGB__]; } // \ru Дать коэффициент общего фона. \en Get a coefficient of ambient background. + float Diffuse ( uint rgb = 0 ) const { return diffuse[rgb%__RGB__]; } // \ru Дать коэффициент диффузного отражения. \en Get a coefficient of diffuse reflection. + float Specularity ( uint rgb = 0 ) const { return specularity[rgb%__RGB__]; } // \ru Дать коэффициент зеркального отражения света. \en Get a coefficient of specular reflection for light. + float Shininess () const { return shininess; } // \ru Дать блеск (показатель степени в законе зеркального отражения). \en Get shininess (index according to the law of specular reflection). + float Opacity () const { return opacity; } // \ru Дать коэффициент непрозрачности. \en Get an opacity coefficient. + float Emission () const { return emission; } // \ru Дать коэффициент излучения. \en Get a coefficient of emissivity. + float Chrom () const { return chrom; } // \ru Дать коэффициент зеркального отражения объектов. \en Get a coefficient of specular reflection for objects. + const float * Ambients () const { return ambient; } // \ru Дать коэффициенты общего фона. \en Get all coefficients of ambient background. + const float * Diffuses () const { return diffuse; } // \ru Дать коэффициенты диффузного отражения. \en Get all coefficients of diffuse reflection. + const float * Specularitys() const { return specularity; } // \ru Дать коэффициенты зеркального отражения света. \en Get all coefficients of specular reflection for light. + + void SetAmbient ( float v, uint rgb = 0 ) { ambient[rgb%__RGB__] = v; } // \ru Установить коэффициент общего фона. \en Set a coefficient of ambient background. + void SetDiffuse ( float v, uint rgb = 0 ) { diffuse[rgb%__RGB__] = v ; } // \ru Установить коэффициент диффузного отражения. \en Set a coefficient of diffuse reflection. + void SetSpecularity ( float v, uint rgb = 0 ) { specularity[rgb%__RGB__] = v; } // \ru Установить коэффициент зеркального отражения света. \en Set a coefficient of specular reflection for light. + void SetShininess ( float v ) { shininess = v; } // \ru Установить блеск (показатель степени в законе зеркального отражения). \en Set shininess (index according to the law of specular reflection). + void SetOpacity ( float v ) { opacity = v; } // \ru Установить коэффициент непрозрачности. \en Set an opacity coefficient. + void SetEmission ( float v ) { emission = v; } // \ru Установить коэффициент излучения. \en Set a coefficient of emissivity. + void SetChrom ( float v ) { chrom = v; } // \ru Установить коэффициент зеркального отражения объектов. \en Set a coefficient of specular reflection for objects. + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbVisual & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVisual ) +}; // MbVisual + +IMPL_PERSISTENT_OPS( MbVisual ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Количество u-линий и v-линий отрисовочной сетки. + \en The number of u-mesh and v-mesh drawing lines. \~ + \details \ru Количество u-линий и v-линий отрисовочной сетки. \n + \en The number of u-mesh and v-mesh drawing lines. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbWireCount : public MbElementaryAttribute { +protected : + size_t uMeshCount; ///< \ru Количество u-линий отрисовочной сетки. \en The number of u-mesh lines. + size_t vMeshCount; ///< \ru Количество v-линий отрисовочной сетки. \en The number of v-mesh lines. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbWireCount( const MbWireCount & init ); +public : + /// \ru Конструктор. \en Constructor. + MbWireCount( size_t uCount, size_t vCount ); + /// \ru Деструктор. \en Destructor. + virtual ~MbWireCount(); + + // \ru Общие функции объекта \en Common functions of object. + + virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. + + /// \ru Установить количество линий отрисовки. \en Set count of drawing lines. + void Init( size_t uCount, size_t vCount ) { uMeshCount = uCount, vMeshCount = vCount; } + /// \ru Выдать количество разбиений по u и v. \en The the number of splittings in u-direction and v-direction. + void Get( size_t & uCount, size_t & vCount ) const { uCount = uMeshCount; vCount = vMeshCount; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbWireCount & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireCount ) +}; // MbWireCount + +IMPL_PERSISTENT_OPS( MbWireCount ) + + +#endif // __ATTR_COLOR_H diff --git a/C3d/Include/attr_common_attribute.h b/C3d/Include/attr_common_attribute.h index ae22d14..f8a479b 100644 --- a/C3d/Include/attr_common_attribute.h +++ b/C3d/Include/attr_common_attribute.h @@ -37,7 +37,7 @@ protected : public : virtual MbeAttributeType AttributeFamily() const; // \ru Выдать тип атрибута. \en Get attribute type. virtual MbeAttributeType AttributeType() const = 0; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ) = 0; // \ru Инициализировать данные по присланным. \en Initialize data. @@ -46,13 +46,13 @@ public : // \ru Выполнить действия при конвертации владельца. \en Perform actions when converting the owner. virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging he owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. @@ -101,7 +101,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -137,7 +137,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -173,7 +173,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -209,7 +209,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -243,7 +243,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -280,7 +280,7 @@ public: public: virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. diff --git a/C3d/Include/attr_dencity.h b/C3d/Include/attr_dencity.h index 025963d..06efd72 100644 --- a/C3d/Include/attr_dencity.h +++ b/C3d/Include/attr_dencity.h @@ -38,7 +38,7 @@ public : // \ru Общие функции объекта \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. @@ -86,7 +86,7 @@ public : // \ru Общие функции объекта \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. @@ -137,7 +137,7 @@ public : // \ru Общие функции объекта \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. diff --git a/C3d/Include/attr_elementary_attribute.h b/C3d/Include/attr_elementary_attribute.h index c5fd3bf..a9acab6 100644 --- a/C3d/Include/attr_elementary_attribute.h +++ b/C3d/Include/attr_elementary_attribute.h @@ -30,7 +30,7 @@ public: public : virtual MbeAttributeType AttributeFamily() const; // \ru Тип атрибута \en Type of an attribute virtual MbeAttributeType AttributeType() const = 0; // \ru Выдать подтип атрибута \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const = 0; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ) = 0; // \ru Инициализировать данные по присланным \en Initialize data. @@ -39,13 +39,13 @@ public : // \ru Действия при конвертации владельца. \en Actions when converting the owner. virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); /// \ru Действия при трансформировании владельца. \en Actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Действия при перемещении владельца. \en Actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Действия при вращении владельца. \en Actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Действия при копировании владельца. \en Actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Действия при объединении владельца. \en Actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Действия при замене владельца. \en Actions when replacing the owner. diff --git a/C3d/Include/attr_flange_attribute.h b/C3d/Include/attr_flange_attribute.h index 74c3a00..a7b62bc 100644 --- a/C3d/Include/attr_flange_attribute.h +++ b/C3d/Include/attr_flange_attribute.h @@ -43,20 +43,20 @@ public: // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbeAttributeType AttributeType() const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Инициализировать данные по присланным. \en Initialize data. virtual bool Init( const MbAttribute & ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); diff --git a/C3d/Include/attr_geometric_attribute.h b/C3d/Include/attr_geometric_attribute.h index 05968b1..e229a30 100644 --- a/C3d/Include/attr_geometric_attribute.h +++ b/C3d/Include/attr_geometric_attribute.h @@ -52,19 +52,19 @@ public: // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbeAttributeType AttributeType() const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Инициализировать данные по присланным. \en Initialize data. virtual bool Init( const MbAttribute & ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); diff --git a/C3d/Include/attr_identifier.h b/C3d/Include/attr_identifier.h index adfe68e..637b918 100644 --- a/C3d/Include/attr_identifier.h +++ b/C3d/Include/attr_identifier.h @@ -39,7 +39,7 @@ public : // \ru Общие функции объекта. \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -92,7 +92,7 @@ public : // \ru Общие функции объекта \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. @@ -159,7 +159,7 @@ public : // \ru Общие функции объекта \en Common functions of object virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. @@ -221,7 +221,7 @@ public : virtual MbeAttributeType AttributeFamily() const; // \ru Дать тип атрибута. \en Get type of an attribute. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data. @@ -233,13 +233,13 @@ public : // \ru Выполнить действия при конвертации владельца \en Perform actions when converting the owner. virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. @@ -289,7 +289,7 @@ public: // \ru Общие функции объекта. \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по атрибуту. \en Initialize by attribute. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. diff --git a/C3d/Include/attr_product.h b/C3d/Include/attr_product.h index 2132e73..5dad842 100644 --- a/C3d/Include/attr_product.h +++ b/C3d/Include/attr_product.h @@ -37,7 +37,7 @@ public : // Выдать подтип атрибута (временно). virtual MbeAttributeType AttributeType() const = 0; // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const = 0; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; virtual bool IsSame( const MbAttribute &, double accuracy ) const = 0; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. // Инициализировать данные по присланным. virtual bool Init( const MbAttribute & ) = 0; @@ -49,13 +49,13 @@ public : // Действия при конвертации владельца. virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // Действия при трансформировании владельца. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // Действия при перемещении владельца. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // Действия при вращении владельца. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // Действия при копировании владельца. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // Действия при объединении владельца. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // Действия при замене владельца. @@ -100,7 +100,7 @@ public : // Выдать подтип атрибута (временно). virtual MbeAttributeType AttributeType() const; // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. // Инициализировать данные по присланным. virtual bool Init( const MbAttribute & ) ; @@ -319,7 +319,7 @@ public : // Выдать подтип атрибута (временно). virtual MbeAttributeType AttributeType() const; // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const ; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const ; virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. // Инициализировать данные по присланным. virtual bool Init( const MbAttribute & ) ; diff --git a/C3d/Include/attr_selected.h b/C3d/Include/attr_selected.h index da48371..f808f21 100644 --- a/C3d/Include/attr_selected.h +++ b/C3d/Include/attr_selected.h @@ -37,7 +37,7 @@ public : // \ru Общие функции объекта. \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data by given attribute. @@ -83,7 +83,7 @@ public : // \ru Общие функции объекта. \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data by given attribute. @@ -129,7 +129,7 @@ public : // \ru Общие функции объекта. \en Common functions of object. virtual MbeAttributeType AttributeType() const; // \ru Дать подтип атрибута. \en Get subtype of an attribute. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data by given attribute. diff --git a/C3d/Include/attr_stamprib_attribute.h b/C3d/Include/attr_stamprib_attribute.h index 73c787e..1833d3e 100644 --- a/C3d/Include/attr_stamprib_attribute.h +++ b/C3d/Include/attr_stamprib_attribute.h @@ -49,20 +49,20 @@ public: // \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbeAttributeType AttributeType() const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Инициализировать данные по присланным. \en Initialize data. virtual bool Init( const MbAttribute & ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); diff --git a/C3d/Include/attr_user_attribute.h b/C3d/Include/attr_user_attribute.h index e986818..ecb3a9d 100644 --- a/C3d/Include/attr_user_attribute.h +++ b/C3d/Include/attr_user_attribute.h @@ -108,7 +108,7 @@ public: /// \ru Выдать подтип пользовательского атрибута по пользовательскому типу. \en Get subtype of an user attribute by user-defined type. static MbeAttributeType AttributeType( const MbUserAttribType & userType ); - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ); // \ru Инициализировать данные по присланным. \en Initialize data by given attribute. @@ -117,13 +117,13 @@ public: // \ru Выполнить действия при конвертации владельца \en Perform actions when converting the owner virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при трансформировании владельца \en Perform actions when transforming the owner - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. @@ -197,7 +197,7 @@ public : /// \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbUserAttribType AttrTypeEx() const = 0; - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame( const MbAttribute &, double accuracy ) const = 0; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. virtual bool Init( const MbAttribute & ) = 0; // \ru Инициализировать данные по присланным. \en Initialize data. @@ -206,13 +206,13 @@ public : // \ru Выполнить действия при конвертации владельца. \en Perform actions when converting the owner. virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при трансформировании владельца. \en Perform actions when transforming the owner. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ); // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. @@ -256,7 +256,7 @@ public: /// \ru Выдать идентификатор атрибута. \en Get attribute identifier. const MbUserAttribType & GetUserAttrId() const { return userAttrId; } /// \ru Выдать атрибуты. \en Get attributes. - const MbAttribute * GetAttribute( size_t k ) const { return ((k < attributes.size()) ? attributes[k] : NULL); } + const MbAttribute * GetAttribute( size_t k ) const { return ((k < attributes.size()) ? attributes[k] : c3d_null); } // \ru Выдать количество атрибутов. \en Get the number of attributes. size_t AttributesCount() const { return attributes.size(); } @@ -300,7 +300,7 @@ MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExter MbUserAttribute * resAttr = new MbUserAttribute( _T("AttrClass"), attrId ); resAttr->InitActions( source ); { - const char * charBuf = NULL; + const char * charBuf = c3d_null; size_t memLen = 0; { membuf memBuf; @@ -330,7 +330,7 @@ MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExter template MbExternalAttribute * UserAttrDefinition::AdvanceUserAttrib( const MbUserAttribute & source ) { - AttrClass * resAttr = NULL; + AttrClass * resAttr = c3d_null; MbUserAttribType attrId; source.GetUserAttribId( attrId ); { @@ -360,7 +360,7 @@ MbExternalAttribute * UserAttrDefinition::AdvanceUserAttrib( const Mb // --- template MbFixAttrSet * UserAttrDefinition::DisassembleUserAttrib( const MbExternalAttribute & /*source*/ ) { - return NULL; + return c3d_null; } @@ -379,7 +379,7 @@ bool UserAttrDefinition::ReassembleUserAttrib( const MbFixAttrSet & / template UserAttrDefinitionInstance::UserAttrDefinitionInstance( const MbUserAttribType & type ) : AttrDefInstance( type ) - , attrDef( NULL ) + , attrDef( c3d_null ) { } @@ -390,7 +390,7 @@ UserAttrDefinitionInstance::UserAttrDefinitionInstance( const MbUs template UserAttrDefinitionInstance::~UserAttrDefinitionInstance() { - if ( attrDef != NULL ) + if ( attrDef != c3d_null ) delete attrDef; } @@ -401,7 +401,7 @@ UserAttrDefinitionInstance::~UserAttrDefinitionInstance() template IAttrDefinition * UserAttrDefinitionInstance::GetAttrDefinition() { - if ( attrDef == NULL ) { + if ( attrDef == c3d_null ) { ScopedLock ll( GetLock() ); attrDef = new AttrDefClass(); } diff --git a/C3d/Include/attribute.h b/C3d/Include/attribute.h index 4720c80..a2f4641 100644 --- a/C3d/Include/attribute.h +++ b/C3d/Include/attribute.h @@ -290,7 +290,7 @@ public : /// \ru Выдать подтип атрибута. \en Get subtype of an attribute. virtual MbeAttributeType AttributeType() const = 0; /// \ru Сделать копию элемента. \en Create a copy of the element. - virtual MbAttribute & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; + virtual MbAttribute & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; /** \brief \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. \~ \details \ru Равными считаются однотипные объекты, все данные которых одинаковы (равны). @@ -335,7 +335,7 @@ public : \en Perform actions when transforming the owner, \n This function is called after transforming the owning object in a case when GetActionForTransform() == trn_Self. The registrator of transformed objects may be passed as input parameter. \~ */ - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ) = 0; + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; /**\ru Выполнить действия при перемещении владельца. \n Вызывается после перемещения владеющего объекта при условии GetActionForTransform() == trn_Self. @@ -343,7 +343,7 @@ public : \en Perform actions when moving the owner. \n This function is called after moving the owning object in a case when GetActionForTransform() == trn_Self. The registrator of transformed objects may be passed as input parameter. \~ */ - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ) = 0; + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = c3d_null ) = 0; /**\ru Выполнить действия при вращении владельца. \n Вызывается после вращения владеющего объекта при условии GetActionForTransform() == trn_Self. @@ -351,7 +351,7 @@ public : \en Perform actions when rotating the owner. \n This function is called after rotating the owning object in a case when GetActionForTransform() == trn_Self. The registrator of transformed objects may be passed as input parameter. \~ */ - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; /**\ru Выполнить действия при копировании владельца. \n Вызывается после копирования владеющего объекта при условии GetActionForCopy() == cpy_Self. \n @@ -359,7 +359,7 @@ public : \en Perform actions when copying the owner. \n This function is called after copying the owning object in a case when GetActionForCopy() == cpy_Self. \n The following objects are passed as input parameters: the owning object copy and registrator of copied objects. \~ */ - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ) = 0; + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = c3d_null ) = 0; /**\ru Выполнить действия при объединении владельца. \n Вызывается перед слиянием владельца при условии GetActionForMerge() == mrg_Self. \n diff --git a/C3d/Include/attribute_container.h b/C3d/Include/attribute_container.h index ad82ea5..cc07b16 100644 --- a/C3d/Include/attribute_container.h +++ b/C3d/Include/attribute_container.h @@ -169,13 +169,13 @@ public: /// \ru Выполнить действия при конвертации атрибутов. \en Perform actions when converting the attributes. void AttributesConvert( MbAttributeContainer & other ) const; /// \ru Выполнить действия при трансформировании атрибутов. \en Perform actions when transforming the attributes. - void AttributesTransform( const MbMatrix3D &, MbRegTransform * = NULL ); + void AttributesTransform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Выполнить действия при перемещении атрибутов. \en Perform actions when moving the attributes. - void AttributesMove ( const MbVector3D &, MbRegTransform * = NULL ); + void AttributesMove ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Выполнить действия при вращении атрибутов. \en Perform actions when rotating the attributes. - void AttributesRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void AttributesRotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /// \ru Выполнить действия при копировании атрибутов. \en Perform actions when copying the attributes. - void AttributesCopy ( MbAttributeContainer & other, MbRegDuplicate * = NULL ) const; + void AttributesCopy ( MbAttributeContainer & other, MbRegDuplicate * = c3d_null ) const; /// \ru Выполнить действия при объединении атрибутов. \en Perform actions when merging the attributes. void AttributesMerge ( MbAttributeContainer & other ); /// \ru Выполнить действия при замене атрибутов. \en Perform actions when replacing the attributes. @@ -226,7 +226,7 @@ public: \return \ru true если есть такой атрибут \n false в противном случае \en True if there is the attribute MbColor \n otherwise false. \~ */ - bool IsColored() const { return (GetSimpleAttribute( at_Color ) != NULL); } + bool IsColored() const { return (GetSimpleAttribute( at_Color ) != c3d_null); } /// \ru Изменить цвет объекта. \en Change color of the object. void SetColor( uint32 ); /// \ru Изменить цвет объекта (0-255). \en Change color of the object (0-255). @@ -293,7 +293,9 @@ OBVIOUS_PRIVATE_COPY( MbAttributeContainer ) \ingroup Model_Attributes */ // --- -MATH_FUNC (bool) GetCommonAttributes( const MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt, c3d::ConstAttrVector & resAttrs ); +MATH_FUNC (bool) GetCommonAttributes( const MbAttributeContainer & attrItem, + const c3d::string_t & attrPrompt, + c3d::ConstAttrVector & resAttrs ); //------------------------------------------------------------------------------ @@ -316,8 +318,11 @@ MATH_FUNC (bool) GetCommonAttributes( const MbAttributeContainer & attrItem, con \ingroup Model_Attributes */ // --- -MATH_FUNC (bool) AddCommonAttributes( const MbAttributeContainer & srcItem, MbeAttributeType attrType, const c3d::string_t & attrPrompt, - MbAttributeContainer & dstItem, c3d::AttrVector * bufAttrs = NULL ); +MATH_FUNC (bool) AddCommonAttributes( const MbAttributeContainer & srcItem, + MbeAttributeType attrType, + const c3d::string_t & attrPrompt, + MbAttributeContainer & dstItem, + c3d::AttrVector * bufAttrs = c3d_null ); //------------------------------------------------------------------------------ /** \brief \ru Удалить обобщенные атрибуты. diff --git a/C3d/Include/cdet_data.h b/C3d/Include/cdet_data.h index 657ae38..c992aaa 100644 --- a/C3d/Include/cdet_data.h +++ b/C3d/Include/cdet_data.h @@ -23,7 +23,7 @@ class MbHRepSolid; */ //---------------------------------------------------------------------------------------- -/// \ru Объект набора для контроля столкновений. \en Object of the set for collision detection. +/// \ru Объект из набора контроля столкновений. \en Object from the set of collision detection. //--- typedef const MbHRepSolid * cdet_item; typedef MbResultType cdet_result; ///< \ru Код результата контроля столкновений. \en Result code of collision queries. @@ -45,18 +45,28 @@ typedef const void * cdet_app_item; //---------------------------------------------------------------------------------------- // Constants //--- -const cdet_item CDET_NULL = C3D_NULL_PTR; ///< \ru Пустой объект набора для контроля столкновений. \en Empty object of the collision query set. -const cdet_app_item CDET_APP_NULL = C3D_NULL_PTR; ///< \ru "Нулевой" объект модели приложения. \en "Null object" of the client app. +const cdet_item CDET_NULL = c3d_null; ///< \ru Пустой объект набора для контроля столкновений. \en Empty object of the collision query set. +const cdet_app_item CDET_APP_NULL = c3d_null; ///< \ru "Нулевой" объект модели приложения. \en "Null object" of the client app. //---------------------------------------------------------------------------------------- -// Base class to implement collision query details +/** \brief \ru Структура данных и обратных вызовов для запроса на поиск соударений. + \en Data structure and callbacks for the collision search request. + \details + \ru Базовый класс, предназначенный для реализации на стороне приложения структуры + запроса к алгоритму поиска соударений. С помощью обратных вызовов приложение + управляет поиском соударений и получает сведения o найденных пересечениях. + \en The base class intended to implement on the application side the structure of a query + to the collision search algorithm. The application uses a callback to control the collision + search and obtain details of detected interferencies. + +*/ //--- struct cdet_query { enum cback_res ///< Result code of the callback function { CBACK_VOID - , CBACK_SUFFICIENT ///< This code means that an app stops collision query for given pair of lamps + , CBACK_SUFFICIENT ///< This code means that an app stops collision query for given pair of lumps , CBACK_SKIP ///< Skip testing a given pair of the lumps , CBACK_BREAK ///< Break search of all collisions of the set , CBACK_SEARCH_MORE = CBACK_VOID ///< This code notifies a collision detector to continue working at cases CDET_INTERSECTED, CDET_TOUCHED. @@ -77,8 +87,8 @@ struct cdet_query const MbRefItem * refItem; const MbMatrix3D * wMatrix; geom_element() - : appItem( C3D_NULL_PTR ) - , refItem( C3D_NULL_PTR ) + : appItem( c3d_null ) + , refItem( c3d_null ) , wMatrix( &MbMatrix3D::identity ) {} }; @@ -117,7 +127,7 @@ struct cdet_query_result: public cdet_query private: static cback_res QueryFunc( cdet_query * query, message code, cback_data & ) { - C3D_ASSERT( C3D_NULL_PTR != query ); + C3D_ASSERT( c3d_null != query ); cdet_query_result * q = static_cast( query ); switch( code ) { @@ -162,7 +172,7 @@ private: { case CDET_QUERY_STARTED: // The collision query is started for all solids of the set { - q->first = q->second = C3D_NULL_PTR; + q->first = q->second = c3d_null; return CBACK_VOID; } case CDET_FINISHED: // A pair of solids is finished. @@ -358,7 +368,7 @@ public: MbCollisionFace( const MbFace & f ) : item( CDET_NULL ) , mathFace( &f ) - , partFace( C3D_NULL_PTR ) + , partFace( c3d_null ) {} const MbFace & Face() const { return *mathFace; } @@ -405,7 +415,6 @@ class MATH_CLASS MbProximityParameters SPtr plane; public: - //cdet_item fstItem, sndItem; // \ru Дескрипторы MbCartPoint3D fstPnt, sndPnt; // \ru Пара точек близости, принадлежащие триангуляционным сеткам. \en The points of the proximity belonging to the triangulation grids. MbCartPoint thePar1, thePar2; // \ru Пара точек близости, заданная в поверхностных координатах граненй. \en The points of the proximity specified in the surface coordinates of the faces. double theDistance; // \ru Расстояние. \en Distance. diff --git a/C3d/Include/cdet_utility.h b/C3d/Include/cdet_utility.h index 0d5e68d..776503e 100644 --- a/C3d/Include/cdet_utility.h +++ b/C3d/Include/cdet_utility.h @@ -15,6 +15,7 @@ class MtRefItem; class MbItem; class MbSolid; +class MbMesh; class MbAssembly; struct MbLumpAndFaces; class MbCollisionDetector; @@ -34,7 +35,7 @@ class MbCollisionDetector; \attention \ru Для гарантированно правильной работы детектора необходимо, чтобы объект типа MbLumpAndFaces, добавляемый в рассмотрение посредством функции AddSolid, имел правильную матрицу преобразования в мир в настоящем его положении, т.е. с самого начала. - \en For the ensure proper functionality of detector it is necessary that + \en For the ensure proper functionality of the detector it is necessary that an object of type MbLumpAndFaces to be added in consideration by function AddSolid will have a correct matrix of transformation to the world coordinate system in its current state, i.e. from the beginning. \~ @@ -54,26 +55,54 @@ public: \en Add a solid with given placement to the collision detection set. \~ \return \ru Дескриптор объекта для контроля столкновений. \en Descriptor of object for collision detection. \~ */ - cdet_item AddItem( const MbSolid & solid, const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL ); + cdet_item AddItem( const MbSolid & solid, const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL ); + /** + \brief \ru Добавить полигональный объект с заданным положением в набор для контроля столкновений. + \en Add a poligonal object with given placement to the collision detection set. \~ + \return \ru Дескриптор объекта для контроля столкновений. \en Descriptor of object for collision detection. \~ + */ + cdet_item AddMesh( const MbMesh & mesh, const MbPlacement3D & place, cdet_app_item appItem = CDET_APP_NULL ); + /** + \brief \ru Добавить новый компонент контроля соударений и параметров близости. + \en Add a new component to track collisions and proximity parameters. \~ + \details \ru Компонент позволяет объединять тела в геометрически-жесткие множества. + \en Component is able to unite solids into the rigid geometric sets. + */ + cdet_item AddComponent( cdet_app_item ); + /** + \brief \ru Добавить новый экземпляр тела в компонент контроля соударений. + \en Add a new instance of a reused solid into the component. \~ + \param[in] compItem - \ru Компонент, которому будет принадлежать экземпляр. + \en A component to witch the instance will belong. + \param[in] solidItem - \ru Оригинальное тело, добавленное методом #AddSolid, по которому изготавливается экземпляр. + \en An original solid added by the method #AddSolid by witch the instance is made. + \param[in] place - \ru Положение, которое занимает тело экземпляра в глобальной СК. + \en The placement that the instance solid takes in global space. + \return \ru Новый экземпляр тела, зарегистрированный с аппарате контроля соударений. + \en The new solid instance registered in the detector. + \note \ru Значение compItem может быть нулевым. Значит просто вставка не будет + принадлежать ни одному компоненту. + \en The value compItem can be CDET_NULL. This just means that the + instance does not belong to any component. + */ + cdet_item AddInstance( cdet_item compItem, cdet_item solidItem, const MbPlacement3D & place ); /** \brief \ru Удалить геометрический объект из набора для контроля столкновений. \en Remove a geometric object from the set of collision detection. \~ */ - void RemoveItem( cdet_item cdItem ); + void RemoveItem( cdet_item cdItem ); /** \brief \ru Поменять текущее положение геометрического объекта в наборе. \en Change current position of a geometric object. \~ */ - void Reposition( cdet_item, const MbPlacement3D & ); + void Reposition( cdet_item, const MbPlacement3D & ); /** \brief \ru Проверить соударения между геометрическими объектами набора. \en Check collisions between geometric objects of the set. \~ \return \ru Функция вернет CDET_RESULT_Intersected при обранужении хотя бы одной коллизии. - \en The function will return CDET_RESULT_Intersected if it detects at least one collision. - + \en The function will return CDET_RESULT_Intersected if it detects at least one collision. */ cdet_result CheckCollisions( cdet_query & ); - /** \brief \ru Проверить соударения между геометрическими объектами набора. \en Check collisions between geometric objects of the set. \~ @@ -98,28 +127,6 @@ public: // the functions below can be deprecated in future version. cdet_item AddSolid( const MbLumpAndFaces & ); /// \ru Добавить тело с заданным положением. \en Add a solid with a given placement. cdet_item AddSolid( const MbSolid &, const MbPlacement3D &, cdet_app_item = CDET_APP_NULL ); - /** - \brief \ru Добавить новый компонент контроля соударений и параметров близости. - \en Add a new component to track collisions and proximity parameters. \~ - */ - cdet_item AddComponent( cdet_app_item ); - /** - \brief \ru Добавить новый экземпляр тела в компонент контроля соударений. - \en Add a new instance of a reused solid into the component. \~ - \param[in] compItem - \ru Компонент, которому будет принадлежать экземпляр. - \en A component to witch the instance will belong. - \param[in] solidItem - \ru Оригинальное тело, добавленное методом #AddSolid, по которому изготавливается экземпляр. - \en An original solid added by the method #AddSolid by witch the instance is made. - \param[in] place - \ru Положение, которое занимает тело экземпляра в глобальной СК. - \en The placement that the instance solid takes in global space. - \return \ru Новый экземпляр тела, зарегистрированный с аппарате контроля соударений. - \en The new solid instance registered in the detector. - \note \ru Значение compItem может быть нулевым. Значит просто вставка не будет - принадлежать ни одному компоненту. - \en The value compItem can be CDET_NULL. This just means that the - instance does not belong to any component. - */ - cdet_item AddInstance( cdet_item compItem, cdet_item solidItem, const MbPlacement3D & place ); /// \ru Удалить твердотельную модель из детектора столкновений. \en Remove a solid model from a collision detector. void RemoveSolid( cdet_item ); /// \ru Выдать количество добавленных твердотельных моделей. \en Get number of added solid models. @@ -155,7 +162,7 @@ public: /* // Use AppItem() insead this cdet_app_item Component( size_t solIdx ) const; // The func is deprecated. Instead, use CheckCollisions - cdet_result InterferenceDetect( void * formalPar = C3D_NULL_PTR ) const; + cdet_result InterferenceDetect( void * formalPar = c3d_null ) const; // The func is deprecated. Use SetDistanceTracking instead. void SetDistanceComputationObjects( const MbLumpAndFaces &, const MbLumpAndFaces & ); // The func is deprecated. Use AddSolid/AddItem instead. @@ -166,6 +173,7 @@ public: /* const MtRefItem * _ComputeBVTree( cdet_item ); private: + /* \brief \ru Добавить объект геометрической модели в набор для контроля столкновений. \en Add an object of geometric model to the set of collision detection control. \~ @@ -189,7 +197,7 @@ inline cdet_result MbCollisionDetectionUtility::CheckCollisions() /// \ru Узел дерева объемов. \en A node of the bounding volume tree. typedef const MtRefItem * cdet_bvt_node; /// \ru Пустое дерево объемов. \en An empty bounding volume tree. -const cdet_bvt_node CDET_BVT_NULL = C3D_NULL_PTR; +const cdet_bvt_node CDET_BVT_NULL = c3d_null; /// \ru Пара ветвей поддерева объемов. \en A pair of branches of the bounding volume subtree. typedef std::pair cdet_bvt_pair; diff --git a/C3d/Include/check_geometry.h b/C3d/Include/check_geometry.h index 46e6fed..a09bb28 100644 --- a/C3d/Include/check_geometry.h +++ b/C3d/Include/check_geometry.h @@ -70,13 +70,13 @@ public: public: /// \ru Пересечение - есть тело. \en Intersection is a solid. - bool IsSolid() const { return ((solid != NULL) || (isSolid && !edges.empty())); } + bool IsSolid() const { return ((solid != c3d_null) || (isSolid && !edges.empty())); } /// \ru Пересечение касательной областью поверхности. \en Intersection by a tangent region of a surface. bool IsSurface() const { return !isTangentCurve && !edges.empty(); } /// \ru Пересечение вдоль касательной линии. \en Intersection along a tangent line. bool IsCurve() const { return isTangentCurve && !edges.empty(); } /// \ru Пересечение точкой (еще не реализовано). \en Intersection is a point (not implemented yet). - bool IsPoint() const { return ((pointFrame != NULL) && (pointFrame->GetVerticesCount() > 0)); } + bool IsPoint() const { return ((pointFrame != c3d_null) && (pointFrame->GetVerticesCount() > 0)); } /// \ru Установить флаг пересечения вдоль касательной линии. \en Set the flag of intersection along a tangent line. //void SetTangent( bool b ) { isTangentCurve = b; } @@ -92,7 +92,7 @@ public: template void GetCurves( EdgesVector & curves ) const; /// \ru Получить указатель на кривую пересечения по индексу. \en Get a pointer to an intersection curve by the index. - const MbCurveEdge * GetCurve( size_t k ) const { return ((k < edges.size()) ? edges[k].get() : NULL); } + const MbCurveEdge * GetCurve( size_t k ) const { return ((k < edges.size()) ? edges[k].get() : c3d_null); } /// \ru Получить номера касающихся граней первого/второго тела. \en Get numbers concerning faces of the first/second solid. template void GetFaceNumbers( bool first, OutputIndicesVector & ) const; @@ -101,7 +101,7 @@ public: void GetFaceNumbersPairs( OutputIndicesPairsVector & ) const; /// \ru Количество точек касания. \en The number of touch points. - size_t GetPointsCount() const { return ((pointFrame != NULL) ? pointFrame->GetVerticesCount() : 0); } + size_t GetPointsCount() const { return ((pointFrame != c3d_null) ? pointFrame->GetVerticesCount() : 0); } /// \ru Получить набор точек касания. \en Get a set of touch points. const MbPointFrame * GetPointFrame() const { return pointFrame; } @@ -117,8 +117,8 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & initEdge : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) - , solid ( NULL ) - , pointFrame ( NULL ) + , solid ( c3d_null ) + , pointFrame ( c3d_null ) , isTangentCurve( false ) , isSolid ( isSolidEgdes ) { @@ -127,7 +127,7 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & initEdge c3d::EdgeSPtr edge; edges.reserve( addCnt ); for ( size_t k = 0; k < addCnt; ++k ) { - if ( initEdges[k] != NULL ) { + if ( initEdges[k] != c3d_null ) { edge = const_cast( &(*initEdges[k]) ); edges.push_back( edge ); } @@ -146,8 +146,8 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & in : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) - , solid ( NULL ) - , pointFrame ( NULL ) + , solid ( c3d_null ) + , pointFrame ( c3d_null ) , isTangentCurve( false ) , isSolid ( false ) { @@ -157,7 +157,7 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & in c3d::EdgeSPtr edge; edges.reserve( edgesCnt ); for ( size_t k = 0; k < edgesCnt; ++k ) { - if ( initEdges[k] != NULL ) { + if ( initEdges[k] != c3d_null ) { edge = const_cast(&(*initEdges[k])); edges.push_back( edge ); } @@ -177,8 +177,8 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) - , solid ( NULL ) - , pointFrame ( NULL ) + , solid ( c3d_null ) + , pointFrame ( c3d_null ) , isTangentCurve( false ) , isSolid ( false ) { @@ -189,7 +189,7 @@ MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & edges.reserve( edgesCnt ); size_t k; for ( k = 0; k < edgesCnt; ++k ) { - if ( initEdges[k] != NULL ) { + if ( initEdges[k] != c3d_null ) { edge = const_cast(&(*initEdges[k])); edges.push_back( edge ); } @@ -340,9 +340,9 @@ bool CheckBoundaryEdges( const Edges & allEdges, Edges * boundaryEdges ) if ( boundaryEdges != &allEdges ) { for ( size_t i = 0, cnt = allEdges.size(); i < cnt; ++i ) { - if ( allEdges[i] != NULL && allEdges[i]->IsBoundaryFace( METRIC_PRECISION ) ) { + if ( allEdges[i] != c3d_null && allEdges[i]->IsBoundaryFace( METRIC_PRECISION ) ) { isBoundary = true; - if ( boundaryEdges != NULL ) + if ( boundaryEdges != c3d_null ) boundaryEdges->push_back( allEdges[i] ); else break; @@ -415,9 +415,9 @@ bool CheckInexactVertices( const Vertices & vertArr, double mAcc, Vertices * ine if ( inexactVerts != &vertArr ) { for ( size_t i = 0, icnt = vertArr.size(); i < icnt; ++i ) { MbVertex * v = vertArr[i]; - if ( v != NULL && v->GetTolerance() > mAcc ) { + if ( v != c3d_null && v->GetTolerance() > mAcc ) { isInexactVertex = true; - if ( inexactVerts != NULL ) + if ( inexactVerts != c3d_null ) inexactVerts->push_back( v ); else break; @@ -480,12 +480,12 @@ bool CheckInexactEdges( const Edges & allEdges, double mAcc, Edges * inexactEdge bool isInexactEdge = false; for ( size_t i = 0, icnt = allEdges.size(); i < icnt; ++i ) { - if ( allEdges[i] != NULL) { + if ( allEdges[i] != c3d_null) { bool isSpaceNear = !::IsInexactEdge( *allEdges[i], mAcc ); if ( !isSpaceNear ) { isInexactEdge = true; - if ( inexactEdges != NULL ) + if ( inexactEdges != c3d_null ) inexactEdges->push_back( allEdges[i] ); else break; @@ -498,7 +498,7 @@ bool CheckInexactEdges( const Edges & allEdges, double mAcc, Edges * inexactEdge double mLen = allEdges[i]->GetLengthEvaluation(); if ( mLen > METRIC_PRECISION && mLen > mTol + METRIC_PRECISION ) { isInexactEdge = true; - if ( inexactEdges != NULL ) + if ( inexactEdges != c3d_null ) inexactEdges->push_back( allEdges[i] ); else break; @@ -797,16 +797,42 @@ MATH_FUNC( bool ) RepairEdges( MbFaceShell & shell, bool updateFacesBounds = tru //------------------------------------------------------------------------------ /** \brief \ru Устранить наличие общих подложек поверхностей. \en Remove common surface substrates. \~ - \details \ru Устранить наличие общих подложек поверхностей. \n - \en Remove common surface substrates. \n \~ - \param[in] shell - \ru Оболочка. - \en A shell. \~ + \details \ru Найти и устранить общие поверхности-подложки в гранях оболочки. \n + Функция устарела и будет удалена. Замените вызовы на RemoveCommonSurfaceSubstrates. \n + \en Find and eliminate common underlying surfaces of a shell faces. \n + The function is deprecated and will be removed. Replace calls with RemoveCommonSurfaceSubstrates. \~ + \param[in] shell - \ru Модифицируемая оболочка. + \en A shell to be modified. \~ + \return \ru Возвращает true, если была выполнена модификация оболочки. + \en Returns true if the shell modification was performed. \~ + \ingroup Algorithms_3D +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC( bool ) CheckIdenticalBaseSufaces( MbFaceShell & shell ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Устранить наличие общих подложек поверхностей. + \en Remove common surface substrates. \~ + \details \ru Найти и устранить общие поверхности-подложки в гранях оболочки. \n + \en Find and eliminate common underlying surfaces of a shell faces. \n \~ + \param[in] shell - \ru Модифицируемая оболочка. + \en A shell to be modified. \~ + \param[in] checkEdges - \ru Выполнить замену в ребрах. + \en Replace in shell edges. \~ \return \ru Возвращает true, если была выполнена модификация оболочки. \en Returns true if the shell modification was performed. \~ \ingroup Algorithms_3D */ //--- -MATH_FUNC( bool ) RemoveCommonSurfaceSubstrates( MbFaceShell & shell ); +MATH_FUNC( bool ) RemoveCommonSurfaceSubstrates( MbFaceShell & shell, bool checkEdges = true ); + + +//------------------------------------------------------------------------------ +// проверка ориентированности оболочки наружу по угловым точкам расширенного габарита +//--- +MATH_FUNC( ThreeStates ) IsOrientedOutward( const MbFaceShell & shell ); #endif // __CHECK_GEOMETRY_H diff --git a/C3d/Include/collection.h b/C3d/Include/collection.h index 57477b0..36f6f05 100644 --- a/C3d/Include/collection.h +++ b/C3d/Include/collection.h @@ -84,10 +84,10 @@ public: // \ru Общие функции геометрического объекта \en Common functions of a geometric object virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. virtual MbeSpaceType Type() const; // \ru Групповой тип объекта. \en Group type of object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem & init, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равным. \en Make the objects equal. virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. diff --git a/C3d/Include/constraint.h b/C3d/Include/constraint.h index b15f24f..dca840d 100644 --- a/C3d/Include/constraint.h +++ b/C3d/Include/constraint.h @@ -42,8 +42,8 @@ public: public: MtGeomArgument( const MbRefItem * p, const MbItem * h ); MtGeomArgument( const MtGeomArgument & ); - MtGeomArgument() : propItem( NULL ), propName( c3d::UNDEFINED_SNAME ) - , hash( c3d::UNDEFINED_SNAME ), item( NULL ), root( NULL ) {} + MtGeomArgument() : propItem( c3d_null ), propName( c3d::UNDEFINED_SNAME ) + , hash( c3d::UNDEFINED_SNAME ), item( c3d_null ), root( c3d_null ) {} public: /** \brief \ru Получить непосредственный объект сборки, содержащий ссылочный объект. @@ -106,7 +106,7 @@ public: public: /// \ru Возвращает true, если ограничение не действительно. \en Return true if the constraint is invalid. - bool IsNull() const { return m_cItem == NULL; } + bool IsNull() const { return m_cItem == c3d_null; } /// \ru Тип сопряжения (геометрического ограничения). \en Type of geometric constraint. MtMateType ConstraintType() const; /// \ru Текущее значение размера. \en Current value of the dimension. diff --git a/C3d/Include/contour_graph.h b/C3d/Include/contour_graph.h index d4fdd11..9b6fe93 100644 --- a/C3d/Include/contour_graph.h +++ b/C3d/Include/contour_graph.h @@ -38,8 +38,8 @@ public: /// \ru Конструктор по точке. \en Constructor by point. MpVertex( const MbCartPoint & initP ) : point( initP ) - , begEdge( NULL ) - , endEdge( NULL ) + , begEdge( c3d_null ) + , endEdge( c3d_null ) {} /// \ru Деструктор. \en Destructor. @@ -398,7 +398,7 @@ public: /// \ru Построить вершины. \en Construct vertices. void CreateVertices(); /// \ru Создать контур по циклу. \en Create a contour by the loop. - MbContour * MakeContour() const; + MbContour * MakeContour( double epsilon = METRIC_ACCURACY ) const; /** \} */ /**\ru \name Операции преобразования. @@ -737,7 +737,7 @@ IMPL_PERSISTENT_OPS( MpGraph ) */ // --- inline void DeleteVertex( MpVertex *& vertex ) { delete vertex; - vertex = NULL; + vertex = c3d_null; } @@ -751,7 +751,7 @@ inline void DeleteVertex( MpVertex *& vertex ) { */ // --- inline void DeleteEdge( MpEdge *& edge ) { delete edge; - edge = NULL; + edge = c3d_null; } @@ -765,7 +765,7 @@ inline void DeleteEdge( MpEdge *& edge ) { */ // --- inline void DeleteLoop( MpLoop *& loop ) { delete loop; - loop = NULL; + loop = c3d_null; } @@ -779,7 +779,7 @@ inline void DeleteLoop( MpLoop *& loop ) { */ // --- inline void DeleteGraph( MpGraph *& graph ) { delete graph; - graph = NULL; + graph = c3d_null; } @@ -848,7 +848,7 @@ MATH_FUNC (MpGraph *) EncloseContoursBuilder( const RPArray & curveLi double accuracy, bool strict, VERSION version, - IProgressIndicator * progInd = NULL ); + IProgressIndicator * progInd = c3d_null ); //------------------------------------------------------------------------------ @@ -886,7 +886,7 @@ MATH_FUNC (MpGraph *) OuterContoursBuilder( const RPArray & curveList, double accuracy, bool strict, VERSION version, - IProgressIndicator * progInd = NULL ); + IProgressIndicator * progInd = c3d_null ); //------------------------------------------------------------------------------ /** \brief \ru Перестроить контуры, построенные ранее вокруг точки. @@ -924,7 +924,7 @@ MATH_FUNC (MpGraph *) ContoursReconstructor( const RPArray & curveLis double accuracy, bool strict, VERSION version, - IProgressIndicator * progInd = NULL ); + IProgressIndicator * progInd = c3d_null ); #endif // __CONTOUR_GRAPH_H diff --git a/C3d/Include/conv_annotation_item.h b/C3d/Include/conv_annotation_item.h index c3c8dbf..98c5565 100644 --- a/C3d/Include/conv_annotation_item.h +++ b/C3d/Include/conv_annotation_item.h @@ -1,878 +1,878 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Объекты, используемые при импорте и экспорте аннотации и размеров. - \en Objects used for import and export of annotation and dimensions \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_ANNOTATION_ITEM_H -#define __CONV_ANNOTATION_ITEM_H - -#include -#include -#include -#include - -#include -#include - -class MbLineSegment3D; -class MbArc3D; -class MbItem; -class MbPlaneItem; - -//------------------------------------------------------------------------------ -/** \brief \ru Тип элемента аннотации. - \en Type of annotation element. \~ -*/ -// --- -enum Mae_AnnotationType { - nt_AnnotationItem, ///< \ru Аннотация без объектов привязки. \en Annotation without binding objects. - nt_Dimension, ///< \ru Размер. \en Dimension - nt_LinearDimension, ///< \ru Линейный размер. \en Linear dimension. - nt_DiameterDimension, ///< \ru Диаметральный размер. \en Diameter dimension. - nt_RadialDimension, ///< \ru Радиальный размер. \en Radial dimension. - nt_AngularDimension, ///< \ru Угловой размер. \en Angular dimension. - nt_Callout, ///< \ru Выноска. \en Callout. - nt_Marking, ///< \ru Обозначение. \en Marking. - nt_Datum, ///< \ru База. \en Datum. - nt_Note, ///< \ru Примечание. \en Note. - nt_Centreline, ///< \ru Осевая линия. \en Centreline. - nt_FeatureControlFrame, ///< \ru Рамка управления характеристиками. \en Feature Control Frame. - nt_ReferencePoint, ///< \ru Точка отсчета. \en Reference Point. - nt_SurfaceRoughness, ///< \ru Шероховатость поверхности. \en Surface roughness. - nt_ShapeTolerance ///< \ru Допуск формы. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тип текстового объекта. - \en Type of a text object. \~ -*/ -// --- -enum MaeTextType { - xt_CompositeText, ///< \ru Набор текстовых блоков. \en Set of text blocks. - xt_TextLiteral, ///< \ru Текст с указанием ЛСК, шрифта, выравнивания. \en Text with specification of LCS, font, alignment. - xt_TextLiteralExtent, ///< \ru Текст с указанием ЛСК, шрифта, выравнивания, геометрического размера. \en Text with specification of LCS, font, alignment, geometric dimension. - xt_SpecificSymbol ///< \ru Спецсимвол. \en Specific symbol. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тэг, определяющий назначение текстового блока. - \en Purpose tag of a text object. \~ -*/ -// --- -enum MaeTextFormatTag { - xft_Enumeration, ///< \ru Перечисление. \en Enumeration. - xft_Paragraph, ///< \ru Параграф. \en Paragraph. - // Тэги в следующей группе являются взаимосиключающими. Tags of the next group are mutually exclusive. - xft_Ground, ///< \ru Положение текста на базовом уровне. \en Ground level text position. - xft_Upper, ///< \ru Верхний индекс или числитель. \en Upper index or numerator. - xft_Lower, ///< \ru Нижний индекс или знаменатель. \en Lower index or denominator. - // Следующая группа тэгов уточняет смысл тэгов предыдущей группы. Next group of tags gives the exact meaning to the tags frem the previosu group. - xft_Fraction, ///< \ru Дробь. \en Fraction. - xft_Index, ///< \ru Наличие индекс. \en Indexed item. - xft_OverUnder, ///< \ru Наличие надстрочного и подстрочного текста. \en Overline and underline text present. - - xft_Undefined, ///< \ru Неопределённое значение тэга, не назначается. \en Undefined can be never assigned to items. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Направление текста. - \en Text direction. \~ -*/ -// --- -enum eTextPath { - txp_Left, ///< \ru Налево. \en To the left. - txp_Right,///< \ru Направо. \en To the right. - txp_Up, ///< \ru Вверх. \en Upward. - txp_Down ///< \ru Вниз. \en Downward. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Спецсимволы. - \en Special symbols. \~ -*/ -enum MbeDefinedDimensionSymbol { - dds_ArcLength, ///< \ru Длина дуги. \en The arc length. - dds_ConicalTaper, ///< \ru Конусность. \en Conicity. - dds_Counterbore, ///< \ru Зенковка. \en Counterbore. - dds_Countersink, ///< \ru Циковка. \en Countersink. - dds_Depth, ///< \ru Глубина. \en Depth. - dds_Diameter, ///< \ru Диаметр. \en Diameter. - dds_PlusMinus, ///< \ru Одинаковая двусторонняя погрешность. \en Equal double-sided tolerance. - dds_Radius, ///< \ru Радиус. \en Radius. - dds_Slope, ///< \ru Склон. \en Slope. - dds_SphericalDiameter, ///< \ru Сферический диаметр. \en Spherical diameter. - dds_SphericalRadius, ///< \ru Сферический радиус. \en Spherical radius. - dds_Square, ///< \ru Квадрат. \en Square. - dds_MetricThread, ///< \ru Метрическая резьба (при экспорте в STEP преобразуется в букву M). \en Metric thread ( in STEP it corresponds M letter ). - - dds_SurfaceCondition, ///< \ru Шереховатость поверхности в нотации STEP (ISO 10303). \en Surface condition in STEP (ISO 10303) codes. - dds_SurfaceCondition_010, - dds_SurfaceCondition_020, - dds_SurfaceCondition_030, - dds_SurfaceCondition_040, - dds_SurfaceCondition_050, - dds_SurfaceCondition_060, - dds_SurfaceCondition_070, - - dds_SurfaceCondition_001, - dds_SurfaceCondition_011, - dds_SurfaceCondition_021, - dds_SurfaceCondition_031, - dds_SurfaceCondition_041, - dds_SurfaceCondition_051, - dds_SurfaceCondition_061, - dds_SurfaceCondition_071, - - dds_SurfaceCondition_100, - dds_SurfaceCondition_110, - dds_SurfaceCondition_120, - dds_SurfaceCondition_130, - dds_SurfaceCondition_140, - dds_SurfaceCondition_150, - dds_SurfaceCondition_160, - dds_SurfaceCondition_170, - - dds_SurfaceCondition_101, - dds_SurfaceCondition_111, - dds_SurfaceCondition_121, - dds_SurfaceCondition_131, - dds_SurfaceCondition_141, - dds_SurfaceCondition_151, - dds_SurfaceCondition_161, - dds_SurfaceCondition_171, - - dds_SurfaceCondition_200, - dds_SurfaceCondition_210, - dds_SurfaceCondition_220, - dds_SurfaceCondition_230, - dds_SurfaceCondition_240, - dds_SurfaceCondition_250, - dds_SurfaceCondition_260, - dds_SurfaceCondition_270, - - dds_SurfaceCondition_201, - dds_SurfaceCondition_211, - dds_SurfaceCondition_221, - dds_SurfaceCondition_231, - dds_SurfaceCondition_241, - dds_SurfaceCondition_251, - dds_SurfaceCondition_261, - dds_SurfaceCondition_271, - - dds_Angularity, ///< \ru Допуск наклона. \en Angularity. - dds_CircularRunout, ///< \ru Допуск биения. \en Circular runout. - dds_Circularity, ///< \ru Допуск круглости. \en Circularity. - dds_Concentricity, ///< \ru Допуск соосности. \en Concentricity. - dds_Cylindricity, ///< \ru Допуск цилиндричности. \en Cylindricity. - dds_DiameterTol, ///< \ru Допуск диаметра. \en Diameter. - dds_Flatness, ///< \ru Допуск плоскостности. \en Flatness. - dds_LeastMaterialCondition, ///< \ru Требование минимума материала. \en Least material condition. - dds_MaximumMaterialCondition, ///< \ru Требование максимума материала. \en Maximum material condition. - dds_Parallelism, ///< \ru Допуск параллельности. \en Parallelism. - dds_Perpendicularity, ///< \ru Допуск перпендикулярности. \en Perpendicularity. - dds_Position, ///< \ru Позиционный допуск. \en Position. - dds_LineProfile, ///< \ru Допуск формы заданного профиля. \en Line profile. - dds_SurfaceProfile, ///< \ru Допуск формы заданной поверхности. \en Surface profile. - dds_ProjectedToleranceZone, ///< \ru Выступающее поле допуска. \en ProejectedToleranceZone. - dds_RegardlessOfFeatureSize, ///< \ru . \en . - dds_Straightness, ///< \ru Допуск прямолинейности. \en Straightness. - dds_Symmetry, ///< \ru Допуск симметричности. \en .Symmetry - dds_TotlaRunout, ///< \ru Допуск полного радиального (либо торцевого) биения. \en Full radial (or face) runout tolerance. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тип законцовки. - \en Type of tip. \~ -*/ -enum MbeDefinedTerminatorSymbol { - dts_BlankedArrow, ///< \ru Незакрашенная стрелка. \en Blank arrow. - dts_BlankedBox, ///< \ru Незакрашенный квадрат. \en Blank square. - dts_BlankedDot, ///< \ru Незакрашенная точка. \en Blank point. - dts_DimensionOrigin, ///< \ru Базовsq объект. \en Base object. - dts_FilledArrow, ///< \ru Закрашенная стрелка. \en Filled arrow. - dts_FilledBox, ///< \ru Закрашенный квадрат. \en Filled square. - dts_FilledDot, ///< \ru Закрашенная точка. \en Filled point. - dts_IntegralSymbol, ///< \ru Знак интеграла. \en Integral symbol. - dts_OpenArrow, ///< \ru Открытая стрелка. \en Open arrow. - dts_Slash, ///< \ru Косая черта. \en Slash. - dts_UnfilledArrow ///< \ru Стрелка без заполнения. \en Unfilled arrow. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тип кривой с терминаторами. -\en Type of curve with terminators. \~ -*/ -enum MbeDecoratedCurveRole { - dcr_ProjectionCurve, ///< \ru Проекционная кривая размера. \en Projection curve of dimension. - dcr_DimensionCurve, ///< \ru Размерная кривая. \en Dimension curve. - dcr_LeaderCurve, ///< \ru Линия выноски. \en Leader curve. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Текстовый объект. - \en Text object. \~ -*/ -// --- -class CONV_CLASS MaTextItem : public MbRefItem { -protected: - bool visibility; // \ru Признак видимости. \en Visibility. - std::set purposeTags; // \ru Тэги форматирования. \en Gormat tags. -public: - - MaTextItem(); ///< \ru Конструктор по умолчанию. \en Default constructor. - - void SetVisibility( bool v ); ///< \ru Задать видимость; \en Set visibility. - bool IsVisible() const; ///< \ru Получить видимость; \en Get visibility. - - bool IsTag( MaeTextFormatTag tag ) const; ///< \ru Установлен ли тэг. \en Is a tag set. - bool GetTagIfUnique( MaeTextFormatTag& tag ) const; ///< \ru получить тэг, если он единственный. \en Get the tag provided it id qnique. - void SetTag( MaeTextFormatTag tag ); ///< \ru Установить тэг. \en Set a tag. - void ResetTag( MaeTextFormatTag tag ); ///< \ru Сбросить тэг. \en reset a tag. - bool TagUniqueOrUndefined() const; ///< \ru Назначено ли менее 2 тэгов. \en If less than two tags assinged. - bool NoTag() const; ///< \ru Отсутствуют ли тэги. \en If threre are no tags. - - virtual MaeTextType IsA() const = 0; - virtual SPtr Duplicate() const = 0; - virtual ~MaTextItem(); ///< \ru Деструктор. \en Destructor. - - OBVIOUS_PRIVATE_COPY( MaTextItem ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Набор текстовых блоков. - \en Set of text blocks. \~ -*/ -// --- -class CONV_CLASS MaCompositeText : public MaTextItem { - std::vector< SPtr > items; ///< \ru Текстовый блок. \en The text block. - -public: - - MaCompositeText(); ///< \ru Конструктор по умолчанию. \en Default constructor. - - std::vector< SPtr > GetItems() const; ///< \ru Получить элементы. \en Get elements. - void SetItems( const std::vector< SPtr >& it ); ///< \ru Задать элементы. \en Set elements. - void AddItem( MaTextItem* item ); ///< \ru Добавить элемент \en Add an element. - size_t ItemsSize() const; ///< \ru Получить число элементов \en Get count of elements. - MaTextItem* GetItem( size_t idx ); ///< \ru Получить элемент. \en Get element. - const MaTextItem* GetItem( size_t idx ) const; ///< \ru Получить элемент. \en Get element. - - virtual MaeTextType IsA() const; ///< \ru Выдать тип элемента. \en Get element type. - virtual SPtr Duplicate() const; - - /** \brief \ru Вставить объект перед всеми вхождениями указанного. - \en Insert an object before all instances of the specified one. \~ - */ - void InsertBefore( const SPtr& itemToInsert, const SPtr& beforeThis ); - - OBVIOUS_PRIVATE_COPY( MaCompositeText ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Текст с указанием ЛСК, шрифта, выравнивания. - \en Text with specification of LCS, font, align. \~ -*/ -// --- -class CONV_CLASS MaTextLiteral : public MaTextItem { -protected: - std::string text; ///< \ru Текст. \en A text. - MbPlacement location; ///< \ru Положение в аннотационной плоскости \en Position in annotation plane - std::string alignment; ///< \ru Выравнивание. \en Alignment. - eTextPath path; ///< \ru Направление текста. \en Text direction. - std::string font; ///< \ru Шрифт текста. \en Text font. - bool isFontExternal; ///< \ru Является ли шрифт нестандартным. \en Is font non-standard. - -public: - - MaTextLiteral(); ///< \ru Конструктор по умолчанию. \en Default constructor. - - MbPlacement & SetLocation(); ///< \ru Получить положение с возможностью модификации. \en Get position with possibility of modification. - const MbPlacement & GetLocation() const; ///< \ru Получить положение. \en Get position. - eTextPath & SetPath(); ///< \ru Получить направление с возможностью модификации. \en Get direction with possibility of modification. - eTextPath GetPath() const; ///< \ru Получить направление. \en Get direction. - void SetFontExternal( bool value ); ///< \ru Задать признак нестандартного шрифта. \en Set the flag of external font. - bool GetFontExternal() const; ///< \ru Получить признак нестандартного шрифта. \en Get the flag of external font. - - void SetText( const std::string& ); ///< \ru Получить текст. \en Get text. - void GetText( std::string& ) const; ///< \ru Задать текст. \en Set text. - void SetAlignment( const std::string& ); ///< \ru Получить выравнивание. \en Get alignment. - void GetAlignment( std::string& ) const; ///< \ru Задать выравнивание. \en Set alignment. - void SetFont( const std::string& ); ///< \ru Получить шрифт. \en Get font. - void GetFont( std::string& ) const; ///< \ru Задать шрифт. \en Set font. - - virtual MaeTextType IsA() const; - virtual SPtr Duplicate() const; - - OBVIOUS_PRIVATE_COPY( MaTextLiteral ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Текст с указанием ЛСК, шрифта, выравнивания, размера. - \en Text with specification of LCS, font, alignment, size. \~ -*/ -// --- -class CONV_CLASS MaTextLiteralExtent : public MaTextLiteral { - double sizeX, sizeY; ///< \ru Размеры по x и у. \en Size by x and size by y. -public: - - MaTextLiteralExtent(); ///< \ru Конструктор по умолчанию. \en Default constructor. - - double & SetSizeX(); ///< \ru Получить размер по x. \en Get size by x with possibility of modification. - double & SetSizeY(); ///< \ru Получить размер по y. \en Get size by y with possibility of modification. - double GetSizeX() const; ///< \ru Получить размер по x. \en Get size by x. - double GetSizeY() const; ///< \ru Получить размер по y. \en Get size by y. - - virtual MaeTextType IsA() const; - virtual SPtr Duplicate() const; - - OBVIOUS_PRIVATE_COPY( MaTextLiteralExtent ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Спецсимвол. - \en Specific symbol. \~ -*/ -// --- -class CONV_CLASS MaSpecificSymbol : public MaTextItem { - MbPlacement location; ///< \ru Положение в аннотационной плоскости \en Position in annotation plane. - double sizeX; ///< \ru Размер по X. \en Size by x. - double sizeY; ///< \ru Размер по Y. \en Size by Y. - MbeDefinedDimensionSymbol preDefinedSym; ///< \ru Код предопределённого символа. \en The predefined symbol code. -public: - - MaSpecificSymbol( MbeDefinedDimensionSymbol symbol, double szX, double szY ); - - MbeDefinedDimensionSymbol GetSymbol() const; ///< \ru Получить код предопределённого символа. \en Get the predefined symbol code. - bool IsSymbolDimension() const; ///< \ru Является ли символ размерным. \en Is symbol dimension. - bool IsSymbolSurfaceCondition() const; ///< \ru Является ли символ обозначением шероховатости. \en Is symbol surface condition. - bool IsSymbolShapeTolerance() const; ///< \ru Является ли символ допуском формы. \en Is symbol shape tolerance. - MbPlacement& SetLocation(); ///< \ru Получить положение с возможностью модификации. \en Get position with possibility of modification. - const MbPlacement& GetLocation() const; ///< \ru Получить положение. \en Get position. - double GetSizeX() const; ///< \ru Получить размер по x. \en Get size by x. - double GetSizeY() const; ///< \ru Получить размер по y. \en Get size by y. - void GetSize( double& x, double& y ) const; ///< \ru Получить размеры. \en Get sizes. - - OBVIOUS_PRIVATE_COPY( MaSpecificSymbol ) - - virtual MaeTextType IsA() const; - virtual SPtr Duplicate() const; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Описание законцовочного символа. -\en Description of the terminator symbol. \~ -*/ -struct MaTerminatorSymbol { - MbeDefinedTerminatorSymbol type; ///< \ru Тип символа \en Symbol type - double parameter; ///< \ru Значенеи параметра на размерной кривой. Если не указан, должен быть равен UNDEFINED_DBL. \en Parameter value on the dimensional curve. If not known, must be equal UNDEFINED_DBL. - double sizeX; ///< \ru Размер по x. \en Size by x. - double sizeY; ///< \ru Размер по у. \en Size by y. - /// \ru Признак сонаправленности с касательной к кривой в точке размещения. В случае неопределённого значения параметра - признак направленности внутрь. - /// \en Flag of the same direction with the tangent to the curve at the location point. In case parameter id undefined it shows if the arrow's direction is inner. - bool sameDirection; - - MbCartPoint3D location; ///< \ru Положение в пространстве. \en Location in space. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Кривая с терминаторами. - \en Curve and terminators. \~ -*/ -class CONV_CLASS MaDecoratedCurve : public MbRefItem { - SPtr curve; - std::vector< MaTerminatorSymbol > terminators; - MbeDecoratedCurveRole curveType; -public: - MaDecoratedCurve( MbeDecoratedCurveRole crvType ); ///< \ru Конструктор. \en Constructor. - MaDecoratedCurve( const MaDecoratedCurve& ); ///< \ru Конструктор копирования. \en Copy constructor. - const MaDecoratedCurve& operator= ( const MaDecoratedCurve& ); ///< \ru Оператор присваивания. \en Assignment operator. - - SPtr GetCurve() const; ///< \ru Получить кривую. \en Get curve. - bool CurveEmpty() const; ///< \ru Пуста ли кривая. \en If curve is empty. - void SetCurve( MbCurve3D* crv ); ///< \ru Задать кривую. \en Set curve. - size_t TerminatorsCount() const; ///< \ru Получить число законцовок. \en Set number of terminators. - bool TerminatorInfo( size_t terminatorIndex, MaTerminatorSymbol& term ) const; ///< \ru Получить законцовку с указанным индексом. \en Get terminator. - void AddTerminator( const MaTerminatorSymbol& term ); ///< \ru Добавить законцовку. \en Add terminator. - - bool IsA( MbeDecoratedCurveRole ) const; ///< \ru Проверка типа кривой. \en Check curve type. - MbeDecoratedCurveRole IsA() const; ///< \ru Проверка типа кривой. \en Check curve type. - - void DuplicateCurve( const MbMatrix3D& transform ); ///< \ru Заменить кривую на преобразованный по матрице дубликат. \en Replace curve by transformed replica. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Объект аннотации. - \en Annotation object. \~ -*/ -class CONV_CLASS MaAnnotationItem : public MbRefItem { -protected: - MbPlacement3D location; ///< \ru Локальная система координат (ЛСК), в плоскости XY которой расположены объекты аннотации. \en Local coordinate system (LCS) the annotation objects are located in XY plane of. - std::vector< const MbItem* > annotationGeometry; ///< \ru Геометрические объекты аннотации. \en Geometric objects of annotation. - std::vector< SPtr > annotationText; ///< \ru Текстовые аннотационные объекты. \en Text annotation objects. - std::string name; ///< \ru Имя. \en Name. - bool visible; ///< \ru Видим ли объект. \en If object is vivible. - // \ru Аналогичным образом реализовать и символьное представление \en Implement symbolic representation similarly. -public: - /// \ru Конструктор по плоскости аннотации. \en Constructor by annotation plane. - MaAnnotationItem( const MbPlacement3D& loc ); - /// \ru Деструктор. \en Destructor. - virtual ~MaAnnotationItem(); - -public: - /// \ru Получить тип объекта. \en Get the object type. - virtual Mae_AnnotationType IsA() const; - /// \ru Получить групповой тип объекта. \en Get the group type of the object. - virtual Mae_AnnotationType Type() const; - - /// \ru Пусто ли визуальное представление. \en Whether the visual representation is empty. - virtual bool VisualItemsEmpty() const; - - /// \ru Отсутствуют ли геометрические элементы. \en Whether there are no geometric items. - bool GeometryEmpty() const; - - /// \ru Отсутствуют ли текстовые элементы. \en Whether there are no text items. - bool TextEmpty() const; - - /// \ru Добавить геометрический визуальный аннотационный элемент. \en Add the geometric visual annotation element of the kernel. - void AddGeometricAnnotationElement( const MbItem& ); - - /// \ru Добавить собственные геометрические визуальные аннотационный элементы в контейнер. \en Add own geometric visual annotation elements to container. - void AddAnnotationGeometryTo( std::vector< SPtr >& addTo ) const; - - /// \ru Число текстовых элементов. \en Count of text items. - size_t TextItemsCount() const; - - /// \ru Получить текстовый элемент с указанным индексом. \en Get specified text item. - SPtr TextItem( size_t ) const; - - /// \ru Задать аннотационные объекты ядра. \en Set the annotation objects of the kernel. - template< typename In > - void SetAnnotationGeometry( In first, In last ); - /// \ru Выдать аннотационные объекты ядра. У приёмника должен быть определён метод push_back. \en Get the annotation objects of the kernel. Method push_back should be defined for the receiver. - template< typename Out > - void GetAnnotationGeometry( Out dest ) const; - - /// \ru Получить текстовые аннотационные объекты. \en Get the text annotation object. - template< typename In > - void SetAnnotationText( In first, In last ); - /// \ru Выдать текстовые аннотационные объекты. У приёмника должен быть определён метод push_back. \en Get text annotation objects. Method push_back should be defined for the receiver. - template< typename Out > - void GetAnnotationText( Out dest ) const; - - /// \ru Добавить плоские геометрические объекты, преобразуя их в пространственные, используя текущую ЛСК. \en Add planar objects to geometric objects using current location. - void AddPlaneItems( const std::vector >& ); - - /// \ru Задать ЛСК. \en Specify LCS. - void SetLocation( const MbPlacement3D & loc ); - /// \ru Получить ЛСК. \en Get LCS. - MbPlacement3D GetLocation() const; - - /// \ru Задать имя. \en Specify name. - void SetName( const std::string & nm ); - - /// \ru Задать имя. \en Specify name. - void GetName( std::string & nm ) const; - - /// \ru Задать видимость. \en Set visibility. - void SetVisibility( bool v ); - /// \ru Видим ли объект. \en Is object vivible. - bool IsVisible() const; - - /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. - virtual SPtr ShallowDuplicateTransform( const MbMatrix3D & ); - - /// \ru Инициализировать все поля за исключением ЛСК данными присланного. \en Init all fields except for location according to the specified item. - void InitExceplLocation( const MaAnnotationItem & init ); - -protected: - - /// \ru Заменить геометрические элементы трансформированными копиями. \en Replace all geometric items by transformed copies. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -typedef SPtr AnnotationSPtr; - -/** \brief \ru Контейнер объектов аннотации. -\en Container of annotation objects. \~ -\ingroup Exchange_Base -*/ -typedef std::vector vector_of_annotation; -typedef std::vector AnnotationSptrVector; - - -/** \brief \ru Ассоциация наборов аннотационных объектов элементам со счётчиком ссылок. -\en Association of sets of annotation objects with elements with reference counter. \~ -\ingroup Exchange_Base -*/ -typedef std::map< SPtr, AnnotationSptrVector > map_of_visual_items; - - -/** \brief \ru Контейнер текстовых блоков. -\en Container of text blocks. \~ -\ingroup Exchange_Base -*/ -typedef std::vector< SPtr > vector_of_text; - - -//------------------------------------------------------------------------------ -/** \brief \ru Размер - родоначальник классов для размеров различных типов. - \en Dimension is the parent of all classes for dimensions of different types. \~ -*/ -// --- -class CONV_CLASS MaDimension : public MaAnnotationItem { - double value; ///< \ru Значение размера. \en A value of dimension. - double valuePlus; ///< \ru Отклонение размера в сторону увеличения. \en Deviation (increase) of size. - double valueMinus; ///< \ru Отклонение размера в сторону уменьшения. \en Deviation (decrease) of size. - bool isRangeSet; ///< \ru Если false, то задан только диапазон изменения, иначе можно вычислить погрешности в обе стороны. \en If it equals false, then only the range of changing is specified, else the tolerances in both directions can be computed. - bool isValueDefined; ///< \ru Задан ли номинал. \en Whether the nominal is given. -protected: - MaDecoratedCurve dimensionCurve; - - OBVIOUS_PRIVATE_COPY( MaDimension ) -protected: - MaDimension( const MbPlacement3D& loc, MbCurve3D* dimCurve ); - MaDimension( const MbPlacement3D& loc, const MaDecoratedCurve& dimCurve ); -public: - /// \ru Получить тип объекта. \en Get the object type. - virtual Mae_AnnotationType IsA() const; - /// \ru Получить групповой тип объекта. \en Get the group type of the object. - virtual Mae_AnnotationType Type() const; - - /// \ru Получить размерную кривую. \en Get the dimensional curve. - MbCurve3D* GetDimensionCurve() const; - - /// \ru Задать номинал. \en Set a value. - void SetValue( double v ); - /// \ru Задать диапазон и значение. \en Set a range and a value. - void SetRange( double v, double vPlus, double vMinus ); - /// \ru Задать диапазон. \en Set range. - void SetRange( double vPlus, double vMinus ); - /// \ru Получить номинал. \en Get value. - bool GetValue( double& v ); - /// \ru Получить границы диапазона и значение, если они заданы. \en Get bounds of range and a value if they are specified. - bool GetRange( double& v, double& vPlus, double& vMinus ) const; - /// \ru Получить границы диапазона, если они заданы. \en Get bounds of the range if they are specified. - bool GetRange( double& vPlus, double& vMinus ) const; - /// \ru Заданы ли границы диапазона. \en Whether the bounds of range are specified. - bool IsRangeDefined() const; - /// \ru Задано ли значение. \en Whether the value is specified. - bool IsValueDefined() const; - /** \brief \ru Добавить законцовочный символ. - \en Add a terminator. \~ - \param [in] init - \ru Параметры задаваемого символа. - \en Parameters of specified symbol. \~ - \return \ru - true, если задана размерная кривая и хотя бы один из законцовочных символов не был задан. - \en - true, if a dimensional curve is specified and at least one of terminators has not been specified. \~ - */ - bool AddTerminator( const MaTerminatorSymbol& init ); - /// \ru Получить первый законцовочный символ. \en Get the first terminator. - bool GetFirstTerminator( MaTerminatorSymbol& first ) const; - /// \ru Получить второй законцовочный символ. \en Get the second terminator. - bool GetSecondTerminator( MaTerminatorSymbol& second ) const; - - void InitValueTerminators( const MaDimension& init ); -protected: - /// \ru Заменить геометрические элементы трансформированными копиями. \en Replace all geometric items by transformed copies. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Линейный размер. - \en Linear dimension. \~ -*/ -// --- -class CONV_CLASS MaLinearDimension : public MaDimension { -private: - SPtr bindBase; ///< \ru Первый объект привязки. \en The first binding object. - SPtr bindTarget; ///< \ru Второй объект привязки. \en The second binding object. - MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к первому объекту привязки в смысле STEP. \en Projection curve to the first binding object in sense of STEP. - MaDecoratedCurve projectionTarget; ///< \ru Проекционная кривая ко второму объекту привязки в смысле STEP. \en Projection curve to the second binding object in sense of STEP. - SPtr path; ///< \ru Кривая, вдоль которой проводится измерение. Если не задана, то размер есть кратчайший. \en A curve along which the measurement is performed. If not specified, then the size is shortest. - - OBVIOUS_PRIVATE_COPY( MaLinearDimension ) -public: - MaLinearDimension ( const MbRefItem* base, const MbRefItem* target, - MbLineSegment3D* projBase, MbLineSegment3D* projTarget, - MbLineSegment3D* dimensionCurve, const MbPlacement3D& loc ); - - MaLinearDimension ( const MbRefItem* base, const MbRefItem* target, - MbLineSegment3D* projBase, MbLineSegment3D* projTarget, - const MaDecoratedCurve dimensionCurve, const MbPlacement3D& loc ); - - virtual Mae_AnnotationType IsA() const; - - virtual bool VisualItemsEmpty() const; - - /// \ru Получить базовый объект привязки. \en Get the base binding object. - const MbRefItem * GetBindBase(); - /// \ru Получить второй объект привязки. \en Get the second binding object. - const MbRefItem * GetBindTarget(); - - /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D* GetProjectionBase() const; - /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. - MbLineSegment3D* GetProjectionTarget() const; - - /// \ru Задать кривую, вдоль которой провдится измерение. \en Set the curve the measurement is performed along. - void SetPath( MbCurve3D* inPath ); - /// \ru Получить кривую, вдоль которой провдится измерение. \en Get the curve the measurement is performed along. - MbCurve3D* GetPath(); - - /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. - virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); - -protected: - // Заменить геометрические элементы трансформированными копиями. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Угловой размер. - \en Angular dimension. \~ -*/ -// --- -class CONV_CLASS MaAngularDimension : public MaDimension { -private: - SPtr bindBase; ///< \ru Первый объект привязки. \en The first binding object. - SPtr bindTarget; ///< \ru Второй объект привязки. \en The second binding object. - MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к первому объекту привязки в смысле STEP. \en Projection curve to the first binding object in sense of STEP. - MaDecoratedCurve projectionTarget; ///< \ru Проекционная кривая ко второму объекту привязки в смысле STEP. \en Projection curve to the second binding object in sense of STEP. - - OBVIOUS_PRIVATE_COPY( MaAngularDimension ) -public: - MaAngularDimension( const MbRefItem* base, const MbRefItem* target, - MbLineSegment3D* projBase, MbLineSegment3D* projTarget, - MbArc3D* dimensionCurve, const MbPlacement3D& loc ); - - MaAngularDimension( const MbRefItem* base, const MbRefItem* target, - MbLineSegment3D* projBase, MbLineSegment3D* projTarget, - const MaDecoratedCurve&, const MbPlacement3D& loc ); - - virtual Mae_AnnotationType IsA() const ; - - virtual bool VisualItemsEmpty() const; - - /// \ru Получить базовый объект привязки. \en Get the base binding object. - const MbRefItem * GetBindBase(); - /// \ru Получить второй объект привязки. \en Get the second binding object. - const MbRefItem * GetBindTarget(); - - /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase() const; - /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. - MbLineSegment3D * GetProjectionTarget() const; - /// \ru Если заданы проекционные кривые и если они не параллельны, получить точку пересечения или скрещивания. Метод работает и за пределеми параметрической области. \en If the projection curves are specified and if they are not parallel, get the point of intersection or crossing. The method works outside the bounds of a parametric region too. - bool NearestBetweenProjections( MbCartPoint3D& pnt ); - /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. - virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); - -protected: - // Заменить геометрические элементы трансформированными копиями. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Радиальный размер. - \en Radial dimension. \~ -*/ -// --- -class CONV_CLASS MaRadialDimension : public MaDimension { -private: - SPtr bindBase; ///< \ru Объект привязки. \en Binding object. - MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к объекту привязки в смысле STEP. \en Projection curve to the binding object in sense of STEP. - - OBVIOUS_PRIVATE_COPY( MaRadialDimension ) -public: - MaRadialDimension( const MbRefItem* base, MbLineSegment3D* projBase, - MbLineSegment3D* dimensionCurve, const MbPlacement3D& loc ); - - MaRadialDimension( const MbRefItem* base, MbLineSegment3D* projBase, - const MaDecoratedCurve& dimensionCurve, const MbPlacement3D& loc ); - - virtual Mae_AnnotationType IsA() const; - - virtual bool VisualItemsEmpty() const; - - /// \ru Получить базовый объект привязки. \en Get the base binding object. - const MbRefItem * GetBindBase(); - /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase() const; - /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. - virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); - -protected: - // Заменить геометрические элементы трансформированными копиями. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Диаметральный размер. - \en Diameter dimension. \~ -*/ -// --- -class CONV_CLASS MaDiameterDimension : public MaDimension { -private: - SPtr bindBase; ///< \ru Объект привязки. \en Binding object. - MaDecoratedCurve projectionBase; ///< \ru Первая проекционная кривая к объекту привязки в смысле STEP. \en The first projection curve to binding object in sense of STEP. - MaDecoratedCurve projectionTarget; ///< \ru Вторая проекционная кривая к объекту привязки в смысле STEP. \en The second projection curve to binding object in sense of STEP. - - OBVIOUS_PRIVATE_COPY( MaDiameterDimension ) -public: - MaDiameterDimension( const MbRefItem* base, MbLineSegment3D* projBase, - MbLineSegment3D* projTarget, MbLineSegment3D* dimCurve, - const MbPlacement3D& loc ); - - MaDiameterDimension( const MbRefItem* base, MbLineSegment3D* projBase, - MbLineSegment3D* projTarget, const MaDecoratedCurve& dimCurve, - const MbPlacement3D& loc ); - - virtual Mae_AnnotationType IsA() const; - - virtual bool VisualItemsEmpty() const; - - /// \ru Получить базовый объект привязки. \en Get the base binding object. - const MbRefItem * GetBindBase(); - - /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase() const; - /// \ru Получить вторую проекционную кривую к объекту привязки. \en Get the first projection curve to the binding object. - MbLineSegment3D * GetProjectionTarget() const; - /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. - virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); - -protected: - // Заменить геометрические элементы трансформированными копиями. - virtual void DuplicateTransformDeometry( const MbMatrix3D & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Выносной элемент - родоначальник классов для обозначений различных типов. -\en Callout is the parent of all classes for callouts of different types. \~ -*/ -// --- -class CONV_CLASS MaCallout : public MaAnnotationItem { - Mae_AnnotationType whatIs; ///< \ru Подтип объекта. \en Object subtype. - std::vector leaderLines; ///< \ru Линии выноски. \en Leader lines. -public: - /// \ru Получить тип объекта. \en Get the object type. - virtual Mae_AnnotationType IsA() const; - /// \ru Получить групповой тип объекта. \en Get the group type of the object. - virtual Mae_AnnotationType Type() const; - /// \ru Создать объект заданного типа объекта. \en Create object of specified type. - static MaCallout* Create( const MbPlacement3D& location, Mae_AnnotationType subtype ); - - void AddLeaderLine( const MaDecoratedCurve& leader ); ///< \ru Добавить линию выноски. \en Add leader line. - void AddLeaderLines( const std::vector& leaders ); ///< \ru Добавить линию выноски. \en Add leader line. - size_t LeaderLinesCount() const; ///< \ru Получить число линий выноски. \en Get number of leader lines. - bool LeaderLineInfo( size_t index, MaDecoratedCurve& callout ) const; ///< \ru Получить линию выноски с указанным индексом. \en Get of leader lines at specified index. -private: - MaCallout( const MbPlacement3D& location, Mae_AnnotationType subtype ); ///< \ru Конструктор. \en Constructor. - - OBVIOUS_PRIVATE_COPY(MaCallout) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Шероховатость поверхности. -\en Surface condition. \~ -*/ -// --- -class CONV_CLASS MaSurfaceCondition : public MaAnnotationItem { - SPtr< const MbRefItem > baseObject; - double value; -public: - /// \ru Конструктор. \en Constructor. - MaSurfaceCondition( const MbPlacement3D& location ); - - /// \ru Получить тип объекта. \en Get the object type. - virtual Mae_AnnotationType IsA() const; - /// \ru Получить групповой тип объекта. \en Get the group type of the object. - virtual Mae_AnnotationType Type() const; - - OBVIOUS_PRIVATE_COPY( MaSurfaceCondition ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Допуск формы. -\en Shape tolerance. \~ -*/ -// --- -class CONV_CLASS MaShapeTolerance : public MaAnnotationItem { - SPtr< const MbRefItem > baseObject; - double value; -public: - /// \ru Конструктор. \en Constructor. - MaShapeTolerance( const MbPlacement3D& location ); - - /// \ru Получить тип объекта. \en Get the object type. - virtual Mae_AnnotationType IsA() const; - /// \ru Получить групповой тип объекта. \en Get the group type of the object. - virtual Mae_AnnotationType Type() const; - - OBVIOUS_PRIVATE_COPY(MaShapeTolerance) -}; - - -//------------------------------------------------------------------------------ -// \ru Задать геометрические объекты аннотации \en Set geometric objects of annotation. -// --- -template< typename In > -void MaAnnotationItem::SetAnnotationGeometry( In first, In last ) { - std::for_each( annotationGeometry.begin(), annotationGeometry.end(), ReleaseItem ); - annotationGeometry.assign( first, last ); - std::for_each( annotationGeometry.begin(), annotationGeometry.end(), AddRefItem ); -} - - -//------------------------------------------------------------------------------ -// \ru Получить геометрические объекты аннотации \en Get geometric objects of annotation. -// --- -template< typename Out > -void MaAnnotationItem::GetAnnotationGeometry( Out dest ) const { - std::copy( annotationGeometry.begin(), annotationGeometry.end(), dest ); -} - - -//------------------------------------------------------------------------------ -// \ru Задать текстовые объекты аннотации \en Set text objects of annotation. -// --- -template< typename In > -void MaAnnotationItem::SetAnnotationText( In first, In last ) { - annotationText.assign( first, last ); -} - - -//------------------------------------------------------------------------------ -// \ru Получить текстовые объекты аннотации \en Get text objects of annotation -// --- -template< typename Out > -void MaAnnotationItem::GetAnnotationText( Out dest ) const { - std::copy( annotationText.begin(), annotationText.end(), dest ); -} - - -#endif // __CONV_ANNOTATION_ITEM_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Объекты, используемые при импорте и экспорте аннотации и размеров. + \en Objects used for import and export of annotation and dimensions \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_ANNOTATION_ITEM_H +#define __CONV_ANNOTATION_ITEM_H + +#include +#include +#include +#include + +#include +#include + +class MbLineSegment3D; +class MbArc3D; +class MbItem; +class MbPlaneItem; + +//------------------------------------------------------------------------------ +/** \brief \ru Тип элемента аннотации. + \en Type of annotation element. \~ +*/ +// --- +enum Mae_AnnotationType { + nt_AnnotationItem, ///< \ru Аннотация без объектов привязки. \en Annotation without binding objects. + nt_Dimension, ///< \ru Размер. \en Dimension + nt_LinearDimension, ///< \ru Линейный размер. \en Linear dimension. + nt_DiameterDimension, ///< \ru Диаметральный размер. \en Diameter dimension. + nt_RadialDimension, ///< \ru Радиальный размер. \en Radial dimension. + nt_AngularDimension, ///< \ru Угловой размер. \en Angular dimension. + nt_Callout, ///< \ru Выноска. \en Callout. + nt_Marking, ///< \ru Обозначение. \en Marking. + nt_Datum, ///< \ru База. \en Datum. + nt_Note, ///< \ru Примечание. \en Note. + nt_Centreline, ///< \ru Осевая линия. \en Centreline. + nt_FeatureControlFrame, ///< \ru Рамка управления характеристиками. \en Feature Control Frame. + nt_ReferencePoint, ///< \ru Точка отсчета. \en Reference Point. + nt_SurfaceRoughness, ///< \ru Шероховатость поверхности. \en Surface roughness. + nt_ShapeTolerance ///< \ru Допуск формы. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тип текстового объекта. + \en Type of a text object. \~ +*/ +// --- +enum MaeTextType { + xt_CompositeText, ///< \ru Набор текстовых блоков. \en Set of text blocks. + xt_TextLiteral, ///< \ru Текст с указанием ЛСК, шрифта, выравнивания. \en Text with specification of LCS, font, alignment. + xt_TextLiteralExtent, ///< \ru Текст с указанием ЛСК, шрифта, выравнивания, геометрического размера. \en Text with specification of LCS, font, alignment, geometric dimension. + xt_SpecificSymbol ///< \ru Спецсимвол. \en Specific symbol. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тэг, определяющий назначение текстового блока. + \en Purpose tag of a text object. \~ +*/ +// --- +enum MaeTextFormatTag { + xft_Enumeration, ///< \ru Перечисление. \en Enumeration. + xft_Paragraph, ///< \ru Параграф. \en Paragraph. + // Тэги в следующей группе являются взаимосиключающими. Tags of the next group are mutually exclusive. + xft_Ground, ///< \ru Положение текста на базовом уровне. \en Ground level text position. + xft_Upper, ///< \ru Верхний индекс или числитель. \en Upper index or numerator. + xft_Lower, ///< \ru Нижний индекс или знаменатель. \en Lower index or denominator. + // Следующая группа тэгов уточняет смысл тэгов предыдущей группы. Next group of tags gives the exact meaning to the tags frem the previosu group. + xft_Fraction, ///< \ru Дробь. \en Fraction. + xft_Index, ///< \ru Наличие индекс. \en Indexed item. + xft_OverUnder, ///< \ru Наличие надстрочного и подстрочного текста. \en Overline and underline text present. + + xft_Undefined, ///< \ru Неопределённое значение тэга, не назначается. \en Undefined can be never assigned to items. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Направление текста. + \en Text direction. \~ +*/ +// --- +enum eTextPath { + txp_Left, ///< \ru Налево. \en To the left. + txp_Right,///< \ru Направо. \en To the right. + txp_Up, ///< \ru Вверх. \en Upward. + txp_Down ///< \ru Вниз. \en Downward. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Спецсимволы. + \en Special symbols. \~ +*/ +enum MbeDefinedDimensionSymbol { + dds_ArcLength, ///< \ru Длина дуги. \en The arc length. + dds_ConicalTaper, ///< \ru Конусность. \en Conicity. + dds_Counterbore, ///< \ru Зенковка. \en Counterbore. + dds_Countersink, ///< \ru Циковка. \en Countersink. + dds_Depth, ///< \ru Глубина. \en Depth. + dds_Diameter, ///< \ru Диаметр. \en Diameter. + dds_PlusMinus, ///< \ru Одинаковая двусторонняя погрешность. \en Equal double-sided tolerance. + dds_Radius, ///< \ru Радиус. \en Radius. + dds_Slope, ///< \ru Склон. \en Slope. + dds_SphericalDiameter, ///< \ru Сферический диаметр. \en Spherical diameter. + dds_SphericalRadius, ///< \ru Сферический радиус. \en Spherical radius. + dds_Square, ///< \ru Квадрат. \en Square. + dds_MetricThread, ///< \ru Метрическая резьба (при экспорте в STEP преобразуется в букву M). \en Metric thread ( in STEP it corresponds M letter ). + + dds_SurfaceCondition, ///< \ru Шереховатость поверхности в нотации STEP (ISO 10303). \en Surface condition in STEP (ISO 10303) codes. + dds_SurfaceCondition_010, + dds_SurfaceCondition_020, + dds_SurfaceCondition_030, + dds_SurfaceCondition_040, + dds_SurfaceCondition_050, + dds_SurfaceCondition_060, + dds_SurfaceCondition_070, + + dds_SurfaceCondition_001, + dds_SurfaceCondition_011, + dds_SurfaceCondition_021, + dds_SurfaceCondition_031, + dds_SurfaceCondition_041, + dds_SurfaceCondition_051, + dds_SurfaceCondition_061, + dds_SurfaceCondition_071, + + dds_SurfaceCondition_100, + dds_SurfaceCondition_110, + dds_SurfaceCondition_120, + dds_SurfaceCondition_130, + dds_SurfaceCondition_140, + dds_SurfaceCondition_150, + dds_SurfaceCondition_160, + dds_SurfaceCondition_170, + + dds_SurfaceCondition_101, + dds_SurfaceCondition_111, + dds_SurfaceCondition_121, + dds_SurfaceCondition_131, + dds_SurfaceCondition_141, + dds_SurfaceCondition_151, + dds_SurfaceCondition_161, + dds_SurfaceCondition_171, + + dds_SurfaceCondition_200, + dds_SurfaceCondition_210, + dds_SurfaceCondition_220, + dds_SurfaceCondition_230, + dds_SurfaceCondition_240, + dds_SurfaceCondition_250, + dds_SurfaceCondition_260, + dds_SurfaceCondition_270, + + dds_SurfaceCondition_201, + dds_SurfaceCondition_211, + dds_SurfaceCondition_221, + dds_SurfaceCondition_231, + dds_SurfaceCondition_241, + dds_SurfaceCondition_251, + dds_SurfaceCondition_261, + dds_SurfaceCondition_271, + + dds_Angularity, ///< \ru Допуск наклона. \en Angularity. + dds_CircularRunout, ///< \ru Допуск биения. \en Circular runout. + dds_Circularity, ///< \ru Допуск круглости. \en Circularity. + dds_Concentricity, ///< \ru Допуск соосности. \en Concentricity. + dds_Cylindricity, ///< \ru Допуск цилиндричности. \en Cylindricity. + dds_DiameterTol, ///< \ru Допуск диаметра. \en Diameter. + dds_Flatness, ///< \ru Допуск плоскостности. \en Flatness. + dds_LeastMaterialCondition, ///< \ru Требование минимума материала. \en Least material condition. + dds_MaximumMaterialCondition, ///< \ru Требование максимума материала. \en Maximum material condition. + dds_Parallelism, ///< \ru Допуск параллельности. \en Parallelism. + dds_Perpendicularity, ///< \ru Допуск перпендикулярности. \en Perpendicularity. + dds_Position, ///< \ru Позиционный допуск. \en Position. + dds_LineProfile, ///< \ru Допуск формы заданного профиля. \en Line profile. + dds_SurfaceProfile, ///< \ru Допуск формы заданной поверхности. \en Surface profile. + dds_ProjectedToleranceZone, ///< \ru Выступающее поле допуска. \en ProejectedToleranceZone. + dds_RegardlessOfFeatureSize, ///< \ru . \en . + dds_Straightness, ///< \ru Допуск прямолинейности. \en Straightness. + dds_Symmetry, ///< \ru Допуск симметричности. \en .Symmetry + dds_TotlaRunout, ///< \ru Допуск полного радиального (либо торцевого) биения. \en Full radial (or face) runout tolerance. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тип законцовки. + \en Type of tip. \~ +*/ +enum MbeDefinedTerminatorSymbol { + dts_BlankedArrow, ///< \ru Незакрашенная стрелка. \en Blank arrow. + dts_BlankedBox, ///< \ru Незакрашенный квадрат. \en Blank square. + dts_BlankedDot, ///< \ru Незакрашенная точка. \en Blank point. + dts_DimensionOrigin, ///< \ru Базовsq объект. \en Base object. + dts_FilledArrow, ///< \ru Закрашенная стрелка. \en Filled arrow. + dts_FilledBox, ///< \ru Закрашенный квадрат. \en Filled square. + dts_FilledDot, ///< \ru Закрашенная точка. \en Filled point. + dts_IntegralSymbol, ///< \ru Знак интеграла. \en Integral symbol. + dts_OpenArrow, ///< \ru Открытая стрелка. \en Open arrow. + dts_Slash, ///< \ru Косая черта. \en Slash. + dts_UnfilledArrow ///< \ru Стрелка без заполнения. \en Unfilled arrow. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тип кривой с терминаторами. +\en Type of curve with terminators. \~ +*/ +enum MbeDecoratedCurveRole { + dcr_ProjectionCurve, ///< \ru Проекционная кривая размера. \en Projection curve of dimension. + dcr_DimensionCurve, ///< \ru Размерная кривая. \en Dimension curve. + dcr_LeaderCurve, ///< \ru Линия выноски. \en Leader curve. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Текстовый объект. + \en Text object. \~ +*/ +// --- +class CONV_CLASS MaTextItem : public MbRefItem { +protected: + bool visibility; // \ru Признак видимости. \en Visibility. + std::set purposeTags; // \ru Тэги форматирования. \en Gormat tags. +public: + + MaTextItem(); ///< \ru Конструктор по умолчанию. \en Default constructor. + + void SetVisibility( bool v ); ///< \ru Задать видимость; \en Set visibility. + bool IsVisible() const; ///< \ru Получить видимость; \en Get visibility. + + bool IsTag( MaeTextFormatTag tag ) const; ///< \ru Установлен ли тэг. \en Is a tag set. + bool GetTagIfUnique( MaeTextFormatTag& tag ) const; ///< \ru получить тэг, если он единственный. \en Get the tag provided it id qnique. + void SetTag( MaeTextFormatTag tag ); ///< \ru Установить тэг. \en Set a tag. + void ResetTag( MaeTextFormatTag tag ); ///< \ru Сбросить тэг. \en reset a tag. + bool TagUniqueOrUndefined() const; ///< \ru Назначено ли менее 2 тэгов. \en If less than two tags assinged. + bool NoTag() const; ///< \ru Отсутствуют ли тэги. \en If threre are no tags. + + virtual MaeTextType IsA() const = 0; + virtual SPtr Duplicate() const = 0; + virtual ~MaTextItem(); ///< \ru Деструктор. \en Destructor. + + OBVIOUS_PRIVATE_COPY( MaTextItem ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Набор текстовых блоков. + \en Set of text blocks. \~ +*/ +// --- +class CONV_CLASS MaCompositeText : public MaTextItem { + std::vector< SPtr > items; ///< \ru Текстовый блок. \en The text block. + +public: + + MaCompositeText(); ///< \ru Конструктор по умолчанию. \en Default constructor. + + std::vector< SPtr > GetItems() const; ///< \ru Получить элементы. \en Get elements. + void SetItems( const std::vector< SPtr >& it ); ///< \ru Задать элементы. \en Set elements. + void AddItem( MaTextItem* item ); ///< \ru Добавить элемент \en Add an element. + size_t ItemsSize() const; ///< \ru Получить число элементов \en Get count of elements. + MaTextItem* GetItem( size_t idx ); ///< \ru Получить элемент. \en Get element. + const MaTextItem* GetItem( size_t idx ) const; ///< \ru Получить элемент. \en Get element. + + virtual MaeTextType IsA() const; ///< \ru Выдать тип элемента. \en Get element type. + virtual SPtr Duplicate() const; + + /** \brief \ru Вставить объект перед всеми вхождениями указанного. + \en Insert an object before all instances of the specified one. \~ + */ + void InsertBefore( const SPtr& itemToInsert, const SPtr& beforeThis ); + + OBVIOUS_PRIVATE_COPY( MaCompositeText ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Текст с указанием ЛСК, шрифта, выравнивания. + \en Text with specification of LCS, font, align. \~ +*/ +// --- +class CONV_CLASS MaTextLiteral : public MaTextItem { +protected: + std::string text; ///< \ru Текст. \en A text. + MbPlacement location; ///< \ru Положение в аннотационной плоскости \en Position in annotation plane + std::string alignment; ///< \ru Выравнивание. \en Alignment. + eTextPath path; ///< \ru Направление текста. \en Text direction. + std::string font; ///< \ru Шрифт текста. \en Text font. + bool isFontExternal; ///< \ru Является ли шрифт нестандартным. \en Is font non-standard. + +public: + + MaTextLiteral(); ///< \ru Конструктор по умолчанию. \en Default constructor. + + MbPlacement & SetLocation(); ///< \ru Получить положение с возможностью модификации. \en Get position with possibility of modification. + const MbPlacement & GetLocation() const; ///< \ru Получить положение. \en Get position. + eTextPath & SetPath(); ///< \ru Получить направление с возможностью модификации. \en Get direction with possibility of modification. + eTextPath GetPath() const; ///< \ru Получить направление. \en Get direction. + void SetFontExternal( bool value ); ///< \ru Задать признак нестандартного шрифта. \en Set the flag of external font. + bool GetFontExternal() const; ///< \ru Получить признак нестандартного шрифта. \en Get the flag of external font. + + void SetText( const std::string& ); ///< \ru Получить текст. \en Get text. + void GetText( std::string& ) const; ///< \ru Задать текст. \en Set text. + void SetAlignment( const std::string& ); ///< \ru Получить выравнивание. \en Get alignment. + void GetAlignment( std::string& ) const; ///< \ru Задать выравнивание. \en Set alignment. + void SetFont( const std::string& ); ///< \ru Получить шрифт. \en Get font. + void GetFont( std::string& ) const; ///< \ru Задать шрифт. \en Set font. + + virtual MaeTextType IsA() const; + virtual SPtr Duplicate() const; + + OBVIOUS_PRIVATE_COPY( MaTextLiteral ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Текст с указанием ЛСК, шрифта, выравнивания, размера. + \en Text with specification of LCS, font, alignment, size. \~ +*/ +// --- +class CONV_CLASS MaTextLiteralExtent : public MaTextLiteral { + double sizeX, sizeY; ///< \ru Размеры по x и у. \en Size by x and size by y. +public: + + MaTextLiteralExtent(); ///< \ru Конструктор по умолчанию. \en Default constructor. + + double & SetSizeX(); ///< \ru Получить размер по x. \en Get size by x with possibility of modification. + double & SetSizeY(); ///< \ru Получить размер по y. \en Get size by y with possibility of modification. + double GetSizeX() const; ///< \ru Получить размер по x. \en Get size by x. + double GetSizeY() const; ///< \ru Получить размер по y. \en Get size by y. + + virtual MaeTextType IsA() const; + virtual SPtr Duplicate() const; + + OBVIOUS_PRIVATE_COPY( MaTextLiteralExtent ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Спецсимвол. + \en Specific symbol. \~ +*/ +// --- +class CONV_CLASS MaSpecificSymbol : public MaTextItem { + MbPlacement location; ///< \ru Положение в аннотационной плоскости \en Position in annotation plane. + double sizeX; ///< \ru Размер по X. \en Size by x. + double sizeY; ///< \ru Размер по Y. \en Size by Y. + MbeDefinedDimensionSymbol preDefinedSym; ///< \ru Код предопределённого символа. \en The predefined symbol code. +public: + + MaSpecificSymbol( MbeDefinedDimensionSymbol symbol, double szX, double szY ); + + MbeDefinedDimensionSymbol GetSymbol() const; ///< \ru Получить код предопределённого символа. \en Get the predefined symbol code. + bool IsSymbolDimension() const; ///< \ru Является ли символ размерным. \en Is symbol dimension. + bool IsSymbolSurfaceCondition() const; ///< \ru Является ли символ обозначением шероховатости. \en Is symbol surface condition. + bool IsSymbolShapeTolerance() const; ///< \ru Является ли символ допуском формы. \en Is symbol shape tolerance. + MbPlacement& SetLocation(); ///< \ru Получить положение с возможностью модификации. \en Get position with possibility of modification. + const MbPlacement& GetLocation() const; ///< \ru Получить положение. \en Get position. + double GetSizeX() const; ///< \ru Получить размер по x. \en Get size by x. + double GetSizeY() const; ///< \ru Получить размер по y. \en Get size by y. + void GetSize( double& x, double& y ) const; ///< \ru Получить размеры. \en Get sizes. + + OBVIOUS_PRIVATE_COPY( MaSpecificSymbol ) + + virtual MaeTextType IsA() const; + virtual SPtr Duplicate() const; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Описание законцовочного символа. +\en Description of the terminator symbol. \~ +*/ +struct MaTerminatorSymbol { + MbeDefinedTerminatorSymbol type; ///< \ru Тип символа \en Symbol type + double parameter; ///< \ru Значенеи параметра на размерной кривой. Если не указан, должен быть равен UNDEFINED_DBL. \en Parameter value on the dimensional curve. If not known, must be equal UNDEFINED_DBL. + double sizeX; ///< \ru Размер по x. \en Size by x. + double sizeY; ///< \ru Размер по у. \en Size by y. + /// \ru Признак сонаправленности с касательной к кривой в точке размещения. В случае неопределённого значения параметра - признак направленности внутрь. + /// \en Flag of the same direction with the tangent to the curve at the location point. In case parameter id undefined it shows if the arrow's direction is inner. + bool sameDirection; + + MbCartPoint3D location; ///< \ru Положение в пространстве. \en Location in space. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Кривая с терминаторами. + \en Curve and terminators. \~ +*/ +class CONV_CLASS MaDecoratedCurve : public MbRefItem { + SPtr curve; + std::vector< MaTerminatorSymbol > terminators; + MbeDecoratedCurveRole curveType; +public: + MaDecoratedCurve( MbeDecoratedCurveRole crvType ); ///< \ru Конструктор. \en Constructor. + MaDecoratedCurve( const MaDecoratedCurve& ); ///< \ru Конструктор копирования. \en Copy constructor. + const MaDecoratedCurve& operator= ( const MaDecoratedCurve& ); ///< \ru Оператор присваивания. \en Assignment operator. + + SPtr GetCurve() const; ///< \ru Получить кривую. \en Get curve. + bool CurveEmpty() const; ///< \ru Пуста ли кривая. \en If curve is empty. + void SetCurve( MbCurve3D* crv ); ///< \ru Задать кривую. \en Set curve. + size_t TerminatorsCount() const; ///< \ru Получить число законцовок. \en Set number of terminators. + bool TerminatorInfo( size_t terminatorIndex, MaTerminatorSymbol& term ) const; ///< \ru Получить законцовку с указанным индексом. \en Get terminator. + void AddTerminator( const MaTerminatorSymbol& term ); ///< \ru Добавить законцовку. \en Add terminator. + + bool IsA( MbeDecoratedCurveRole ) const; ///< \ru Проверка типа кривой. \en Check curve type. + MbeDecoratedCurveRole IsA() const; ///< \ru Проверка типа кривой. \en Check curve type. + + void DuplicateCurve( const MbMatrix3D& transform ); ///< \ru Заменить кривую на преобразованный по матрице дубликат. \en Replace curve by transformed replica. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Объект аннотации. + \en Annotation object. \~ +*/ +class CONV_CLASS MaAnnotationItem : public MbRefItem { +protected: + MbPlacement3D location; ///< \ru Локальная система координат (ЛСК), в плоскости XY которой расположены объекты аннотации. \en Local coordinate system (LCS) the annotation objects are located in XY plane of. + std::vector< const MbItem* > annotationGeometry; ///< \ru Геометрические объекты аннотации. \en Geometric objects of annotation. + std::vector< SPtr > annotationText; ///< \ru Текстовые аннотационные объекты. \en Text annotation objects. + std::string name; ///< \ru Имя. \en Name. + bool visible; ///< \ru Видим ли объект. \en If object is vivible. + // \ru Аналогичным образом реализовать и символьное представление \en Implement symbolic representation similarly. +public: + /// \ru Конструктор по плоскости аннотации. \en Constructor by annotation plane. + MaAnnotationItem( const MbPlacement3D& loc ); + /// \ru Деструктор. \en Destructor. + virtual ~MaAnnotationItem(); + +public: + /// \ru Получить тип объекта. \en Get the object type. + virtual Mae_AnnotationType IsA() const; + /// \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual Mae_AnnotationType Type() const; + + /// \ru Пусто ли визуальное представление. \en Whether the visual representation is empty. + virtual bool VisualItemsEmpty() const; + + /// \ru Отсутствуют ли геометрические элементы. \en Whether there are no geometric items. + bool GeometryEmpty() const; + + /// \ru Отсутствуют ли текстовые элементы. \en Whether there are no text items. + bool TextEmpty() const; + + /// \ru Добавить геометрический визуальный аннотационный элемент. \en Add the geometric visual annotation element of the kernel. + void AddGeometricAnnotationElement( const MbItem& ); + + /// \ru Добавить собственные геометрические визуальные аннотационный элементы в контейнер. \en Add own geometric visual annotation elements to container. + void AddAnnotationGeometryTo( std::vector< SPtr >& addTo ) const; + + /// \ru Число текстовых элементов. \en Count of text items. + size_t TextItemsCount() const; + + /// \ru Получить текстовый элемент с указанным индексом. \en Get specified text item. + SPtr TextItem( size_t ) const; + + /// \ru Задать аннотационные объекты ядра. \en Set the annotation objects of the kernel. + template< typename In > + void SetAnnotationGeometry( In first, In last ); + /// \ru Выдать аннотационные объекты ядра. У приёмника должен быть определён метод push_back. \en Get the annotation objects of the kernel. Method push_back should be defined for the receiver. + template< typename Out > + void GetAnnotationGeometry( Out dest ) const; + + /// \ru Получить текстовые аннотационные объекты. \en Get the text annotation object. + template< typename In > + void SetAnnotationText( In first, In last ); + /// \ru Выдать текстовые аннотационные объекты. У приёмника должен быть определён метод push_back. \en Get text annotation objects. Method push_back should be defined for the receiver. + template< typename Out > + void GetAnnotationText( Out dest ) const; + + /// \ru Добавить плоские геометрические объекты, преобразуя их в пространственные, используя текущую ЛСК. \en Add planar objects to geometric objects using current location. + void AddPlaneItems( const std::vector >& ); + + /// \ru Задать ЛСК. \en Specify LCS. + void SetLocation( const MbPlacement3D & loc ); + /// \ru Получить ЛСК. \en Get LCS. + MbPlacement3D GetLocation() const; + + /// \ru Задать имя. \en Specify name. + void SetName( const std::string & nm ); + + /// \ru Задать имя. \en Specify name. + void GetName( std::string & nm ) const; + + /// \ru Задать видимость. \en Set visibility. + void SetVisibility( bool v ); + /// \ru Видим ли объект. \en Is object vivible. + bool IsVisible() const; + + /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. + virtual SPtr ShallowDuplicateTransform( const MbMatrix3D & ); + + /// \ru Инициализировать все поля за исключением ЛСК данными присланного. \en Init all fields except for location according to the specified item. + void InitExceplLocation( const MaAnnotationItem & init ); + +protected: + + /// \ru Заменить геометрические элементы трансформированными копиями. \en Replace all geometric items by transformed copies. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +typedef SPtr AnnotationSPtr; + +/** \brief \ru Контейнер объектов аннотации. +\en Container of annotation objects. \~ +\ingroup Exchange_Base +*/ +typedef std::vector vector_of_annotation; +typedef std::vector AnnotationSptrVector; + + +/** \brief \ru Ассоциация наборов аннотационных объектов элементам со счётчиком ссылок. +\en Association of sets of annotation objects with elements with reference counter. \~ +\ingroup Exchange_Base +*/ +typedef std::map< SPtr, AnnotationSptrVector > map_of_visual_items; + + +/** \brief \ru Контейнер текстовых блоков. +\en Container of text blocks. \~ +\ingroup Exchange_Base +*/ +typedef std::vector< SPtr > vector_of_text; + + +//------------------------------------------------------------------------------ +/** \brief \ru Размер - родоначальник классов для размеров различных типов. + \en Dimension is the parent of all classes for dimensions of different types. \~ +*/ +// --- +class CONV_CLASS MaDimension : public MaAnnotationItem { + double value; ///< \ru Значение размера. \en A value of dimension. + double valuePlus; ///< \ru Отклонение размера в сторону увеличения. \en Deviation (increase) of size. + double valueMinus; ///< \ru Отклонение размера в сторону уменьшения. \en Deviation (decrease) of size. + bool isRangeSet; ///< \ru Если false, то задан только диапазон изменения, иначе можно вычислить погрешности в обе стороны. \en If it equals false, then only the range of changing is specified, else the tolerances in both directions can be computed. + bool isValueDefined; ///< \ru Задан ли номинал. \en Whether the nominal is given. +protected: + MaDecoratedCurve dimensionCurve; + + OBVIOUS_PRIVATE_COPY( MaDimension ) +protected: + MaDimension( const MbPlacement3D& loc, MbCurve3D* dimCurve ); + MaDimension( const MbPlacement3D& loc, const MaDecoratedCurve& dimCurve ); +public: + /// \ru Получить тип объекта. \en Get the object type. + virtual Mae_AnnotationType IsA() const; + /// \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual Mae_AnnotationType Type() const; + + /// \ru Получить размерную кривую. \en Get the dimensional curve. + MbCurve3D* GetDimensionCurve() const; + + /// \ru Задать номинал. \en Set a value. + void SetValue( double v ); + /// \ru Задать диапазон и значение. \en Set a range and a value. + void SetRange( double v, double vPlus, double vMinus ); + /// \ru Задать диапазон. \en Set range. + void SetRange( double vPlus, double vMinus ); + /// \ru Получить номинал. \en Get value. + bool GetValue( double& v ); + /// \ru Получить границы диапазона и значение, если они заданы. \en Get bounds of range and a value if they are specified. + bool GetRange( double& v, double& vPlus, double& vMinus ) const; + /// \ru Получить границы диапазона, если они заданы. \en Get bounds of the range if they are specified. + bool GetRange( double& vPlus, double& vMinus ) const; + /// \ru Заданы ли границы диапазона. \en Whether the bounds of range are specified. + bool IsRangeDefined() const; + /// \ru Задано ли значение. \en Whether the value is specified. + bool IsValueDefined() const; + /** \brief \ru Добавить законцовочный символ. + \en Add a terminator. \~ + \param [in] init - \ru Параметры задаваемого символа. + \en Parameters of specified symbol. \~ + \return \ru - true, если задана размерная кривая и хотя бы один из законцовочных символов не был задан. + \en - true, if a dimensional curve is specified and at least one of terminators has not been specified. \~ + */ + bool AddTerminator( const MaTerminatorSymbol& init ); + /// \ru Получить первый законцовочный символ. \en Get the first terminator. + bool GetFirstTerminator( MaTerminatorSymbol& first ) const; + /// \ru Получить второй законцовочный символ. \en Get the second terminator. + bool GetSecondTerminator( MaTerminatorSymbol& second ) const; + + void InitValueTerminators( const MaDimension& init ); +protected: + /// \ru Заменить геометрические элементы трансформированными копиями. \en Replace all geometric items by transformed copies. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Линейный размер. + \en Linear dimension. \~ +*/ +// --- +class CONV_CLASS MaLinearDimension : public MaDimension { +private: + SPtr bindBase; ///< \ru Первый объект привязки. \en The first binding object. + SPtr bindTarget; ///< \ru Второй объект привязки. \en The second binding object. + MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к первому объекту привязки в смысле STEP. \en Projection curve to the first binding object in sense of STEP. + MaDecoratedCurve projectionTarget; ///< \ru Проекционная кривая ко второму объекту привязки в смысле STEP. \en Projection curve to the second binding object in sense of STEP. + SPtr path; ///< \ru Кривая, вдоль которой проводится измерение. Если не задана, то размер есть кратчайший. \en A curve along which the measurement is performed. If not specified, then the size is shortest. + + OBVIOUS_PRIVATE_COPY( MaLinearDimension ) +public: + MaLinearDimension ( const MbRefItem* base, const MbRefItem* target, + MbLineSegment3D* projBase, MbLineSegment3D* projTarget, + MbLineSegment3D* dimensionCurve, const MbPlacement3D& loc ); + + MaLinearDimension ( const MbRefItem* base, const MbRefItem* target, + MbLineSegment3D* projBase, MbLineSegment3D* projTarget, + const MaDecoratedCurve dimensionCurve, const MbPlacement3D& loc ); + + virtual Mae_AnnotationType IsA() const; + + virtual bool VisualItemsEmpty() const; + + /// \ru Получить базовый объект привязки. \en Get the base binding object. + const MbRefItem * GetBindBase(); + /// \ru Получить второй объект привязки. \en Get the second binding object. + const MbRefItem * GetBindTarget(); + + /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. + MbLineSegment3D* GetProjectionBase() const; + /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. + MbLineSegment3D* GetProjectionTarget() const; + + /// \ru Задать кривую, вдоль которой провдится измерение. \en Set the curve the measurement is performed along. + void SetPath( MbCurve3D* inPath ); + /// \ru Получить кривую, вдоль которой провдится измерение. \en Get the curve the measurement is performed along. + MbCurve3D* GetPath(); + + /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. + virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); + +protected: + // Заменить геометрические элементы трансформированными копиями. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Угловой размер. + \en Angular dimension. \~ +*/ +// --- +class CONV_CLASS MaAngularDimension : public MaDimension { +private: + SPtr bindBase; ///< \ru Первый объект привязки. \en The first binding object. + SPtr bindTarget; ///< \ru Второй объект привязки. \en The second binding object. + MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к первому объекту привязки в смысле STEP. \en Projection curve to the first binding object in sense of STEP. + MaDecoratedCurve projectionTarget; ///< \ru Проекционная кривая ко второму объекту привязки в смысле STEP. \en Projection curve to the second binding object in sense of STEP. + + OBVIOUS_PRIVATE_COPY( MaAngularDimension ) +public: + MaAngularDimension( const MbRefItem* base, const MbRefItem* target, + MbLineSegment3D* projBase, MbLineSegment3D* projTarget, + MbArc3D* dimensionCurve, const MbPlacement3D& loc ); + + MaAngularDimension( const MbRefItem* base, const MbRefItem* target, + MbLineSegment3D* projBase, MbLineSegment3D* projTarget, + const MaDecoratedCurve&, const MbPlacement3D& loc ); + + virtual Mae_AnnotationType IsA() const ; + + virtual bool VisualItemsEmpty() const; + + /// \ru Получить базовый объект привязки. \en Get the base binding object. + const MbRefItem * GetBindBase(); + /// \ru Получить второй объект привязки. \en Get the second binding object. + const MbRefItem * GetBindTarget(); + + /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. + MbLineSegment3D * GetProjectionBase() const; + /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. + MbLineSegment3D * GetProjectionTarget() const; + /// \ru Если заданы проекционные кривые и если они не параллельны, получить точку пересечения или скрещивания. Метод работает и за пределеми параметрической области. \en If the projection curves are specified and if they are not parallel, get the point of intersection or crossing. The method works outside the bounds of a parametric region too. + bool NearestBetweenProjections( MbCartPoint3D& pnt ); + /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. + virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); + +protected: + // Заменить геометрические элементы трансформированными копиями. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Радиальный размер. + \en Radial dimension. \~ +*/ +// --- +class CONV_CLASS MaRadialDimension : public MaDimension { +private: + SPtr bindBase; ///< \ru Объект привязки. \en Binding object. + MaDecoratedCurve projectionBase; ///< \ru Проекционная кривая к объекту привязки в смысле STEP. \en Projection curve to the binding object in sense of STEP. + + OBVIOUS_PRIVATE_COPY( MaRadialDimension ) +public: + MaRadialDimension( const MbRefItem* base, MbLineSegment3D* projBase, + MbLineSegment3D* dimensionCurve, const MbPlacement3D& loc ); + + MaRadialDimension( const MbRefItem* base, MbLineSegment3D* projBase, + const MaDecoratedCurve& dimensionCurve, const MbPlacement3D& loc ); + + virtual Mae_AnnotationType IsA() const; + + virtual bool VisualItemsEmpty() const; + + /// \ru Получить базовый объект привязки. \en Get the base binding object. + const MbRefItem * GetBindBase(); + /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. + MbLineSegment3D * GetProjectionBase() const; + /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. + virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); + +protected: + // Заменить геометрические элементы трансформированными копиями. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Диаметральный размер. + \en Diameter dimension. \~ +*/ +// --- +class CONV_CLASS MaDiameterDimension : public MaDimension { +private: + SPtr bindBase; ///< \ru Объект привязки. \en Binding object. + MaDecoratedCurve projectionBase; ///< \ru Первая проекционная кривая к объекту привязки в смысле STEP. \en The first projection curve to binding object in sense of STEP. + MaDecoratedCurve projectionTarget; ///< \ru Вторая проекционная кривая к объекту привязки в смысле STEP. \en The second projection curve to binding object in sense of STEP. + + OBVIOUS_PRIVATE_COPY( MaDiameterDimension ) +public: + MaDiameterDimension( const MbRefItem* base, MbLineSegment3D* projBase, + MbLineSegment3D* projTarget, MbLineSegment3D* dimCurve, + const MbPlacement3D& loc ); + + MaDiameterDimension( const MbRefItem* base, MbLineSegment3D* projBase, + MbLineSegment3D* projTarget, const MaDecoratedCurve& dimCurve, + const MbPlacement3D& loc ); + + virtual Mae_AnnotationType IsA() const; + + virtual bool VisualItemsEmpty() const; + + /// \ru Получить базовый объект привязки. \en Get the base binding object. + const MbRefItem * GetBindBase(); + + /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. + MbLineSegment3D * GetProjectionBase() const; + /// \ru Получить вторую проекционную кривую к объекту привязки. \en Get the first projection curve to the binding object. + MbLineSegment3D * GetProjectionTarget() const; + /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. + virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); + +protected: + // Заменить геометрические элементы трансформированными копиями. + virtual void DuplicateTransformDeometry( const MbMatrix3D & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Выносной элемент - родоначальник классов для обозначений различных типов. +\en Callout is the parent of all classes for callouts of different types. \~ +*/ +// --- +class CONV_CLASS MaCallout : public MaAnnotationItem { + Mae_AnnotationType whatIs; ///< \ru Подтип объекта. \en Object subtype. + std::vector leaderLines; ///< \ru Линии выноски. \en Leader lines. +public: + /// \ru Получить тип объекта. \en Get the object type. + virtual Mae_AnnotationType IsA() const; + /// \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual Mae_AnnotationType Type() const; + /// \ru Создать объект заданного типа объекта. \en Create object of specified type. + static MaCallout* Create( const MbPlacement3D& location, Mae_AnnotationType subtype ); + + void AddLeaderLine( const MaDecoratedCurve& leader ); ///< \ru Добавить линию выноски. \en Add leader line. + void AddLeaderLines( const std::vector& leaders ); ///< \ru Добавить линию выноски. \en Add leader line. + size_t LeaderLinesCount() const; ///< \ru Получить число линий выноски. \en Get number of leader lines. + bool LeaderLineInfo( size_t index, MaDecoratedCurve& callout ) const; ///< \ru Получить линию выноски с указанным индексом. \en Get of leader lines at specified index. +private: + MaCallout( const MbPlacement3D& location, Mae_AnnotationType subtype ); ///< \ru Конструктор. \en Constructor. + + OBVIOUS_PRIVATE_COPY(MaCallout) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Шероховатость поверхности. +\en Surface condition. \~ +*/ +// --- +class CONV_CLASS MaSurfaceCondition : public MaAnnotationItem { + SPtr< const MbRefItem > baseObject; + double value; +public: + /// \ru Конструктор. \en Constructor. + MaSurfaceCondition( const MbPlacement3D& location ); + + /// \ru Получить тип объекта. \en Get the object type. + virtual Mae_AnnotationType IsA() const; + /// \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual Mae_AnnotationType Type() const; + + OBVIOUS_PRIVATE_COPY( MaSurfaceCondition ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Допуск формы. +\en Shape tolerance. \~ +*/ +// --- +class CONV_CLASS MaShapeTolerance : public MaAnnotationItem { + SPtr< const MbRefItem > baseObject; + double value; +public: + /// \ru Конструктор. \en Constructor. + MaShapeTolerance( const MbPlacement3D& location ); + + /// \ru Получить тип объекта. \en Get the object type. + virtual Mae_AnnotationType IsA() const; + /// \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual Mae_AnnotationType Type() const; + + OBVIOUS_PRIVATE_COPY(MaShapeTolerance) +}; + + +//------------------------------------------------------------------------------ +// \ru Задать геометрические объекты аннотации \en Set geometric objects of annotation. +// --- +template< typename In > +void MaAnnotationItem::SetAnnotationGeometry( In first, In last ) { + std::for_each( annotationGeometry.begin(), annotationGeometry.end(), ReleaseItem ); + annotationGeometry.assign( first, last ); + std::for_each( annotationGeometry.begin(), annotationGeometry.end(), AddRefItem ); +} + + +//------------------------------------------------------------------------------ +// \ru Получить геометрические объекты аннотации \en Get geometric objects of annotation. +// --- +template< typename Out > +void MaAnnotationItem::GetAnnotationGeometry( Out dest ) const { + std::copy( annotationGeometry.begin(), annotationGeometry.end(), dest ); +} + + +//------------------------------------------------------------------------------ +// \ru Задать текстовые объекты аннотации \en Set text objects of annotation. +// --- +template< typename In > +void MaAnnotationItem::SetAnnotationText( In first, In last ) { + annotationText.assign( first, last ); +} + + +//------------------------------------------------------------------------------ +// \ru Получить текстовые объекты аннотации \en Get text objects of annotation +// --- +template< typename Out > +void MaAnnotationItem::GetAnnotationText( Out dest ) const { + std::copy( annotationText.begin(), annotationText.end(), dest ); +} + + +#endif // __CONV_ANNOTATION_ITEM_H diff --git a/C3d/Include/conv_binary_object.h b/C3d/Include/conv_binary_object.h index 16290a0..a7fa293 100644 --- a/C3d/Include/conv_binary_object.h +++ b/C3d/Include/conv_binary_object.h @@ -1,24 +1,24 @@ -//////////////////////////////////////////////////////////////////////////////// -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __BINOBJ_H -#define __BINOBJ_H - - -//------------------------------------------------------------------------------ -// бинарный объект -// --- -struct BinaryObj { - - void * p; - void * pSort; - - BinaryObj( void *otherId, void *otherP ) : p( otherId ), pSort( otherP ) {} - - bool operator == ( const BinaryObj &o ) const { return pSort == o.pSort; } - bool operator < ( const BinaryObj &o ) const { return pSort < o.pSort; } -}; - - +//////////////////////////////////////////////////////////////////////////////// +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __BINOBJ_H +#define __BINOBJ_H + + +//------------------------------------------------------------------------------ +// бинарный объект +// --- +struct BinaryObj { + + void * p; + void * pSort; + + BinaryObj( void *otherId, void *otherP ) : p( otherId ), pSort( otherP ) {} + + bool operator == ( const BinaryObj &o ) const { return pSort == o.pSort; } + bool operator < ( const BinaryObj &o ) const { return pSort < o.pSort; } +}; + + #endif \ No newline at end of file diff --git a/C3d/Include/conv_exchange_settings.h b/C3d/Include/conv_exchange_settings.h index 159e308..23c7f6c 100644 --- a/C3d/Include/conv_exchange_settings.h +++ b/C3d/Include/conv_exchange_settings.h @@ -1,540 +1,577 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Настройки импорта и экспорта. - \en Settings of import and export procedure. \~ - \details \ru Интерфейс настроек и предопределённая реализация ConvConvertorProperty3D. - \en Interface of settings and pre-defined implementation ConvConvertorProperty3D. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_MODEL_PROPERTIES_H -#define __CONV_MODEL_PROPERTIES_H - -#include -#include -#include -#include - -class MbProductInfo; - -//------------------------------------------------------------------------------ -/** \brief \ru Константы единиц измерения. -\en Length units constants.\~ -\ingroup Data_Interface -*/ -// --- -/// \ru Миллиметры. \en Millimeters. -#define LENGTH_UNIT_MM 1.0 -/// \ru Сантиметры. \en Centimeters. -#define LENGTH_UNIT_CM 10.0 -/// \ru Дециметры. \en Decimeters. -#define LENGTH_UNIT_DM 100.0 -/// \ru Метры. \en Meters. -#define LENGTH_UNIT_METER 1000.0 -/// \ru Дюймы. \en Inches. -#define LENGTH_UNIT_INCH 25.4 - - -//------------------------------------------------------------------------------ -/** \brief \ru Прикладной протокол. -\en Applied protocol.\~ -\ingroup Data_Interface -*/ -// --- -enum MbeImpExpFormat { - ief_STEP203, ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). - ief_STEP214, ///< \ru STEP прикладной протокол 214 ( Проектирование автомобилей ). \en STEP applied protocol STEP 214 (Automotive design). - ief_STEP242, ///< \ru STEP прикладной протокол 242 ( Проектирование автомобилей ). \en STEP applied protocol STEP 242 (Automotive design). -}; - - -#define EXPORT_DEFAULT -1 ///< \ru По умолчанию для заданного формата. \en Default for specified format. -#define EXPORT_STEP_203 203 ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). -#define EXPORT_STEP_214 214 ///< \ru STEP прикладной протокол 214 ( Проектирование автомобилей ). \en STEP applied protocol STEP 214 (Automotive design). -#define EXPORT_STEP_242 242 ///< \ru STEP прикладной протокол 242. \en STEP applied protocol STEP 242. -#define EXPORT_ACIS_4 4 ///< \ru ACIS версия 4.0. \en ACIS version 4.0. -#define EXPORT_ACIS_7 7 ///< \ru ACIS версия 7.0 (по умолчанию). \en ACIS version 7.0 (default). -#define EXPORT_ACIS_10 10 ///< \ru ACIS версия 10.0. \en ACIS version 10.0. - - -//------------------------------------------------------------------------------ -/** \brief \ru Индексы строк, передаваемых через конвертер. -\en Indices of strings, transmitted through converter.\~ -\ingroup Data_Interface -*/ -// --- -enum MbeConverterStrings { - cvs_BEGIN = 0, ///< \ru Для удобства перебора. \en For lookup only. - cvs_STEPAuthor, ///< \ru Автор для конвертера STEP. \en Author of the document, in STEP. - cvs_STEPOrganization, ///< \ru Организация для конвертера STEP. \en The organization, the author is related with, in STEP. - cvs_STEPComment, ///< \ru Комментарий файла формата STEP. \en Annotation, in STEP. - cvs_CAD_NAME, ///< \ru Название САПР при экспорте. \en CAD Name for export. - cvs_END ///< \ru Для удобства перебора. \en For lookup only. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Индексы, управляющие разрешением на чтение или запись объектов. -\en Indeces, which filter imported/exported objects or properties.\~ -\ingroup Data_Interface -*/ -// --- -enum MbeIOPermiss { - iop_rSolid = 0, ///< \ru Разрешение на чтение твёрдых тел. \en Import solid solids. - iop_wSolid, ///< \ru Разрешение на запись твёрдых тел. \en Export solid solids. - iop_rSurface, ///< \ru Разрешение на чтение поверхностей. \en Import surfaces. - iop_wSurface, ///< \ru Разрешение на запись поверхностей. \en Export surfaces. - iop_rCurve, ///< \ru Разрешение на чтение кривых. \en Import curves. - iop_wCurve, ///< \ru Разрешение на запись кривых. \en Export curves. - iop_rDrafts, ///< \ru Разрешение на чтение эскизов (не применяется). \en Import drafts (ignored). - iop_wDrafts, ///< \ru Разрешение на запись эскизов. \en Export drafts. - iop_rInvisible, ///< \ru Разрешение на чтение невидимых объектов (не применяется). \en Import invisible objects (not applied). - iop_wInvisible, ///< \ru Разрешение на запись невидимых объектов. \en Export invisible objects. - iop_rPoint, ///< \ru Разрешение на чтение точек. \en Import points. - iop_wPoint, ///< \ru Разрешение на запись точек. \en Export points. - iop_rDocInfo, ///< \ru Разрешение на чтение информации о документе (автор, организация, комментарии). \en Import components info ( author, organization, description ). - iop_wDocInfo, ///< \ru Разрешение на запись информации о документе (автор, организация, комментарии). \en Export components info ( author, organization, description ). - iop_rTextDescription, ///< \ru Разрешение на чтение технических требований. \en Import technical requirements. - iop_wTextDescription, ///< \ru Разрешение на запись технических требований. \en Export technical requirements. - iop_rDimensions, ///< \ru Разрешение на чтение размеров. \en Import dimensions. - iop_wDimensions, ///< \ru Разрешение на запись размеров. \en Export dimensions. - iop_rAttributes, ///< \ru Разрешение на чтение атрибутов. \en Import attributes. - iop_wAttributes, ///< \ru Разрешение на запись атрибутов. \en Export attributes. - iop_rBRep, ///< \ru Разрешение на чтение форм изделий в граничном представлении (только в JT). \en Import shapes in boundary representation (JT only). - iop_wBRep, ///< \ru Разрешение на запись форм изделий в граничном представлении (только в JT). \en Export shapes in boundary representation (JT only). - iop_rPolygonal, ///< \ru Разрешение на чтение полигональных форм изделий. \en Import polygonal shapes. - iop_wPolygonal, ///< \ru Разрешение на запись полигональных форм изделий. \en Export polygonal shapes. - iop_rLOD0, ///< \ru Разрешение на чтение полигональных форм изделий уровня детализации 0. \en Import polygonal shapes of the 0-th LOD. - iop_wLOD0, ///< \ru Разрешение на запись полигональных форм изделий уровня детализации 0. \en Export polygonal shapes of the 0-th LOD. - iop_rAssociated, ///< \ru Разрешение на чтение ассоциированной геометрии (резьбы и др). \en Import associated geometry (threads etc). - iop_wAssociated, ///< \ru Разрешение на запись ассоциированной геометрии (резьбы и др). \en Export associated geometry (threads etc). - iop_rDensity, ///< \ru Разрешение на чтение единиц плотности. \en Import density units. - iop_wDensity, ///< \ru Разрешение на запись единиц плотности. \en Export density units. - iop_rValidationProperties, ///< \ru Разрешение на чтение контрольных параметров - объёма, площади поверхности, центра масс. \en Import validation properties - volume, surface area, centroid. - iop_wValidationProperties, ///< \ru Разрешение на запись контрольных параметров - объёма, площади поверхности, центра масс. \en Export validation properties - volume, surface area, centroid. - iop_rStyle, ///< \ru Разрешение на чтение элементов оформления (цвет, начертание, и т.п.). \en Import appearance. - iop_wStyle, ///< \ru Разрешение на запись элементов оформления (цвет, начертание, и т.п.). \en Export appearance. - iop_END -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тип сообщения об ошибке при выводе в лог. -\en Type of a log message.\~ -\ingroup Data_Exchange -*/ -// --- -enum eMsgType { - emt_ErrorNoId,///< \ru Ошибка формата. Значение id игнорируется, выводится только текст. \en Error not related with a certain record. The id field is ignored. - emt_TextOnly, ///< \ru Значение id игнорируется, выводится только текст. \en Used to type message only. The id field is ignored. - emt_Info, ///< \ru Рабочая информация. \en Info. - emt_Warning, ///< \ru Предупреждение. \en Warning. - emt_Error ///< \ru Ошибка формата или неустранимая ошибка преобразования. \en Format mismatch or fatal converting error. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Код подробного сообщения об ошибке при выводе в лог. -\en The key of a detailed log message.\~ -\ingroup Data_Interface -*/ -// --- -enum eMsgDetail { - emd_Title, ///< \ru Заголовок файла. \en File header. - emd_HEADError, ///< \ru Тип сообщения - ошибка. \en Error. - emd_HEADWarinig, ///< \ru Тип сообщения - Предупреждение. \en Warning. - emd_HEADInfo, ///< \ru Тип сообщения - Информация. \en Info. - emd_HEADDefaultMsg, ///< \ru Тип сообщения - Сообщение. \en Message. - - emd_STOPFileOpenError, ///< \ru Ошибка открытия файла. \en Cannot open file. - emd_STOPFileOpenErrorOrEmpty, ///< \ru Ошибка открытия файла или файл пуст. \en Cannot open file or file is empty. - emd_STOPHeaderReadError, ///< \ru Не удалось прочитать заголовок файла. \en Cannot read file header. - emd_STOPNoOrBadData, ///< \ru Файл не содержит данных или их не удалось распознать. \en File body does not exist or incorrect. - emd_STOPIncorrectStructure, ///< \ru Неверная структура файла. \en Incorrect file structure. - emd_STOPAddressConflict, ///< \ru Данный адрес имеют два различных объекта. \en Two or more entities have the same id. - - emd_ErrorNoRootObject, ///< \ru Не найден корневой объект. \en Root object not found. - emd_ErrorSyntaxIncorrectFormFloat, ///< \ru Невозможно прочитать действительную константу. \en Error reading floating-point number. - emd_ErrorEmptyLoop, ///< \ru Цикл грани пуст. \en Face has an empty loop. - emd_ErrorEmptyQueriesList, ///< \ru Список запросов пуст. \en - emd_ErrorEmptyObjectsList, ///< \ru Список объектов пуст. \en List of objects is empty. - emd_ErrorEmptyGeomObjectsList, ///< \ru Список геометрических объектов пуст. \en List of geometric objects is empty. - emd_ErrorEmptyShellsList, ///< \ru Список оболочек пуст. \en List of shells is empty. - emd_ErrorEmptyListOfWrieframes, ///< \ru Список каркасов пуст. \en List of frames is empty. - emd_ErrorEmptyCurveCompositesList, ///< \ru Список компонент составной кривой пуст. \en Composite curve has an empty list of composites. - emd_ErrorEmptyBoundCurvesList, ///< \ru Список граничных кривых пуст. \en List of boundary curves is empty. - emd_ErrorEmptyEdgeList, ///< \ru Список рёбер пуст. \en List of edges is empty. - emd_ErrorEmptyFacesList, ///< \ru Список граней пуст. \en List of faces is empty. - emd_ErrorEmptyReferencesList, ///< \ru Список ссылок пуст. \en List of references is empty. - emd_ErrorEmptyOrMore2ReferencesList,///< \ru Список ссылок пуст или содержит более 2 элементов. \en List of references is empty or contains more than 2 items. - emd_ErrorUndefinedFaceSurfaceRef, ///< \ru Ссылка на базовую поверхность грани не определена. \en Invalid reference to base surface. - emd_ErrorUndefinedBaseCurveRef, ///< \ru Ссылка на базовую кривую не определена. \en Invalid reference to base curve. - emd_ErrorRadiusTooCloseToZero, ///< \ru Радиус слишком мал. \en Too small radius. - emd_ErrorRadiusValueNegative, ///< \ru Отрицательное значение радиуса. \en Negative value of radius. - emd_ErrorEllipseAxisTooCloseToZero, ///< \ru Длина полуоси эллипса слишком мала. \en Ellipse axis is too short. - emd_ErrorEllipseAxisNegative, ///< \ru Отрицательная длина полуоси эллипса. \en Ellipse axis length is negative. - emd_ErrorNegativeDegree, ///< \ru Отрицательный порядок сплайна. \en Negative spline order. - emd_ErrorNegativeUDegree, ///< \ru Отрицательный порядок сплайновой поверхности по U. \en Spline surface order along U is negative. - emd_ErrorNegativeVDegree, ///< \ru Отрицательный порядок сплайновой поверхности по V. \en Spline surface order along V is negative. - emd_ErrorDegreeFixImpossible, ///< \ru Невозможно исправить порядок сплайна. \en Cannot fix spline order. - emd_ErrorPolylinePointListLess2, ///< \ru Список точек ломаной содержит менее 2 элементов. \en Polyline contains less then 2 points. - emd_ErrorPointListLess2, ///< \ru Список точек содержит менее 2 элементов. \en List of points contains less then 2 points. - emd_ErrorKnotsListLess2, ///< \ru Список узлов содержит менее 2 элементов. \en List of knots contains less then 2 values. - emd_ErrorWeightsListLess2, ///< \ru Список весов содержит менее 2 элементов. \en List of weights contains less then 2 values. - emd_ErrorUPointListLess2, ///< \ru Список точек по U содержит менее 2 элементов. \en List of points along U contains less then 2 points. - emd_ErrorUKnotsListLess2, ///< \ru Список узлов по U содержит менее 2 элементов. \en List of knots along U contains less then 2 values. - emd_ErrorUWeightsListLess2, ///< \ru Список весов по U содержит менее 2 элементов. \en List of weights along U contains less then 2 values. - emd_ErrorVPointListLess2, ///< \ru Список точек по V содержит менее 2 элементов. \en List of points along V contains less then 2 points. - emd_ErrorVKnotsListLess2, ///< \ru Список узлов по V содержит менее 2 элементов. \en List of knots along V contains less then 2 values. - emd_ErrorVWeightsListLess2, ///< \ru Список весов по V содержит менее 2 элементов. \en List of weights along V contains less then 2 values. - emd_ErrorListsSizeMismatch, ///< \ru Размеры списков не согласуются. \en Lists size mismatch. - emd_ErrorKnotsWeightsListsOrderMismatch, ///< \ru Размеры списков узлов и весов не согласуются с порядком сплайна. \en Sizes of knots and weights lists do not agree with the spline order. - emd_ErrorKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов не согласуются. \en Size of knots list does not agree with the size of the list of weights. - emd_ErrorUKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов по U не согласуются. \en Sizes of knots and weights lists along U do not agree. - emd_ErrorVKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов по V не согласуются. \en Sizes of knots and weights lists along V do not agree. - emd_ErrorSplineCurveNotCreatedUndefinedKnotsVector, ///< \ru Сплайновая кривая не создана - не определёны узлы. \en Cannot create spline, because knots are not defined. - emd_ErrorSplineSurfaceNotCreatedUndefinedKnotsVectors, ///< \ru Сплайновая поверхность не создана - не определёны узлы. \en Cannot create spline surface, because knots are not defined. - emd_ErrorInCorrectSplineSurfaceData, ///< \ru Неверно заданы параметры NURBS поверхности. \en Spline surface parameters are not valid. - - emd_WarningNoSectionTerminator, ///< \ru Маркер завершения раздела не обнаружен. \en Section terminator not found. - emd_WarningSyntaxMultipleDotInFloat, ///< \ru Повторяющаяся точка в действительном числе. \en Too many dots in a floating-point number. - emd_WarningSyntaxMultipleEInFloat, ///< \ru Повторяющаяся E в действительном числе. \en Too many E signs in a floating-point number. - emd_WarningLoopNotClosed, ///< \ru Цикл не замкнут. \en Loop is not closed. - emd_WarningContourNotClosed, ///< \ru Контур не замкнут. \en contour is not closed. - emd_WarningUndefinedRef, ///< \ru Ссылка не определена. \en Invalid reference. - emd_WarningToroidalSurfaceDegenerated, ///< \ru Тороидальная поверхность вырождена. \en Toroidal surface is degenerate. - emd_WarningUndefinedBasisCurve, ///< \ru Не определена базовая кривая. \en Base curve not defined. - emd_WarningUndefinedSweptCurve, ///< \ru Не определена образующая кривая. \en Generatrix curve is not defined. - emd_WarningUndefinedExtrusionDirection, ///< \ru Не определено направление выдавливания. \en Extrusion direction is not defined. - emd_WarningUndefinedAxis, ///< \ru Не определена ось. \en Axis is not defined. - emd_WarningUndefinedAxisOfRevolution, ///< \ru Не определена ось вращения. \en Rotation axis is not defined. - emd_WarningUndefinedBasisSurface, ///< \ru Не определена базовая поверхность. \en Base surface is not defined. - emd_WarningUndefinedRepresentation, ///< \ru Не определено представление. \en Representation is not defined. - emd_WarningUndefinedTransformationOperator, ///< \ru Не определён оператор преобразования. \en Transformation is not defined. - emd_WarningUndefinedObjectTransformBy, ///< \ru Не определён объект, по которому ведётся преобразование. \en Basic object of transformation is not defined. - emd_WarningUndefinedObjectToTransform, ///< \ru Не определён преобразуемый объект. \en No object to transform is defined. - emd_WarningUndefinedCurve, ///< \ru Не определена кривая. \en Curve is not defined. - emd_WarningUndefinedCompositeSegment, ///< \ru Не определён сегмент составной кривой. \en Composite curve segment is not defined. - emd_WarningUndefinedDirection, ///< \ru Не определено направление. \en Direction is not defined. - emd_WarningUndefinedAxisDirection, ///< \ru Не определено направление оси. \en Axis direction is not defined. - emd_WarningDegeneratedItemWasSkipped, ///< \ru Проигнорирован (пропущен) вырожденный объект. \en Degenerate object was missed. - emd_WarningFloatParceFailureDefaultUsed, ///< \ru Ошибка разпознавания числа с плавающей точкой, подставлено значение по умолчанию. \en Floating point value couldn't be parced; default value was used. - emd_WarningSameShapeEdgeTwiceInLoop, ///< \ru В цикле дважды встречается одинаковое ребро. \en Edge based on same curves twice enters a loop. - emd_WarningIncorrectFaceWasNotAddedToShell, ///< \ru Некорректная грань не была добавлена в оболочку. \en Incorrect face was not added to shell. - emd_WarningBoundsNotConnectedWithSeams, ///< \ru Границы замкнутой грани не стыкуются со швами. \en Bounds of periodic face not connected with seams. - emd_WarningIntCurveWasReplacedBySegment, ///< \ru Кривая пересечения была заменена отрезком. \en Intersection curve was replaced by segment. - - emd_MessageWeightsFilled, ///< \ru Веса заданы. \en Weights are set. - - emd_ErrorSTEPEdgeCurveFlagTSingleRedefinition, ///< \ru При создании ребра в конвертере STEP дважды указана грань с флагом .T.. \en Double .T. face inclusion in STEP. - emd_ErrorSTEPEdgeCurveFlagFSingleRedefinition, ///< \ru При создании ребра в конвертере STEP дважды указана грань с флагом .F.. \en Double .F. face inclusion in STEP. - emd_ErrorSTEPEdgeCurveFlagTMultipleRedefinition, ///< \ru При создании ребра в конвертере STEP более чем дважды указана грань с флагом .T.. \en Multiple .T. face inclusion in STEP. - emd_ErrorSTEPEdgeCurveFlagFMultipleRedefinition, ///< \ru При создании ребра в конвертере STEP более чем дважды указана грань с флагом .F.. \en Multiple .F. face inclusion in STEP. - emd_ErrorSTEPUndefinedFaceGeometry, ///< \ru Не определена геометрия грани в конвертере STEP. \en Face geometry is not defined in STEP. - emd_ErrorSTEPSyntaxMultipleDotInEnum, ///< \ru Синтаксическая ошибка в файле формата STEP - в перечислении символ "." встречается более 1 раза подряд. \en Too many dots in a enumeration record in STEP. - emd_WarningSTEPPointCorrection, ///< \ru Скорректированы координаты точки. \en Point location corrected. ( by BUG_73871 ) - emd_WarningSTEPEdgeCurveByVertices, ///< \ru Кривая ребра скорректирована с учётом координат вершин. \en Edge curve corrected in accordance with vertices. ( by BUG_73871 ) - emd_MessageSTEPFlagChangedToF, ///< \ru Произведена замена флага на .F.. \en Flag was set as .F. in STEP. - emd_MessageSTEPFlagChangedToT, ///< \ru Произведена замена флага на .T.. \en Flag was set as .T. in STEP. - emd_WarningBooleanUndefined, ///< \ru Булево значение не определено. \en Boolean value not defined. - - emd_WarningACISUnsupportedInterpoleCurveType, ///< \ru Данный подтип ACIS интерполяционной кривой не поддерживается. \en Interpolation curve type is not supported by SAT converter. - emd_WarningACISUnsupportedParametricCurveType, ///< \ru Данный подтип ACIS параметрической кривой не поддерживается. \en Parametric curve type is not supported by SAT converter. - emd_ErrorACISUnsupportedVersion, ///< \ru Данная версия ACIS NT не поддерживается. \en Th version of file is not supported by SAT converter. - emd_WarningACISCannotImportEntityId, ///< \ru Не удалось импортировать объект с данным Id. \en Cannot import this object by SAT converter. - emd_WarningACISIncorrectIntAttribute, ///< \ru Некорректный целочисленный атрибут. \en Incorrect integer attribute. - emd_WarningVRMLGridDuplicatesInMeshes, ///< \ru Присутствуют дубликаты объектов в сетках. \en There are grid duplicates in meshes. - emd_WarningACISLawIntCurveIsNotCreated, ///< \ru Кривая по закону не создана. \en Law intersection curve is not created. - - emd_ErrorIGESIncorrectExternalReference, ///< \ru Неверное имя внешней ссылки. \en Invalid external reference in IGES. - - emd_ErrorSTLTooManyTrianglesForBinary, ///< \ru Триангуляция исходной модели содержит больше треугольников, чем допустимо стандартом ( не выражается 32-битным беззнаковым числом ) ( by BUG_71422 ). \en Too many triangles (not represented by unsigned 32-bit number) for export to binary STL. - - emd_ErrorXTUnsupportedVersion, ///< \ru Данная версия X_T не поддерживается. \en Th version of file is not supported by X_T converter. - - emd_ErrorJTUnsupportedVersion ///< \ru Данная версия JT не поддерживается. \en Th version of file is not supported by JT converter. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс генератора однострочного идентификатора компонента. - \en Interface of component's identifier generator. \~ - \details \ru Предназначен для для экспорта в форматы, в которых для идентификации компонента предусмотрено одно строковое значение. - \en Demanded for export to formats having one string field for product inetifier. \~ -\ingroup Exchange_Interface -*/ -struct IProductIdMaker : public MbRefItem -{ - virtual c3d::string_t operator()( const MbProductInfo& ) const = 0; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс свойств конвертера. -\en Interface of converter's properties. \~ -\details \ru Интерфейс свойств конвертера реализует выдачу имени документа и других сведений о нём, таких как автор, -и управление режимами работы - сшивкой поверхностей с возможностью создания твёрдых -тел, фильтрацией объектов, формирование журнала трансляции. -\en Interface of converter's properties realizes getting the document's name and other information about it, such as the author, -and management of modes of operations - stitching of surfaces with possibility of solids creation, -objects filtration, generation of translation journal. \~ -\ingroup Exchange_Interface -*/ -class CONV_CLASS IConvertorProperty3D { -public : - virtual ~IConvertorProperty3D() {} - -public: - /// \ru Получить имя документа. \en Get document's name. - virtual const std::string GetDocumentName () const = 0; //{ return std::string( GetDocName().get_str() ); }; - /// \ru Получить имя файла для конвертирования. \en Get file name for converting. - virtual const c3d::path_string FullFilePath () const = 0 ;//{ return c3d::path_string( GetFileName().c_str() ); }; - /// \ru Является ли файл текстовым. \en Whether the file is a text file. - virtual bool IsFileAscii () const = 0; - /// \ru Получить версию формата при экспорте. \en Get the version of format for export. - virtual long int GetFormatVersion () const { return EXPORT_DEFAULT; }; - /// \ru Задать формат для экспорта \en Set format for export - DEPRECATE_DECLARE virtual MbeImpExpFormat GetFormat () const { return ief_STEP203; } - /// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ). - virtual bool IsOutOnlySurfaces() const = 0; - /// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly. - virtual bool IsAssembling () const = 0; - /// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type. - virtual bool GetIoPermission( MbeIOPermiss nPermission ) const = 0; - /// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types. - virtual void GetIoPermissions( std::vector& ioPermissions ) const = 0; - /// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type. - virtual void SetIoPermission( MbeIOPermiss nPermission, bool set ) = 0; - /// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter. - virtual bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const = 0; - /// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter. - virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ) = 0; - /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. - virtual eTextForm GetAnnotationTextRepresentation () const { return exf_TextOnly; } - /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). - virtual bool ExportComponentsSeparately() const { return false; } - /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. - virtual MbPlacement3D GetOriginLocation() const = 0; - /// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented. - virtual bool ReplaceLocationsToRight() const = 0; - /** \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 = 0; - - /** \brief \ru Получить множитель единиц длины по отношению к миллиметру. - \en Get the factor of the length units to millimeters. \~ - \details \ru При импорте, если единицы измерения не заданы явно с помощью средств, предоставляемых обменным форматом, - все размеры (координаты точек, радиусы) умножаются на возвращаемое значение. При экспорте либо с помощью - средств, предоставляемых обменным форматом, задаются единицы измерения, либо все размеры модели (координаты - точек, радиусы) умножаются на возвращаемое значение. - \en During the import all spatial objects (coordinate values, radiuses) are multiplied by the returned value, - unless the scale factor comes from the exchange file. During the export the exchange format facilities are - used to specify the length units or all spatial objects (coordinate values, radiuses) are multiplied by the - returned value. \~ - */ - virtual double LengthUnitsFactor() const { return LENGTH_UNIT_MM; } - - - /** \brief \ru Получить дополнительный множитель единиц длины по отношению к миллиметру в модели приложения. - \en Get addifional factor of the length units to millimeters in the application model. \~ - \details \ru При импорте из всех форматов за исключением JT, если единицы измерения, в том числе и заданные - явно с помощью средств, предоставляемых обменным форматом, все размеры (координаты точек, радиусы) умножаются - на возвращаемое значение. При экспорте либо с помощью средств, предоставляемых обменным форматом, задаются - единицы измерения, либо все размеры модели (координаты точек, радиусы) умножаются на возвращаемое значение. - \en During the import from all formats except for JT all spatial objects (coordinate values, radiuses) are - multiplied by the returned value, even if the scale factor comes from the exchange file. During the export the - exchange format facilities are used to specify the length units or all spatial objects (coordinate values, - radiuses) are multiplied by the returned value. \~ - */ - virtual double AppLengthUnitsFactor() const { return LENGTH_UNIT_MM; } - - /** \brief \ru Сделать запись в журнал конвертирования. - \en Make a record in the converter report. \~ - \param[in] id - \ru Идентификатор элемента внутри файла стороннего формата. - \en Identifier of an element inside the file of a foreign format. \~ - \param[in] msgType - \ru Тип сообщения. - \en Message type. \~ - \param[in] msgText - \ru Код сообщения. - \en Message code. \~ - */ - virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ) = 0; - - // /** \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 = 0; - /// \ru Дать данные вычисления триангуляции (для конвертера JT, STL и VRML). \en Get data for step calculation during triangulation (for JT, STL, VRML only). - virtual MbStepData TesselationParameters() const { return MbStepData(); } - /// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly). - virtual MbStepData LOD0TesselationParameters() const { return TesselationParameters(); } - /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). - virtual bool DualSeams() const { return true; } - /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). - virtual void DualSeams( bool ) {} - /// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. - virtual bool JoinSimilarFaces() const { return true; } - /// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells. - virtual bool AddRemovedFacesAsShells() const { return false; } - /// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier. - virtual SPtr ProductIdentifierGenerator() const { return SPtr(); } - - /// \ru Проводить ли аудит траснляции. \en Whether to audit the translation. - virtual bool TotalAudit() const { return false; } - /// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. - virtual bool AttatchIdAttributes() const { return true; } - -}; // IConvertorProperty3D - - -//------------------------------------------------------------------------------ -/** \brief \ru Реализация генератора однострочного идентификатора компонента. - \en Implementation of component's identifier generator. \~ - \details \ru Реализация по умолчанию предполагает передачу наименования компонента. - \en Default implementatio implies export of component's name. \~ -\ingroup Exchange_Interface -*/ -struct NameProductIdMaker : public IProductIdMaker -{ - virtual c3d::string_t operator()( const MbProductInfo& ) const; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Предопределённая реализация интерфейса свойств конвертера. - \en Pre-defined implementation of converter's properties. \~ -\ingroup Exchange_Interface -*/ -class CONV_CLASS ConvConvertorProperty3D : public IConvertorProperty3D { -public: - std::string docName; ///< \ru Имя документа. \en Document name. - c3d::path_string fileName; ///< \ru Имя файла. \en File name. - bool fileASCII; ///< \ru Экспортировать ли в текстовый файл (если формат поддерживает двоичный). \en Export to text file (if format supports binary one). - long int formatVersion; /// \ru Версия формата при экспорте. \en The version of format for export. - bool exportIGESTopology; ///< \ru Экспортировать ли топологию в IGES. \en Export topology items into IGES. - std::vector ioPermissions; ///< \ru Фильтр объектов по типам. \en Type objects filter. - std::map propertyStrings; ///< \ru Особые значения сведений о документе. \en Specific values of documents properties. - eTextForm annotTextReprSTEP; ///< \ru Представление текста элементов аннотации. \en Text representation in annotation items. - MbPlacement3D originLocation; ///< \ru ЛСК документа. \en Own placement of the document. - bool replaceLocationsToRight; ///< \ru Следует ли принудительно преобразовывать ЛСК объектов к правым (для форматов, допускающих левые). \en Force replacement of locations to right ones. - bool enableAutostitch; ///< \ru Сшивать ли поверхности автоматически. \en Automatically stitch surfaces into shells. - double autostitchPrecision; ///< \ru Точность сшивки. \en Stitch precision. - bool showMessages; ///< \ru Отображать ли сообщения. \en Invoke messages show. - MbStepData tesseleationStepData; ///< \ru Параметры триангуляции при экспорте в STL и VRML. \en Tessellation parameters for export into STL and VRML. - MbStepData LOD0StepData; ///< \ru Параметры триангуляции при экспорте в JT. \en Tessellation parameters for export into JT. - bool dualSeams; ///< \ru Признак сдваивания швов при экспорте в STL и VRML. \en Make dual seams when export into STL and VRML. - bool joinSimilarFaces; ///< \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. - bool addRemovedFacesAsShells; ///< \ru Добавлять ли удаленные грани в качестве отдельных оболочек. \en Whether to add removed faces as shells. - double lengthUnitsFactor; ///< \ru Единицы длины модели. \en Length units of the model. - double appUnitsFactor; ///< \ru Единицы длины модели пользовательского приложения. \en Length units of the model used in user application. - bool attatchIdAttributes; ///< \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. - bool auditEnabled; - - /// \ru Сведения о сообщениях конвертера. \en Converter message data. - struct LogRecord { - ptrdiff_t id; ///< \ru Идентификатор записи. \en Record id. - eMsgType msgType; ///< \ru Тип сообщения. \en Message type. - eMsgDetail msgText; ///< \ru Код сообщения. \en Message code. - }; - - std::vector< LogRecord > logRecords; ///< \ru Сообщения конвертера. \en Converter messages. - -public: - - ConvConvertorProperty3D(); ///< \ru Конструктор. \en Constructor. - - /// \ru Получить имя документа. \en Get document's name. - virtual const std::string GetDocumentName () const { return docName; }; - /// \ru Получить имя файла для конвертирования. \en Get file name for converting. - virtual const c3d::path_string FullFilePath () const { return fileName; }; - /// \ru Является ли файл текстовым. \en Whether the file is a text file. - virtual bool IsFileAscii () const; - /// \ru Получить версию формата при экспорте. \en Get the version of format for export. - virtual long int GetFormatVersion () const; - /// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ). - virtual bool IsOutOnlySurfaces() const; - /// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly. - virtual bool IsAssembling () const { return true; }; - /// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type. - virtual bool GetIoPermission( MbeIOPermiss nPermission ) const; - /// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types. - virtual void GetIoPermissions( std::vector& ioPermissions ) const; - /// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type. - virtual void SetIoPermission( MbeIOPermiss nPermission, bool isSet ); - /// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter. - virtual bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const; - /// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter. - virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ); - /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. - virtual eTextForm GetAnnotationTextRepresentation () const; - /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). - virtual bool ExportComponentsSeparately() const; - /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. - virtual MbPlacement3D GetOriginLocation() const; - /// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented. - virtual bool ReplaceLocationsToRight() const; - /** \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; - - /// \ru Получить множитель единиц длины по отношению к миллиметру. \en Get the factor of the length units to millimeters. - virtual double LengthUnitsFactor() const; - - /** \brief \ru Получить множитель единиц длины по отношению к миллиметру в модели приложения. - \en Get the factor of the length units to millimeters in the application model. \~ - */ - virtual double AppLengthUnitsFactor() const; - - /** \brief \ru Сделать запись в журнал конвертирования. - \en Make a record in the converter report. \~ - \param[in] id - \ru Идентификатор элемента внутри файла стороннего формата. - \en Identifier of an element inside the file of a foreign format. \~ - \param[in] msgType - \ru Тип сообщения. - \en Message type. \~ - \param[in] msgText - \ru Код сообщения. - \en Message code. \~ - */ - virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ); - -// /** \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; - - /// \ru Дать данные вычисления триангуляции (для конвертера STL и VRML). \en Get data for step calculation during triangulation (for STL, VRML only). - virtual MbStepData TesselationParameters() const; - /// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly). - virtual MbStepData LOD0TesselationParameters() const; - /// \ru Получить флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). - virtual bool DualSeams() const; - /// \ru Задать флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). - virtual void DualSeams( bool ); - /// \ru Проводить ли аудит траснляции. \en Whether to audit the translation. - virtual bool TotalAudit() const; - /// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. - virtual bool AttatchIdAttributes() const; - /// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. - virtual bool JoinSimilarFaces() const { return joinSimilarFaces; } - /// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells. - virtual bool AddRemovedFacesAsShells() const { return addRemovedFacesAsShells; } - /// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier. - virtual SPtr ProductIdentifierGenerator() const { return SPtr( new NameProductIdMaker() ); } - - OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D ) - -}; // IConvertorProperty3D - - - -#endif // __CONV_MODEL_PROPERTIES_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Настройки импорта и экспорта. + \en Settings of import and export procedure. \~ + \details \ru Интерфейс настроек и предопределённая реализация ConvConvertorProperty3D. + \en Interface of settings and pre-defined implementation ConvConvertorProperty3D. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_MODEL_PROPERTIES_H +#define __CONV_MODEL_PROPERTIES_H + +#include +#include +#include +#include + +class MbProductInfo; + +//------------------------------------------------------------------------------ +/** \brief \ru Константы единиц измерения. +\en Length units constants.\~ +\ingroup Data_Interface +*/ +// --- +/// \ru Миллиметры. \en Millimeters. +#define LENGTH_UNIT_MM 1.0 +/// \ru Сантиметры. \en Centimeters. +#define LENGTH_UNIT_CM 10.0 +/// \ru Дециметры. \en Decimeters. +#define LENGTH_UNIT_DM 100.0 +/// \ru Метры. \en Meters. +#define LENGTH_UNIT_METER 1000.0 +/// \ru Дюймы. \en Inches. +#define LENGTH_UNIT_INCH 25.4 + + +//------------------------------------------------------------------------------ +/** \brief \ru Прикладной протокол. +\en Applied protocol.\~ +\ingroup Data_Interface +*/ +// --- +enum MbeImpExpFormat { + ief_STEP203, ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). + ief_STEP214, ///< \ru STEP прикладной протокол 214 ( Проектирование автомобилей ). \en STEP applied protocol STEP 214 (Automotive design). + ief_STEP242, ///< \ru STEP прикладной протокол 242 ( Проектирование автомобилей ). \en STEP applied protocol STEP 242 (Automotive design). +}; + + +#define EXPORT_DEFAULT -1 ///< \ru По умолчанию для заданного формата. \en Default for specified format. +#define EXPORT_STEP_203 203 ///< \ru STEP прикладной протокол 203 ( Проектирование с управляемой конфигурацией ). \en STEP applied protocol STEP 203 (Configuration controlled design). +#define EXPORT_STEP_214 214 ///< \ru STEP прикладной протокол 214 ( Проектирование автомобилей ). \en STEP applied protocol STEP 214 (Automotive design). +#define EXPORT_STEP_242 242 ///< \ru STEP прикладной протокол 242. \en STEP applied protocol STEP 242. +#define EXPORT_ACIS_4 4 ///< \ru ACIS версия 4.0. \en ACIS version 4.0. +#define EXPORT_ACIS_7 7 ///< \ru ACIS версия 7.0 (по умолчанию). \en ACIS version 7.0 (default). +#define EXPORT_ACIS_10 10 ///< \ru ACIS версия 10.0. \en ACIS version 10.0. + + +//------------------------------------------------------------------------------ +/** \brief \ru Индексы строк, передаваемых через конвертер. +\en Indices of strings, transmitted through converter.\~ +\ingroup Data_Interface +*/ +// --- +enum MbeConverterStrings { + cvs_BEGIN = 0, ///< \ru Для удобства перебора. \en For lookup only. + cvs_STEPAuthor, ///< \ru Автор для конвертера STEP. \en Author of the document, in STEP. + cvs_STEPOrganization, ///< \ru Организация для конвертера STEP. \en The organization, the author is related with, in STEP. + cvs_STEPComment, ///< \ru Комментарий файла формата STEP. \en Annotation, in STEP. + cvs_CAD_NAME, ///< \ru Название САПР при экспорте. \en CAD Name for export. + cvs_END ///< \ru Для удобства перебора. \en For lookup only. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Индексы, управляющие разрешением на чтение или запись объектов. +\en Indeces, which filter imported/exported objects or properties.\~ +\ingroup Data_Interface +*/ +// --- +enum MbeIOPermiss { + iop_rSolid = 0, ///< \ru Разрешение на чтение твёрдых тел. \en Import solid solids. + iop_wSolid, ///< \ru Разрешение на запись твёрдых тел. \en Export solid solids. + iop_rSurface, ///< \ru Разрешение на чтение поверхностей. \en Import surfaces. + iop_wSurface, ///< \ru Разрешение на запись поверхностей. \en Export surfaces. + iop_rCurve, ///< \ru Разрешение на чтение кривых. \en Import curves. + iop_wCurve, ///< \ru Разрешение на запись кривых. \en Export curves. + iop_rDrafts, ///< \ru Разрешение на чтение эскизов (не применяется). \en Import drafts (ignored). + iop_wDrafts, ///< \ru Разрешение на запись эскизов. \en Export drafts. + iop_rInvisible, ///< \ru Разрешение на чтение невидимых объектов (не применяется). \en Import invisible objects (not applied). + iop_wInvisible, ///< \ru Разрешение на запись невидимых объектов. \en Export invisible objects. + iop_rPoint, ///< \ru Разрешение на чтение точек. \en Import points. + iop_wPoint, ///< \ru Разрешение на запись точек. \en Export points. + iop_rDocInfo, ///< \ru Разрешение на чтение информации о документе (автор, организация, комментарии). \en Import components info ( author, organization, description ). + iop_wDocInfo, ///< \ru Разрешение на запись информации о документе (автор, организация, комментарии). \en Export components info ( author, organization, description ). + iop_rTextDescription, ///< \ru Разрешение на чтение технических требований. \en Import technical requirements. + iop_wTextDescription, ///< \ru Разрешение на запись технических требований. \en Export technical requirements. + iop_rDimensions, ///< \ru Разрешение на чтение размеров. \en Import dimensions. + iop_wDimensions, ///< \ru Разрешение на запись размеров. \en Export dimensions. + iop_rAttributes, ///< \ru Разрешение на чтение атрибутов. \en Import attributes. + iop_wAttributes, ///< \ru Разрешение на запись атрибутов. \en Export attributes. + iop_rBRep, ///< \ru Разрешение на чтение форм изделий в граничном представлении (только в JT). \en Import shapes in boundary representation (JT only). + iop_wBRep, ///< \ru Разрешение на запись форм изделий в граничном представлении (только в JT). \en Export shapes in boundary representation (JT only). + iop_rPolygonal, ///< \ru Разрешение на чтение полигональных форм изделий. \en Import polygonal shapes. + iop_wPolygonal, ///< \ru Разрешение на запись полигональных форм изделий. \en Export polygonal shapes. + iop_rLOD0, ///< \ru Разрешение на чтение полигональных форм изделий уровня детализации 0. \en Import polygonal shapes of the 0-th LOD. + iop_wLOD0, ///< \ru Разрешение на запись полигональных форм изделий уровня детализации 0. \en Export polygonal shapes of the 0-th LOD. + iop_rAssociated, ///< \ru Разрешение на чтение ассоциированной геометрии (резьбы и др). \en Import associated geometry (threads etc). + iop_wAssociated, ///< \ru Разрешение на запись ассоциированной геометрии (резьбы и др). \en Export associated geometry (threads etc). + iop_rDensity, ///< \ru Разрешение на чтение единиц плотности. \en Import density units. + iop_wDensity, ///< \ru Разрешение на запись единиц плотности. \en Export density units. + iop_rValidationProperties, ///< \ru Разрешение на чтение контрольных параметров - объёма, площади поверхности, центра масс. \en Import validation properties - volume, surface area, centroid. + iop_wValidationProperties, ///< \ru Разрешение на запись контрольных параметров - объёма, площади поверхности, центра масс. \en Export validation properties - volume, surface area, centroid. + iop_rStyle, ///< \ru Разрешение на чтение элементов оформления (цвет, начертание, и т.п.). \en Import appearance. + iop_wStyle, ///< \ru Разрешение на запись элементов оформления (цвет, начертание, и т.п.). \en Export appearance. + iop_END +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тип сообщения об ошибке при выводе в лог. +\en Type of a log message.\~ +\ingroup Data_Exchange +*/ +// --- +enum eMsgType { + emt_ErrorNoId,///< \ru Ошибка формата. Значение id игнорируется, выводится только текст. \en Error not related with a certain record. The id field is ignored. + emt_TextOnly, ///< \ru Значение id игнорируется, выводится только текст. \en Used to type message only. The id field is ignored. + emt_Info, ///< \ru Рабочая информация. \en Info. + emt_Warning, ///< \ru Предупреждение. \en Warning. + emt_Error ///< \ru Ошибка формата или неустранимая ошибка преобразования. \en Format mismatch or fatal converting error. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Код подробного сообщения об ошибке при выводе в лог. +\en The key of a detailed log message.\~ +\ingroup Data_Interface +*/ +// --- +enum eMsgDetail { + emd_Title, ///< \ru Заголовок файла. \en File header. + emd_HEADError, ///< \ru Тип сообщения - ошибка. \en Error. + emd_HEADWarinig, ///< \ru Тип сообщения - Предупреждение. \en Warning. + emd_HEADInfo, ///< \ru Тип сообщения - Информация. \en Info. + emd_HEADDefaultMsg, ///< \ru Тип сообщения - Сообщение. \en Message. + + emd_STOPFileOpenError, ///< \ru Ошибка открытия файла. \en Cannot open file. + emd_STOPFileOpenErrorOrEmpty, ///< \ru Ошибка открытия файла или файл пуст. \en Cannot open file or file is empty. + emd_STOPHeaderReadError, ///< \ru Не удалось прочитать заголовок файла. \en Cannot read file header. + emd_STOPNoOrBadData, ///< \ru Файл не содержит данных или их не удалось распознать. \en File body does not exist or incorrect. + emd_STOPIncorrectStructure, ///< \ru Неверная структура файла. \en Incorrect file structure. + emd_STOPAddressConflict, ///< \ru Данный адрес имеют два различных объекта. \en Two or more entities have the same id. + + emd_ErrorNoRootObject, ///< \ru Не найден корневой объект. \en Root object not found. + emd_ErrorSyntaxIncorrectFormFloat, ///< \ru Невозможно прочитать действительную константу. \en Error reading floating-point number. + emd_ErrorEmptyLoop, ///< \ru Цикл грани пуст. \en Face has an empty loop. + emd_ErrorEmptyQueriesList, ///< \ru Список запросов пуст. \en + emd_ErrorEmptyObjectsList, ///< \ru Список объектов пуст. \en List of objects is empty. + emd_ErrorEmptyGeomObjectsList, ///< \ru Список геометрических объектов пуст. \en List of geometric objects is empty. + emd_ErrorEmptyShellsList, ///< \ru Список оболочек пуст. \en List of shells is empty. + emd_ErrorEmptyListOfWrieframes, ///< \ru Список каркасов пуст. \en List of frames is empty. + emd_ErrorEmptyCurveCompositesList, ///< \ru Список компонент составной кривой пуст. \en Composite curve has an empty list of composites. + emd_ErrorEmptyBoundCurvesList, ///< \ru Список граничных кривых пуст. \en List of boundary curves is empty. + emd_ErrorEmptyEdgeList, ///< \ru Список рёбер пуст. \en List of edges is empty. + emd_ErrorEmptyFacesList, ///< \ru Список граней пуст. \en List of faces is empty. + emd_ErrorEmptyReferencesList, ///< \ru Список ссылок пуст. \en List of references is empty. + emd_ErrorEmptyOrMore2ReferencesList,///< \ru Список ссылок пуст или содержит более 2 элементов. \en List of references is empty or contains more than 2 items. + emd_ErrorUndefinedFaceSurfaceRef, ///< \ru Ссылка на базовую поверхность грани не определена. \en Invalid reference to base surface. + emd_ErrorUndefinedBaseCurveRef, ///< \ru Ссылка на базовую кривую не определена. \en Invalid reference to base curve. + emd_ErrorRadiusTooCloseToZero, ///< \ru Радиус слишком мал. \en Too small radius. + emd_ErrorRadiusValueNegative, ///< \ru Отрицательное значение радиуса. \en Negative value of radius. + emd_ErrorEllipseAxisTooCloseToZero, ///< \ru Длина полуоси эллипса слишком мала. \en Ellipse axis is too short. + emd_ErrorEllipseAxisNegative, ///< \ru Отрицательная длина полуоси эллипса. \en Ellipse axis length is negative. + emd_ErrorNegativeDegree, ///< \ru Отрицательный порядок сплайна. \en Negative spline order. + emd_ErrorNegativeUDegree, ///< \ru Отрицательный порядок сплайновой поверхности по U. \en Spline surface order along U is negative. + emd_ErrorNegativeVDegree, ///< \ru Отрицательный порядок сплайновой поверхности по V. \en Spline surface order along V is negative. + emd_ErrorDegreeFixImpossible, ///< \ru Невозможно исправить порядок сплайна. \en Cannot fix spline order. + emd_ErrorPolylinePointListLess2, ///< \ru Список точек ломаной содержит менее 2 элементов. \en Polyline contains less then 2 points. + emd_ErrorPointListLess2, ///< \ru Список точек содержит менее 2 элементов. \en List of points contains less then 2 points. + emd_ErrorKnotsListLess2, ///< \ru Список узлов содержит менее 2 элементов. \en List of knots contains less then 2 values. + emd_ErrorWeightsListLess2, ///< \ru Список весов содержит менее 2 элементов. \en List of weights contains less then 2 values. + emd_ErrorUPointListLess2, ///< \ru Список точек по U содержит менее 2 элементов. \en List of points along U contains less then 2 points. + emd_ErrorUKnotsListLess2, ///< \ru Список узлов по U содержит менее 2 элементов. \en List of knots along U contains less then 2 values. + emd_ErrorUWeightsListLess2, ///< \ru Список весов по U содержит менее 2 элементов. \en List of weights along U contains less then 2 values. + emd_ErrorVPointListLess2, ///< \ru Список точек по V содержит менее 2 элементов. \en List of points along V contains less then 2 points. + emd_ErrorVKnotsListLess2, ///< \ru Список узлов по V содержит менее 2 элементов. \en List of knots along V contains less then 2 values. + emd_ErrorVWeightsListLess2, ///< \ru Список весов по V содержит менее 2 элементов. \en List of weights along V contains less then 2 values. + emd_ErrorListsSizeMismatch, ///< \ru Размеры списков не согласуются. \en Lists size mismatch. + emd_ErrorKnotsWeightsListsOrderMismatch, ///< \ru Размеры списков узлов и весов не согласуются с порядком сплайна. \en Sizes of knots and weights lists do not agree with the spline order. + emd_ErrorKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов не согласуются. \en Size of knots list does not agree with the size of the list of weights. + emd_ErrorUKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов по U не согласуются. \en Sizes of knots and weights lists along U do not agree. + emd_ErrorVKnotsWeightsListsSizeMismatch, ///< \ru Размеры списков узлов и весов по V не согласуются. \en Sizes of knots and weights lists along V do not agree. + emd_ErrorSplineCurveNotCreatedUndefinedKnotsVector, ///< \ru Сплайновая кривая не создана - не определёны узлы. \en Cannot create spline, because knots are not defined. + emd_ErrorSplineSurfaceNotCreatedUndefinedKnotsVectors, ///< \ru Сплайновая поверхность не создана - не определёны узлы. \en Cannot create spline surface, because knots are not defined. + emd_ErrorInCorrectSplineSurfaceData, ///< \ru Неверно заданы параметры NURBS поверхности. \en Spline surface parameters are not valid. + + emd_WarningNoSectionTerminator, ///< \ru Маркер завершения раздела не обнаружен. \en Section terminator not found. + emd_WarningSyntaxMultipleDotInFloat, ///< \ru Повторяющаяся точка в действительном числе. \en Too many dots in a floating-point number. + emd_WarningSyntaxMultipleEInFloat, ///< \ru Повторяющаяся E в действительном числе. \en Too many E signs in a floating-point number. + emd_WarningLoopNotClosed, ///< \ru Цикл не замкнут. \en Loop is not closed. + emd_WarningContourNotClosed, ///< \ru Контур не замкнут. \en contour is not closed. + emd_WarningUndefinedRef, ///< \ru Ссылка не определена. \en Invalid reference. + emd_WarningToroidalSurfaceDegenerated, ///< \ru Тороидальная поверхность вырождена. \en Toroidal surface is degenerate. + emd_WarningUndefinedBasisCurve, ///< \ru Не определена базовая кривая. \en Base curve not defined. + emd_WarningUndefinedSweptCurve, ///< \ru Не определена образующая кривая. \en Generatrix curve is not defined. + emd_WarningUndefinedExtrusionDirection, ///< \ru Не определено направление выдавливания. \en Extrusion direction is not defined. + emd_WarningUndefinedAxis, ///< \ru Не определена ось. \en Axis is not defined. + emd_WarningUndefinedAxisOfRevolution, ///< \ru Не определена ось вращения. \en Rotation axis is not defined. + emd_WarningUndefinedBasisSurface, ///< \ru Не определена базовая поверхность. \en Base surface is not defined. + emd_WarningUndefinedRepresentation, ///< \ru Не определено представление. \en Representation is not defined. + emd_WarningUndefinedTransformationOperator, ///< \ru Не определён оператор преобразования. \en Transformation is not defined. + emd_WarningUndefinedObjectTransformBy, ///< \ru Не определён объект, по которому ведётся преобразование. \en Basic object of transformation is not defined. + emd_WarningUndefinedObjectToTransform, ///< \ru Не определён преобразуемый объект. \en No object to transform is defined. + emd_WarningUndefinedCurve, ///< \ru Не определена кривая. \en Curve is not defined. + emd_WarningUndefinedCompositeSegment, ///< \ru Не определён сегмент составной кривой. \en Composite curve segment is not defined. + emd_WarningUndefinedDirection, ///< \ru Не определено направление. \en Direction is not defined. + emd_WarningUndefinedAxisDirection, ///< \ru Не определено направление оси. \en Axis direction is not defined. + emd_WarningDegeneratedItemWasSkipped, ///< \ru Проигнорирован (пропущен) вырожденный объект. \en Degenerate object was missed. + emd_WarningFloatParceFailureDefaultUsed, ///< \ru Ошибка разпознавания числа с плавающей точкой, подставлено значение по умолчанию. \en Floating point value couldn't be parced; default value was used. + emd_WarningSameShapeEdgeTwiceInLoop, ///< \ru В цикле дважды встречается одинаковое ребро. \en Edge based on same curves twice enters a loop. + emd_WarningIncorrectFaceWasNotAddedToShell, ///< \ru Некорректная грань не была добавлена в оболочку. \en Incorrect face was not added to shell. + emd_WarningBoundsNotConnectedWithSeams, ///< \ru Границы замкнутой грани не стыкуются со швами. \en Bounds of periodic face not connected with seams. + emd_WarningIntCurveWasReplacedBySegment, ///< \ru Кривая пересечения была заменена отрезком. \en Intersection curve was replaced by segment. + + emd_MessageWeightsFilled, ///< \ru Веса заданы. \en Weights are set. + + emd_ErrorSTEPEdgeCurveFlagTSingleRedefinition, ///< \ru При создании ребра в конвертере STEP дважды указана грань с флагом .T.. \en Double .T. face inclusion in STEP. + emd_ErrorSTEPEdgeCurveFlagFSingleRedefinition, ///< \ru При создании ребра в конвертере STEP дважды указана грань с флагом .F.. \en Double .F. face inclusion in STEP. + emd_ErrorSTEPEdgeCurveFlagTMultipleRedefinition, ///< \ru При создании ребра в конвертере STEP более чем дважды указана грань с флагом .T.. \en Multiple .T. face inclusion in STEP. + emd_ErrorSTEPEdgeCurveFlagFMultipleRedefinition, ///< \ru При создании ребра в конвертере STEP более чем дважды указана грань с флагом .F.. \en Multiple .F. face inclusion in STEP. + emd_ErrorSTEPUndefinedFaceGeometry, ///< \ru Не определена геометрия грани в конвертере STEP. \en Face geometry is not defined in STEP. + emd_ErrorSTEPSyntaxMultipleDotInEnum, ///< \ru Синтаксическая ошибка в файле формата STEP - в перечислении символ "." встречается более 1 раза подряд. \en Too many dots in a enumeration record in STEP. + emd_WarningSTEPPointCorrection, ///< \ru Скорректированы координаты точки. \en Point location corrected. ( by BUG_73871 ) + emd_WarningSTEPEdgeCurveByVertices, ///< \ru Кривая ребра скорректирована с учётом координат вершин. \en Edge curve corrected in accordance with vertices. ( by BUG_73871 ) + emd_MessageSTEPFlagChangedToF, ///< \ru Произведена замена флага на .F.. \en Flag was set as .F. in STEP. + emd_MessageSTEPFlagChangedToT, ///< \ru Произведена замена флага на .T.. \en Flag was set as .T. in STEP. + emd_WarningBooleanUndefined, ///< \ru Булево значение не определено. \en Boolean value not defined. + + emd_WarningACISUnsupportedInterpoleCurveType, ///< \ru Данный подтип ACIS интерполяционной кривой не поддерживается. \en Interpolation curve type is not supported by SAT converter. + emd_WarningACISUnsupportedParametricCurveType, ///< \ru Данный подтип ACIS параметрической кривой не поддерживается. \en Parametric curve type is not supported by SAT converter. + emd_ErrorACISUnsupportedVersion, ///< \ru Данная версия ACIS NT не поддерживается. \en Th version of file is not supported by SAT converter. + emd_WarningACISCannotImportEntityId, ///< \ru Не удалось импортировать объект с данным Id. \en Cannot import this object by SAT converter. + emd_WarningACISIncorrectIntAttribute, ///< \ru Некорректный целочисленный атрибут. \en Incorrect integer attribute. + emd_WarningVRMLGridDuplicatesInMeshes, ///< \ru Присутствуют дубликаты объектов в сетках. \en There are grid duplicates in meshes. + emd_WarningACISLawIntCurveIsNotCreated, ///< \ru Кривая по закону не создана. \en Law intersection curve is not created. + + emd_ErrorIGESIncorrectExternalReference, ///< \ru Неверное имя внешней ссылки. \en Invalid external reference in IGES. + + emd_ErrorSTLTooManyTrianglesForBinary, ///< \ru Триангуляция исходной модели содержит больше треугольников, чем допустимо стандартом ( не выражается 32-битным беззнаковым числом ) ( by BUG_71422 ). \en Too many triangles (not represented by unsigned 32-bit number) for export to binary STL. + + emd_ErrorXTUnsupportedVersion, ///< \ru Данная версия X_T не поддерживается. \en Th version of file is not supported by X_T converter. + + emd_ErrorJTUnsupportedVersion, ///< \ru Данная версия JT не поддерживается. \en Th version of file is not supported by JT converter. + + emd_ErrorStringEncoding, ///< \ru Ошибка кодировки строки. \en String encoding error. + + emd_WarningCurveParametrizationCorrected ///< \ru Исправлена параметризация кривой. \en Curve parameterization was corrected. + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс генератора однострочного идентификатора компонента. + \en Interface of component's identifier generator. \~ + \details \ru Предназначен для для экспорта в форматы, в которых для идентификации компонента предусмотрено одно строковое значение. + \en Demanded for export to formats having one string field for product inetifier. \~ +\ingroup Exchange_Interface +*/ +struct IProductIdMaker : public MbRefItem +{ + virtual c3d::string_t operator()( const MbProductInfo& ) const = 0; +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс для преобразования строк. + \en An interface for string encoding. \~ + \ingroup Base_Tools_String +*/ +class IC3DCharEncodingTransformer : public MbRefItem +{ +public: + virtual ~IC3DCharEncodingTransformer() {} + + //------------------------------------------------------------------------------ + /** \brief \ru Преобразование строки из wchar_t* в char*. + \en Transform string from wchar_t* to char*. \~ + \ingroup Base_Tools_String + */ + virtual bool StdToC3D( const c3d::string_t& from, std::string& to ) = 0; + + //------------------------------------------------------------------------------ + /** \brief \ru Преобразование строки из char* в wchar_t*. + \en Transform string from char* в wchar_t*. \~ + \ingroup Base_Tools_String + */ + virtual bool C3DToStd( const std::string& from, c3d::string_t& to ) = 0; +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс свойств конвертера. +\en Interface of converter's properties. \~ +\details \ru Интерфейс свойств конвертера реализует выдачу имени документа и других сведений о нём, таких как автор, +и управление режимами работы - сшивкой поверхностей с возможностью создания твёрдых +тел, фильтрацией объектов, формирование журнала трансляции. +\en Interface of converter's properties realizes getting the document's name and other information about it, such as the author, +and management of modes of operations - stitching of surfaces with possibility of solids creation, +objects filtration, generation of translation journal. \~ +\ingroup Exchange_Interface +*/ +class CONV_CLASS IConvertorProperty3D { +public : + virtual ~IConvertorProperty3D() {} + +public: + /// \ru Получить имя документа. \en Get document's name. + virtual const std::string GetDocumentName () const = 0; //{ return std::string( GetDocName().get_str() ); }; + /// \ru Получить имя файла для конвертирования. \en Get file name for converting. + virtual const c3d::path_string FullFilePath () const = 0 ;//{ return c3d::path_string( GetFileName().c_str() ); }; + /// \ru Является ли файл текстовым. \en Whether the file is a text file. + virtual bool IsFileAscii () const = 0; + /// \ru Получить версию формата при экспорте. \en Get the version of format for export. + virtual long int GetFormatVersion () const { return EXPORT_DEFAULT; }; + /// \ru Задать формат для экспорта \en Set format for export + DEPRECATE_DECLARE virtual MbeImpExpFormat GetFormat () const { return ief_STEP203; } + /// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ). + virtual bool IsOutOnlySurfaces() const = 0; + /// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly. + virtual bool IsAssembling () const = 0; + /// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type. + virtual bool GetIoPermission( MbeIOPermiss nPermission ) const = 0; + /// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types. + virtual void GetIoPermissions( std::vector& ioPermissions ) const = 0; + /// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type. + virtual void SetIoPermission( MbeIOPermiss nPermission, bool set ) = 0; + /// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter. + virtual bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const = 0; + /// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter. + virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ) = 0; + /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. + virtual eTextForm GetAnnotationTextRepresentation () const { return exf_TextOnly; } + /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). + virtual bool ExportComponentsSeparately() const { return false; } + /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. + virtual MbPlacement3D GetOriginLocation() const = 0; + /// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented. + virtual bool ReplaceLocationsToRight() const = 0; + /** \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 = 0; + + /** \brief \ru Получить множитель единиц длины по отношению к миллиметру. + \en Get the factor of the length units to millimeters. \~ + \details \ru При импорте, если единицы измерения не заданы явно с помощью средств, предоставляемых обменным форматом, + все размеры (координаты точек, радиусы) умножаются на возвращаемое значение. При экспорте либо с помощью + средств, предоставляемых обменным форматом, задаются единицы измерения, либо все размеры модели (координаты + точек, радиусы) умножаются на возвращаемое значение. + \en During the import all spatial objects (coordinate values, radiuses) are multiplied by the returned value, + unless the scale factor comes from the exchange file. During the export the exchange format facilities are + used to specify the length units or all spatial objects (coordinate values, radiuses) are multiplied by the + returned value. \~ + */ + virtual double LengthUnitsFactor() const { return LENGTH_UNIT_MM; } + + + /** \brief \ru Получить дополнительный множитель единиц длины по отношению к миллиметру в модели приложения. + \en Get addifional factor of the length units to millimeters in the application model. \~ + \details \ru При импорте из всех форматов за исключением JT, если единицы измерения, в том числе и заданные + явно с помощью средств, предоставляемых обменным форматом, все размеры (координаты точек, радиусы) умножаются + на возвращаемое значение. При экспорте либо с помощью средств, предоставляемых обменным форматом, задаются + единицы измерения, либо все размеры модели (координаты точек, радиусы) умножаются на возвращаемое значение. + \en During the import from all formats except for JT all spatial objects (coordinate values, radiuses) are + multiplied by the returned value, even if the scale factor comes from the exchange file. During the export the + exchange format facilities are used to specify the length units or all spatial objects (coordinate values, + radiuses) are multiplied by the returned value. \~ + */ + virtual double AppLengthUnitsFactor() const { return LENGTH_UNIT_MM; } + + /** \brief \ru Сделать запись в журнал конвертирования. + \en Make a record in the converter report. \~ + \param[in] id - \ru Идентификатор элемента внутри файла стороннего формата. + \en Identifier of an element inside the file of a foreign format. \~ + \param[in] msgType - \ru Тип сообщения. + \en Message type. \~ + \param[in] msgText - \ru Код сообщения. + \en Message code. \~ + */ + virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ) = 0; + + // /** \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 = 0; + /// \ru Дать данные вычисления триангуляции (для конвертера JT, STL и VRML). \en Get data for step calculation during triangulation (for JT, STL, VRML only). + virtual MbStepData TesselationParameters() const { return MbStepData(); } + /// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly). + virtual MbStepData LOD0TesselationParameters() const { return TesselationParameters(); } + /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). + virtual bool DualSeams() const { return true; } + /// \ru Флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). + virtual void DualSeams( bool ) {} + /// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. + virtual bool JoinSimilarFaces() const { return true; } + /// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells. + virtual bool AddRemovedFacesAsShells() const { return false; } + /// \ru Получить генератор однострочного идентификтора изделия. \en Get generator of one-line product identifier. + virtual SPtr ProductIdentifierGenerator() const { return SPtr(); } + + /// \ru Проводить ли аудит траснляции. \en Whether to audit the translation. + virtual bool TotalAudit() const { return false; } + /// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. + virtual bool AttatchIdAttributes() const { return true; } + + /// \ru Получить пользовательский преобразователь строк. \en Get user string transformer. + virtual SPtr GetUserCharEncodingTransformer() const { return SPtr(c3d_null); } + +}; // IConvertorProperty3D + + +//------------------------------------------------------------------------------ +/** \brief \ru Реализация генератора однострочного идентификатора компонента. + \en Implementation of component's identifier generator. \~ + \details \ru Реализация по умолчанию предполагает передачу наименования компонента. + \en Default implementatio implies export of component's name. \~ +\ingroup Exchange_Interface +*/ +struct NameProductIdMaker : public IProductIdMaker +{ + virtual c3d::string_t operator()( const MbProductInfo& ) const; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Предопределённая реализация интерфейса свойств конвертера. + \en Pre-defined implementation of converter's properties. \~ +\ingroup Exchange_Interface +*/ +class CONV_CLASS ConvConvertorProperty3D : public IConvertorProperty3D { +public: + std::string docName; ///< \ru Имя документа. \en Document name. + c3d::path_string fileName; ///< \ru Имя файла. \en File name. + bool fileASCII; ///< \ru Экспортировать ли в текстовый файл (если формат поддерживает двоичный). \en Export to text file (if format supports binary one). + long int formatVersion; /// \ru Версия формата при экспорте. \en The version of format for export. + bool exportIGESTopology; ///< \ru Экспортировать ли топологию в IGES. \en Export topology items into IGES. + std::vector ioPermissions; ///< \ru Фильтр объектов по типам. \en Type objects filter. + SPtr userEncodingTransformer; ///< \ru Пользовательский преобразователь строк. \en User string transformer. + std::map propertyStrings; ///< \ru Особые значения сведений о документе. \en Specific values of documents properties. + eTextForm annotTextReprSTEP; ///< \ru Представление текста элементов аннотации. \en Text representation in annotation items. + MbPlacement3D originLocation; ///< \ru ЛСК документа. \en Own placement of the document. + bool replaceLocationsToRight; ///< \ru Следует ли принудительно преобразовывать ЛСК объектов к правым (для форматов, допускающих левые). \en Force replacement of locations to right ones. + bool enableAutostitch; ///< \ru Сшивать ли поверхности автоматически. \en Automatically stitch surfaces into shells. + double autostitchPrecision; ///< \ru Точность сшивки. \en Stitch precision. + bool showMessages; ///< \ru Отображать ли сообщения. \en Invoke messages show. + MbStepData tesseleationStepData; ///< \ru Параметры триангуляции при экспорте в STL и VRML. \en Tessellation parameters for export into STL and VRML. + MbStepData LOD0StepData; ///< \ru Параметры триангуляции при экспорте в JT. \en Tessellation parameters for export into JT. + bool dualSeams; ///< \ru Признак сдваивания швов при экспорте в STL и VRML. \en Make dual seams when export into STL and VRML. + bool joinSimilarFaces; ///< \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. + bool addRemovedFacesAsShells; ///< \ru Добавлять ли удаленные грани в качестве отдельных оболочек. \en Whether to add removed faces as shells. + double lengthUnitsFactor; ///< \ru Единицы длины модели. \en Length units of the model. + double appUnitsFactor; ///< \ru Единицы длины модели пользовательского приложения. \en Length units of the model used in user application. + bool attatchIdAttributes; ///< \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. + bool auditEnabled; + + /// \ru Сведения о сообщениях конвертера. \en Converter message data. + struct LogRecord { + ptrdiff_t id; ///< \ru Идентификатор записи. \en Record id. + eMsgType msgType; ///< \ru Тип сообщения. \en Message type. + eMsgDetail msgText; ///< \ru Код сообщения. \en Message code. + }; + + std::vector< LogRecord > logRecords; ///< \ru Сообщения конвертера. \en Converter messages. + +public: + + ConvConvertorProperty3D(); ///< \ru Конструктор. \en Constructor. + virtual ~ConvConvertorProperty3D() {};///< \ru Деструктор. \en Destructor. + + /// \ru Получить имя документа. \en Get document's name. + virtual const std::string GetDocumentName () const { return docName; }; + /// \ru Получить имя файла для конвертирования. \en Get file name for converting. + virtual const c3d::path_string FullFilePath () const { return fileName; }; + /// \ru Является ли файл текстовым. \en Whether the file is a text file. + virtual bool IsFileAscii () const; + /// \ru Получить версию формата при экспорте. \en Get the version of format for export. + virtual long int GetFormatVersion () const; + /// \ru Следует ли экспортировать только поверхности ( введено для работы конвертера IGES ). \en Whether to export only surfaces (introduced for work with converter IGES ). + virtual bool IsOutOnlySurfaces() const; + /// \ru Является ли экспортируемый документ сборкой. \en Whether the document for export is an assembly. + virtual bool IsAssembling () const { return true; }; + /// \ru Получить значение разрешения на импорт экспорт объектов определенного типа. \en Get the value of permission for import-export of objects of a certain type. + virtual bool GetIoPermission( MbeIOPermiss nPermission ) const; + /// \ru Получить значения разрешений на импорт экспорт объектов определенных типов. \en Get values of permission for import-export of objects of certain types. + virtual void GetIoPermissions( std::vector& ioPermissions ) const; + /// \ru Установить разрешение на импорт экспорт объектов определенного типа. \en Set permission for import-export of objects of a certain type. + virtual void SetIoPermission( MbeIOPermiss nPermission, bool isSet ); + /// \ru Получить значение специфичной строки для конвертера. \en Get the value of a certain string for the converter. + virtual bool GetPropertyString ( MbeConverterStrings nString, std::string & propertyString ) const; + /// \ru Установить значение специфичной строки для конвертера. \en Set the value of a certain string for the converter. + virtual void SetPropertyString ( MbeConverterStrings nString, const std::string & propertyString ); + /// \ru Представление текста в аннотационных объектах. \en Text representation in annotation objects. + virtual eTextForm GetAnnotationTextRepresentation () const; + /// \ru Следует ли компоненты экспортировать в разные файлы (если позволяет формат). \en Export components into separate files ( if provided in format). + virtual bool ExportComponentsSeparately() const; + /// \ru Получить ЛСК, относительно которой позиционирована модель. \en Get the location, the model is placed in. + virtual MbPlacement3D GetOriginLocation() const; + /// \ru Заменять ли принудительно СК компонент на правые. \en Replace components' placements to right-oriented. + virtual bool ReplaceLocationsToRight() const; + /** \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; + + /// \ru Получить множитель единиц длины по отношению к миллиметру. \en Get the factor of the length units to millimeters. + virtual double LengthUnitsFactor() const; + + /** \brief \ru Получить множитель единиц длины по отношению к миллиметру в модели приложения. + \en Get the factor of the length units to millimeters in the application model. \~ + */ + virtual double AppLengthUnitsFactor() const; + + /** \brief \ru Сделать запись в журнал конвертирования. + \en Make a record in the converter report. \~ + \param[in] id - \ru Идентификатор элемента внутри файла стороннего формата. + \en Identifier of an element inside the file of a foreign format. \~ + \param[in] msgType - \ru Тип сообщения. + \en Message type. \~ + \param[in] msgText - \ru Код сообщения. + \en Message code. \~ + */ + virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ); + +// /** \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; + + /// \ru Дать данные вычисления триангуляции (для конвертера STL и VRML). \en Get data for step calculation during triangulation (for STL, VRML only). + virtual MbStepData TesselationParameters() const; + /// \ru Дать данные вычисления триангуляции уровня детализации (для конвертера JT). \en Get data for step calculation during triangulation of LOD0 (for JTonly). + virtual MbStepData LOD0TesselationParameters() const; + /// \ru Получить флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). + virtual bool DualSeams() const; + /// \ru Задать флаг сохранения совпадающих точек швов. (для конвертера STL и VRML). \en Whether to keep coincident points of seams (for STL, VRML only). + virtual void DualSeams( bool ); + /// \ru Проводить ли аудит траснляции. \en Whether to audit the translation. + virtual bool TotalAudit() const; + /// \ru Следует ли формировать атрибут на основе идентификатора элемнта в файле. \en Whether to attatch the element's id in file as attribute. + virtual bool AttatchIdAttributes() const; + /// \ru Выполнять ли слияние подобных граней. \en Whether to join similar faces. + virtual bool JoinSimilarFaces() const { return joinSimilarFaces; } + /// \ru Добавлять ли удаленные грани в качестве оболочек. \en Whether to add removed faces as shells. + virtual bool AddRemovedFacesAsShells() const { 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; + + OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D ) + +}; // IConvertorProperty3D + + + +#endif // __CONV_MODEL_PROPERTIES_H diff --git a/C3d/Include/conv_model_document.h b/C3d/Include/conv_model_document.h index 2f704a3..bf5307b 100644 --- a/C3d/Include/conv_model_document.h +++ b/C3d/Include/conv_model_document.h @@ -1,575 +1,575 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Сущности конвертерной модели: документ, деталь, сборка, вставка. - \en Entities of converter-compatible model: document, part, assembly, instance. \~ - \details \ru Интерфейсы сущностей и предопределённая реализация модельного документа C3dModelDocument. - \en Interfaces of entities and pre-defined implementation of model document C3dModelDocument. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_MODEL_DOCUMENT_H -#define __CONV_MODEL_DOCUMENT_H - -#include -#include -#include -#include -#include -#include -#include - - - -class MbPlacement3D; -class MbName; - -class MbAttributeContainer; - -class ItModelAssembly; -class ItModelPart; -class ItModelInstance; - -class IProgressIndicator; - -typedef SPtr ModelAssemblyPtr; -typedef SPtr ModelPartPtr; -typedef SPtr ModelInstancePtr; - - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс документа модели сборки или детали. -\en Interface of document of an assembly model or a part model. \~ -\ingroup Exchange_Interface -*/ -// --- -class CONV_CLASS ItModelDocument : public MbRefItem -{ -public: - /// \ru Это сборка? \en Is it an assembly? - virtual bool IsAssembly() const = 0; - /// \ru Это ни сборка, ни деталь? \en Is it neither an assembly nor a part? - virtual bool IsEmpty() const = 0; - - /** \brief \ru Прообраз новой интерфейсной функции - задать модель ЛСК, относительно которой позиционируется модель. - \en Prototype of a new interface function - get the placement the model is defined in. \~ - */ - //virtual MbPlacement3D GetOriginLocation() const = 0; - - /** \brief \ru Прообраз новой интерфейсной функции - задать модель для наполнения. - \en Prototype of a new interface function - set a model to fill. \~ - */ - virtual void SetContent( MbItem* /*content*/) = 0; - - /** \brief \ru Прообраз новой интерфейсной функции - получить наполнение. - \en Prototype of a new interface function - get the filling. \~ - */ - virtual MbItem * GetContent() /*{ return NULL; }*/ = 0; - - /** \brief \ru Создать документ с новой сборкой при импорте. - \en Create a document with a new assembly while importing. \~ - \details \ru Увеличить счётчик ссылок результирующего документа на 1. - \en Increase the reference counter of the resultant document by 1. \~ - \param[in] fileName - \ru Имя сборки. - \en Assembly name. \~ - \param[in] solids - \ru Тела, добавляемые в сборку. - \en Solids to add into the assembly. \~ - \return \ru Экземпляр сборки, если операция прошла успешно, NULL в противном случае. - \en Instance of an assembly if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelAssemblyPtr CreateAssembly( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; - - - /** \brief \ru Создать документ с новой деталью при импорте. - \en Create a document with a new part while importing. \~ - \details \ru Увеличить счётчик ссылок результирующего документа на 1. - \en Increase the reference counter of the resultant document by 1. \~ - \param[in] solids - \ru Тела, добавляемые в деталь. - \en Solids to add into a part. \~ - \param[in] fileName - \ru Имя детали. - \en A part name. \~ - \return \ru Экземпляр детали, если операция прошла успешно, NULL в противном случае. - \en Instance of the part if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelPartPtr CreatePart( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; - - /** \brief \ru Получить сборку для экспорта. - \en Get an assembly for export. \~ - \details \ru Увеличить счётчик ссылок результирующей сборки на 1. - \en Increase the reference counter of the resultant assembly by 1. \~ - \return \ru Экземпляр сборки, если операция прошла успешно, NULL в противном случае. - \en Instance of an assembly if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelAssemblyPtr GetInstanceAssembly( ) = 0; - - - /** \brief \ru Получить деталь для экспорта. - \en Get the detail for export. \~ - \details \ru Увеличить счётчик ссылок результирующей детали на 1. - \en Increase the reference counter of the resultant part by 1. \~ - \return \ru Экземпляр детали, если операция прошла успешно, NULL в противном случае. - \en Instance of the part if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelPartPtr GetInstancePart( ) = 0; - - /** \brief \ru Завершить импорт и сохранить документ. - \en Complete the import and save the document. \~ - \return \ru true, если операция прошла успешно, false в противном случае. - \en true if the operation succeeded, false - otherwise. \~ - \param[in] \ru indicator Объект для отображения хода процесса. - \en indicator An object indicating a process progress. \~ - */ - virtual bool FinishImport( IProgressIndicator * indicator ) = 0; - - /** \brief \ru Получить элементы аннотации, соответствующие элементам геометрической модели. - \en Get elements of annotation, corresponding items of geometric model. \~ - \param[in] eTextForm - \ru Форма представления текста. - \en Text representation form. \~ - \return \ru Контейнер объектов аннотации. - \en Vector of annotation objects. \~ - */ - virtual map_of_visual_items GetAnnotationItems( eTextForm ) const = 0; - - /// \ru Задать размеры. \en Set sizes. - virtual void SetAnnotationItems( const map_of_visual_items& ) = 0; - - /// \ru Открыть документ. \en Open a document. - virtual void OpenDocument() = 0; - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Формирователь геометрического представления текста. -\en Generator of text element's geometry shape. \~ -\ingroup Exchange_Interface -*/ -// --- -class CONV_CLASS C3DSymbolToItem : public MbRefItem { -public: - virtual SPtr TextToItem( const MaTextItem*, const MbPlacement3D& location ) const; - virtual SPtr TerminatorToItem( const MaTerminatorSymbol*, const MbPlacement3D& location ) const; - - virtual ~C3DSymbolToItem(); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Формирователь геометрического представления PMI. -\en Generator of PMI's geometry shape. \~ -\ingroup Exchange_Interface -*/ -// --- -class CONV_CLASS C3DPmiToItem : public MbRefItem { - SPtr symToItem; -public: - C3DPmiToItem( SPtr = SPtr() ); - virtual SPtr operator() ( const MaAnnotationItem* ) const; - - virtual ~C3DPmiToItem(); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Реализация документа модели, формирующая регулярную структуру. -\en Implementation of model document which has regular structure. \~ -\ingroup Exchange_Interface -*/ -// --- -class CONV_CLASS C3dModelDocument: public ItModelDocument { - - ModelPartPtr part; ///< \ru Представление в виде детали. \en Representation as detail. - ModelAssemblyPtr assembly; ///< \ru Представление в виде сборки. \en Representation as assembly. - map_of_visual_items visualItems; ///< \ru Элементы аннотации. \en Annotation items. - c3d::ItemSPtr rawContent; ///< \ru Передаваемый модельный элемент. \en Converted model item. - SPtr pmiToItem; ///< \ru Включены ли элементы аннотации непосредственно в модельный элемент. \en Model item contains PMI. -public: - - C3dModelDocument( SPtr pmiToContent = SPtr() ); ///< \ru Конструктор. \en Conscructor. - - virtual ~C3dModelDocument(); ///< \ru Деструктор. \en Descructor. - - // Является ли сборкой. - virtual bool IsAssembly() const; - // Пуст ли. - virtual bool IsEmpty() const; - // Задать модель напрямую. - virtual void SetContent( MbItem* /*content*/); - // Выдать модель напрямую. - virtual MbItem * GetContent(); - // Создать сборку. - virtual ModelAssemblyPtr CreateAssembly( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ); - // Создать деталь. - virtual ModelPartPtr CreatePart( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ); - // Выдать сборку. - virtual ModelAssemblyPtr GetInstanceAssembly( ); - // Выдать деталь. - virtual ModelPartPtr GetInstancePart( ); - // Завершить импорт. - virtual bool FinishImport( IProgressIndicator * ); - // Выдать элементы аннотации. - virtual map_of_visual_items GetAnnotationItems( eTextForm ) const; - // Задать элементы аннотации. - virtual void SetAnnotationItems( const map_of_visual_items& vi ); - // Открыть документ. - virtual void OpenDocument(); - - /// \ru Включены ли PMI в элемент модели. \en If PMI is included into model item. - SPtrPmiInContent() const; - - /// \ru Зарегистрировать элемент аннотации. \en Register annotation object. - void RegisterAnnotation( c3d::ItemSPtr component, const AnnotationSptrVector& annotation, const AnnotationSptrVector& requirements ); -}; - - -typedef C3dModelDocument RegularModelDocument; -typedef C3dModelDocument ConvModelDocument; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс свойств вставки, подсборки или детали. -\en Interface of properties of an instance, a subassembly or a part. \~ -\ingroup Exchange_Interface -*/ -// --- -class ItModelInstanceProperties : public MbRefItem -{ -public: - - /// \ru Атрибуты. \en Attributes. - - /// \ru Задать атрибуты. \en Set attributes. - virtual bool SetAttributes( const c3d::AttrSPtrVector& /*attributes*/ ) = 0; - - /// \ru Получить атрибуты. \en Get attributes. - virtual c3d::AttrSPtrVector GetAttributes( ) const = 0;// { return c3d::AttrSPtrVector(); } - - - /// \ru Технические требования. \en Technical requirements. - - /// \ru Получить технические требования. \en Get technical requirements. - virtual void GetRequirements( AnnotationSptrVector &, eTextForm ) const = 0; - - /// \ru Задать технические требования. \en Set technical requirements. - virtual void SetRequirements( const AnnotationSptrVector & ) = 0; - - /// \ru Наименование. \en Name. - - /// \ru Задать имя документа. \en Set document's name. - DEPRECATE_DECLARE virtual bool SetName( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя документа. \en Get document's name. - DEPRECATE_DECLARE virtual std::string Name() const { return std::string(); }; - - /// \ru Обозначение. \en Marking. - - /// \ru Задать обозначение документа. \en Set document marking. - DEPRECATE_DECLARE virtual bool SetMarking( const std::string& /*name*/ ) { return false; }; - /// \ru Получить обозначение документа. \en Get document marking. - DEPRECATE_DECLARE virtual std::string Marking() const { return std::string(); }; - - /// \ru Автор. \en Author. - - /// \ru Задать имя автора. \en Set author's name. - DEPRECATE_DECLARE virtual bool SetAuthor( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя автора. \en Get author's name. - DEPRECATE_DECLARE virtual std::string Author() const { return std::string(); }; - - /// \ru Организация. \en Organization. - - /// \ru Задать имя автора. \en Set author's name. - DEPRECATE_DECLARE virtual bool SetOrganization( const std::string& /*name*/ ) { return false; }; - /// \ru Получить имя автора. \en Get author's name. - DEPRECATE_DECLARE virtual std::string Organization() const { return std::string(); }; - - /// \ru Комментарий. \en Comment. - - /// \ru Задать комментарии. \en Set the comments. - DEPRECATE_DECLARE virtual bool SetComments( const std::vector< std::string > & /*comments*/ ) { return false; }; - /// \ru Получить следующий комментарий. \en Get the next comment. - DEPRECATE_DECLARE virtual std::vector< std::string > GetComments( ) const { return std::vector< std::string >(); }; - - /// \ru Цвет сборки, детали или вставки. \en Color of an assembly, a part or an instance. - - /// \ru Задать цветовые свойства. \en Set color properties. - DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer & ) { return false; }; - /// \ru Получить цветовые свойства. \en Get color properties. - DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer & ) const { return false; }; - - /// \ru Цвет тела. \en Solid color. - - /// \ru Задать цветовые свойства оболочки. \en Set color properties of a shell. - DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, size_t ) { return false; }; - - /// \ru Цвет грани. \en Face color. - - /// \ru Задать цветовые свойства грани \en Set color properties of a face. - DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, const MbName & ) { return false; }; - /// \ru Получить цветовые свойства грани. \en Get color properties of a face. - DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer &, const MbName & ) const { return false; }; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс вставки компоненты. -\en Interface of the component instance. \~ -\ingroup Exchange_Interface -*/ -// --- -class ItModelInstance : public ItModelInstanceProperties -{ -public: - // \ru Выдать идентификатор сборки или детали \en Get identifier of an assembly or a part - virtual void * GetId() = 0; - /// \ru Выдать расположение этой вставки в координатах родителя. \en Get the placement of this instance in parent's coordinates. - virtual bool GetPlacement( MbPlacement3D & ) const = 0; - /// \ru Это сборка? \en Is it an assembly? - virtual bool IsAssembly() const = 0; - /// \ru Это ни сборка, ни деталь? \en Is it neither an assembly nor a part? - virtual bool IsEmpty() const = 0; - - /** \brief \ru Создать пустую сборку при импорте и увеличить счётчик ссылок на 1. - \en Create an empty assembly while importing and increase the reference counter by 1. \~ - \param[in] place - \ru ЛСК сборки в родительской модели. - \en LCS of the assembly in the parent's model. \~ - \param[in] fileName - \ru Имя сборки. - \en Assembly name. \~ - \return \ru Экземпляр сборки, если операция прошла успешно, NULL в противном случае. - \en Instance of an assembly if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelAssemblyPtr CreateAssembly( const MbPlacement3D &place, const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; - - /** \brief \ru Создать деталь при импорте. - \en Create a part while importing. \~ - \details \ru Увеличить счётчик ссылок детали на 1. - \en Increase the reference counter of a part by 1. \~ - \param[in] place - \ru ЛСК детали. - \en LCS of a part. \~ - \param[in] solids - \ru Тела, включаемые в деталь. - \en Solids included in the part. \~ - \param[in] fileName - \ru Название детали. - \en Solid's name. \~ - \return \ru Экземпляр детали, если операция прошла успешно, NULL в противном случае. - \en Instance of the part if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelPartPtr CreatePart( const MbPlacement3D &place, const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; - - /** \brief \ru Получить сборку для экспорта. - \en Get an assembly for export. \~ - \return \ru Экземпляр сборки, если операция прошла успешно, NULL в противном случае. - \en Instance of an assembly if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelAssemblyPtr GetInstanceAssembly( ) = 0; - - - /** \brief \ru Получить деталь для экспорта. - \en Get the detail for export. \~ - \return \ru Экземпляр детали, если операция прошла успешно, NULL в противном случае. - \en Instance of the part if the operation succeeded, NULL - otherwise. \~ - */ - virtual ModelPartPtr GetInstancePart( ) = 0; - - /** \brief \ru Создать подсборку при импорте, и её вставку. - \en Create a subassembly and its instance while importing. \~ - \param[in] place - \ru ЛСК сборки в родительской модели. - \en LCS of the assembly in the parent's model. \~ - \param[in] existing - \ru Сборка, подлежащая вставке. - \en An assembly to insert. \~ - \return \ru true, если операция прошла успешно, false в противном случае. - \en true if the operation succeeded, false - otherwise. \~ - */ - virtual bool SetAssembly( const MbPlacement3D & place, const ItModelAssembly * existing ) = 0; - - /** \brief \ru Создать деталь при импорте, и её вставку. - \en Create a part while importing and its instance. \~ - \param[in] place - \ru ЛСК детали в родительской модели. - \en LCS of a part in the parent's model. \~ - \param[in] existing - \ru Деталь, подлежащая вставке. - \en Detail to insert. \~ - \return \ru true, если операция прошла успешно, false в противном случае. - \en true if the operation succeeded, false - otherwise. \~ - */ - virtual bool SetPart( const MbPlacement3D & place, const ItModelPart * existing ) = 0; - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Тип объектов, которые необходимо выдать для экспорта или добавить при импорте. -\en Type of objects to be returned for export or to be added while importing. \~ -\ingroup Data_Interface -*/ -// --- -enum MbeGettingItemType { - git_Item = 0, ///< \ru Получить элементы всех типов. \en Get items of all types. - git_Solid, ///< \ru Получить тела. \en Get solids. - git_Surface, ///< \ru Получить поверхности. \en Get surfaces. - git_WireFrame, ///< \ru Получить проволочные каркасы. \en Get wire frames. - git_PlaneInstance, ///< \ru Получить вставки плоских объектов (эскизы). \en Get plane instances (drafts). - git_PointFrame, ///< \ru Получить точечные каркасы. \en Get point frames. - git_AssociatedGeometry ///< \ru Получить ассоциированные геометрические объекты (резьбы). \en Get associated geometry objects (threads). -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс сборки. -\en Interface of the assembly. \~ -\details \ru Экземпляр должен порождаться в методах CreateAssembly реализаций -интерфейсов ItModelDocument и ItModelAInstance. Собственные элементы детали -должны передаваться как параметры конструктора. \~ \en The object should be -created in the CreateAssembly method of the implementations of the -ItModelDocument and ItModelInstance interfaces. Own Items of the detail should -be arguments of the constructor. -\ingroup Exchange_Interface -*/ -// --- -class ItModelAssembly : public ItModelInstanceProperties -{ -public: - /** \brief \ru Получить имя файла сборки без пути и расширения для экспорта. - \en Get the file name of an assembly without the path and the extension for export. \~ - \return \ru Имя файла сборки. - \en An assembly file name. \~ - */ - virtual c3d::path_string PureFileName() const = 0; - - /** \brief \ru Получить пустой интерфейс вставки для создания подсборки или детали при импорте. - \en Get an empty interface of the insertion for creation of subassembly or a part while importing. \~ - \details \ru Увеличить счётчик ссылок на 1. - \en Increase the reference counter by 1. \~ - \return \ru Интерфейс вставки, если операция прошла успешно или NULL в противном случае. - \en Interface of the instance if the operation succeeded and NULL otherwise. \~ - */ - virtual ModelInstancePtr PrepareInstance() = 0; - - /** \brief \ru Получить интерфейс следующей вставки для создания подсборки или детали при экспорте. - \en Get the interface of the next insertion for creation of a subassembly or a part while exporting. \~ - \return \ru Интерфейс вставки, если операция прошла успешно или NULL в противном случае. - \en Interface of the insertion if the operation succeeded and NULL otherwise. \~ - */ - virtual ModelInstancePtr NextInstance( bool includeInvisible ) = 0; - - /// \ru Выдать ЛСК, общую для элементов компонента. \en Get the placement, which all the items of the component use for transformation. - virtual bool GetPlacement( MbPlacement3D & ) const { return false; }; - - /** \brief \ru Получить объекты из корня сборки при экспорте. - \en Get objects from the assembly root while exporting. \~ - \param[out] items - \ru Наполняемый массив (состоит из объектов классов MbSolid, MbCurve3D, MbCartPoint3D). - \en Array to fill (consist of objects of classes MbSolid, MbCurve3D, MbCartPoint3D). \~ - \param[in] includeInvisible - \ru Если true, то выдаются все тела, включая невидимые, если false - только видимые. - \en If true, then all the solids are returned, including invisible ones, if false - only visible ones. \~ - */ - virtual void GetItems( c3d::ItemsSPtrVector & items, MbeGettingItemType itemType, bool includeInvisible ) const = 0; - - /** \brief \ru Добавить объекты в корень сборки при импорте. - \en Add objects to the assembly root while importing. \~ - \param[in] items - \ru Объекты, добавляемые в модель (тела, кривые и точки). - \en Objects to add to the model (solids, curves and points). \~ - */ - virtual void AddItems( const c3d::ItemsSPtrVector & items ) = 0; - - /** \brief \ru Получить элементы аннотации из сборки. - \en Get elements of annotation from the assembly. \~ - \param[in] eTextForm - \ru Форма представления текста. - \en Text representation form. \~ - \param[in] includeInvisible - \ru Если true, то выдаются все объекты аннотации, включая невидимые, если false - только видимые. - \en If true, all the annotation objects are returned, including invisible ones, if false - only visible ones. \~ - \return \ru Контейнер объектов аннотации. - \en Vector of annotation objects. \~ - */ - virtual AnnotationSptrVector GetAnnotationItems( eTextForm, bool ) const { return AnnotationSptrVector(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D - virtual AnnotationSptrVector GetAnnotationItems( eTextForm ) const { return AnnotationSptrVector(); }; // Будет удалена после её реализации на стороне 3D - - /** \brief \ru Задать элементы аннотации в сборке. - \en Set elements of annotation in the assembly. \~ - \param[in] sourceDim - \ru Элементы аннотации - \en Elements of annotation. \~ - */ - virtual void SetAnnotationItems( const AnnotationSptrVector & ) = 0; - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс детали. -\en Interface of a part. \~ -\details \ru Экземпляр должен порождаться в методах CreatePart реализаций -интерфейсов ItModelDocument и ItModelAInstance. Собственные элементы детали -должны передаваться как параметры конструктора. \~ \en The object should be -created in the CreatePart method of the implementations of the -ItModelDocument and ItModelInstance interfaces. Own Items of the detail should -be arguments of the constructor. -\ingroup Exchange_Interface -*/ -// --- -class ItModelPart : public ItModelInstanceProperties -{ -public: - /** \brief \ru Получить имя файла детали без пути и расширения для экспорта. - \en Get the file name of a part without the path and extension for export. \~ - \return \ru Имя файла детали. - \en A part file name. \~ - */ - virtual c3d::path_string PureFileName() const = 0; - - /** \brief \ru Получить пустой интерфейс вставки для создания подсборки или детали при импорте. - \en Get an empty interface of the insertion for creation of subassembly or a part while importing. \~ - \details \ru Увеличить счётчик ссылок на 1. - \en Increase the reference counter by 1. \~ - \return \ru Интерфейс вставки, если операция прошла успешно или NULL в противном случае. - \en Interface of the instance if the operation succeeded and NULL otherwise. \~ - */ - virtual ModelInstancePtr PrepareInstance() = 0; - - /** \brief \ru Получить интерфейс следующей вставки для создания подсборки или детали при экспорте. - \en Get the interface of the next insertion for creation of a subassembly or a part while exporting. \~ - \return \ru Интерфейс вставки, если операция прошла успешно или NULL в противном случае. - \en Interface of the insertion if the operation succeeded and NULL otherwise. \~ - */ - virtual ModelInstancePtr NextInstance( bool includeInvisible ) = 0; - - /// \ru Выдать ЛСК, общую для элементов компонента. \en Get the placement, which all the items of the component use for transformation. - virtual bool GetPlacement( MbPlacement3D & ) const { return false; }; - - /** \brief \ru Получить объекты из детали при экспорте. - \en Get objects from the part while exporting. \~ - \param[out] items - \ru Наполняемый массив (состоит из объектов классов MbSolid, MbWireFrame, MbPointFrame). - \en Array to fill (consists of objects of classes MbSolid, MbWireFrame, MbPointFrame). \~ - \param[in] itemType - \ru Тип объектов, которыми нужно наполнить массив. - \en Type of objects the array should be filled with. \~ - \param[in] includeInvisible - \ru Если true, то выдаются все тела, включая невидимые, если false - только видимые. - \en If true, all the solids are returned, including invisible ones, if false - only visible ones. \~ - */ - virtual void GetItems( c3d::ItemsSPtrVector & items, MbeGettingItemType itemType, bool includeInvisible ) const = 0; - - /** \brief \ru Добавить объекты в деталь при импорте. - \en Add objects to a part while importing. \~ - \param[in] items - \ru Объекты, добавляемые в модель (кривые и точки). - \en Objects to be added to the model (curves and points). \~ - */ - virtual void AddItems( const c3d::ItemsSPtrVector & items ) = 0; - - /** \brief \ru Получить элементы аннотации из детали. - \en Get elements of annotation from the detail. \~ - \param[in] eTextForm - \ru Форма представления текста. - \en Text representation form. \~ - \param[in] includeInvisible - \ru Если true, то выдаются все объекты аннотации, включая невидимые, если false - только видимые. - \en If true, all the annotation objects are returned, including invisible ones, if false - only visible ones. \~ - \return \ru Контейнер объектов аннотации. - \en Vector of annotation objects. \~ - */ - virtual AnnotationSptrVector GetAnnotationItems( eTextForm, bool ) const { return AnnotationSptrVector(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D - virtual AnnotationSptrVector GetAnnotationItems( eTextForm ) const { return AnnotationSptrVector(); }; // Будет удалена после её реализации на стороне 3D - - - /** \brief \ru Задать элементы аннотации в детали. - \en Set elements of annotation in the part. \~ - \param[in] sourceDim - \ru Элементы аннотации - \en Elements of annotation. \~ - */ - virtual void SetAnnotationItems( const AnnotationSptrVector & ) = 0; - -}; - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Сущности конвертерной модели: документ, деталь, сборка, вставка. + \en Entities of converter-compatible model: document, part, assembly, instance. \~ + \details \ru Интерфейсы сущностей и предопределённая реализация модельного документа C3dModelDocument. + \en Interfaces of entities and pre-defined implementation of model document C3dModelDocument. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_MODEL_DOCUMENT_H +#define __CONV_MODEL_DOCUMENT_H + +#include +#include +#include +#include +#include +#include +#include + + + +class MbPlacement3D; +class MbName; + +class MbAttributeContainer; + +class ItModelAssembly; +class ItModelPart; +class ItModelInstance; + +class IProgressIndicator; + +typedef SPtr ModelAssemblyPtr; +typedef SPtr ModelPartPtr; +typedef SPtr ModelInstancePtr; + + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс документа модели сборки или детали. +\en Interface of document of an assembly model or a part model. \~ +\ingroup Exchange_Interface +*/ +// --- +class CONV_CLASS ItModelDocument : public MbRefItem +{ +public: + /// \ru Это сборка? \en Is it an assembly? + virtual bool IsAssembly() const = 0; + /// \ru Это ни сборка, ни деталь? \en Is it neither an assembly nor a part? + virtual bool IsEmpty() const = 0; + + /** \brief \ru Прообраз новой интерфейсной функции - задать модель ЛСК, относительно которой позиционируется модель. + \en Prototype of a new interface function - get the placement the model is defined in. \~ + */ + //virtual MbPlacement3D GetOriginLocation() const = 0; + + /** \brief \ru Прообраз новой интерфейсной функции - задать модель для наполнения. + \en Prototype of a new interface function - set a model to fill. \~ + */ + virtual void SetContent( MbItem* /*content*/) = 0; + + /** \brief \ru Прообраз новой интерфейсной функции - получить наполнение. + \en Prototype of a new interface function - get the filling. \~ + */ + virtual MbItem * GetContent() /*{ return c3d_null; }*/ = 0; + + /** \brief \ru Создать документ с новой сборкой при импорте. + \en Create a document with a new assembly while importing. \~ + \details \ru Увеличить счётчик ссылок результирующего документа на 1. + \en Increase the reference counter of the resultant document by 1. \~ + \param[in] fileName - \ru Имя сборки. + \en Assembly name. \~ + \param[in] solids - \ru Тела, добавляемые в сборку. + \en Solids to add into the assembly. \~ + \return \ru Экземпляр сборки, если операция прошла успешно, c3d_null в противном случае. + \en Instance of an assembly if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelAssemblyPtr CreateAssembly( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; + + + /** \brief \ru Создать документ с новой деталью при импорте. + \en Create a document with a new part while importing. \~ + \details \ru Увеличить счётчик ссылок результирующего документа на 1. + \en Increase the reference counter of the resultant document by 1. \~ + \param[in] solids - \ru Тела, добавляемые в деталь. + \en Solids to add into a part. \~ + \param[in] fileName - \ru Имя детали. + \en A part name. \~ + \return \ru Экземпляр детали, если операция прошла успешно, c3d_null в противном случае. + \en Instance of the part if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelPartPtr CreatePart( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; + + /** \brief \ru Получить сборку для экспорта. + \en Get an assembly for export. \~ + \details \ru Увеличить счётчик ссылок результирующей сборки на 1. + \en Increase the reference counter of the resultant assembly by 1. \~ + \return \ru Экземпляр сборки, если операция прошла успешно, c3d_null в противном случае. + \en Instance of an assembly if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelAssemblyPtr GetInstanceAssembly( ) = 0; + + + /** \brief \ru Получить деталь для экспорта. + \en Get the detail for export. \~ + \details \ru Увеличить счётчик ссылок результирующей детали на 1. + \en Increase the reference counter of the resultant part by 1. \~ + \return \ru Экземпляр детали, если операция прошла успешно, c3d_null в противном случае. + \en Instance of the part if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelPartPtr GetInstancePart( ) = 0; + + /** \brief \ru Завершить импорт и сохранить документ. + \en Complete the import and save the document. \~ + \return \ru true, если операция прошла успешно, false в противном случае. + \en true if the operation succeeded, false - otherwise. \~ + \param[in] \ru indicator Объект для отображения хода процесса. + \en indicator An object indicating a process progress. \~ + */ + virtual bool FinishImport( IProgressIndicator * indicator ) = 0; + + /** \brief \ru Получить элементы аннотации, соответствующие элементам геометрической модели. + \en Get elements of annotation, corresponding items of geometric model. \~ + \param[in] eTextForm - \ru Форма представления текста. + \en Text representation form. \~ + \return \ru Контейнер объектов аннотации. + \en Vector of annotation objects. \~ + */ + virtual map_of_visual_items GetAnnotationItems( eTextForm ) const = 0; + + /// \ru Задать размеры. \en Set sizes. + virtual void SetAnnotationItems( const map_of_visual_items& ) = 0; + + /// \ru Открыть документ. \en Open a document. + virtual void OpenDocument() = 0; + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Формирователь геометрического представления текста. +\en Generator of text element's geometry shape. \~ +\ingroup Exchange_Interface +*/ +// --- +class CONV_CLASS C3DSymbolToItem : public MbRefItem { +public: + virtual SPtr TextToItem( const MaTextItem*, const MbPlacement3D& location ) const; + virtual SPtr TerminatorToItem( const MaTerminatorSymbol*, const MbPlacement3D& location ) const; + + virtual ~C3DSymbolToItem(); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Формирователь геометрического представления PMI. +\en Generator of PMI's geometry shape. \~ +\ingroup Exchange_Interface +*/ +// --- +class CONV_CLASS C3DPmiToItem : public MbRefItem { + SPtr symToItem; +public: + C3DPmiToItem( SPtr = SPtr() ); + virtual SPtr operator() ( const MaAnnotationItem* ) const; + + virtual ~C3DPmiToItem(); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Реализация документа модели, формирующая регулярную структуру. +\en Implementation of model document which has regular structure. \~ +\ingroup Exchange_Interface +*/ +// --- +class CONV_CLASS C3dModelDocument: public ItModelDocument { + + ModelPartPtr part; ///< \ru Представление в виде детали. \en Representation as detail. + ModelAssemblyPtr assembly; ///< \ru Представление в виде сборки. \en Representation as assembly. + map_of_visual_items visualItems; ///< \ru Элементы аннотации. \en Annotation items. + c3d::ItemSPtr rawContent; ///< \ru Передаваемый модельный элемент. \en Converted model item. + SPtr pmiToItem; ///< \ru Включены ли элементы аннотации непосредственно в модельный элемент. \en Model item contains PMI. +public: + + C3dModelDocument( SPtr pmiToContent = SPtr() ); ///< \ru Конструктор. \en Conscructor. + + virtual ~C3dModelDocument(); ///< \ru Деструктор. \en Descructor. + + // Является ли сборкой. + virtual bool IsAssembly() const; + // Пуст ли. + virtual bool IsEmpty() const; + // Задать модель напрямую. + virtual void SetContent( MbItem* /*content*/); + // Выдать модель напрямую. + virtual MbItem * GetContent(); + // Создать сборку. + virtual ModelAssemblyPtr CreateAssembly( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ); + // Создать деталь. + virtual ModelPartPtr CreatePart( const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ); + // Выдать сборку. + virtual ModelAssemblyPtr GetInstanceAssembly( ); + // Выдать деталь. + virtual ModelPartPtr GetInstancePart( ); + // Завершить импорт. + virtual bool FinishImport( IProgressIndicator * ); + // Выдать элементы аннотации. + virtual map_of_visual_items GetAnnotationItems( eTextForm ) const; + // Задать элементы аннотации. + virtual void SetAnnotationItems( const map_of_visual_items& vi ); + // Открыть документ. + virtual void OpenDocument(); + + /// \ru Включены ли PMI в элемент модели. \en If PMI is included into model item. + SPtrPmiInContent() const; + + /// \ru Зарегистрировать элемент аннотации. \en Register annotation object. + void RegisterAnnotation( c3d::ItemSPtr component, const AnnotationSptrVector& annotation, const AnnotationSptrVector& requirements ); +}; + + +typedef C3dModelDocument RegularModelDocument; +typedef C3dModelDocument ConvModelDocument; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс свойств вставки, подсборки или детали. +\en Interface of properties of an instance, a subassembly or a part. \~ +\ingroup Exchange_Interface +*/ +// --- +class ItModelInstanceProperties : public MbRefItem +{ +public: + + /// \ru Атрибуты. \en Attributes. + + /// \ru Задать атрибуты. \en Set attributes. + virtual bool SetAttributes( const c3d::AttrSPtrVector& /*attributes*/ ) = 0; + + /// \ru Получить атрибуты. \en Get attributes. + virtual c3d::AttrSPtrVector GetAttributes( ) const = 0;// { return c3d::AttrSPtrVector(); } + + + /// \ru Технические требования. \en Technical requirements. + + /// \ru Получить технические требования. \en Get technical requirements. + virtual void GetRequirements( AnnotationSptrVector &, eTextForm ) const = 0; + + /// \ru Задать технические требования. \en Set technical requirements. + virtual void SetRequirements( const AnnotationSptrVector & ) = 0; + + /// \ru Наименование. \en Name. + + /// \ru Задать имя документа. \en Set document's name. + DEPRECATE_DECLARE virtual bool SetName( const std::string& /*name*/ ) { return false; }; + /// \ru Получить имя документа. \en Get document's name. + DEPRECATE_DECLARE virtual std::string Name() const { return std::string(); }; + + /// \ru Обозначение. \en Marking. + + /// \ru Задать обозначение документа. \en Set document marking. + DEPRECATE_DECLARE virtual bool SetMarking( const std::string& /*name*/ ) { return false; }; + /// \ru Получить обозначение документа. \en Get document marking. + DEPRECATE_DECLARE virtual std::string Marking() const { return std::string(); }; + + /// \ru Автор. \en Author. + + /// \ru Задать имя автора. \en Set author's name. + DEPRECATE_DECLARE virtual bool SetAuthor( const std::string& /*name*/ ) { return false; }; + /// \ru Получить имя автора. \en Get author's name. + DEPRECATE_DECLARE virtual std::string Author() const { return std::string(); }; + + /// \ru Организация. \en Organization. + + /// \ru Задать имя автора. \en Set author's name. + DEPRECATE_DECLARE virtual bool SetOrganization( const std::string& /*name*/ ) { return false; }; + /// \ru Получить имя автора. \en Get author's name. + DEPRECATE_DECLARE virtual std::string Organization() const { return std::string(); }; + + /// \ru Комментарий. \en Comment. + + /// \ru Задать комментарии. \en Set the comments. + DEPRECATE_DECLARE virtual bool SetComments( const std::vector< std::string > & /*comments*/ ) { return false; }; + /// \ru Получить следующий комментарий. \en Get the next comment. + DEPRECATE_DECLARE virtual std::vector< std::string > GetComments( ) const { return std::vector< std::string >(); }; + + /// \ru Цвет сборки, детали или вставки. \en Color of an assembly, a part or an instance. + + /// \ru Задать цветовые свойства. \en Set color properties. + DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer & ) { return false; }; + /// \ru Получить цветовые свойства. \en Get color properties. + DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer & ) const { return false; }; + + /// \ru Цвет тела. \en Solid color. + + /// \ru Задать цветовые свойства оболочки. \en Set color properties of a shell. + DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, size_t ) { return false; }; + + /// \ru Цвет грани. \en Face color. + + /// \ru Задать цветовые свойства грани \en Set color properties of a face. + DEPRECATE_DECLARE virtual bool SetColor( const MbAttributeContainer &, const MbName & ) { return false; }; + /// \ru Получить цветовые свойства грани. \en Get color properties of a face. + DEPRECATE_DECLARE virtual bool GetColor( MbAttributeContainer &, const MbName & ) const { return false; }; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс вставки компоненты. +\en Interface of the component instance. \~ +\ingroup Exchange_Interface +*/ +// --- +class ItModelInstance : public ItModelInstanceProperties +{ +public: + // \ru Выдать идентификатор сборки или детали \en Get identifier of an assembly or a part + virtual void * GetId() = 0; + /// \ru Выдать расположение этой вставки в координатах родителя. \en Get the placement of this instance in parent's coordinates. + virtual bool GetPlacement( MbPlacement3D & ) const = 0; + /// \ru Это сборка? \en Is it an assembly? + virtual bool IsAssembly() const = 0; + /// \ru Это ни сборка, ни деталь? \en Is it neither an assembly nor a part? + virtual bool IsEmpty() const = 0; + + /** \brief \ru Создать пустую сборку при импорте и увеличить счётчик ссылок на 1. + \en Create an empty assembly while importing and increase the reference counter by 1. \~ + \param[in] place - \ru ЛСК сборки в родительской модели. + \en LCS of the assembly in the parent's model. \~ + \param[in] fileName - \ru Имя сборки. + \en Assembly name. \~ + \return \ru Экземпляр сборки, если операция прошла успешно, c3d_null в противном случае. + \en Instance of an assembly if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelAssemblyPtr CreateAssembly( const MbPlacement3D &place, const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; + + /** \brief \ru Создать деталь при импорте. + \en Create a part while importing. \~ + \details \ru Увеличить счётчик ссылок детали на 1. + \en Increase the reference counter of a part by 1. \~ + \param[in] place - \ru ЛСК детали. + \en LCS of a part. \~ + \param[in] solids - \ru Тела, включаемые в деталь. + \en Solids included in the part. \~ + \param[in] fileName - \ru Название детали. + \en Solid's name. \~ + \return \ru Экземпляр детали, если операция прошла успешно, c3d_null в противном случае. + \en Instance of the part if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelPartPtr CreatePart( const MbPlacement3D &place, const c3d::ItemsSPtrVector & componentItems, const c3d::string_t& fileName ) = 0; + + /** \brief \ru Получить сборку для экспорта. + \en Get an assembly for export. \~ + \return \ru Экземпляр сборки, если операция прошла успешно, c3d_null в противном случае. + \en Instance of an assembly if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelAssemblyPtr GetInstanceAssembly( ) = 0; + + + /** \brief \ru Получить деталь для экспорта. + \en Get the detail for export. \~ + \return \ru Экземпляр детали, если операция прошла успешно, c3d_null в противном случае. + \en Instance of the part if the operation succeeded, c3d_null - otherwise. \~ + */ + virtual ModelPartPtr GetInstancePart( ) = 0; + + /** \brief \ru Создать подсборку при импорте, и её вставку. + \en Create a subassembly and its instance while importing. \~ + \param[in] place - \ru ЛСК сборки в родительской модели. + \en LCS of the assembly in the parent's model. \~ + \param[in] existing - \ru Сборка, подлежащая вставке. + \en An assembly to insert. \~ + \return \ru true, если операция прошла успешно, false в противном случае. + \en true if the operation succeeded, false - otherwise. \~ + */ + virtual bool SetAssembly( const MbPlacement3D & place, const ItModelAssembly * existing ) = 0; + + /** \brief \ru Создать деталь при импорте, и её вставку. + \en Create a part while importing and its instance. \~ + \param[in] place - \ru ЛСК детали в родительской модели. + \en LCS of a part in the parent's model. \~ + \param[in] existing - \ru Деталь, подлежащая вставке. + \en Detail to insert. \~ + \return \ru true, если операция прошла успешно, false в противном случае. + \en true if the operation succeeded, false - otherwise. \~ + */ + virtual bool SetPart( const MbPlacement3D & place, const ItModelPart * existing ) = 0; + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тип объектов, которые необходимо выдать для экспорта или добавить при импорте. +\en Type of objects to be returned for export or to be added while importing. \~ +\ingroup Data_Interface +*/ +// --- +enum MbeGettingItemType { + git_Item = 0, ///< \ru Получить элементы всех типов. \en Get items of all types. + git_Solid, ///< \ru Получить тела. \en Get solids. + git_Surface, ///< \ru Получить поверхности. \en Get surfaces. + git_WireFrame, ///< \ru Получить проволочные каркасы. \en Get wire frames. + git_PlaneInstance, ///< \ru Получить вставки плоских объектов (эскизы). \en Get plane instances (drafts). + git_PointFrame, ///< \ru Получить точечные каркасы. \en Get point frames. + git_AssociatedGeometry ///< \ru Получить ассоциированные геометрические объекты (резьбы). \en Get associated geometry objects (threads). +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс сборки. +\en Interface of the assembly. \~ +\details \ru Экземпляр должен порождаться в методах CreateAssembly реализаций +интерфейсов ItModelDocument и ItModelAInstance. Собственные элементы детали +должны передаваться как параметры конструктора. \~ \en The object should be +created in the CreateAssembly method of the implementations of the +ItModelDocument and ItModelInstance interfaces. Own Items of the detail should +be arguments of the constructor. +\ingroup Exchange_Interface +*/ +// --- +class ItModelAssembly : public ItModelInstanceProperties +{ +public: + /** \brief \ru Получить имя файла сборки без пути и расширения для экспорта. + \en Get the file name of an assembly without the path and the extension for export. \~ + \return \ru Имя файла сборки. + \en An assembly file name. \~ + */ + virtual c3d::path_string PureFileName() const = 0; + + /** \brief \ru Получить пустой интерфейс вставки для создания подсборки или детали при импорте. + \en Get an empty interface of the insertion for creation of subassembly or a part while importing. \~ + \details \ru Увеличить счётчик ссылок на 1. + \en Increase the reference counter by 1. \~ + \return \ru Интерфейс вставки, если операция прошла успешно или c3d_null в противном случае. + \en Interface of the instance if the operation succeeded and c3d_null otherwise. \~ + */ + virtual ModelInstancePtr PrepareInstance() = 0; + + /** \brief \ru Получить интерфейс следующей вставки для создания подсборки или детали при экспорте. + \en Get the interface of the next insertion for creation of a subassembly or a part while exporting. \~ + \return \ru Интерфейс вставки, если операция прошла успешно или c3d_null в противном случае. + \en Interface of the insertion if the operation succeeded and c3d_null otherwise. \~ + */ + virtual ModelInstancePtr NextInstance( bool includeInvisible ) = 0; + + /// \ru Выдать ЛСК, общую для элементов компонента. \en Get the placement, which all the items of the component use for transformation. + virtual bool GetPlacement( MbPlacement3D & ) const { return false; }; + + /** \brief \ru Получить объекты из корня сборки при экспорте. + \en Get objects from the assembly root while exporting. \~ + \param[out] items - \ru Наполняемый массив (состоит из объектов классов MbSolid, MbCurve3D, MbCartPoint3D). + \en Array to fill (consist of objects of classes MbSolid, MbCurve3D, MbCartPoint3D). \~ + \param[in] includeInvisible - \ru Если true, то выдаются все тела, включая невидимые, если false - только видимые. + \en If true, then all the solids are returned, including invisible ones, if false - only visible ones. \~ + */ + virtual void GetItems( c3d::ItemsSPtrVector & items, MbeGettingItemType itemType, bool includeInvisible ) const = 0; + + /** \brief \ru Добавить объекты в корень сборки при импорте. + \en Add objects to the assembly root while importing. \~ + \param[in] items - \ru Объекты, добавляемые в модель (тела, кривые и точки). + \en Objects to add to the model (solids, curves and points). \~ + */ + virtual void AddItems( const c3d::ItemsSPtrVector & items ) = 0; + + /** \brief \ru Получить элементы аннотации из сборки. + \en Get elements of annotation from the assembly. \~ + \param[in] eTextForm - \ru Форма представления текста. + \en Text representation form. \~ + \param[in] includeInvisible - \ru Если true, то выдаются все объекты аннотации, включая невидимые, если false - только видимые. + \en If true, all the annotation objects are returned, including invisible ones, if false - only visible ones. \~ + \return \ru Контейнер объектов аннотации. + \en Vector of annotation objects. \~ + */ + virtual AnnotationSptrVector GetAnnotationItems( eTextForm, bool ) const { return AnnotationSptrVector(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D + virtual AnnotationSptrVector GetAnnotationItems( eTextForm ) const { return AnnotationSptrVector(); }; // Будет удалена после её реализации на стороне 3D + + /** \brief \ru Задать элементы аннотации в сборке. + \en Set elements of annotation in the assembly. \~ + \param[in] sourceDim - \ru Элементы аннотации + \en Elements of annotation. \~ + */ + virtual void SetAnnotationItems( const AnnotationSptrVector & ) = 0; + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс детали. +\en Interface of a part. \~ +\details \ru Экземпляр должен порождаться в методах CreatePart реализаций +интерфейсов ItModelDocument и ItModelAInstance. Собственные элементы детали +должны передаваться как параметры конструктора. \~ \en The object should be +created in the CreatePart method of the implementations of the +ItModelDocument and ItModelInstance interfaces. Own Items of the detail should +be arguments of the constructor. +\ingroup Exchange_Interface +*/ +// --- +class ItModelPart : public ItModelInstanceProperties +{ +public: + /** \brief \ru Получить имя файла детали без пути и расширения для экспорта. + \en Get the file name of a part without the path and extension for export. \~ + \return \ru Имя файла детали. + \en A part file name. \~ + */ + virtual c3d::path_string PureFileName() const = 0; + + /** \brief \ru Получить пустой интерфейс вставки для создания подсборки или детали при импорте. + \en Get an empty interface of the insertion for creation of subassembly or a part while importing. \~ + \details \ru Увеличить счётчик ссылок на 1. + \en Increase the reference counter by 1. \~ + \return \ru Интерфейс вставки, если операция прошла успешно или c3d_null в противном случае. + \en Interface of the instance if the operation succeeded and c3d_null otherwise. \~ + */ + virtual ModelInstancePtr PrepareInstance() = 0; + + /** \brief \ru Получить интерфейс следующей вставки для создания подсборки или детали при экспорте. + \en Get the interface of the next insertion for creation of a subassembly or a part while exporting. \~ + \return \ru Интерфейс вставки, если операция прошла успешно или c3d_null в противном случае. + \en Interface of the insertion if the operation succeeded and c3d_null otherwise. \~ + */ + virtual ModelInstancePtr NextInstance( bool includeInvisible ) = 0; + + /// \ru Выдать ЛСК, общую для элементов компонента. \en Get the placement, which all the items of the component use for transformation. + virtual bool GetPlacement( MbPlacement3D & ) const { return false; }; + + /** \brief \ru Получить объекты из детали при экспорте. + \en Get objects from the part while exporting. \~ + \param[out] items - \ru Наполняемый массив (состоит из объектов классов MbSolid, MbWireFrame, MbPointFrame). + \en Array to fill (consists of objects of classes MbSolid, MbWireFrame, MbPointFrame). \~ + \param[in] itemType - \ru Тип объектов, которыми нужно наполнить массив. + \en Type of objects the array should be filled with. \~ + \param[in] includeInvisible - \ru Если true, то выдаются все тела, включая невидимые, если false - только видимые. + \en If true, all the solids are returned, including invisible ones, if false - only visible ones. \~ + */ + virtual void GetItems( c3d::ItemsSPtrVector & items, MbeGettingItemType itemType, bool includeInvisible ) const = 0; + + /** \brief \ru Добавить объекты в деталь при импорте. + \en Add objects to a part while importing. \~ + \param[in] items - \ru Объекты, добавляемые в модель (кривые и точки). + \en Objects to be added to the model (curves and points). \~ + */ + virtual void AddItems( const c3d::ItemsSPtrVector & items ) = 0; + + /** \brief \ru Получить элементы аннотации из детали. + \en Get elements of annotation from the detail. \~ + \param[in] eTextForm - \ru Форма представления текста. + \en Text representation form. \~ + \param[in] includeInvisible - \ru Если true, то выдаются все объекты аннотации, включая невидимые, если false - только видимые. + \en If true, all the annotation objects are returned, including invisible ones, if false - only visible ones. \~ + \return \ru Контейнер объектов аннотации. + \en Vector of annotation objects. \~ + */ + virtual AnnotationSptrVector GetAnnotationItems( eTextForm, bool ) const { return AnnotationSptrVector(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D + virtual AnnotationSptrVector GetAnnotationItems( eTextForm ) const { return AnnotationSptrVector(); }; // Будет удалена после её реализации на стороне 3D + + + /** \brief \ru Задать элементы аннотации в детали. + \en Set elements of annotation in the part. \~ + \param[in] sourceDim - \ru Элементы аннотации + \en Elements of annotation. \~ + */ + virtual void SetAnnotationItems( const AnnotationSptrVector & ) = 0; + +}; + + #endif // __CONV_MODEL_DOCUMENT_H \ No newline at end of file diff --git a/C3d/Include/conv_model_exchange.h b/C3d/Include/conv_model_exchange.h index b1d4550..1b9a8ef 100644 --- a/C3d/Include/conv_model_exchange.h +++ b/C3d/Include/conv_model_exchange.h @@ -1,1137 +1,1159 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Общий интерфейс конвертера. - \en Common API of the converter. \~ - \details \ru Функции чтения и записи в буфер и файл с автоопределением формата по - расширению файла, класс-конвертер с методами для каждого формата и возможностью - подключения плагина, функции для работы с каждым форматом. - \en Functions for export and import from buffer and file using file's extension - for format detection, class of converter for format-specific methods and API for - plugin, format-specific import and export functions. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_I_CONVERTER_H -#define __CONV_I_CONVERTER_H - -#include -#include -#include - -class IProgressIndicator; -struct IScaleRequestor; -class ItModelDocument; -class IConvertorProperty3D; - -/** - \addtogroup Exchange_Interface - \{ -*/ - -//------------------------------------------------------------------------------ -/** \brief \ru Обменный формат модели. -\en Model exchange format.\~ -\ingroup Data_Interface -*/ -// --- -enum MbeModelExchangeFormat { - mxf_autodetect, ///< \ru Интерпретировать содержимое по расширению файла. \en File extension defines format. - mxf_ACIS, ///< \ru Интерпретировать содержимое как ACIS (.sat). \en Read data from buffer as ACIS (.sat). - mxf_IGES, ///< \ru Интерпретировать содержимое как IGES (.igs или .iges). \en Read data from buffer as IGES (.igs or .iges). - mxf_JT, ///< \ru Интерпретировать содержимое как JT (.jt). \en Read data from buffer as JT (.jt). - mxf_Parasolid, ///< \ru Интерпретировать содержимое как Parasolid (.x_t, .x_b, .xmt_txt, .xmp_txt, .xmt_bin или .xmp_bin ). \en Read data from buffer as Parasolid (.x_t, .x_b, .xmt_txt, .xmp_txt, .xmt_bin or .xmp_bin ). - mxf_STEP, ///< \ru Интерпретировать содержимое как STEP (.stp или .step). \en Read data from buffer as STEP (.stp or .step). - mxf_STL, ///< \ru Интерпретировать содержимое как STL (.stl). \en Read data from buffer as STL (.stl). - mxf_VRML, ///< \ru Интерпретировать содержимое как VRML (.wrl). \en Read data from buffer as VRML (.wrl). - mxf_GRDECL, ///< \ru Интерпретировать содержимое как GRDECL (.grdecl). \en Read data from buffer as GRDECL (.grdecl). - mxf_ASCIIPoint, ///< \ru Интерпретировать содержимое как облако точек в ASCII (.txt, .asc или .xyz). \en Read data from buffer as ASCII point cloud (.txt, .asc or .xyz). - mxf_C3D, ///< \ru Интерпретировать содержимое как C3D (.c3d). \en Read data from buffer as C3D (.c3d). -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Результат конвертирования. -\en Result of converting operation. -\ingroup Data_Interface -*/ -// --- -enum MbeConvResType { - cnv_Success = 0, ///< \ru Успешное завершение. \en Success. - cnv_Error, ///< \ru Ошибка в процессе конвертирования. \en Error. - cnv_UserCanceled, ///< \ru Процесс прерван пользователем. \en Process interrupted by user. - cnv_NoBody, ///< \ru Не найдено тел. \en No solids found. - cnv_NoObjects, ///< \ru Не найдено объектов. \en No objects found. - cnv_FileOpenError, ///< \ru Ошибка открытия файла. \en File open error. - cnv_FileWriteError, ///< \ru Ошибка записи файла. \en File write error. - cnv_FileDeleteError, ///< \ru Ошибка удаления файла. \en Could not delete file. - cnv_ImpossibleReadAssembly,///< \ru Не поддерживает работу со сборками. \en Assemblies are not supported. - cnv_LicenseNotFound, ///< \ru Ошибка получения лицензии. \en License check failure. - cnv_NotEnoughMemory, ///< \ru Недостаточно памяти. \en Not enough memory. - cnv_UnknownExtension ///< \ru Неизвестное расширение файла. \en Unknown file extenstion. -}; - - -namespace c3d { - - class C3DExchangeBuffer; - - /** \brief \ru Прочитать файл обменного формата в модель. - \en Read a file of an exchange format into model. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. - \param[out] model - \ru Модель. - \en The model. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ImportFromFile( MbModel & model, - const path_string & fileName, - IConvertorProperty3D * prop = C3D_NULL_PTR, - IProgressIndicator * indicator = C3D_NULL_PTR ); - - - /** \brief \ru Прочитать файл обменного формата в элемент. - \en Read a file of an exchange format into element. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. - \param[out] item - \ru Замещаемый элемент. - \en The element to replace. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ImportFromFile( c3d::ItemSPtr& item, - const path_string& filePath, - IConvertorProperty3D* prop = C3D_NULL_PTR, - IProgressIndicator* indicator = C3D_NULL_PTR ); - - /** \brief \ru Прочитать файл обменного формата в модель. - \en Read a file of an exchange format into model. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. - \param[out] mDoc - \ru Модельный документ. - \en The model. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ImportFromFile( ItModelDocument & mDoc, - const path_string & filePath, - IConvertorProperty3D * prop = C3D_NULL_PTR, - IProgressIndicator * indicator = C3D_NULL_PTR ); - - /** \brief \ru Записать модель в файл обменного формата. - \en Write the model into an exchange format file. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. - \param[out] model - \ru Модель. - \en The model. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ExportIntoFile( MbModel & model, - const path_string & filePath, - IConvertorProperty3D * prop = C3D_NULL_PTR, - IProgressIndicator * indicator = C3D_NULL_PTR ); - - /** \brief \ru Записать модель в файл обменного формата. - \en Write the model into an exchange format file. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. - \param[out] model - \ru Экспортируемый лемент. - \en The exported element. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType ) ExportIntoFile( MbItem& item, - const path_string& filePath, - IConvertorProperty3D* prop = C3D_NULL_PTR, - IProgressIndicator* indicator = C3D_NULL_PTR ); - - /** \brief \ru Записать модельный документ в файл обменного формата. - \en Write the model into an exchange format file. \~ - \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. - В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ - \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath - method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. - \param[in] mDoc - \ru Экспортируемый модельный документ. - \en The exported model document. \~ - \param[in] filePath - \ru Путь файла. - \en File path. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType ) ExportIntoFile( ItModelDocument& mDoc, - const path_string& filePath, - IConvertorProperty3D* prop = C3D_NULL_PTR, - IProgressIndicator* indicator = C3D_NULL_PTR ); - - - /** \brief \ru Импортировать данные из буфера в модель. - \en Import data from buffer into model. \~ - \param[out] model - \ru Модель. - \en The model. \~ - \param[in] buffer - \ru Буфер. - \en Buffer. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ImportFromBuffer( MbModel & model, - const C3DExchangeBuffer& buffer, - MbeModelExchangeFormat modelFormat, - IConvertorProperty3D * prop = C3D_NULL_PTR, - IProgressIndicator * indicator = C3D_NULL_PTR ); - - - /** \brief \ru Импортировать данные из буфера в модель. - \en Import data from buffer into model. \~ - \param[out] item - \ru Замещаемый элемент. - \en The item to replace. \~ - \param[in] buffer - \ru Буфер. - \en Buffer. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC(MbeConvResType) ImportFromBuffer( c3d::ItemSPtr& item, - const C3DExchangeBuffer& buffer, - MbeModelExchangeFormat modelFormat, - IConvertorProperty3D* prop = C3D_NULL_PTR, - IProgressIndicator* indicator = C3D_NULL_PTR ); - - - /** \brief \ru Экспортировать модель в буфер. - \en Export model into buffer. \~ - \param[in] model - \ru Модель. - \en The model. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[out] buffer - \ru Буфер. - \en Buffer. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC (MbeConvResType) ExportIntoBuffer( MbModel & model, - MbeModelExchangeFormat modelFormat, - C3DExchangeBuffer& buffer, - IConvertorProperty3D * prop = C3D_NULL_PTR, - IProgressIndicator * indicator = C3D_NULL_PTR ); - - - /** \brief \ru Экспортировать модель в буфер. - \en Export model into buffer. \~ - \param[in] item - \ru Экспортируемый элемент. - \en The item to export. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[out] buffer - \ru Буфер. - \en Buffer. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - CONV_FUNC(MbeConvResType) ExportIntoBuffer( MbItem& item, - MbeModelExchangeFormat modelFormat, - C3DExchangeBuffer& buffer, - IConvertorProperty3D* prop = C3D_NULL_PTR, - IProgressIndicator* indicator = C3D_NULL_PTR ); - - - //------------------------------------------------------------------------------ - /** \brief \ru Буфер для обмена. - \en Memory buffer for data exchange. \~ - \details \ru Обеспечивает обмен данными через оперативную память с контролем выделения и освобождения. - \en Prvides data exchange with memory allocation and deallocation control. \~ - \ingroup Exchange_Interface - */ - class C3DExchangeBuffer { - char* data; ///< \ru Адрес буфера. \en Buffer address. - size_t count; ///< \ru Число байт. \en Bytes count. - public: - - // \ru Конструктор. \en Constructor. - C3DExchangeBuffer() - : data( C3D_NULL_PTR ) - , count( 0 ) { - } - - // \ru Деструктор. \en Destructor. - ~C3DExchangeBuffer() { - Clear(); - } - - // \ru Очистить. \en Clear. - inline void Clear() { - delete[] data; - count = 0; - } - - // \ru Инициализировать буфер. \en Initialize buffer. - inline void Init( const char* init, size_t size ) { - Clear(); - data = new char[size]; - count = size; - ::memcpy( data, init, count ); - } - - // \ru Инициализировать буфер. \en Initialize buffer. - inline void Swap( char*& init, size_t& size ) { - std::swap( init, data ); - std::swap( size, count ); - } - - // \ru Получить адрес буфера. \en Get buffer address. - inline const char* Data() const { - return data; - } - - // \ru Получить число байт. \en Get count of bytes. - inline size_t Count() const { - return count; - } - }; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс конвертера. - \en Converter's interface. \~ - \details \ru Интерфейс конвертера реализует методы экспорта модели в файлы обменных форматов - и импорта из них. - \en Converter's interface implements methods of export of the model to files of exchange formats - and import from them. \~ -*/ -class IConvertor3D { -public: - virtual ~IConvertor3D() {} - -public: - /** \brief \ru Прочитать файл формата SAT. - \en Read a file of SAT format. \~ - \details \ru Прочитать файл формата SAT или указанный поток. - Если задан поток, то запись производится в присланный поток. - Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n - \en Read a file of SAT format or a specified stream. - If a stream is specified, then the record is performed to the given stream. - If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] stream - \ru Поток, из которого производится чтение (может быть NULL). - \en Stream from which reading is performed (can be NULL). \~ - \param[in] indicator - \ru Индикатор хода процесса (может быть NULL). - \en The process progress indicator (can be NULL). \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ACIS_Exchange - */ - virtual MbeConvResType SATRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, std::iostream * stream, IProgressIndicator * indicator, MbRefItem * qeuryStitch ) = 0; - - /** \brief \ru Записать файл формата SAT. - \en Write file of SAT format. \~ - \details \ru Записать файл формата SAT или указанный поток. - Если задан поток, то запись производится в присланный поток. - Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n - \en Write file of SAT format or the specified stream. - If a stream is specified, then the record is performed to the given stream. - If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] stream - \ru Поток, в который производится запись (может быть NULL). - \en Stream in which the record is performed (can be NULL). \~ - \param[in] indicator - \ru Индикатор хода процесса (может быть NULL). - \en The process progress indicator (can be NULL). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ACIS_Exchange - */ - virtual MbeConvResType SATWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, std::iostream * stream, IProgressIndicator * indicator ) = 0; - - /** \brief \ru Прочитать файл формата SAT. - \en Read a file of SAT format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ACIS_Exchange - */ - virtual MbeConvResType SATRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата SAT. - \en Write file of SAT format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ACIS_Exchange - */ - virtual MbeConvResType SATWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата IGES. - \en Read a file of IGES format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup IGES_Exchange - */ - virtual MbeConvResType IGSRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата IGES. - \en Write a file of IGES format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup IGES_Exchange - */ - virtual MbeConvResType IGSWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата JT. - \en Read a file of JT format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup IGES_Exchange - */ - virtual MbeConvResType JTRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата JT. - \en Write a file of JT format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup IGES_Exchange - */ - virtual MbeConvResType JTWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата Parasolid. - \en Read a file of Parasolid format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Parasolid_Exchange - */ - virtual MbeConvResType XTRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата Parasolid. - \en Write a file of Parasolid format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. - \en Dialog of request for stitching the surfaces. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Parasolid_Exchange - */ - virtual MbeConvResType XTWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата STEP. - \en Read a file of STEP format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup STEP_Exchange - */ - virtual MbeConvResType STEPRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата STEP. - \en Write a file of STEP format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup STEP_Exchange - */ - virtual MbeConvResType STEPWrite( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата STL. - \en Read a file of STL format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup STL_Exchange - */ - virtual MbeConvResType STLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата STL. - \en Write a file of STL format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup STL_Exchange - */ - virtual MbeConvResType STLWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата VRML. - \en Read a file of VRML format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup VRML_Exchange - */ - virtual MbeConvResType VRMLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата VRML. - \en Write a file of VRML format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \param[in] devSag - \ru Угловой шаг для расчёта триангуляционной сетки. - \en Deviate sag requiref for grid calculateion. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup VRML_Exchange - */ - virtual MbeConvResType VRMLWrite( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл формата GRDECL. - \en Read a file of GRDECL format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup VRML_Exchange - */ - virtual MbeConvResType GRDECLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл формата GRDECL. - \en Write a file of GRDECL format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup STL_Exchange - */ - virtual MbeConvResType GRDECLWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Прочитать файл с облаком точек в формате ASCII. - \en Read a file of ASCII Point Cloud format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType ASCIIPointCloudRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - /** \brief \ru Записать файл с облаком точек в формате ASCII.. - \en Write a point cloud file of ASCII format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). - \en Dialog of request for stitching the surfaces (not used). \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType ASCIIPointCloudWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0, MbRefItem * qeuryStitch = 0 ) = 0; - - - /** \brief \ru Загрузить плагин получения данных для построения модели. - \en Load plugin for getting information necessary to build model. \~ - \param[in] pluginName - \ru Имя подключаемого файла. - \en Name of the file to link. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName ) = 0; - - - /** \brief \ru Отключить загруженный плагин получения данных для построения модели. - \en Release the loaded plugin for getting information necessary to build model. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType ReleaseForeignReader() = 0; - - /** \brief \ru Прочитать файл с использованием плагина. - \en Read a file using plugin. \~ - \param[in] path - \ru ПУть к файлу, который нужно прочитать. - \en Path of the file to read. \~ - \param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup ASCII_Exchange - */ - virtual MbeConvResType ImportForeign( const c3d::path_string& path, ItModelDocument & idoc, IConvertorProperty3D * prop = 0, IProgressIndicator * indicator = 0 ) = 0; - -}; // IConvertor3D - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить интерфейс конвертера. - \en Get the converter interface. \~ -\ingroup Exchange_Interface -*/ -CONV_FUNC (IConvertor3D *) GetConvertor3D(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Освободить интерфейс конвертера. - \en Release the converter interface. \~ -\ingroup Exchange_Interface -*/ -CONV_FUNC( void ) ReleaseConvertor3D( IConvertor3D* ); - - -/** \brief \ru Прочитать файл формата SAT. - \en Read a file of SAT format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup ACIS_Exchange -*/ -CONV_FUNC (MbeConvResType ) SATRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator ); - -/** \brief \ru Записать файл формата SAT. - \en Write file of SAT format. \~ -\details \ru Записать файл формата SAT или указанный поток. - Если задан поток, то запись производится в присланный поток. - Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n - \en Write file of SAT format or the specified stream. - If a stream is specified, then the record is performed to the given stream. - If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса (может быть NULL). - \en The process progress indicator (can be NULL). \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup ACIS_Exchange -*/ -CONV_FUNC (MbeConvResType ) SATWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator ); -/** \brief \ru Прочитать файл формата IGES. - \en Read a file of IGES format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup IGES_Exchange -*/ -CONV_FUNC (MbeConvResType ) IGSRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата IGES. - \en Write a file of IGES format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup IGES_Exchange -*/ -CONV_FUNC (MbeConvResType ) IGSWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата JT. - \en Read a file of JT format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup IGES_Exchange -*/ -CONV_FUNC (MbeConvResType ) JTRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата JT. - \en Write a file of JT format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup IGES_Exchange -*/ -CONV_FUNC (MbeConvResType ) JTWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата Parasolid. - \en Read a file of Parasolid format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~\~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup Parasolid_Exchange -*/ -CONV_FUNC (MbeConvResType ) XTRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата Parasolid. - \en Write a file of Parasolid format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup Parasolid_Exchange -*/ -CONV_FUNC (MbeConvResType ) XTWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата STEP. - \en Read a file of STEP format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup STEP_Exchange -*/ -CONV_FUNC (MbeConvResType ) STEPRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата STEP. - \en Write a file of STEP format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup STEP_Exchange -*/ -CONV_FUNC (MbeConvResType ) STEPWrite( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата STL. - \en Read a file of STL format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup STL_Exchange -*/ -CONV_FUNC (MbeConvResType ) STLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата STL. - \en Write a file of STL format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup STL_Exchange -*/ -CONV_FUNC (MbeConvResType ) STLWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата VRML. - \en Read a file of VRML format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup VRML_Exchange -*/ -CONV_FUNC (MbeConvResType ) VRMLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Прочитать файл формата GRDECL. - \en Read a file of GRDECL format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup VRML_Exchange -*/ -CONV_FUNC (MbeConvResType ) GRDECLRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата GRDECL. - \en Write a file of GRDECL format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup STL_Exchange -*/ -CONV_FUNC (MbeConvResType ) GRDECLWrite ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - -/** \brief \ru Записать файл формата VRML. - \en Write a file of VRML format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup VRML_Exchange -*/ -CONV_FUNC (MbeConvResType ) VRMLWrite( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - - -/** \brief \ru Прочитать файл с облаком точек в формате ASCII. - \en Read a file of ASCII Point Cloud format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup ASCII_Exchange -*/ -CONV_FUNC (MbeConvResType ) ASCIIPointCloudRead ( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - - -/** \brief \ru Записать файл с облаком точек в формате ASCII.. - \en Write a point cloud file of ASCII format. \~ -\param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ -\param[in] idoc - \ru Реализация интерфейса документа. - \en Implementation of document interface. \~ -\param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ -\return \ru Код завершения операции. - \en Code of the operation termination. \~ -\ingroup ASCII_Exchange -*/ -CONV_FUNC (MbeConvResType ) ASCIIPointCloudWrite( IConvertorProperty3D & prop, ItModelDocument & idoc, IProgressIndicator * indicator = 0 ); - - -namespace c3d { - - /** \brief \ru Импортировать данные из буфера в модель. - \en Import data from buffer into model. \~ - \param[out] model - \ru Модель. - \en The model. \~ - \param[in] data - \ru Буфер. - \en Buffer. \~ - \param[in] length - \ru Размер буфера. - \en Buffer size. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - DEPRECATE_DECLARE CONV_FUNC (MbeConvResType) ImportFromBuffer( MbModel & model, - const char* data, - size_t length, - MbeModelExchangeFormat modelFormat, - IConvertorProperty3D * prop = 0, - IProgressIndicator * indicator = 0 ); - - /** \brief \ru Импортировать данные из буфера в модель. - \en Import data from buffer into model. \~ - \param[out] item - \ru Замещаемый элемент. - \en The item to replace. \~ - \param[in] data - \ru Буфер. - \en Buffer. \~ - \param[in] length - \ru Размер буфера. - \en Buffer size. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - DEPRECATE_DECLARE CONV_FUNC(MbeConvResType) ImportFromBuffer( c3d::ItemSPtr& item, - const char* data, - size_t length, - MbeModelExchangeFormat modelFormat, - IConvertorProperty3D* prop = NULL, IProgressIndicator* indicator = NULL); - - /** \brief \ru Экспортировать модель в буфер. - \en Export model into buffer. \~ - \param[in] model - \ru Модель. - \en The model. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[out] data - \ru Буфер. - \en Buffer. \~ - \param[out] length - \ru Размер буфера. - \en Buffer size. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - DEPRECATE_DECLARE CONV_FUNC (MbeConvResType) ExportIntoBuffer( MbModel & model, - MbeModelExchangeFormat modelFormat, - char*& data, - size_t& length, - IConvertorProperty3D * prop = 0, - IProgressIndicator * indicator = 0 ); - - - /** \brief \ru Экспортировать модель в буфер. - \en Export model into buffer. \~ - \param[in] item - \ru Экспортируемый элемент. - \en The item to export. \~ - \param[in] modelFormat - \ru Формат модели. - \en Model format. \~ - \param[out] data - \ru Буфер. - \en Buffer. \~ - \param[out] length - \ru Размер буфера. - \en Buffer size. \~ - \param[in] prop - \ru Реализация интерфейса свойств конвертера. - \en Implementation of converter's properties interface. \~ - \param[in] indicator - \ru Индикатор хода процесса. - \en The process progress indicator. \~ - \return \ru Код завершения операции. - \en Code of the operation termination. \~ - \ingroup Exchange_Interface - */ - DEPRECATE_DECLARE CONV_FUNC(MbeConvResType) ExportIntoBuffer( MbItem& item, MbeModelExchangeFormat modelFormat, - char*& data, - size_t& length, - IConvertorProperty3D* prop = NULL, IProgressIndicator* indicator = NULL); - -} - - -/** \} */ - - -#endif // __CONV_I_CONVERTER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Общий интерфейс конвертера. + \en Common API of the converter. \~ + \details \ru Функции чтения и записи в буфер и файл с автоопределением формата по + расширению файла, класс-конвертер с методами для каждого формата и возможностью + подключения плагина, функции для работы с каждым форматом. + \en Functions for export and import from buffer and file using file's extension + for format detection, class of converter for format-specific methods and API for + plugin, format-specific import and export functions. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_I_CONVERTER_H +#define __CONV_I_CONVERTER_H + +#include +#include +#include + +#include + +class IProgressIndicator; +struct IScaleRequestor; +class ItModelDocument; +class IConvertorProperty3D; + +/** + \addtogroup Exchange_Interface + \{ +*/ + +//------------------------------------------------------------------------------ +/** \brief \ru Обменный формат модели. +\en Model exchange format.\~ +\ingroup Data_Interface +*/ +// --- +enum MbeModelExchangeFormat { + mxf_autodetect, ///< \ru Интерпретировать содержимое по расширению файла. \en File extension defines format. + mxf_ACIS, ///< \ru Интерпретировать содержимое как ACIS (.sat). \en Read data from buffer as ACIS (.sat). + mxf_IGES, ///< \ru Интерпретировать содержимое как IGES (.igs или .iges). \en Read data from buffer as IGES (.igs or .iges). + mxf_JT, ///< \ru Интерпретировать содержимое как JT (.jt). \en Read data from buffer as JT (.jt). + mxf_Parasolid, ///< \ru Интерпретировать содержимое как Parasolid (.x_t, .x_b, .xmt_txt, .xmp_txt, .xmt_bin или .xmp_bin ). \en Read data from buffer as Parasolid (.x_t, .x_b, .xmt_txt, .xmp_txt, .xmt_bin or .xmp_bin ). + mxf_STEP, ///< \ru Интерпретировать содержимое как STEP (.stp или .step). \en Read data from buffer as STEP (.stp or .step). + mxf_STL, ///< \ru Интерпретировать содержимое как STL (.stl). \en Read data from buffer as STL (.stl). + mxf_VRML, ///< \ru Интерпретировать содержимое как VRML (.wrl). \en Read data from buffer as VRML (.wrl). + mxf_GRDECL, ///< \ru Интерпретировать содержимое как GRDECL (.grdecl). \en Read data from buffer as GRDECL (.grdecl). + mxf_ASCIIPoint, ///< \ru Интерпретировать содержимое как облако точек в ASCII (.txt, .asc или .xyz). \en Read data from buffer as ASCII point cloud (.txt, .asc or .xyz). + mxf_C3D, ///< \ru Интерпретировать содержимое как C3D (.c3d). \en Read data from buffer as C3D (.c3d). +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Результат конвертирования. +\en Result of converting operation. +\ingroup Data_Interface +*/ +// --- +enum MbeConvResType { + cnv_Success = 0, ///< \ru Успешное завершение. \en Success. + cnv_Error, ///< \ru Ошибка в процессе конвертирования. \en Error. + cnv_UserCanceled, ///< \ru Процесс прерван пользователем. \en Process interrupted by user. + cnv_NoBody, ///< \ru Не найдено тел. \en No solids found. + cnv_NoObjects, ///< \ru Не найдено объектов. \en No objects found. + cnv_FileOpenError, ///< \ru Ошибка открытия файла. \en File open error. + cnv_FileWriteError, ///< \ru Ошибка записи файла. \en File write error. + cnv_FileDeleteError, ///< \ru Ошибка удаления файла. \en Could not delete file. + cnv_ImpossibleReadAssembly,///< \ru Не поддерживает работу со сборками. \en Assemblies are not supported. + cnv_LicenseNotFound, ///< \ru Ошибка получения лицензии. \en License check failure. + cnv_NotEnoughMemory, ///< \ru Недостаточно памяти. \en Not enough memory. + cnv_UnknownExtension ///< \ru Неизвестное расширение файла. \en Unknown file extenstion. +}; + + +namespace c3d { + + class C3DExchangeBuffer; + + typedef std::map optionNameValuePairs_t; ///< \ru Набор имеованных значений опций. \en The container of named values of options. + + /** \brief \ru Прочитать файл обменного формата в модель. + \en Read a file of an exchange format into model. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. + \param[out] model - \ru Модель. + \en The model. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ImportFromFile( MbModel& model, + const path_string& fileName, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + /** \brief \ru Прочитать файл обменного формата в элемент. + \en Read a file of an exchange format into element. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. + \param[out] item - \ru Замещаемый элемент. + \en The element to replace. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ImportFromFile( c3d::ItemSPtr& item, + const path_string& filePath, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + /** \brief \ru Прочитать файл обменного формата в модель. + \en Read a file of an exchange format into model. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае импорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for import. + \param[out] mDoc - \ru Модельный документ. + \en The model. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ImportFromFile( ItModelDocument& mDoc, + const path_string& filePath, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + /** \brief \ru Записать модель в файл обменного формата. + \en Write the model into an exchange format file. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. + \param[out] model - \ru Модель. + \en The model. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoFile( MbModel& model, + const path_string& filePath, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + /** \brief \ru Записать модель в файл обменного формата. + \en Write the model into an exchange format file. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. + \param[out] model - \ru Экспортируемый лемент. + \en The exported element. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoFile( MbItem& item, + const path_string& filePath, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + /** \brief \ru Записать модельный документ в файл обменного формата. + \en Write the model into an exchange format file. \~ + \details \ru Если свойства конвертера заданы, аргумент fileName игнорируется, а имя файла берётся из свойств конвертера. + В противном случае экспорт идёт с умолчательными параметрами, соответствующими реализации ConvConvertorProperty3D. \~ + \en The fileName argument is not used if converter properties are defined obviously, file path comes from the FullFilePath + method. Otherwise default parameters corresponding ConvConvertorProperty3D implementation are used for export. + \param[in] mDoc - \ru Экспортируемый модельный документ. + \en The exported model document. \~ + \param[in] filePath - \ru Путь файла. + \en File path. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoFile( ItModelDocument& mDoc, + const path_string& filePath, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + /** \brief \ru Импортировать данные из буфера в модель. + \en Import data from buffer into model. \~ + \param[out] model - \ru Модель. + \en The model. \~ + \param[in] buffer - \ru Буфер. + \en Buffer. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ImportFromBuffer( MbModel& model, + const C3DExchangeBuffer& buffer, + MbeModelExchangeFormat modelFormat, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + /** \brief \ru Импортировать данные из буфера в модель. + \en Import data from buffer into model. \~ + \param[out] item - \ru Замещаемый элемент. + \en The item to replace. \~ + \param[in] buffer - \ru Буфер. + \en Buffer. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ImportFromBuffer( c3d::ItemSPtr& item, + const C3DExchangeBuffer& buffer, + MbeModelExchangeFormat modelFormat, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + /** \brief \ru Экспортировать модель в буфер. + \en Export model into buffer. \~ + \param[in] model - \ru Модель. + \en The model. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[out] buffer - \ru Буфер. + \en Buffer. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoBuffer( MbModel& model, + MbeModelExchangeFormat modelFormat, + C3DExchangeBuffer& buffer, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + /** \brief \ru Экспортировать модель в буфер. + \en Export model into buffer. \~ + \param[in] item - \ru Экспортируемый элемент. + \en The item to export. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[out] buffer - \ru Буфер. + \en Buffer. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + CONV_FUNC( MbeConvResType ) ExportIntoBuffer( MbItem& item, + MbeModelExchangeFormat modelFormat, + C3DExchangeBuffer& buffer, + IConvertorProperty3D* prop = c3d_null, + IProgressIndicator* indicator = c3d_null ); + + + //------------------------------------------------------------------------------ + /** \brief \ru Буфер для обмена. + \en Memory buffer for data exchange. \~ + \details \ru Обеспечивает обмен данными через оперативную память с контролем выделения и освобождения. + \en Prvides data exchange with memory allocation and deallocation control. \~ + \ingroup Exchange_Interface + */ + class C3DExchangeBuffer { + char* data; ///< \ru Адрес буфера. \en Buffer address. + size_t count; ///< \ru Число байт. \en Bytes count. + public: + + // \ru Конструктор. \en Constructor. + C3DExchangeBuffer() + : data( c3d_null ) + , count( 0 ) { + } + + // \ru Деструктор. \en Destructor. + ~C3DExchangeBuffer() { + Clear(); + } + + // \ru Очистить. \en Clear. + inline void Clear() { + delete[] data; + count = 0; + } + + // \ru Инициализировать буфер. \en Initialize buffer. + inline void Init( const char* init, size_t size ) { + Clear(); + data = new char[size]; + count = size; + ::memcpy( data, init, count ); + } + + // \ru Инициализировать буфер. \en Initialize buffer. + inline void Swap( char*& init, size_t& size ) { + std::swap( init, data ); + std::swap( size, count ); + } + + // \ru Получить адрес буфера. \en Get buffer address. + inline const char* Data() const { + return data; + } + + // \ru Получить число байт. \en Get count of bytes. + inline size_t Count() const { + return count; + } + }; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс конвертера. + \en Converter's interface. \~ + \details \ru Интерфейс конвертера реализует методы экспорта модели в файлы обменных форматов + и импорта из них. + \en Converter's interface implements methods of export of the model to files of exchange formats + and import from them. \~ +*/ +class IConvertor3D { +public: + virtual ~IConvertor3D() {} + +public: + /** \brief \ru Прочитать файл формата SAT. + \en Read a file of SAT format. \~ + \details \ru Прочитать файл формата SAT или указанный поток. + Если задан поток, то запись производится в присланный поток. + Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n + \en Read a file of SAT format or a specified stream. + If a stream is specified, then the record is performed to the given stream. + If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] stream - \ru Поток, из которого производится чтение (может быть c3d_null). + \en Stream from which reading is performed (can be c3d_null). \~ + \param[in] indicator - \ru Индикатор хода процесса (может быть c3d_null). + \en The process progress indicator (can be c3d_null). \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ACIS_Exchange + */ + virtual MbeConvResType SATRead( IConvertorProperty3D& prop, ItModelDocument& idoc, std::iostream* stream, IProgressIndicator* indicator, MbRefItem* qeuryStitch ) = 0; + + /** \brief \ru Записать файл формата SAT. + \en Write file of SAT format. \~ + \details \ru Записать файл формата SAT или указанный поток. + Если задан поток, то запись производится в присланный поток. + Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n + \en Write file of SAT format or the specified stream. + If a stream is specified, then the record is performed to the given stream. + If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] stream - \ru Поток, в который производится запись (может быть c3d_null). + \en Stream in which the record is performed (can be c3d_null). \~ + \param[in] indicator - \ru Индикатор хода процесса (может быть c3d_null). + \en The process progress indicator (can be c3d_null). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ACIS_Exchange + */ + virtual MbeConvResType SATWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, std::iostream* stream, IProgressIndicator* indicator ) = 0; + + /** \brief \ru Прочитать файл формата SAT. + \en Read a file of SAT format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ACIS_Exchange + */ + virtual MbeConvResType SATRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата SAT. + \en Write file of SAT format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ACIS_Exchange + */ + virtual MbeConvResType SATWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата IGES. + \en Read a file of IGES format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup IGES_Exchange + */ + virtual MbeConvResType IGSRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата IGES. + \en Write a file of IGES format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup IGES_Exchange + */ + virtual MbeConvResType IGSWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата JT. + \en Read a file of JT format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup IGES_Exchange + */ + virtual MbeConvResType JTRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата JT. + \en Write a file of JT format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup IGES_Exchange + */ + virtual MbeConvResType JTWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата Parasolid. + \en Read a file of Parasolid format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Parasolid_Exchange + */ + virtual MbeConvResType XTRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата Parasolid. + \en Write a file of Parasolid format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей. + \en Dialog of request for stitching the surfaces. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Parasolid_Exchange + */ + virtual MbeConvResType XTWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата STEP. + \en Read a file of STEP format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup STEP_Exchange + */ + virtual MbeConvResType STEPRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата STEP. + \en Write a file of STEP format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup STEP_Exchange + */ + virtual MbeConvResType STEPWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата STL. + \en Read a file of STL format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup STL_Exchange + */ + virtual MbeConvResType STLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата STL. + \en Write a file of STL format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup STL_Exchange + */ + virtual MbeConvResType STLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата VRML. + \en Read a file of VRML format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup VRML_Exchange + */ + virtual MbeConvResType VRMLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата VRML. + \en Write a file of VRML format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \param[in] devSag - \ru Угловой шаг для расчёта триангуляционной сетки. + \en Deviate sag requiref for grid calculateion. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup VRML_Exchange + */ + virtual MbeConvResType VRMLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл формата GRDECL. + \en Read a file of GRDECL format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup VRML_Exchange + */ + virtual MbeConvResType GRDECLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл формата GRDECL. + \en Write a file of GRDECL format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup STL_Exchange + */ + virtual MbeConvResType GRDECLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Прочитать файл с облаком точек в формате ASCII. + \en Read a file of ASCII Point Cloud format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType ASCIIPointCloudRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + /** \brief \ru Записать файл с облаком точек в формате ASCII.. + \en Write a point cloud file of ASCII format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \param[in] qeuryStitch - \ru Диалог запроса на сшивку поверхностей (не используется). + \en Dialog of request for stitching the surfaces (not used). \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType ASCIIPointCloudWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0, MbRefItem* qeuryStitch = 0 ) = 0; + + + /** \brief \ru Загрузить плагин получения данных для построения модели. + \en Load plugin for getting information necessary to build model. \~ + \note \ru Экспериментальное API. \en Expereimental API. \~ + \param[in] pluginName - \ru Имя подключаемого файла. + \en Name of the file to link. \~ + \param[in] thirdPartyLocation - \ru Расположение стороннего компонента, который подключается с помощью плагина. + \en Location of the third-party component linked by plugin. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName, const c3d::path_string& thirdPartyLocation = c3d::path_string() ) = 0; + + /** \brief \ru Загрузить плагин получения данных для построения модели. + \en Load plugin for getting information necessary to build model. \~ + \details \ru Описание специфичных для плагина настроек следует получить у поставщика комопонента. + \en The description of plugin-specific settings shoud be taken from the plugin's vendor. \~ + \note \ru Экспериментальное API. \en Expereimental API. \~ + \param[in] pluginName - \ru Имя подключаемого файла. + \en Name of the file to link. \~ + \param[in] pluginSpecificSettings - \ru Специфические для плагина настройки. + \en Plugin-specific settings. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType LoadForeignReader( const c3d::path_string& pluginName, const c3d::optionNameValuePairs_t& pluginSpecificSettings ) = 0; + + + /** \brief \ru Отключить загруженный плагин получения данных для построения модели. + \en Release the loaded plugin for getting information necessary to build model. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType ReleaseForeignReader() = 0; + + /** \brief \ru Прочитать файл с использованием плагина. + \en Read a file using plugin. \~ + \param[in] path - \ru ПУть к файлу, который нужно прочитать. + \en Path of the file to read. \~ + \param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup ASCII_Exchange + */ + virtual MbeConvResType ImportForeign( const c3d::path_string& path, ItModelDocument& idoc, IConvertorProperty3D* prop = 0, IProgressIndicator* indicator = 0 ) = 0; + +}; // IConvertor3D + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить интерфейс конвертера. + \en Get the converter interface. \~ +\ingroup Exchange_Interface +*/ +CONV_FUNC( IConvertor3D* ) GetConvertor3D(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Освободить интерфейс конвертера. + \en Release the converter interface. \~ +\ingroup Exchange_Interface +*/ +CONV_FUNC( void ) ReleaseConvertor3D( IConvertor3D* ); + + +/** \brief \ru Прочитать файл формата SAT. + \en Read a file of SAT format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup ACIS_Exchange +*/ +CONV_FUNC( MbeConvResType ) SATRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator ); + +/** \brief \ru Записать файл формата SAT. + \en Write file of SAT format. \~ +\details \ru Записать файл формата SAT или указанный поток. + Если задан поток, то запись производится в присланный поток. + Если поток не задан (нулевой), то открывается поток для файла, заданного в свойствах конвертера. \n + \en Write file of SAT format or the specified stream. + If a stream is specified, then the record is performed to the given stream. + If a stream is not specified (null), then a stream is being opened for file specified in the properties of the converter. \n \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса (может быть c3d_null). + \en The process progress indicator (can be c3d_null). \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup ACIS_Exchange +*/ +CONV_FUNC( MbeConvResType ) SATWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator ); +/** \brief \ru Прочитать файл формата IGES. + \en Read a file of IGES format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup IGES_Exchange +*/ +CONV_FUNC( MbeConvResType ) IGSRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата IGES. + \en Write a file of IGES format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup IGES_Exchange +*/ +CONV_FUNC( MbeConvResType ) IGSWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата JT. + \en Read a file of JT format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup IGES_Exchange +*/ +CONV_FUNC( MbeConvResType ) JTRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата JT. + \en Write a file of JT format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup IGES_Exchange +*/ +CONV_FUNC( MbeConvResType ) JTWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата Parasolid. + \en Read a file of Parasolid format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~\~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup Parasolid_Exchange +*/ +CONV_FUNC( MbeConvResType ) XTRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата Parasolid. + \en Write a file of Parasolid format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup Parasolid_Exchange +*/ +CONV_FUNC( MbeConvResType ) XTWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата STEP. + \en Read a file of STEP format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup STEP_Exchange +*/ +CONV_FUNC( MbeConvResType ) STEPRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата STEP. + \en Write a file of STEP format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup STEP_Exchange +*/ +CONV_FUNC( MbeConvResType ) STEPWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата STL. + \en Read a file of STL format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup STL_Exchange +*/ +CONV_FUNC( MbeConvResType ) STLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата STL. + \en Write a file of STL format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup STL_Exchange +*/ +CONV_FUNC( MbeConvResType ) STLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата VRML. + \en Read a file of VRML format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup VRML_Exchange +*/ +CONV_FUNC( MbeConvResType ) VRMLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Прочитать файл формата GRDECL. + \en Read a file of GRDECL format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup VRML_Exchange +*/ +CONV_FUNC( MbeConvResType ) GRDECLRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата GRDECL. + \en Write a file of GRDECL format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup STL_Exchange +*/ +CONV_FUNC( MbeConvResType ) GRDECLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + +/** \brief \ru Записать файл формата VRML. + \en Write a file of VRML format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup VRML_Exchange +*/ +CONV_FUNC( MbeConvResType ) VRMLWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + + +/** \brief \ru Прочитать файл с облаком точек в формате ASCII. + \en Read a file of ASCII Point Cloud format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup ASCII_Exchange +*/ +CONV_FUNC( MbeConvResType ) ASCIIPointCloudRead( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + + +/** \brief \ru Записать файл с облаком точек в формате ASCII.. + \en Write a point cloud file of ASCII format. \~ +\param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ +\param[in] idoc - \ru Реализация интерфейса документа. + \en Implementation of document interface. \~ +\param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ +\return \ru Код завершения операции. + \en Code of the operation termination. \~ +\ingroup ASCII_Exchange +*/ +CONV_FUNC( MbeConvResType ) ASCIIPointCloudWrite( IConvertorProperty3D& prop, ItModelDocument& idoc, IProgressIndicator* indicator = 0 ); + + +namespace c3d { + + /** \brief \ru Импортировать данные из буфера в модель. + \en Import data from buffer into model. \~ + \param[out] model - \ru Модель. + \en The model. \~ + \param[in] data - \ru Буфер. + \en Buffer. \~ + \param[in] length - \ru Размер буфера. + \en Buffer size. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + DEPRECATE_DECLARE CONV_FUNC( MbeConvResType ) ImportFromBuffer( MbModel& model, + const char* data, + size_t length, + MbeModelExchangeFormat modelFormat, + IConvertorProperty3D* prop = 0, + IProgressIndicator* indicator = 0 ); + + /** \brief \ru Импортировать данные из буфера в модель. + \en Import data from buffer into model. \~ + \param[out] item - \ru Замещаемый элемент. + \en The item to replace. \~ + \param[in] data - \ru Буфер. + \en Buffer. \~ + \param[in] length - \ru Размер буфера. + \en Buffer size. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + DEPRECATE_DECLARE CONV_FUNC( MbeConvResType ) ImportFromBuffer( c3d::ItemSPtr& item, + const char* data, + size_t length, + MbeModelExchangeFormat modelFormat, + IConvertorProperty3D* prop = c3d_null, IProgressIndicator* indicator = c3d_null ); + + /** \brief \ru Экспортировать модель в буфер. + \en Export model into buffer. \~ + \param[in] model - \ru Модель. + \en The model. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[out] data - \ru Буфер. + \en Buffer. \~ + \param[out] length - \ru Размер буфера. + \en Buffer size. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + DEPRECATE_DECLARE CONV_FUNC( MbeConvResType ) ExportIntoBuffer( MbModel& model, + MbeModelExchangeFormat modelFormat, + char*& data, + size_t& length, + IConvertorProperty3D* prop = 0, + IProgressIndicator* indicator = 0 ); + + + /** \brief \ru Экспортировать модель в буфер. + \en Export model into buffer. \~ + \param[in] item - \ru Экспортируемый элемент. + \en The item to export. \~ + \param[in] modelFormat - \ru Формат модели. + \en Model format. \~ + \param[out] data - \ru Буфер. + \en Buffer. \~ + \param[out] length - \ru Размер буфера. + \en Buffer size. \~ + \param[in] prop - \ru Реализация интерфейса свойств конвертера. + \en Implementation of converter's properties interface. \~ + \param[in] indicator - \ru Индикатор хода процесса. + \en The process progress indicator. \~ + \return \ru Код завершения операции. + \en Code of the operation termination. \~ + \ingroup Exchange_Interface + */ + DEPRECATE_DECLARE CONV_FUNC( MbeConvResType ) ExportIntoBuffer( MbItem& item, MbeModelExchangeFormat modelFormat, + char*& data, + size_t& length, + IConvertorProperty3D* prop = c3d_null, IProgressIndicator* indicator = c3d_null ); + +} + + +/** \} */ + + +#endif // __CONV_I_CONVERTER_H diff --git a/C3d/Include/conv_plugin_import.h b/C3d/Include/conv_plugin_import.h new file mode 100644 index 0000000..c3045ff --- /dev/null +++ b/C3d/Include/conv_plugin_import.h @@ -0,0 +1,827 @@ +//////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief \ru API для передачи моделей, прочитанных сторонним модулем. +\en API for models read by 3d party component.\~ +\details \ru Определен интерфейс, который должен реализовать модуль и структуры +для передачи информации о модели, топологии, геометрии. +\en Declared API the module has to implement and structures for structure, +topology and geomentry transmission.\~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_PUGIN_IMPORT_H +#define __CONV_PUGIN_IMPORT_H + +#include + +//////////////////////////////////////////////////////////////////////////////// +// +// Dynamic-link library API +// +//////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------ +/** \brief \ru Имена функций инициализации и завершения работы плагина. + \en Initialize and release functions of plugin.\~ +\ingroup Data_Interface +*/ +// --- +#define C3D_PLUGIN_INIT_SOURCE InitSource +#define C3D_PLUGIN_C_SET_PLUGIN_OPTION CSetPluginOption +#define C3D_PLUGIN_W_SET_PLUGIN_OPTION WSetPluginOption +#define C3D_PLUGIN_RELEASE_SOURCE ReleaseSource + +//------------------------------------------------------------------------------ +/** \brief \ru Имена функций инициализации и завершения работы плагина. + \en Initialize and release functions of plugin.\~ +\ingroup Data_Interface +*/ +// --- +#define C3D_PLUGIN_INIT_SOURCE_NAME "InitSource" +#define C3D_PLUGIN_C_SET_PLUGIN_OPTION_NAME "CSetPluginOption" +#define C3D_PLUGIN_W_SET_PLUGIN_OPTION_NAME "WSetPluginOption" +#define C3D_PLUGIN_RELEASE_SOURCE_NAME "ReleaseSource" + + +struct ObModelSource; + + +//------------------------------------------------------------------------------ +/** \brief \ru Объявление функций инициализации и завершения работы плагина. + \en Declare initialize and release functions of plugin.\~ +\ingroup Data_Interface +*/ +// --- +#ifdef WIN32 +#define C3D_PLUGIN_INIT_EXPORT_DECLARE extern "C" __declspec( dllexport ) ObModelSource* _cdecl C3D_PLUGIN_INIT_SOURCE ( const char*, const char* ); +#define C3D_PLUGIN_C_SET_PLUGIN_OPTION_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_C_SET_PLUGIN_OPTION ( const char*, const char* ); +#define C3D_PLUGIN_W_SET_PLUGIN_OPTION_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_W_SET_PLUGIN_OPTION ( const wchar_t*, const wchar_t* ); +#define C3D_PLUGIN_RELEASE_EXPORT_DECLARE extern "C" __declspec( dllexport ) void _cdecl C3D_PLUGIN_RELEASE_SOURCE ( ObModelSource* ); +#else +#define C3D_PLUGIN_INIT_EXPORT_DECLARE ObModelSource* C3D_PLUGIN_INIT_SOURCE ( const char*, const char* ); +#define C3D_PLUGIN_C_SET_PLUGIN_OPTION_DECLARE void C3D_PLUGIN_C_SET_PLUGIN_OPTION ( const char*, const char* ); +#define C3D_PLUGIN_W_SET_PLUGIN_OPTION_DECLARE void C3D_PLUGIN_W_SET_PLUGIN_OPTION ( const wchar_t*, const wchar_t* ); +#define C3D_PLUGIN_RELEASE_EXPORT_DECLARE void C3D_PLUGIN_RELEASE_SOURCE ( ObModelSource* ); +#endif // WIN32 + + +//------------------------------------------------------------------------------ +/** \brief \ru Объявление типа функций инициализации и завершения работы плагина. + \en Declare types of initialize and release functions of plugin.\~ +\ingroup Data_Interface +*/ +// --- +#ifdef WIN32 +typedef ObModelSource* ( _cdecl* C3D_PLUGIN_INIT_SOURCE_CALL ) ( const char*, const char* ); +typedef void ( _cdecl* C3D_PLUGIN_C_SET_OPTION_CALL ) ( const char*, const char* ); +typedef void ( _cdecl* C3D_PLUGIN_W_SET_OPTION_CALL ) ( const wchar_t*, const wchar_t* ); +typedef void ( _cdecl* C3D_PLUGIN_RELEASE_SOURCE_CALL )( ObModelSource* ); +#else +typedef ObModelSource* ( * C3D_PLUGIN_INIT_SOURCE_CALL ) ( const char*, const char* ); +typedef void ( * C3D_PLUGIN_C_SET_OPTION_CALL ) ( const char*, const char* ); +typedef void ( * C3D_PLUGIN_W_SET_OPTION_CALL ) ( const wchar_t*, const wchar_t* ); +typedef void ( * C3D_PLUGIN_RELEASE_SOURCE_CALL ) ( ObModelSource* ); +#endif // WIN32 + + +//////////////////////////////////////////////////////////////////////////////// +// +// Plugin types +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Объявление булевых значений. +\en Declare boolean values.\~ +\ingroup Data_Interface +*/ +// --- +#define C3D_PLUGIN_BOOL int +#define C3D_PLUGIN_TRUE 1 +#define C3D_PLUGIN_FALSE 0 + +//#define C3D_SYMBOL_COMPOSITE_TEXT 3 +#define C3D_SYMBOL_TEXT_LINE 0 +//#define C3D_SYMBOL_PRREDEFINED 1 + +#define C3D_SYMBOL_ARC_LENGTH 1 +#define C3D_SYMBOL_CONICAL_TAPER 2 +#define C3D_SYMBOL_COUNTERBORE 3 +#define C3D_SYMBOL_COUNTERSINK 4 +#define C3D_SYMBOL_DEPTH 5 +#define C3D_SYMBOL_DIAMETER 6 +#define C3D_SYMBOL_PLUS_MINUS 7 +#define C3D_SYMBOL_SLOPE 8 +#define C3D_SYMBOL_SPHERICAL_DIAMETER 9 +#define C3D_SYMBOL_SPHERICAL_RADIUS 10 +#define C3D_SYMBOL_SQUARE 11 +#define C3D_SYMBOL_ANGULARITY 12 +#define C3D_SYMBOL_CIRCULAR_RUNOUT 13 +#define C3D_SYMBOL_CIRCULARITY 14 +#define C3D_SYMBOL_CONCENTRICITY 15 +#define C3D_SYMBOL_CYLINDRICITY 16 +#define C3D_SYMBOL_FLATNESS 17 +#define C3D_SYMBOL_PARALLELISM 18 +#define C3D_SYMBOL_PERPENDICULARITY 19 +#define C3D_SYMBOL_POSITION 20 +#define C3D_SYMBOL_LINE_PROFILE 21 +#define C3D_SYMBOL_SURFACE_PROFILE 22 +#define C3D_SYMBOL_STRAIGHTNESS 23 +#define C3D_SYMBOL_SYMMETRY 24 +#define C3D_SYMBOL_TOTAL_RUNOUT 25 + + +#define C3D_CALLOUT_GENERAL 0 +#define C3D_CALLOUT_DIMENSION 1 +#define C3D_CALLOUT_PROJECTION 2 + + +#define C3D_TERMINATOR_EMPTY 0 +#define C3D_TERMINATOR_BLANKED_ARROW 1 +#define C3D_TERMINATOR_BLANKED_BOX 2 +#define C3D_TERMINATOR_BLANKED_DOT 3 +#define C3D_TERMINATOR_DIMENSION_ORIGIN 4 +#define C3D_TERMINATOR_FILLED_ARROW 5 +#define C3D_TERMINATOR_FILLED_BOX 6 +#define C3D_TERMINATOR_FILLED_DOT 7 +#define C3D_TERMINATOR_INTEGRAL_SYMBOL 8 +#define C3D_TERMINATOR_OPEN_ARROW 9 +#define C3D_TERMINATOR_SLASH 10 +#define C3D_TERMINATOR_UNFILLED_ARROW 11 + + +#define C3D_DIMENSION_GENERAL 0 +#define C3D_DIMENSION_LINEAR 1 +#define C3D_DIMENSION_ANGULAR 2 + + + +//////////////////////////////////////////////////////////////////////////////// +// +// Curves +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Примитив трехмерного пространства (точка либо вектор). + \en Spatial primitive (point or vector).\~ +\ingroup Data_Interface +*/ +// --- +struct ObPrimitive3D { + double x, y, z; + + ObPrimitive3D() + : x( 0.0 ), y( 0.0 ), z( 0.0 ) + {} +}; + + +//------------------------------------------------------------------------------ +// Инициализировать примитив +// --- +inline void SetObPrimitiveZero( ObPrimitive3D& ob ) { + ob.x = ob.y = ob.z = 0.0; +} + + +//------------------------------------------------------------------------------ +// Инициализировать примитив +// --- +inline bool IsObPrimitiveZero( const ObPrimitive3D& ob ) { + return (ob.x == 0.0) && (ob.y == 0.0) && (ob.z == 0.0); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Локальная система координат в трехмерном пространстве. + \en Spatial placement.\~ +\ingroup Data_Interface +*/ +// --- +struct ObLocation3D { + ObPrimitive3D origin, axisX, axisY, axisZ; + + ObLocation3D() + : origin(), axisX(), axisY(), axisZ() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Одномерный диапазон. + \en One dimensional range.\~ +\ingroup Data_Interface +*/ +// --- +struct ObRange1D { + double start, end; + + ObRange1D() + : start( 0.0 ), end( 0.0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерный отрезок. + \en Spatial line segment.\~ +\ingroup Data_Interface +*/ +// --- +struct ObSegment3D { + static const int CurveType = 1; + ObRange1D domain; + ObPrimitive3D start, end; + + ObSegment3D() + : domain(), start(), end() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерная полилиния. + \en Spatial polyline.\~ +\ingroup Data_Interface +*/ +// --- +struct ObPolyline3D { + static const int CurveType = 2; + int pointsArrayId; + + ObPolyline3D() + : pointsArrayId( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерная дуга. + \en Spatial arc.\~ +\ingroup Data_Interface +*/ +// --- +struct ObArc3D { + static const int CurveType = 3; + ObLocation3D location; + double majorAxis, minorAxis; + ObRange1D domain; + + ObArc3D() + : location(), majorAxis( 0.0 ), minorAxis( 0.0 ), domain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерная парабола. + \en Spatial parabola.\~ +\ingroup Data_Interface +*/ +// --- +struct ObParabola3D { + static const int CurveType = 4; + ObLocation3D location; + double focalLength; + ObRange1D domain; + + ObParabola3D() + : location(), focalLength( 0.0 ), domain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерная дуга. + \en Spatial arc.\~ +\ingroup Data_Interface +*/ +// --- +struct ObHyperbola3D { + static const int CurveType = 5; + ObLocation3D location; + double majorSemiAxis, minorSemiAxis; + ObRange1D domain; + + ObHyperbola3D() + : location(), majorSemiAxis( 0.0 ), minorSemiAxis( 0.0 ), domain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерный сплайн. + \en Spatial spline.\~ +\ingroup Data_Interface +*/ +// --- +struct ObSplineCurve3D { + static const int CurveType = 6; + int knotsId, vertcisId; + int degree; + int closed; + + ObSplineCurve3D() + : knotsId( 0 ), vertcisId( 0 ), degree( 0 ), closed( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерный NURBS. + \en Spatial NURBS.\~ +\ingroup Data_Interface +*/ +// --- +struct ObNURBSCurve3D { + static const int CurveType = 7; + int knotsId, vertcisId, weightsId; + int degree; + C3D_PLUGIN_BOOL closed; + ObRange1D domain; + + ObNURBSCurve3D() + : knotsId( 0 ), vertcisId( 0 ), weightsId( 0 ), degree( 0 ), closed( 0 ), domain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерная составная кривая. + \en Spatial composite curve.\~ +\ingroup Data_Interface +*/ +// --- +struct ObCompositeCurve3D { + static const int CurveType = 8; + int segmentsArrIndicis; + + ObCompositeCurve3D() + : segmentsArrIndicis( 0 ) + {} +}; + + +//////////////////////////////////////////////////////////////////////////////// +// +// Surfaces +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Плоскость. + \en Plane.\~ +\ingroup Data_Interface +*/ +// --- +struct ObPlane { + static const int SurfaceType = 1; + ObLocation3D location; + ObRange1D uDomain, vDomain; + + ObPlane() + : location(), uDomain(), vDomain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Цилиндрическая поверхность. + \en Cylinder surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObCylinder { + static const int SurfaceType = 2; + ObLocation3D location; + double r, h; + ObRange1D uDomain, vDomain; + + ObCylinder() + : location(), r( 0.0 ), h( 0.0 ), uDomain(), vDomain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Коническая поверхность. + \en Cone surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObCone { + static const int SurfaceType = 3; + ObLocation3D location; + double r, h, halfAngle; + ObRange1D uDomain, vDomain; + + ObCone() + : location(), r( 0.0 ), h( 0.0 ), halfAngle( 0.0 ), uDomain(), vDomain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Сферическая поверхность. + \en Sphere surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObSphere { + static const int SurfaceType = 4; + ObLocation3D location; + double r; + ObRange1D uDomain, vDomain; + + ObSphere() + : location(), r( 0.0 ), uDomain(), vDomain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Тороидальная поверхность. + \en Torus surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObTorus { + static const int SurfaceType = 5; + ObLocation3D location; + double rMin, rMax; + ObRange1D uDomain, vDomain; + + ObTorus() + : location(), rMin( 0.0 ), rMax( 0.0 ), uDomain(), vDomain() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность выдавливания. + \en Extrusion surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObExtrusion { + static const int SurfaceType = 6; + int curve; + ObPrimitive3D direction; + + ObExtrusion() + : curve( 0 ), direction() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность вращения. + \en Revolution surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObRevolution { + static const int SurfaceType = 7; + int curveId; + ObPrimitive3D axisOrigin, axisDirection; + ObRange1D vRange; + + ObRevolution() + : curveId( 0 ), axisOrigin(), axisDirection(), vRange() + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Линейчатая поверхность. + \en Ruled surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObRuled { + static const int SurfaceType = 8; + int curve1, curve2; + + ObRuled() + : curve1( 0 ), curve2( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Сплайновая поверхность. + \en Spline surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObSplineSurface { + static const int SurfaceType = 9; + int knotsUId, knotsVId, verticisListId; + int degreeU, degreeV; + int closedU, closedV; + + ObSplineSurface() + : knotsUId( 0 ), knotsVId( 0 ), verticisListId( 0 ), degreeU( 0 ), degreeV( 0 ), closedU( 0 ), closedV( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Сплайновая поверхность. + \en Spline surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObNURBSSurface { + static const int SurfaceType = 10; + int knotsUId, knotsVId, verticisListListId, weightsListListId; + int degreeU, degreeV; + C3D_PLUGIN_BOOL closedU, closedV; + + ObNURBSSurface() + : knotsUId( 0 ), knotsVId( 0 ), verticisListListId( 0 ), weightsListListId( 0 ), degreeU( 0 ), degreeV( 0 ), closedU( 0 ), closedV( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Смещённая поверхность. + \en Offset surface.\~ +\ingroup Data_Interface +*/ +// --- +struct ObOffsetSurface { + static const int SurfaceType = 11; + int baseSurface; + double offset; + + ObOffsetSurface() + : baseSurface( 0 ), offset( 0.0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Цвет. + \en Colour.\~ +\ingroup Data_Interface +*/ +// --- +struct ObColour { + double red, green, blue; + + ObColour() + : red( 0.0 ), green( 0.0 ), blue( 0.0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Неопределённый компонент цвета. + \en Undefined component of colour.\~ +\ingroup Data_Interface +*/ +// --- +const double ObUndefinedColourComponent = -1.0; + + +//------------------------------------------------------------------------------ +/** \brief \ru Элемент аннотации. + \en PMI item.\~ +\ingroup Data_Interface +*/ +// --- +struct ObPMI { + ObLocation3D location; + int visualArray; + int textBlockIdArray; + + ObPMI() + : location(), visualArray( 0 ), textBlockIdArray( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Элемент текста. + \en Text item.\~ +\ingroup Data_Interface +*/ +// --- +struct ObTextBlock { + double originX, originY; + double dirX, dirY; + double extentX, extentY; + + ObTextBlock() + : originX( 0.0 ), originY( 0.0 ), dirX( 0.0 ), dirY( 0.0 ), extentX( 0.0 ), extentY( 0.0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Размер. + \en Dimension.\~ +\ingroup Data_Interface +*/ +// --- +struct ObDimension { + double value; + double deviationMin, deviationMax; + int type; + int calloutArrId; + + ObDimension() + : value( 0.0 ), deviationMin( 0.0 ), deviationMax( 0.0 ), type( 0 ), calloutArrId( 0 ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Особая линия. + \en Special line.\~ +\ingroup Data_Interface +*/ +// --- +struct ObPMICallout { + int type; + //int geometry; + ObPrimitive3D head, tail; + bool isArc; + ObPrimitive3D center; + int terminatorHead; + int terminatorTail; + + ObPMICallout() + : type( 0 ), head(), tail(), isArc( false ), center(), terminatorHead( 0 ), terminatorTail( 0 ) + {} +}; + + +//////////////////////////////////////////////////////////////////////////////// +// +// Model source plugin. Basic interface. +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Источник данных модели. + \en Model source.\~ +\ingroup Data_Interface +*/ +// --- +struct ObModelSource { + + virtual ~ObModelSource() {}; + + virtual C3D_PLUGIN_BOOL LastOperationSuccess() = 0; + + // Операции с файлом + virtual C3D_PLUGIN_BOOL IsPathWCS() = 0; + virtual C3D_PLUGIN_BOOL Open( const char* ) = 0; + virtual C3D_PLUGIN_BOOL Open( const wchar_t* ) = 0; + virtual void Close() = 0; + + // Значение неопределённого идентификатора. + virtual int UndefinedId() = 0; + + // Управление трассировкой событий + virtual void EnableLog() = 0; + virtual void DisableLog() = 0; + + // Контейнеры + + virtual unsigned int ArrayCount ( int arrayId ) = 0; + virtual int ArrayIdentifier ( int arrayId, unsigned int index ) = 0; + virtual double ArrayFloat ( int arrayId, unsigned int index ) = 0; + virtual ObPrimitive3D ArrayPrimitive ( int arrayId, unsigned int index ) = 0; + + virtual ObColour ItemColour( int itemId ) = 0; + + // Модель + virtual int ModelPart() = 0; + + virtual unsigned int PartInstanceCount( int partId ) = 0; + virtual int PartInstance( int partId, unsigned int inst ) = 0; + + virtual const wchar_t* WPartName( int partId ) = 0; + virtual const wchar_t* WPartLabel( int partId ) = 0; + virtual const wchar_t* WPartAuthor( int partId ) = 0; + virtual const wchar_t* WPartOrganization( int partId ) = 0; + virtual const wchar_t* WPartDescription( int partId ) = 0; + + virtual const char* CPartName( int partId ) = 0; + virtual const char* CPartLabel( int partId ) = 0; + virtual const char* CPartAuthor( int partId ) = 0; + virtual const char* CPartOrganization( int partId ) = 0; + virtual const char* CPartDescription( int partId ) = 0; + + virtual int InstancePart( int instanceId ) = 0; + virtual ObLocation3D InstanceLocation( int instanceId ) = 0; + + virtual unsigned int SolidsCount( int partId ) = 0; + + // Топология граничного представления + virtual int Solid( int partId, unsigned int solid ) = 0; + virtual ObLocation3D SolidLocation( int solidId ) = 0; + + virtual unsigned int SpaceCurvesCount( int partId ) = 0; + virtual int SpaceCurve( int partId, unsigned int curve ) = 0; + + virtual unsigned int ShellsCount( int solidId ) = 0; + virtual int Shell( int solid, unsigned int shell ) = 0; + + virtual C3D_PLUGIN_BOOL ShellClosed( int shellId ) = 0; + virtual unsigned int ShellFacesCount( int shellId ) = 0; + virtual int ShellFace( int shellId, unsigned int face ) = 0; + + virtual unsigned int FaceBoundsCount( int faceId ) = 0; + virtual int FaceBound( int faceId, unsigned int bound ) = 0; + virtual C3D_PLUGIN_BOOL FaceSurfaceSameOriented( int faceId ) = 0; + + virtual int BoundType( int boundId ) = 0; + virtual unsigned int BoundCoedgesCount( int boundId ) = 0; + virtual int BoundCoedge( int boundId, unsigned int coedge ) = 0; + + virtual int CoedgeEdge( int coedgeId ) = 0; + virtual C3D_PLUGIN_BOOL CoedgeEdgeSameOriented( int coedgeId ) = 0; + + virtual int EdgeStartVertex( int edgeId ) = 0; + virtual int EdgeEndVertex( int edgeId ) = 0; + + // Методы получения геометрии + + virtual int FaceGeometry( int faceId ) = 0; + virtual int EdgeGeometry( int edgeId ) = 0; + virtual ObPrimitive3D VertexGeometry( int vertexId ) = 0; + + // Типы геометрических объектов + + virtual int SurfaceType( int surfaceId ) = 0; + virtual int Curve3DType( int curveId ) = 0; + + // Данные геометрии + + // Пространственные кривые + + virtual ObSegment3D LineSegment3D( int curveId ) = 0; + virtual ObPolyline3D Polyline3D( int curveId ) = 0; + virtual ObArc3D Arc3D( int curveId ) = 0; + virtual ObParabola3D Parabola3D( int curveId ) = 0; + virtual ObHyperbola3D Hyperbola3D( int curveId ) = 0; + virtual ObSplineCurve3D SplineCurve3D( int curveId ) = 0; + virtual ObNURBSCurve3D NURBSCurve3D( int curveId ) = 0; + virtual ObCompositeCurve3D CompositeCurve3D( int curveId ) = 0; + + virtual unsigned int CompositeCurveSegmentsCount( int curveId ) = 0; + virtual int CompositeCurveSegment( int curveId, unsigned int index ) = 0; + virtual C3D_PLUGIN_BOOL CompositeCurveSegmentsSameOriented( int curveId, unsigned int index ) = 0; + + // Поверхности + + virtual ObPlane Plane( int surfaceId ) = 0; + virtual ObCylinder Cylinder( int surfaceId ) = 0; + virtual ObCone Cone( int surfaceId ) = 0; + virtual ObSphere Sphere( int surfaceId ) = 0; + virtual ObTorus Torus( int surfaceId ) = 0; + virtual ObExtrusion Extrusion( int surfaceId ) = 0; + virtual ObRevolution Revolution( int surfaceId ) = 0; + virtual ObRuled Ruled( int surfaceId ) = 0; + virtual ObSplineSurface SplineSurface( int surfaceId ) = 0; + virtual ObNURBSSurface NURBSSurface( int surfaceId ) = 0; + virtual ObOffsetSurface OffsetSurface( int surfaceId ) = 0; + + virtual unsigned int PartPMICount( int partIdId ) = 0; + virtual int PartPMI( int partId, unsigned int index ) = 0; + virtual ObPMI PMI( int pmiId ) = 0; + + virtual bool IsDimension( int pmiId ) = 0; + virtual bool Dimension( int pmiId, ObDimension& dim ) = 0; + + virtual ObPMICallout PMICallout( int calloutId ) = 0; + + virtual unsigned int PMITextCount( int textId ) = 0; + virtual int PMIText( int textId, unsigned int index ) = 0; + + virtual int PMITextType( int textBlockId ) = 0; + virtual ObTextBlock PMITextLocation( int textBlockId ) = 0; + virtual int PMITextSymbol( int textBlockId ) = 0; + virtual const wchar_t* WPMIText( int textId ) = 0; + virtual const char* CPMIText( int textBlockId ) = 0; + virtual unsigned int CompositeTextCount( int textId ) = 0; + virtual int CompositeText( int textId, unsigned int index ) = 0; + + virtual unsigned int PMICalloutCount( int pmiId ) = 0; + virtual ObPMICallout PMICallout( int pmiId, unsigned int index ) = 0; + +}; + + +#endif // __CONV_PUGIN_IMPORT_H + diff --git a/C3d/Include/conv_predefined.h b/C3d/Include/conv_predefined.h index bec7f66..f218121 100644 --- a/C3d/Include/conv_predefined.h +++ b/C3d/Include/conv_predefined.h @@ -1,151 +1,151 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Перечисления, используемые при импорте и экспорте. - \en Enumerations for import/export operations.\~ - \details \ru Определены перечисления, определяющие результат конвертирования, - разрешение на чтение и запись различных объектов и передаваемых черезх конвертер строк. - \en Converting result, objects and properties filters, special strings - of enumerations are defined.\~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_ERROR_RESULT_H -#define __CONV_ERROR_RESULT_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Представление текста при экспорте. -\en Representation of exported text.\~ -\ingroup Data_Exchange -*/ -// --- -enum eTextForm { - exf_TextOnly, ///< \ru Только текст. \en Text only. - exf_GeometryOnly, ///< \ru Только геометрия. \en Geometry only. -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Предопределённые ключи атрибутов для передачи контрольных параметров. -\en Predefined key of attributes used for validation properties' exchange.\~ -\ingroup Data_Interface -*/ -// --- -/// \ru Объём. \en Volume. -#define C3D_CAD_VALIDATION_PROPERTY_VOLUME c3d::c3dStr_ValidationPropertyVolumeExchange -/// \ru Площать поверхости. \en Surface area. -#define C3D_CAD_VALIDATION_PROPERTY_AREA c3d::c3dStr_ValidationPropertySurfaceAreaExchange -/// \ru Масса. \en Mass. -#define C3D_CAD_VALIDATION_PROPERTY_MASS c3d::c3dStr_ValidationPropertyMassExchange -/// \ru Идентификатор элемента. \en Item Identifier. -#define C3D_CAD_ITEM_IDENTIFIER c3d::c3dStr_ItemIdentifierExchange - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы линий, передаваемых через конвертер. -\en Types of lines passed via converter. \~ -\ingroup Data_Interface -*/ -// --- -enum MbeLineFontPattern { - lfp_BEGIN = 0, ///< \ru Для удобства перебора. \en For the convenient search. - lfp_STEPcontinuous, ///< \ru Непрерывная в конвертерах STEP и IGES. \en Continuous line in STEP and IGES (Solid) converters. - lfp_STEPchain, ///< \ru Штрих-пунктирная в конвертерах STEP и IGES. \en Chain line( dash-dotted) in STEP and IGES converters. - lfp_STEPchainDoubleDash, ///< \ru Штриховая с двумя пунктирами в конвертерах STEP и IGES. \en Dash-double-dot line in STEP and IGES (Phantom) converter. - lfp_STEPdashed, ///< \ru Штриховая в конвертерах STEP и IGES. \en Dash line in STEP and IGES converters. - lfp_STEPdotted, ///< \ru Пунктирная в конвертерах STEP и IGES. \en Dotted line in STEP and IGES converters. - lfp_END ///< \ru Для удобства перебора. \en For search -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Отображение точек, передаваемых через конвертер. -\en Representation of points passed via converter. \~ -\ingroup Data_Interface -*/ -// --- -enum MbeDotMarkerSymbol { - dms_BEGIN = 0, ///< \ru Для удобства перебора. \en For the convenient search. - dms_STEPdot, ///< \ru Точка. \en A point. - dms_STEPx, ///< \ru Косой крест. \en x - cross. - dms_STEPplus, ///< \ru Прямой крест. \en Plus. - dms_STEPasterisk, ///< \ru Звёздочка. \en Asterisk. - dms_STEPring, ///< \ru Кольцо. \en Ring. - dms_STEPsquare, ///< \ru Квадрат. \en Square. - dms_STEPtriangle, ///< \ru Треугольник. \en Triangle. - dms_END ///< \ru Для удобства перебора. \en For the convenient search. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Ключи строк, соответствующих названию специальных атрибутов. - \en Keys of the strings, which mark special attributes.\~ -\ingroup Data_Interface -*/ -// --- -enum ePromtAttributeKey { - pac_GConverterInternalIsDummy, ///< \ru Является ли элемент пустышкой.\~ - pac_GeneralIsAssembly, ///< \ru Является ли элемент сборкой. \en Is item assembly.\~ - pac_GeneralFileName, ///< \ru Имя файла. \en File name.\~ - pac_STEPHeader, ///< \ru Заголовок STEP. \en STEP header.\~ - pac_STEPProduct, ///< \ru Изделие STEP. \en STEP product.\~ - pac_STEPPersonOrganization, ///< \ru Лицо и организация STEP. \en STEP person and organization.\~ - pac_STEPAssignedRole ///< \ru Назначенная роль STEP. \en The role, assigned to the person.\~ -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения конвертации данных. - \en Identifiers of the execution progress indicator messages converters data exchange \~ -\ingroup Data_Exchange -*/ -//--- -enum MbeProgBarId_Converters { - pbarId_Cnv_Beg = pbarId_PointsSurface_End + 1, - - pbarId_Cnv_Parse_Data, // \ru Синтаксический анализ... \en Syntactic analysis... - pbarId_Cnv_Create_Objects, // \ru Создание объектов... \en Creation of objects... - pbarId_Cnv_Process_Surfaces, // \ru Обработка поверхностей... \en Surfaces processing... - pbarId_Cnv_Process_Annotation,// \ru Обработка аннотации... \en Annotation processing... - pbarId_Cnv_Create_Model, // \ru Создание модели... \en Creation of model... - pbarId_Cnv_Write_Model, // \ru Запись модели... \en Writing of model... - - pbarId_Cnv_End, -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения триангуляции при выполнении конвертации данных. - \en Identifiers of the execution progress indicator messages triangulation. \~ -\ingroup Data_Exchange -*/ -//--- -enum MbeProgBarId_Triangulation { - pbarId_Triangulation_Beg = pbarId_Cnv_End + 1, - - pbarId_Calc_Triangulation, // \ru Расчет триангуляции \en Calculating of triangulation - - pbarId_Triangulation_End, -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения расчёта - масс-инерционные характеристики детали или сборки при выполнении конвертации данных. - \en Identifiers of the execution progress indicator messages of mass-inertial properties of assembly or a detail. \~ -\ingroup Data_Exchange -*/ -//--- -enum MbeProgBarId_MassInertiaProperties { - pbarId_MassInertiaProperties_Beg = pbarId_Triangulation_End + 1, - - pbarId_Calc_MassInertiaProperties, // \ru Расчет масс-инерционных характеристик \en Mass-inertial properties calculation - - pbarId_MassInertiaProperties_End, -}; - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Перечисления, используемые при импорте и экспорте. + \en Enumerations for import/export operations.\~ + \details \ru Определены перечисления, определяющие результат конвертирования, + разрешение на чтение и запись различных объектов и передаваемых черезх конвертер строк. + \en Converting result, objects and properties filters, special strings + of enumerations are defined.\~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_ERROR_RESULT_H +#define __CONV_ERROR_RESULT_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Представление текста при экспорте. +\en Representation of exported text.\~ +\ingroup Data_Exchange +*/ +// --- +enum eTextForm { + exf_TextOnly, ///< \ru Только текст. \en Text only. + exf_GeometryOnly, ///< \ru Только геометрия. \en Geometry only. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Предопределённые ключи атрибутов для передачи контрольных параметров. +\en Predefined key of attributes used for validation properties' exchange.\~ +\ingroup Data_Interface +*/ +// --- +/// \ru Объём. \en Volume. +#define C3D_CAD_VALIDATION_PROPERTY_VOLUME c3d::c3dStr_ValidationPropertyVolumeExchange +/// \ru Площать поверхости. \en Surface area. +#define C3D_CAD_VALIDATION_PROPERTY_AREA c3d::c3dStr_ValidationPropertySurfaceAreaExchange +/// \ru Масса. \en Mass. +#define C3D_CAD_VALIDATION_PROPERTY_MASS c3d::c3dStr_ValidationPropertyMassExchange +/// \ru Идентификатор элемента. \en Item Identifier. +#define C3D_CAD_ITEM_IDENTIFIER c3d::c3dStr_ItemIdentifierExchange + + +//------------------------------------------------------------------------------ +/** \brief \ru Типы линий, передаваемых через конвертер. +\en Types of lines passed via converter. \~ +\ingroup Data_Interface +*/ +// --- +enum MbeLineFontPattern { + lfp_BEGIN = 0, ///< \ru Для удобства перебора. \en For the convenient search. + lfp_STEPcontinuous, ///< \ru Непрерывная в конвертерах STEP и IGES. \en Continuous line in STEP and IGES (Solid) converters. + lfp_STEPchain, ///< \ru Штрих-пунктирная в конвертерах STEP и IGES. \en Chain line( dash-dotted) in STEP and IGES converters. + lfp_STEPchainDoubleDash, ///< \ru Штриховая с двумя пунктирами в конвертерах STEP и IGES. \en Dash-double-dot line in STEP and IGES (Phantom) converter. + lfp_STEPdashed, ///< \ru Штриховая в конвертерах STEP и IGES. \en Dash line in STEP and IGES converters. + lfp_STEPdotted, ///< \ru Пунктирная в конвертерах STEP и IGES. \en Dotted line in STEP and IGES converters. + lfp_END ///< \ru Для удобства перебора. \en For search +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Отображение точек, передаваемых через конвертер. +\en Representation of points passed via converter. \~ +\ingroup Data_Interface +*/ +// --- +enum MbeDotMarkerSymbol { + dms_BEGIN = 0, ///< \ru Для удобства перебора. \en For the convenient search. + dms_STEPdot, ///< \ru Точка. \en A point. + dms_STEPx, ///< \ru Косой крест. \en x - cross. + dms_STEPplus, ///< \ru Прямой крест. \en Plus. + dms_STEPasterisk, ///< \ru Звёздочка. \en Asterisk. + dms_STEPring, ///< \ru Кольцо. \en Ring. + dms_STEPsquare, ///< \ru Квадрат. \en Square. + dms_STEPtriangle, ///< \ru Треугольник. \en Triangle. + dms_END ///< \ru Для удобства перебора. \en For the convenient search. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Ключи строк, соответствующих названию специальных атрибутов. + \en Keys of the strings, which mark special attributes.\~ +\ingroup Data_Interface +*/ +// --- +enum ePromtAttributeKey { + pac_GConverterInternalIsDummy, ///< \ru Является ли элемент пустышкой.\~ + pac_GeneralIsAssembly, ///< \ru Является ли элемент сборкой. \en Is item assembly.\~ + pac_GeneralFileName, ///< \ru Имя файла. \en File name.\~ + pac_STEPHeader, ///< \ru Заголовок STEP. \en STEP header.\~ + pac_STEPProduct, ///< \ru Изделие STEP. \en STEP product.\~ + pac_STEPPersonOrganization, ///< \ru Лицо и организация STEP. \en STEP person and organization.\~ + pac_STEPAssignedRole ///< \ru Назначенная роль STEP. \en The role, assigned to the person.\~ +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения конвертации данных. + \en Identifiers of the execution progress indicator messages converters data exchange \~ +\ingroup Data_Exchange +*/ +//--- +enum MbeProgBarId_Converters { + pbarId_Cnv_Beg = pbarId_PointsSurface_End + 1, + + pbarId_Cnv_Parse_Data, // \ru Синтаксический анализ... \en Syntactic analysis... + pbarId_Cnv_Create_Objects, // \ru Создание объектов... \en Creation of objects... + pbarId_Cnv_Process_Surfaces, // \ru Обработка поверхностей... \en Surfaces processing... + pbarId_Cnv_Process_Annotation,// \ru Обработка аннотации... \en Annotation processing... + pbarId_Cnv_Create_Model, // \ru Создание модели... \en Creation of model... + pbarId_Cnv_Write_Model, // \ru Запись модели... \en Writing of model... + + pbarId_Cnv_End, +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения триангуляции при выполнении конвертации данных. + \en Identifiers of the execution progress indicator messages triangulation. \~ +\ingroup Data_Exchange +*/ +//--- +enum MbeProgBarId_Triangulation { + pbarId_Triangulation_Beg = pbarId_Cnv_End + 1, + + pbarId_Calc_Triangulation, // \ru Расчет триангуляции \en Calculating of triangulation + + pbarId_Triangulation_End, +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения расчёта + масс-инерционные характеристики детали или сборки при выполнении конвертации данных. + \en Identifiers of the execution progress indicator messages of mass-inertial properties of assembly or a detail. \~ +\ingroup Data_Exchange +*/ +//--- +enum MbeProgBarId_MassInertiaProperties { + pbarId_MassInertiaProperties_Beg = pbarId_Triangulation_End + 1, + + pbarId_Calc_MassInertiaProperties, // \ru Расчет масс-инерционных характеристик \en Mass-inertial properties calculation + + pbarId_MassInertiaProperties_End, +}; + + #endif // __CONV_ERROR_RESULT_H \ No newline at end of file diff --git a/C3d/Include/conv_requestor.h b/C3d/Include/conv_requestor.h index f53d5d3..61057ac 100644 --- a/C3d/Include/conv_requestor.h +++ b/C3d/Include/conv_requestor.h @@ -1,35 +1,35 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Интерфейс запроса масштаба. Интерфейс запроса сшивки. - \en Interface of scale request. Interface of stitching request. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_REQUESTOR_H -#define __CONV_REQUESTOR_H - - -#include - - -//------------------------------------------------------------------------------ -/// \ru Интерфейс запроса масштаба. \en Interface of scale request. -// --- -struct IScaleRequestor : public MbRefItem -{ - virtual double ScaleRequest() = 0; -}; - - -//------------------------------------------------------------------------------ -/// \ru Интерфейс запроса сшивки. \en Interface of stitching request. -// --- -struct IStitchRequestor : public MbRefItem -{ - virtual bool StitchRequest() = 0; -}; - - -#endif // __CONV_REQUESTOR_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Интерфейс запроса масштаба. Интерфейс запроса сшивки. + \en Interface of scale request. Interface of stitching request. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_REQUESTOR_H +#define __CONV_REQUESTOR_H + + +#include + + +//------------------------------------------------------------------------------ +/// \ru Интерфейс запроса масштаба. \en Interface of scale request. +// --- +struct IScaleRequestor : public MbRefItem +{ + virtual double ScaleRequest() = 0; +}; + + +//------------------------------------------------------------------------------ +/// \ru Интерфейс запроса сшивки. \en Interface of stitching request. +// --- +struct IStitchRequestor : public MbRefItem +{ + virtual bool StitchRequest() = 0; +}; + + +#endif // __CONV_REQUESTOR_H diff --git a/C3d/Include/conv_topo_mesh.h b/C3d/Include/conv_topo_mesh.h index d5e2ad9..d3c23bc 100644 --- a/C3d/Include/conv_topo_mesh.h +++ b/C3d/Include/conv_topo_mesh.h @@ -1,90 +1,90 @@ -//////////////////////////////////////////////////////////////////////////////// -/** -\file -\brief Преобразователь сетки к форме, сохраняющей связи граней и полигонов. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_TOPO_MESH_H -#define __CONV_TOPO_MESH_H - -#include - -#include -#include - -#include -#include - -class MbMesh; - -namespace JTC { - - class TopoMesh; - class TopoGrid; - class TopoLoop; - class TopoVertex; - class MeshVertex; - class MeshPolygon; - - typedef SPtr TopoMeshPtr; - typedef SPtr TopoGridPtr; - typedef SPtr TopoLoopPtr; - typedef SPtr TopoVertexPtr; - typedef SPtr MeshVertexPtr; - typedef SPtr MeshPolygonPtr; - - typedef std::vector RawTopoGridVector; - typedef std::vector TopoGridVector; - typedef std::vector TopoLoopVector; - typedef std::vector TopoVertexVector; - typedef std::vector MeshVertexVector; - typedef std::vector MeshPolygonVector; - - - //------------------------------------------------------------------------------ - // Сетка с топологической информацией - // --- - class CONV_CLASS TopoMesh : public MbRefItem { - SPtr mesh; - TopoGridVector grids; - MeshVertexVector ownPoints; - MeshPolygonVector ownFacePolygons; - std::map< size_t, std::vector > degeneratedTriangles; - std::vector boundaryPoints; - double metricTolerance; - public: - TopoMesh(); // Конструктор - - virtual ~TopoMesh(); //Деструктор - - bool Init( const MbMesh& mesh, bool enableDiagnostics = false ); // Инициализировать - - const MbMesh* GetMesh() const; // Получить сетку - - size_t MeshPolygonsCount() const; // Число полигонов - - MeshPolygonPtr Polygon( size_t index ) const; // Получить полигон - - size_t MeshVerticisCount() const; // Число вершин - - MeshVertexPtr Vertex( size_t index ) const; // Получить вершину - - std::map< size_t, std::vector > GetDegeneratedTriangles() const; // Получить вырожденные треуголники - - std::vector GetBoundaryPoints() const; // Получить граничные точки сетки - - void Reset(); // Сбросить все данные - - size_t NextBoundaryVertex( size_t indexBoundaryVertex, const std::vector& allBoundary ) const; // Получить следующую в цепочке граничную вершину. - - bool InitVoidBoundFrom( std::vector& freeBoundaryVerticis ); // Сформировать внешнюю границу начиная с указанной вершины. - - double MetricTolerance() const; // Получить точность задания расстояния. - - OBVIOUS_PRIVATE_COPY( TopoMesh ) - }; - -}; - -#endif // !__CONV_TOPO_MESH_H +//////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief Преобразователь сетки к форме, сохраняющей связи граней и полигонов. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONV_TOPO_MESH_H +#define __CONV_TOPO_MESH_H + +#include + +#include +#include + +#include +#include + +class MbMesh; + +namespace JTC { + + class TopoMesh; + class TopoGrid; + class TopoLoop; + class TopoVertex; + class MeshVertex; + class MeshPolygon; + + typedef SPtr TopoMeshPtr; + typedef SPtr TopoGridPtr; + typedef SPtr TopoLoopPtr; + typedef SPtr TopoVertexPtr; + typedef SPtr MeshVertexPtr; + typedef SPtr MeshPolygonPtr; + + typedef std::vector RawTopoGridVector; + typedef std::vector TopoGridVector; + typedef std::vector TopoLoopVector; + typedef std::vector TopoVertexVector; + typedef std::vector MeshVertexVector; + typedef std::vector MeshPolygonVector; + + + //------------------------------------------------------------------------------ + // Сетка с топологической информацией + // --- + class CONV_CLASS TopoMesh : public MbRefItem { + SPtr mesh; + TopoGridVector grids; + MeshVertexVector ownPoints; + MeshPolygonVector ownFacePolygons; + std::map< size_t, std::vector > degeneratedTriangles; + std::vector boundaryPoints; + double metricTolerance; + public: + TopoMesh(); // Конструктор + + virtual ~TopoMesh(); //Деструктор + + bool Init( const MbMesh& mesh, bool enableDiagnostics = false ); // Инициализировать + + const MbMesh* GetMesh() const; // Получить сетку + + size_t MeshPolygonsCount() const; // Число полигонов + + MeshPolygonPtr Polygon( size_t index ) const; // Получить полигон + + size_t MeshVerticisCount() const; // Число вершин + + MeshVertexPtr Vertex( size_t index ) const; // Получить вершину + + std::map< size_t, std::vector > GetDegeneratedTriangles() const; // Получить вырожденные треуголники + + std::vector GetBoundaryPoints() const; // Получить граничные точки сетки + + void Reset(); // Сбросить все данные + + size_t NextBoundaryVertex( size_t indexBoundaryVertex, const std::vector& allBoundary ) const; // Получить следующую в цепочке граничную вершину. + + bool InitVoidBoundFrom( std::vector& freeBoundaryVerticis ); // Сформировать внешнюю границу начиная с указанной вершины. + + double MetricTolerance() const; // Получить точность задания расстояния. + + OBVIOUS_PRIVATE_COPY( TopoMesh ) + }; + +}; + +#endif // !__CONV_TOPO_MESH_H diff --git a/C3d/Include/cr_attribute_provider.h b/C3d/Include/cr_attribute_provider.h index 086e2e3..b01d81b 100644 --- a/C3d/Include/cr_attribute_provider.h +++ b/C3d/Include/cr_attribute_provider.h @@ -70,20 +70,20 @@ public: ~MbAttributeProvider(); virtual MbeCreatorType IsA() const; // \ru Выдать тип элемента. \en Get an element type. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. virtual bool SetEqual( const MbCreator & ); // \ru Сделать равным. \en Make equal. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию. \en Create a copy. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию. \en Create a copy. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction. + RPArray * items = c3d_null ); // \ru Построение \en Construction. // \ru Добавить отдельный атрибут (забрать во владение) \en Add a separate attribute. void AddAttribute( const MbName & name, MbAttribute * attr ); @@ -125,7 +125,7 @@ public: /// \ru Записать полученные атрибуты. \en Save the received attributes. void ReceiveAttributes ( c3d::AttrVector & attrs ); /// \ru Скопировать атрибуты. \en Copy attributes. - void DuplicateAttributes( c3d::AttrVector & attrs, MbRegDuplicate * iReg = NULL ) const; + void DuplicateAttributes( c3d::AttrVector & attrs, MbRegDuplicate * iReg = c3d_null ) const; /// \ru Дать количество атрибутов. \en Get the attributes count. size_t AttributesCount() const { return attributes.size(); } /// \ru Добавить атрибут. \en Add an attribute. diff --git a/C3d/Include/cr_boolean_solid.h b/C3d/Include/cr_boolean_solid.h index d8953c1..1f3e3dc 100644 --- a/C3d/Include/cr_boolean_solid.h +++ b/C3d/Include/cr_boolean_solid.h @@ -67,10 +67,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * ireg = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -90,7 +90,7 @@ public : // \ru Общие функции твердого тела. \en Common functions of solid. virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual void SetYourVersion( VERSION version, bool forAll ); @@ -107,7 +107,7 @@ public: /// \ru Общее количество строителей. \en Total count of creators. size_t GetCreatorsCount() const { return creators.size(); } /// \ru Дать строитель. \en Get the creator. - const MbCreator * GetCreator( size_t k ) const { return ( (k < creators.size()) ? creators[k] : NULL ); } + const MbCreator * GetCreator( size_t k ) const { return ( (k < creators.size()) ? creators[k] : c3d_null ); } /// \ru Удалить из журнала строители первого тела. \en Delete first-solid creators from the history tree. bool DeleteFirstCreators(); private : diff --git a/C3d/Include/cr_chamfer_solid.h b/C3d/Include/cr_chamfer_solid.h index 5f74396..f311a8b 100644 --- a/C3d/Include/cr_chamfer_solid.h +++ b/C3d/Include/cr_chamfer_solid.h @@ -39,7 +39,7 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties &properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -51,7 +51,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private : virtual void ReadDistances ( reader &in ); diff --git a/C3d/Include/cr_connecting_curve.h b/C3d/Include/cr_connecting_curve.h index f9c196b..657a176 100644 --- a/C3d/Include/cr_connecting_curve.h +++ b/C3d/Include/cr_connecting_curve.h @@ -59,15 +59,15 @@ public : // \ru Общие функции строителя \en The common functions of the creator virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -77,7 +77,7 @@ public : virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateSpaceCurve( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateSpaceCurve( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ @@ -97,13 +97,13 @@ IMPL_PERSISTENT_OPS( MbConnectingCurveCreator ) \en Create two curves fillet constructor.\n \~ \param[in] curve1 - \ru Кривая 1. \en Curve 1. \~ - \param[in/out] t1 - \ru Параметр точки на кривой 1 соединения с кривой соединения. + \param[in,out] t1 - \ru Параметр точки на кривой 1 соединения с кривой соединения. \en A point parameter on curve 1 of connection with fillet curve. \~ \param[in] curve2 - \ru Кривая 2. \en Curve 2. \~ - \param[in/out] t2 - \ru Параметр точки на кривой 2 соединения с кривой соединения. + \param[in,out] t2 - \ru Параметр точки на кривой 2 соединения с кривой соединения. \en A point parameter on curve 2 of connection with fillet curve. \~ - \param[in/out] radius - \ru Радиус дуги или цилиндра. + \param[in,out] radius - \ru Радиус дуги или цилиндра. \en The radius of an arc or a cylinder. \~ \param[in] type - \ru Тип скругления. \en The fillet type. \~ @@ -111,8 +111,8 @@ IMPL_PERSISTENT_OPS( MbConnectingCurveCreator ) \en An object defining the edges names. \~ \param[out] res - \ru Код результата операции. \en Operation result code. \~ - \param[out] surface - \ru Поверхность, которая будет создана и на которой базируется соединительная кривая, (может быть возращён NULL). - \en A surface on which the fillet curve is based on, it will be created by the method (can be NULL). \~ + \param[out] surface - \ru Поверхность, которая будет создана и на которой базируется соединительная кривая, (может быть возращён c3d_null). + \en A surface on which the fillet curve is based on, it will be created by the method (can be c3d_null). \~ \result \ru Возвращает строитель. \en Returns the constructor. \~ \ingroup Curve3D_Modeling diff --git a/C3d/Include/cr_cutting_solid.h b/C3d/Include/cr_cutting_solid.h index ffc5c89..af52814 100644 --- a/C3d/Include/cr_cutting_solid.h +++ b/C3d/Include/cr_cutting_solid.h @@ -66,10 +66,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -85,7 +85,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = NULL ); // \ru Построение \en Construction + RPArray * = c3d_null ); // \ru Построение \en Construction // \ru Оставляемая часть (если part больше 0, то оставляем часть тела со стороны нормали поверхности). \en A part to be kept (if part is bigger than 0, then keep a part of solid from the side of surface normal). ThreeStates GetPart() const { return part; } diff --git a/C3d/Include/cr_detach_solid.h b/C3d/Include/cr_detach_solid.h index a933875..c61ebd2 100644 --- a/C3d/Include/cr_detach_solid.h +++ b/C3d/Include/cr_detach_solid.h @@ -42,10 +42,10 @@ public : \en \name Common functions of the mathematical object. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -56,7 +56,7 @@ public : virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным. \en Make equal. virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction /** \} */ /** \ru \name Функции строителя, разделяющие отдельные части оболочки. \en \name Functions of the creator subdividing separate parts of the shell. @@ -183,7 +183,7 @@ MbCreator * CreateDetach( MbFaceShell & solid, MbResultType & res ) { res = rt_Error; - MbCreator * result = NULL; + MbCreator * result = c3d_null; ::MakeDetachShells( solid, partSolid, sort ); diff --git a/C3d/Include/cr_displace_creator.h b/C3d/Include/cr_displace_creator.h new file mode 100644 index 0000000..0159523 --- /dev/null +++ b/C3d/Include/cr_displace_creator.h @@ -0,0 +1,214 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строители перемещения объектов в пространстве. + \en Constructors of displacement of an object. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_DISPLACE_CREATOR_H +#define __CR_DISPLACE_CREATOR_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Перемещение объекта вдоль вектора. + \en The shift of an object. \~ + \details \ru Строитель перемещает объект вдоль вектора на его длину. \n + \en Constructor displaces an object along the vector by its length. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbMotionMaker : public MbCreator { +protected: + MbVector3D vector; ///< \ru Вектор перемещения. \en The displacement vector. + +public: // \ru Конструктор по параметрам. \en Constructor by parameters. + MbMotionMaker( const MbVector3D & ); +private: // \ru Конструктор дублирующий. \en Duplication constructor. + MbMotionMaker( const MbMotionMaker &, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbMotionMaker( const MbMotionMaker & ); + +public: // \ru Деструктор \en Destructor + ~MbMotionMaker(); + +public: // \ru Общие функции математического объекта \en Common functions of the mathematical object + virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element + virtual MbeCreatorType Type() const; // \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis + + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + + /// \ru Построение оболочки \en Creation of a shell. + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса кривых. \en Creation of a wire-frame. + virtual bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса точек. \en Creation of a point-frame. + virtual bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Переместить строитель. \en Displace the creator. + virtual bool Perform( MbCreator * ) const; + + // \ru Добавить перемещение объекта вдоль вектора. \en Add a displacement vector. + void AddVector( const MbVector3D & ); + // \ru Дать параметры. \en Get the parameters. + void GetVector( MbVector3D & m ) const { m = vector; } + // \ru Установить параметры. \en Set the parameters. + void SetVector( const MbVector3D & m ) { vector = m; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbMotionMaker & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMotionMaker ) +}; + +IMPL_PERSISTENT_OPS( MbMotionMaker ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Поворот объекта вокруг оси. + \en Rotate an object around an axis. \~ + \details \ru Строитель поворачивает объект вокруг оси на заданный угол. \n + \en Constructor rotates an object around the axis by the specified angle. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbRotationMaker : public MbCreator { +protected: + MbAxis3D axis; ///< \ru Ось вращения. \en The axis. + double angle; ///< \ru Угол поворота. \en The angle of rotatation. + +public: // \ru Конструктор по параметрам. \en Constructor by parameters. + MbRotationMaker( const MbAxis3D & ax, double an ); +private: // \ru Конструктор дублирующий. \en Duplication constructor. + MbRotationMaker( const MbRotationMaker &, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbRotationMaker( const MbRotationMaker & ); + +public: // \ru Деструктор \en Destructor + ~MbRotationMaker(); + +public: // \ru Общие функции математического объекта \en Common functions of the mathematical object + virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element + virtual MbeCreatorType Type() const; // \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis + + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + + /// \ru Построение оболочки \en Creation of a shell. + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса кривых. \en Creation of a wire-frame. + virtual bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса точек. \en Creation of a point-frame. + virtual bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Переместить строитель. \en Displace the creator. + virtual bool Perform( MbCreator * ) const; + + // \ru Добавить поворот вокруг оси. \en Add an angle of rotatation. + bool AddAngle( const MbAxis3D & ax, double an ); + // \ru Дать параметры. \en Get the parameters. + void GetAxis3D( MbAxis3D & m ) const { m = axis; } + // \ru Установить параметры. \en Set the parameters. + void SetAxis3D( const MbAxis3D & m ) { axis = m; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbRotationMaker & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRotationMaker ) +}; + +IMPL_PERSISTENT_OPS( MbRotationMaker ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Трансформация объекта по матрице. + \en Transformation of an object by matrix. \~ + \details \ru Строитель трансформирует объект по матрице. \n + \en Constructor transforms an object by the matrix. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbTransformationMaker : public MbCreator { +protected: + MbMatrix3D matrix; ///< \ru Матрица преобразования. \en The transform matrix. + +public: // \ru Конструктор по параметрам. \en Constructor by parameters. + MbTransformationMaker( const MbMatrix3D & ); +private: // \ru Конструктор дублирующий. \en Duplication constructor. + MbTransformationMaker( const MbTransformationMaker &, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbTransformationMaker( const MbTransformationMaker & ); + +public: // \ru Деструктор \en Destructor + ~MbTransformationMaker(); + +public: // \ru Общие функции математического объекта \en Common functions of the mathematical object + virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element + virtual MbeCreatorType Type() const; // \ru Получить групповой тип объекта. \en Get the group type of the object. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis + + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + + /// \ru Построение оболочки \en Creation of a shell. + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса кривых. \en Creation of a wire-frame. + virtual bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Построение каркаса точек. \en Creation of a point-frame. + virtual bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, + RPArray * items = c3d_null ); + /// \ru Переместить строитель. \en Displace the creator. + virtual bool Perform( MbCreator * ) const; + + // \ru Добавить модификацию по матрице \en Add a modification by a matrix + void AddMatrix( const MbMatrix3D & ); + // \ru Дать параметры. \en Get the parameters. + void GetMatrix( MbMatrix3D & m ) const { m = matrix; } + // \ru Установить параметры. \en Set the parameters. + void SetMatrix( const MbMatrix3D & m ) { matrix = m; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbTransformationMaker & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformationMaker ) +}; + +IMPL_PERSISTENT_OPS( MbTransformationMaker ) + + +#endif // __CR_DISPLACE_CREATOR_H diff --git a/C3d/Include/cr_draft_solid.h b/C3d/Include/cr_draft_solid.h index c15ef1f..b7c916b 100644 --- a/C3d/Include/cr_draft_solid.h +++ b/C3d/Include/cr_draft_solid.h @@ -47,7 +47,7 @@ public: , fp ( faceProp ) , np ( new MbPlacement3D( nPlace ) ) , edgeNb ( -1 ) - , pl ( NULL ) + , pl ( c3d_null ) , reverse ( rev ) , step ( false ) { @@ -65,7 +65,7 @@ public: , angle ( ang ) , faceIndices( ) , fp ( faceProp ) - , np ( nPlace ? new MbPlacement3D( *nPlace ) : NULL ) + , np ( nPlace ? new MbPlacement3D( *nPlace ) : c3d_null ) , edgeNb ( edgeInd ) , pl ( new SArray( partLines ) ) , reverse ( rev ) @@ -82,10 +82,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -98,7 +98,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = NULL ); // \ru Построение \en Construction + RPArray * = c3d_null ); // \ru Построение \en Construction private : // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/cr_duplication_solid.h b/C3d/Include/cr_duplication_solid.h index 5a81df9..03636fe 100644 --- a/C3d/Include/cr_duplication_solid.h +++ b/C3d/Include/cr_duplication_solid.h @@ -46,10 +46,10 @@ public: \{ */ /// \ru Получить регистрационный тип (для копирования, дублирования). \en Get the registration type (for copying, duplication). virtual MbeCreatorType IsA() const; - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru сделать копию \en create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru сделать копию \en create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & ); // \ru выдать свойства объекта \en get properties of the object virtual void SetProperties( const MbProperties & ); // \ru записать свойства объекта \en set properties of the object @@ -60,7 +60,7 @@ public: virtual bool SetEqual ( const MbCreator & ); // \ru сделать равным \en make equal virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction /** \} */ private : diff --git a/C3d/Include/cr_elementary_solid.h b/C3d/Include/cr_elementary_solid.h index 43f630c..f68766b 100644 --- a/C3d/Include/cr_elementary_solid.h +++ b/C3d/Include/cr_elementary_solid.h @@ -10,11 +10,9 @@ #ifndef __CR_ELEMENTARY_SOLID_H #define __CR_ELEMENTARY_SOLID_H - #include #include - class MATH_CLASS MbElementarySurface; @@ -46,17 +44,17 @@ class MATH_CLASS MbElementarySurface; // --- class MATH_CLASS MbElementarySolid : public MbCreator { protected : - SArray points; ///< \ru Опорные точки оболочки тела. \en Support points of a solid shell. - ElementaryShellType type; ///< \ru Тип тела. \en Type of a solid. - MbPlacement3D position; ///< \ru Локальная система координат тела. \en Local coordinate system оf a solid. - double radius; ///< \ru Радиус основания тела. \en Radius of the base of the solid. - double minorRadius; ///< \ru Малый радиус основания тела. \en Small radius of the base of the solid. - double height; ///< \ru Высота тела. \en Height of a solid. - double length; ///< \ru Длина тела. \en Length of a solid. - double minorLength; ///< \ru Малая длина тела. \en Small length of a solid. - double width; ///< \ru Ширина тела. \en Width of a solid. - double angle; ///< \ru Угол между осью position.axisZ и боковой образующей. \en Angle between position.axisZ axis and lateral generatrix. - double ratio; ///< \ru Коэффициент растяжения. \en Stretch factor. + SArray points; ///< \ru Опорные точки оболочки тела. \en Support points of a solid shell. + ElementaryShellType type; ///< \ru Тип тела. \en Type of a solid. + MbPlacement3D position; ///< \ru Локальная система координат тела. \en Local coordinate system оf a solid. + double radius; ///< \ru Радиус основания тела. \en Radius of the base of the solid. + double minorRadius; ///< \ru Малый радиус основания тела. \en Small radius of the base of the solid. + double height; ///< \ru Высота тела. \en Height of a solid. + double length; ///< \ru Длина тела. \en Length of a solid. + double minorLength; ///< \ru Малая длина тела. \en Small length of a solid. + double width; ///< \ru Ширина тела. \en Width of a solid. + double angle; ///< \ru Угол между осью position.axisZ и боковой образующей. \en Angle between position.axisZ axis and lateral generatrix. + double ratio; ///< \ru Коэффициент растяжения. \en Stretch factor. public : /** \brief \ru Конструктор. \en Constructor. \~ @@ -97,13 +95,13 @@ public : \param[in] n - \ru Именователь операции. \en An object defining names generation in the operation. \~ */ - template - MbElementarySolid( const Points & pnts, ElementaryShellType t, const MbSNameMaker & n ); - + template + MbElementarySolid( const PointsVector & pnts, ElementaryShellType t, const MbSNameMaker & n ); private : - MbElementarySolid( const MbElementarySolid &, MbRegDuplicate * iReg ); // \ru Конструктор копирования с регистратором \en Copy-constructor with the registrator - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + MbElementarySolid( const MbElementarySolid &, MbRegDuplicate * ); + /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbElementarySolid( const MbElementarySolid & ); public : /// \ru Деструктор. \en Destructor. @@ -113,15 +111,15 @@ public : \en \name Common functions of the shell creator. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property - virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object - virtual void GetBasisItems( RPArray & s ); // \ru Дать базовые объекты \en Get the basis objects + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + virtual void GetBasisItems( RPArray & ); // \ru Дать базовые объекты \en Get the basis objects virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. @@ -130,9 +128,12 @@ public : virtual bool SetEqual( const MbCreator & ); // \ru Сделать равным \en Make equal virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * = NULL ); // \ru Построение \en Construction + RPArray * = c3d_null ); // \ru Построение \en Construction /** \} */ +private: + /// \ru Установить параметры по типу и набору точек. \en Set parameters by type and points. + bool SetParameters(); private : // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const MbElementarySolid & ); @@ -142,6 +143,35 @@ private : IMPL_PERSISTENT_OPS( MbElementarySolid ) + +//------------------------------------------------------------------------------ +// \ru Конструктор по точкам и типу тела. При этом, по массиву точек тела и его типу, заполняются соответствующие его параметры. +// \en Constructor by points and type of solid. +// --- +template +MbElementarySolid::MbElementarySolid( const PointsVector & pnts, ElementaryShellType t, const MbSNameMaker & n ) + : MbCreator ( n ) + , points ( ) + , type ( t ) + , position ( ) + , radius ( 0.0 ) + , minorRadius( 0.0 ) + , height ( 0.0 ) + , length ( 0.0 ) + , minorLength( 0.0 ) + , width ( 0.0 ) + , angle ( 0.0 ) + , ratio ( 0.0 ) +{ + size_t cnt = pnts.size(); + points.reserve( cnt ); + for ( size_t k = 0; k < cnt; ++k ) { + points.push_back( pnts[k] ); + } + SetParameters(); +} + + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку элементарного тела. \en Create a shell of an elementary solid. \~ @@ -186,7 +216,7 @@ MATH_FUNC (MbCreator *) CreateElementary( const SArray & points, const ElementaryShellType t, const MbSNameMaker & n, MbResultType & res, - MbFaceShell *& shell ); + c3d::ShellSPtr & shell ); //------------------------------------------------------------------------------ @@ -214,7 +244,7 @@ MATH_FUNC (MbCreator *) CreateElementary( const SArray & points, MATH_FUNC (MbCreator *) CreateElementary( const MbElementarySurface & surface, const MbSNameMaker & n, MbResultType & res, - MbFaceShell *& shell ); + c3d::ShellSPtr & shell ); #endif // __CR_ELEMENTARY_SOLID_H diff --git a/C3d/Include/cr_evolution_solid.h b/C3d/Include/cr_evolution_solid.h index 127abf3..f2e211a 100644 --- a/C3d/Include/cr_evolution_solid.h +++ b/C3d/Include/cr_evolution_solid.h @@ -27,7 +27,7 @@ class MATH_CLASS MbCurveEvolutionSolid : public MbCurveSweptSolid { protected : MbSweptData sweptData; ///< \ru Данные об образующей. \en Generating curve data. SPtr spineCurve; ///< \ru Направляющая кривая. \en Spine curve. - SPtr directionCurve; ///< \ru Кривая вектора ориентации матрицы преобразования (может быть NULL для простой траектории). \en A curve of the transformation matrix orientation (it may be NULL for a simple trajectory). + SPtr directionCurve; ///< \ru Кривая вектора ориентации матрицы преобразования (может быть c3d_null для простой траектории). \en A curve of the transformation matrix orientation (it may be c3d_null for a simple trajectory). MbVector3D direction; ///< \ru Вектор ориентации матрицы преобразования (может быть нулевой, в случае автоопределения). \en Vector of transformation matrix orientation (it's equal zero in the mode of automatic direction calculation). SPtr spineNames; ///< \ru Именователь направляющей. \en An object defining the name of the spine curve. EvolutionValues parameters; ///< \ru Параметры. \en Parameters. @@ -128,10 +128,10 @@ public : \en \name Common functions of the mathematical object. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object diff --git a/C3d/Include/cr_extension_shell.h b/C3d/Include/cr_extension_shell.h index a906d9e..bf2a62c 100644 --- a/C3d/Include/cr_extension_shell.h +++ b/C3d/Include/cr_extension_shell.h @@ -46,10 +46,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -62,7 +62,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( ExtensionValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_extrusion_solid.h b/C3d/Include/cr_extrusion_solid.h index ef6c1de..93e122d 100644 --- a/C3d/Include/cr_extrusion_solid.h +++ b/C3d/Include/cr_extrusion_solid.h @@ -59,7 +59,7 @@ public : OperationType oType, const MbSNameMaker & operNames, const RPArray & contoursNames, - const c3d::CreatorsSPtrVector * creators = NULL, + const c3d::CreatorsSPtrVector * creators = c3d_null, bool sameCreators = true ); private : @@ -73,10 +73,10 @@ public : \en \name Common functions of the mathematical object. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию. \en Make a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию. \en Make a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -94,7 +94,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение. \en Construction. + RPArray * items = c3d_null ); // \ru Построение. \en Construction. virtual MbFaceShell * InitShell( bool in ); virtual void InitBasis( RPArray & items ); @@ -139,7 +139,7 @@ IMPL_PERSISTENT_OPS( MbCurveExtrusionSolid ) \en Face set the construction is complemented with respect to. \~ \param[in] sameShell - \ru Способ копирования граней. \en The method of copying faces. \~ - \param[in] creators - \ru Строители тела solid. + \param[in] solidCreators - \ru Строители тела solid. \en Creators of the solid. \~ \param[in] sweptData - \ru Данные об образующей. \en The generating curve data. \~ diff --git a/C3d/Include/cr_fillet_solid.h b/C3d/Include/cr_fillet_solid.h index b12681a..1bea799 100644 --- a/C3d/Include/cr_fillet_solid.h +++ b/C3d/Include/cr_fillet_solid.h @@ -60,10 +60,10 @@ public : // \ru Общие функции математического объекта. \en Common functions of the mathematical object. virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -76,7 +76,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private : virtual void ReadDistances ( reader &in ); diff --git a/C3d/Include/cr_hole_solid.h b/C3d/Include/cr_hole_solid.h index df9908d..66aa257 100644 --- a/C3d/Include/cr_hole_solid.h +++ b/C3d/Include/cr_hole_solid.h @@ -69,10 +69,10 @@ public : // \ru Переопределение функций базового класса \en The base class functions override virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -88,7 +88,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual MbFaceShell * InitShell( bool in ); virtual void InitBasis( RPArray & items ); diff --git a/C3d/Include/cr_intersection_curve.h b/C3d/Include/cr_intersection_curve.h index b9eacc6..eec1a5b 100644 --- a/C3d/Include/cr_intersection_curve.h +++ b/C3d/Include/cr_intersection_curve.h @@ -39,15 +39,15 @@ public: // \ru Общие функции строителя. \en The common functions of the creator. virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -57,7 +57,7 @@ public: virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ diff --git a/C3d/Include/cr_join_shell.h b/C3d/Include/cr_join_shell.h index b8a3999..8058e1e 100644 --- a/C3d/Include/cr_join_shell.h +++ b/C3d/Include/cr_join_shell.h @@ -39,10 +39,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; ///< \ru Тип элемента \en Element type - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; ///< \ru Сделать копию \en Make a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); ///< \ru Преобразовать элемент согласно матрице \en Transform an element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); ///< \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); ///< \ru Поворот вокруг оси \en Rotation about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; ///< \ru Сделать копию \en Make a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); ///< \ru Преобразовать элемент согласно матрице \en Transform an element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); ///< \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); ///< \ru Поворот вокруг оси \en Rotation about an axis virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными. \en Whether the objects are similar @@ -58,7 +58,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); ///< \ru Построение \en Construction + RPArray * items = c3d_null ); ///< \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. diff --git a/C3d/Include/cr_lofted_solid.h b/C3d/Include/cr_lofted_solid.h index 3407b37..52e35be 100644 --- a/C3d/Include/cr_lofted_solid.h +++ b/C3d/Include/cr_lofted_solid.h @@ -29,7 +29,7 @@ protected : RPArray curves; ///< \ru Плоские сечения. \en Plane sections. SPtr spine; ///< \ru Осевая линия (может отсутствовать). \en Spine curve (can be absent). LoftedValues parameters; ///< \ru Параметры. \en Parameters. - RPArray * guideCurves; ///< \ru Массив направляющих кривых (может быть NULL). \en An array of guide curves (can be NULL). + RPArray * guideCurves; ///< \ru Массив направляющих кривых (может быть c3d_null). \en An array of guide curves (can be c3d_null). SArray * userPnts; ///< \ru Пользовательские точки на сечениях. \en Custom points on the sections. public: @@ -64,10 +64,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать \en Transform - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать \en Transform + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object diff --git a/C3d/Include/cr_median_shell.h b/C3d/Include/cr_median_shell.h index edda9cf..4c4105d 100644 --- a/C3d/Include/cr_median_shell.h +++ b/C3d/Include/cr_median_shell.h @@ -48,13 +48,13 @@ private: public: virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -62,7 +62,7 @@ public: // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); /// \ru Дать параметры. \en Get the parameters. void GetParameters( MedianShellValues & params ) const { params = parameters; } @@ -89,7 +89,7 @@ IMPL_PERSISTENT_OPS( MbMedianShell ) The function simultaneously creates the shell and its constructor.\n \~ \param[in] solid - \ru Исходное тело. \en The initial solid. \~ - \param[in] faces - \ru Выбранные пары граней. + \param[in] faceIndexes - \ru Выбранные пары граней. \en Selected face pairs. \~ \param[in] parameters - \ru Параметры операции. \en Parameters of operation. \~ diff --git a/C3d/Include/cr_mesh_shell.h b/C3d/Include/cr_mesh_shell.h index 5b59c37..d0097ca 100644 --- a/C3d/Include/cr_mesh_shell.h +++ b/C3d/Include/cr_mesh_shell.h @@ -42,12 +42,12 @@ public: public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; ///< \ru Тип элемента \en Element type - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; ///< \ru Сделать копию \en Make a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; ///< \ru Сделать копию \en Make a copy virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); ///< \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); ///< \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); ///< \ru Сдвиг по вектору \en Translation by the vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); ///< \ru Поворот вокруг оси \en Rotation about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); ///< \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); ///< \ru Сдвиг по вектору \en Translation by the vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); ///< \ru Поворот вокруг оси \en Rotation about an axis virtual MbePrompt GetPropertyName(); ///< \ru Выдать заголовок свойства объекта \en Get name of object property virtual void GetProperties( MbProperties & ); ///< \ru Выдать свойства объекта \en Get properties of the object @@ -59,7 +59,7 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); // \ru Дать параметры. \en Get the parameters. void GetParameters( MeshSurfaceValues & params ) const; // \ru Установить параметры. \en Set the parameters. diff --git a/C3d/Include/cr_modified_nurbs_.h b/C3d/Include/cr_modified_nurbs_.h index 7e5ca95..e42dfbf 100644 --- a/C3d/Include/cr_modified_nurbs_.h +++ b/C3d/Include/cr_modified_nurbs_.h @@ -41,12 +41,12 @@ public: // \ru деструктор \en destructor public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru сделать копию \en create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru сделать копию \en create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru сделать равным \en make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru сдвиг по вектору \en translation by a vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru сдвиг по вектору \en translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru выдать заголовок свойства объекта \en get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru выдать свойства объекта \en get properties of the object @@ -56,7 +56,7 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки. \en creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell // \ru Выдать базовые объекты. \en Get basis objects. virtual void GetBasisItems( RPArray & s ); @@ -106,12 +106,12 @@ public: // \ru деструктор \en destructor public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru сделать копию \en create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru сделать копию \en create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru сделать равным \en make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru сдвиг по вектору \en translation by a vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru сдвиг по вектору \en translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru выдать заголовок свойства объекта \en get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru выдать свойства объекта \en get properties of the object @@ -121,7 +121,7 @@ public: // \ru Общие функции математического объе /// \ru построение оболочки \en creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell // \ru Выдать базовые объекты. \en Get basis objects. virtual void GetBasisItems( RPArray & s ); diff --git a/C3d/Include/cr_modified_solid.h b/C3d/Include/cr_modified_solid.h index 02954b1..981e0d9 100644 --- a/C3d/Include/cr_modified_solid.h +++ b/C3d/Include/cr_modified_solid.h @@ -62,12 +62,12 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг по вектору \en Translation by the vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by the vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -77,7 +77,7 @@ public: /// \ru Построение оболочки \en Creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & outer ); ///< \ru Обновить форму оболочки \en Update shape of the shell // \ru Дать параметры. \en Get the parameters. diff --git a/C3d/Include/cr_nurbs3d.h b/C3d/Include/cr_nurbs3d.h index 48ba21e..23d8e42 100644 --- a/C3d/Include/cr_nurbs3d.h +++ b/C3d/Include/cr_nurbs3d.h @@ -11,6 +11,7 @@ #include +#include #include @@ -24,14 +25,14 @@ // --- class MATH_CLASS MbNurbs3DCreator : public MbCreator { private: - SArray points; // \ru Точки, через которые проходит сплайн \en Points which the spline passes through - SArray weights; // \ru Веса \en Weights - SArray knots; // \ru Узлы \en Knots - RPArray< MbPntMatingData > matingData; // \ru Данные сопряжения в точках \en Data about mating in the points - MbeSplineParamType paramType; // \ru Тип параметризации \en Parametrization type - size_t degree; // \ru Степень сплайна \en Spline degree - bool closed; // \ru Замкнутость сплайна \en Spline closedness - bool throughPnts; // \ru через точки \en Through points + SArray points; // \ru Точки, через которые проходит сплайн \en Points which the spline passes through + SArray weights; // \ru Веса \en Weights + SArray knots; // \ru Узлы \en Knots + RPArray matingData; // \ru Данные сопряжения в точках \en Data about mating in the points + MbeSplineParamType paramType; // \ru Тип параметризации \en Parametrization type + size_t degree; // \ru Степень сплайна \en Spline degree + bool closed; // \ru Замкнутость сплайна \en Spline closedness + bool throughPnts; // \ru через точки \en Through points protected: MbNurbs3DCreator( const MbNurbs3DCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor @@ -42,24 +43,24 @@ public: MbeSplineParamType paramType, size_t degree, bool closed, const SArray * weights, const SArray * knots, - const RPArray< MbPntMatingData > & matingData, + const RPArray & matingData, const MbSNameMaker & snMaker ); public: virtual ~MbNurbs3DCreator(); // \ru Общие функции строителя. \en The common functions of the creator. virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis - virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name + virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты \en Get the basis objects @@ -67,7 +68,7 @@ public: virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ @@ -80,6 +81,7 @@ private: IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Создать пространственный сплайн через точки и с сопряжениями. \en Create a spatial spline through points and with the given tangents. \~ @@ -94,14 +96,14 @@ IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbCreator *) CreateSplineThrough( const SArray & points, // \ru Точки \en Points - MbeSplineParamType paramType, // \ru Тип параметризации \en Parametrization type - size_t degree, // \ru Порядок сплайна \en Spline degree - bool closed, // \ru Замкнуть \en Make close - RPArray< MbPntMatingData > & transitions, // \ru Сопряжения \en Tangents - const MbSNameMaker & snMaker, // \ru Именователь \en An object for naming the new objects - MbResultType & resType, - MbCurve3D *& resCurve ); +MATH_FUNC (MbCreator *) CreateSplineThrough( const SArray & points, // \ru Точки \en Points + MbeSplineParamType paramType, // \ru Тип параметризации \en Parametrization type + size_t degree, // \ru Порядок сплайна \en Spline degree + bool closed, // \ru Замкнуть \en Make close + RPArray & transitions, // \ru Сопряжения \en Tangents + const MbSNameMaker & snMaker, // \ru Именователь \en An object for naming the new objects + MbResultType & resType, + MbCurve3D *& resCurve ); //------------------------------------------------------------------------------ @@ -115,15 +117,15 @@ MATH_FUNC (MbCreator *) CreateSplineThrough( const SArray & point */ //--- MATH_FUNC (MbCreator *) CreateSplineBy( const SArray & points, // \ru Точки \en Points - size_t degree, // \ru Порядок сплайна \en Spline degree - bool closed, // \ru Замкнуть \en Make close + size_t degree, // \ru Порядок сплайна \en Spline degree + bool closed, // \ru Замкнуть \en Make close const SArray * weights, // \ru Веса \en Weights const SArray * knots, // \ru Узлы \en Knots - MbPntMatingData * begData, // \ru Сопряжение в начале \en Tangent at the start point - MbPntMatingData * endData, // \ru Сопряжение в конце \en Tangent at the end point + c3d::PntMatingData3D * begData, // \ru Сопряжение в начале \en Tangent at the start point + c3d::PntMatingData3D * endData, // \ru Сопряжение в конце \en Tangent at the end point const MbSNameMaker & snMaker, // \ru Именователь \en An object for naming the new objects - MbResultType & resType, - MbCurve3D *& resCurve ); + MbResultType & resType, + MbCurve3D *& resCurve ); #endif // __CR_NURBS3D_H diff --git a/C3d/Include/cr_nurbs_block_solid.h b/C3d/Include/cr_nurbs_block_solid.h index 1b2aeff..6c4f70c 100644 --- a/C3d/Include/cr_nurbs_block_solid.h +++ b/C3d/Include/cr_nurbs_block_solid.h @@ -40,12 +40,12 @@ public: // \ru Деструктор \en Destructor public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг по вектору \en Translation by a vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -57,7 +57,7 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & outer ); ///< \ru Обновить форму оболочки \en Update shape of the shell private: diff --git a/C3d/Include/cr_nurbs_surfaces_shell.h b/C3d/Include/cr_nurbs_surfaces_shell.h index 02a0ede..dc84e16 100644 --- a/C3d/Include/cr_nurbs_surfaces_shell.h +++ b/C3d/Include/cr_nurbs_surfaces_shell.h @@ -24,38 +24,36 @@ class IProgressIndicator; \en Construct a shell from NURBS-surfaces. \~ \details \ru Построить оболочку из NURBS-поверхностей MbSplineSurface по заданному множеству точек условно расположенных в узлах четырехугольной сетки. \n \en Construct a shell from NURBS-surfaces MbSplineSurface by a given set of points conventionally located at the nodes of a quadrangle grid. \n \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ + \param[in] params - \ru Параметры построения. + \en Parameters of a shell creation. \~ \param[in] operNames - \ru Именователь граней. \en An object for naming faces. \~ \param[in] isPhantom - \ru Режим создания фантома. \en Create in the phantom mode. \~ \param[out] res - \ru Код результата операции. \en Operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ \param[out] indicator - \ru Индикатор хода построения позволяющий прервать построение. \en Construction process indicator which allow to interrupt the construction. \~ - \result \ru Возвращает оболочку. - \en Returns the constructуed shell. \~ + \result \ru Возвращает построенную оболочку. + \en Returns the constructed shell. \~ \ingroup Model_Creators */ // --- -MATH_FUNC (MbFaceShell *) CreateNurbsSurfacesShell( NurbsSurfaceValues & params, - const MbSNameMaker & operNames, - bool isPhantom, - MbResultType & res, - IProgressIndicator * = NULL ); +MATH_FUNC (MbFaceShell *) CreateNurbsSurfacesShell( NurbsSurfaceValues & params, + const MbSNameMaker & operNames, + bool isPhantom, + MbResultType & res, + IProgressIndicator * indicator = c3d_null ); //------------------------------------------------------------------------------ -// проверить оболочку из нурбс-поверхностей -/** \brief \ru Построить оболочку из NURBS-поверхностей. - \en Construct a shell from NURBS-surfaces. \~ - \details \ru Построить оболочку из NURBS-поверхностей MbSplineSurface по заданному множеству точек условно расположенных в узлах четырехугольной сетки. \n - \en Construct a shell from NURBS-surfaces MbSplineSurface by a given set of points conventionally located at the nodes of a quadrangle grid. \n \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ +// Проверить оболочку из нурбс-поверхностей +/** \brief \ru Проверить оболочку из NURBS-поверхностей. + \en Check a shell from NURBS-surfaces. \~ + \details \ru Проверить построенную оболочку из NURBS-поверхностей MbSplineSurface по заданному множеству точек условно расположенных в узлах четырехугольной сетки. \n + \en Check a constructed shell from NURBS-surfaces MbSplineSurface by a given set of points conventionally located at the nodes of a quadrangle grid. \n \~ + \param[in] params - \ru Параметры построения. + \en Parameters of a shell creation. \~ \param[in] shell - \ru Оболочка, построенная по заданным параметрам. \en The shell constructed by given parameters. \~ \param[out] indicator - \ru Индикатор хода построения позволяющий прервать построение. @@ -66,8 +64,8 @@ MATH_FUNC (MbFaceShell *) CreateNurbsSurfacesShell( NurbsSurfaceValues & params, */ // --- MATH_FUNC (MbResultType) CheckNurbsSurfacesShell( const NurbsSurfaceValues & params, - const MbFaceShell & shell, - IProgressIndicator * = NULL ); + const MbFaceShell & shell, + IProgressIndicator * indicator = c3d_null ); #endif // __NURBS_SURFACES_SHELL_H diff --git a/C3d/Include/cr_nurbs_surfaces_solid.h b/C3d/Include/cr_nurbs_surfaces_solid.h index 6cec11e..d4d335b 100644 --- a/C3d/Include/cr_nurbs_surfaces_solid.h +++ b/C3d/Include/cr_nurbs_surfaces_solid.h @@ -50,12 +50,12 @@ public: public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru сделать копию \en create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru сделать копию \en create a copy virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru сделать равным \en make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru сдвиг по вектору \en translation by a vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru сдвиг по вектору \en translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru выдать заголовок свойства объекта \en get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru выдать свойства объекта \en get properties of the object @@ -67,7 +67,7 @@ public: // \ru Общие функции математического объе public: /// \ru построение оболочки \en creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell // \ru Дать параметры. \en Get the parameters. @@ -110,7 +110,7 @@ MATH_FUNC (MbCreator *) CreateNurbsShell( NurbsSurfaceValues & parameters, bool isPhantom, MbResultType & res, MbFaceShell *& shell, - IProgressIndicator * indicator = NULL ); + IProgressIndicator * indicator = c3d_null ); #endif // __CR_NURBS_SURFACES_SOLID_H diff --git a/C3d/Include/cr_offset_curve.h b/C3d/Include/cr_offset_curve.h index 7cfd3fc..5d4082f 100644 --- a/C3d/Include/cr_offset_curve.h +++ b/C3d/Include/cr_offset_curve.h @@ -12,6 +12,7 @@ #include #include +#include #include @@ -29,46 +30,74 @@ class MATH_CLASS MbCurve3D; class MATH_CLASS MbOffsetCurveCreator : public MbCreator { private: // \ru Основные параметры \en The basic parameters - SPtr curve; // \ru Исходная кривая. \en The initial curve. - MbVector3D dir; // \ru Направление смещения. \en The offset direction. - double dist; // \ru Величина смещения. \en The offset distance. - bool fromBeg; // \ru Вектор смещения привязан к началу кривой (иначе к концу). \en The translation vector is associated with the beginning (with the end otherwise). + c3d::SpaceCurveSPtr curve; ///< \ru Исходная кривая. \en The initial curve. + MbVector3D dir; ///< \ru Направление смещения. \en The offset direction. + double dist; ///< \ru Величина смещения. \en The offset distance. + bool fromBeg; ///< \ru Вектор смещения привязан к началу кривой (иначе к концу). \en The translation vector is associated with the beginning (with the end otherwise). // \ru Дополнительные параметры (эквидистанта в пространстве) \en Auxiliary parameters (spatial offset) - bool useFillet; // \ru Заполнять ли разрывы скруглениями (иначе продлять сегменты). \en Whether to fill the gaps with fillets (extend segments otherwise). - bool keepRadius; // \ru Сохранять ли радиусы в скруглениях. \en Whether to keep the radii at fillets. - bool bluntAngle; // \ru Притуплять острые углы стыков сегментов \en Whether to blunt the sharp edges of segments joints. + bool useFillet; ///< \ru Заполнять ли разрывы скруглениями (иначе продлять сегменты). \en Whether to fill the gaps with fillets (extend segments otherwise). + bool keepRadius; ///< \ru Сохранять ли радиусы в скруглениях. \en Whether to keep the radii at fillets. + bool bluntAngle; ///< \ru Притуплять острые углы стыков сегментов \en Whether to blunt the sharp edges of segments joints. + bool bySurfaceNormal; ///< \ru Эквидистанта согласована с нормалью к поверхности. \en Offset point is moved according to surface normal. + c3d::SurfaceSPtr surface; ///< \ru Поверхность кривой или подобная ей. \en Curve's surface or similar to such surface. // \ru Дополнительные параметры (эквидистанта на поверхности грани оболочки) \en Auxiliary parameters (offset on the shell face surface) - c3d::CreatorsSPtrVector shellCreators; // \ru Журнал построения оболочки. \en The shell history tree. + c3d::CreatorsSPtrVector shellCreators; ///< \ru Журнал построения оболочки. \en The shell history tree. protected: MbOffsetCurveCreator( const MbOffsetCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor MbOffsetCurveCreator( const MbOffsetCurveCreator & ); // \ru Не реализовано \en Not implemented MbOffsetCurveCreator(); // \ru Не реализовано \en Not implemented public: - // \ru Конструктор эквидистанты в пространстве \en Constructor of offset in the space - MbOffsetCurveCreator( const MbCurve3D &, bool fromBeg, const MbVector3D & dir, double dist, - bool useFillet, bool keepRadius, bool bluntAngle, - const MbSNameMaker & snMaker ); - // \ru Конструктор эквидистанты на поверхности грани оболочки \en Constructor of offset on the shell face surface - MbOffsetCurveCreator( const MbCurve3D &, bool fromBeg, const MbVector3D & dir, double dist, - const RPArray & shellCreators, bool sameCreators, - const MbSNameMaker & snMaker ); + /** \brief \ru Конструктор эквидистанты в пространстве. + \en Constructor of offset in the space. \~ + \details \ru Конструктор эквидистанты в пространстве. \n + \en Constructor of offset in the space. \n \~ + \param[in] curve - \ru Базовая кривая. + \en The base curve. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[in] snMaker - \ru Именователь с версия исполнения. + \en Names makers with a version. \~ + */ + MbOffsetCurveCreator( const MbCurve3D & curve, + const MbSpatialOffsetCurveParams & params, + const MbSNameMaker & snMaker ); + /** \brief \ru Конструктор эквидистанты на поверхности грани оболочки. + \en Constructor of offset on the shell face surface. \~ + \details \ru Конструктор эквидистанты на поверхности грани оболочки. \n + \en Constructor of offset on the shell face surface. \n \~ + \param[in] curve - \ru Базовая кривая. + \en The base curve. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[in] shellCreators - \ru Построители тела. + \en Creators of a solid. \~ + \param[in] sameCreators - \ru Признак использования оригиналов построителей. + \en Flag of using the original creators. \~ + \param[in] snMaker - \ru Именователь с версия исполнения. + \en Names makers with a version. \~ + */ + MbOffsetCurveCreator( const MbCurve3D & curve, + const MbSurfaceOffsetCurveParams & params, + const c3d::CreatorsSPtrVector & shellCreators, + bool sameCreators, + const MbSNameMaker & snMaker ); public : virtual ~MbOffsetCurveCreator(); // \ru Общие функции строителя. \en The common functions of the creator. virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -81,7 +110,7 @@ public : virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ); // \ru Получить внутренние построители по типу. \en Get internal creators by type. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ @@ -89,7 +118,7 @@ private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. void operator = ( const MbOffsetCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurveCreator ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurveCreator ) }; IMPL_PERSISTENT_OPS( MbOffsetCurveCreator ) @@ -97,22 +126,14 @@ IMPL_PERSISTENT_OPS( MbOffsetCurveCreator ) //------------------------------------------------------------------------------ /** \brief \ru Создать офсетную кривую по трехмерной кривой и вектору направления. \en Create an offset curve from three-dimensional curve and direction. \~ - \details \ru Создать офсетную кривую по трехмерной кривой и вектору направления. \n - \en Create an offset curve from three-dimensional curve and direction. \n \~ - \param[in] initCurve - \ru Постранственная кривая, к которой строится эквидистантная. + \details \ru Создать офсетную кривую в пространстве по трехмерной кривой и вектору направления. \n + \en Create an offset curve in space from three-dimensional curve and direction. \n \~ + \param[in] initCurve - \ru Пространственная кривая, к которой строится эквидистантная. \en A space curve for which to construct the offset curve. \~ - \param[in] offsetVect - \ru Вектор, задающий смещение в точке кривой. - \en The displacement vector at a point of the curve. \~ - \param[in] useFillet - \ru Если true, то разрывы заполнять скруглением, иначе продолженными кривыми. - \en If 'true', the gaps are to be filled with fillet, otherwise with the extended curves. \~ - \param[in] keepRadius - \ru Если true, то в существующих скруглениях сохранять радиусы. - \en If 'true', the existent fillet radii are to be kept. \~ - \param[in] fromBeg - \ru Вектор смещения привязан к началу. - \en The translation vector is associated with the beginning. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] resType - \ru Код результата операции - \en Operation result code \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] resType - \ru Код результата операции + \en Operation result code \~ \param[out] resCurve - \ru Эквидистантная кривая. \en The offset curve. \~ \return \ru Возвращает строитель. @@ -120,15 +141,10 @@ IMPL_PERSISTENT_OPS( MbOffsetCurveCreator ) \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & initCurve, - const MbVector3D & offsetVect, - const bool useFillet, - const bool keepRadius, - const bool bluntAngle, - const bool fromBeg, - const MbSNameMaker & snMaker, - MbResultType & resType, - MbCurve3D *& resCurve ); +MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & initCurve, + const MbSpatialOffsetCurveParams & params, + MbResultType & resType, + MbCurve3D *& resCurve ); //------------------------------------------------------------------------------ @@ -136,18 +152,12 @@ MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & initCurve, \en Create an offset curve from a spatial curve and offset value. \~ \details \ru Создать офсетную кривую по поверхностной кривой и значению смещения. \n \en Create an offset curve from a spatial curve and offset value. \n \~ - \param[in] curve - \ru Кривая на поверхности грани face. - \en A curve on face 'face' surface. \~ - \param[in] face - \ru Грань, на которой строится эквидистанта. - \en The edge on which to build the offset curve. \~ - \param[in] dirAxis - \ru Направление смещения с точкой приложения. - \en The offset direction with a point of application. \~ - \param[in] dist - \ru Величина смещения. - \en The offset distance. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] resType - \ru Код результата операции - \en Operation result code \~ + \param[in] curve - \ru Кривая на поверхности грани face. + \en A curve on face 'face' surface. \~ + \param[in] params - \ru Параметры. + \en Parameters. \~ + \param[out] resType - \ru Код результата операции + \en Operation result code \~ \param[out] resCurves - \ru Множество эквидистантных кривых. \en Offset curve array. \~ \return \ru Возвращает строитель. @@ -155,13 +165,10 @@ MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & initCurve, \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & curve, - const MbFace & face, - const MbAxis3D & dirAxis, - double dist, - const MbSNameMaker & snMaker, - MbResultType & resType, - RPArray & resCurves ); +MATH_FUNC (MbCreator *) CreateOffsetCurve( const MbCurve3D & curve, + const MbSurfaceOffsetCurveParams & params, + MbResultType & resType, + RPArray & resCurves ); #endif // __CR_OFFSET_CURVE_H diff --git a/C3d/Include/cr_patch_creator.h b/C3d/Include/cr_patch_creator.h index 249e62f..cfd14bc 100644 --- a/C3d/Include/cr_patch_creator.h +++ b/C3d/Include/cr_patch_creator.h @@ -54,10 +54,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -72,7 +72,7 @@ public : // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); // \ru Дать параметры. \en Get the parameters. void GetParameters( PatchValues & params ) const { params = parameters; } @@ -145,8 +145,8 @@ MATH_FUNC (MbCreator *) CreatePatchSet( const RPArray & initEdges, Одновременно с построением оболочки функция создает её строитель.\n \en Construct a patch-shaped shell from the given curves. The function simultaneously creates the shell and its constructor.\n \~ - \param[in] initEdges - \ru Кривые, определяющие края заплатки. - \en Curves determining the bounds of the patch. \~ + \param[in] initCurves - \ru Кривые, определяющие края заплатки. + \en Curves determining the bounds of the patch. \~ \param[in] parameters - \ru Параметры построения. \en Parameters of shell creation. \~ \param[in] operNames - \ru Именователь граней. @@ -160,11 +160,11 @@ MATH_FUNC (MbCreator *) CreatePatchSet( const RPArray & initEdges, \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *)CreatePatchSet( const RPArray & initCurves, - const PatchValues & parameters, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); +MATH_FUNC (MbCreator *) CreatePatchSet( const RPArray & initCurves, + const PatchValues & parameters, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); #endif // __CR_PATCH_CREATOR_H diff --git a/C3d/Include/cr_projection_curve.h b/C3d/Include/cr_projection_curve.h index 0fcbee4..847cbd9 100644 --- a/C3d/Include/cr_projection_curve.h +++ b/C3d/Include/cr_projection_curve.h @@ -49,15 +49,15 @@ public: // \ru Общие функции строителя. \en The common functions of the creator. virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -70,7 +70,7 @@ public: virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ); // \ru Получить внутренние построители по типу. \en Get internal creators by type. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ diff --git a/C3d/Include/cr_revolution_solid.h b/C3d/Include/cr_revolution_solid.h index 0ead11a..c645843 100644 --- a/C3d/Include/cr_revolution_solid.h +++ b/C3d/Include/cr_revolution_solid.h @@ -65,10 +65,10 @@ public : \en \name Common functions of the mathematical object. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -156,7 +156,7 @@ MATH_FUNC (MbCreator *) CreateCurveRevolution( MbFaceShell * sol const MbSNameMaker & operNames, const RPArray & contoursNames, MbResultType & resType, - MbFaceShell *& shell ); + c3d::ShellSPtr & shell ); #endif // __CR_REVOLUTION_SOLID_H diff --git a/C3d/Include/cr_rib_solid.h b/C3d/Include/cr_rib_solid.h index 3744a18..d2ca4c2 100644 --- a/C3d/Include/cr_rib_solid.h +++ b/C3d/Include/cr_rib_solid.h @@ -43,10 +43,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy - virtual void Transform ( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual void Transform ( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -59,7 +59,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction + RPArray *items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( RibValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_ruled_shell.h b/C3d/Include/cr_ruled_shell.h index 5d8b130..06d1c5b 100644 --- a/C3d/Include/cr_ruled_shell.h +++ b/C3d/Include/cr_ruled_shell.h @@ -46,12 +46,12 @@ public: public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; ///< \ru Тип элемента \en Element type - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; ///< \ru Сделать копию \en Make a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; ///< \ru Сделать копию \en Make a copy virtual bool IsSame( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); ///< \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); ///< \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); ///< \ru Сдвиг по вектору \en Translation by the vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); ///< \ru Поворот вокруг оси \en Rotation about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); ///< \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); ///< \ru Сдвиг по вектору \en Translation by the vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); ///< \ru Поворот вокруг оси \en Rotation about an axis virtual void GetProperties( MbProperties & properties ); ///< \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); ///< \ru Записать свойства объекта \en Write properties of the object @@ -63,7 +63,7 @@ public: // \ru Общие функции математического объе public: /// \ru Построение оболочки \en Creation of a shell virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); // \ru Дать параметры. \en Get the parameters. void GetParameters( RuledSurfaceValues & params ) const; // \ru Установить параметры. \en Set the parameters. diff --git a/C3d/Include/cr_section_shell.h b/C3d/Include/cr_section_shell.h index a2fafd4..3626994 100644 --- a/C3d/Include/cr_section_shell.h +++ b/C3d/Include/cr_section_shell.h @@ -2,7 +2,7 @@ /** \file \brief \ru Строитель оболочки на поверхности переменного сечения. - \en Constructor of shell of evolution solid. \~ + \en Constructor of shell on mutable section surface. \~ */ //////////////////////////////////////////////////////////////////////////////// @@ -22,7 +22,7 @@ class MATH_CLASS MbFaceShell; //------------------------------------------------------------------------------ /** \brief \ru Строитель оболочки на поверхности переменного сечения. - \en Constructor of the shell on swept mutable section surface. \~ + \en Constructor of the shell on mutable section surface. \~ \details \ru Грань оболочки строится путём движения переменного сечения по опорной кривой. \n \en Constructor of face by moving generating curve along a reference spine curve. \n \~ \ingroup Model_Creators @@ -30,13 +30,13 @@ class MATH_CLASS MbFaceShell; // --- class MATH_CLASS MbSectionShell : public MbCreator { protected : - MbSectionData sectionData; ///< \ru Данные о поверхности переменного сечения. \en Data about swept mutable section surface. - MbSectionCode sectionCode; ///< \ru Данные о поверхности переменного сечения. \en Data about swept mutable section surface. + MbSectionData sectionData; ///< \ru Данные о поверхности переменного сечения. \en Data about mutable section surface. + MbSectionCode sectionCode; ///< \ru Данные о поверхности переменного сечения. \en Data about mutable section surface. /** \brief \ru Конструктор. \en Constructor. \~ \param[in] data - \ru Данные о поверхности переменного сечения. - \en Data about swept mutable section surface. \~ + \en Data about mutable section surface. \~ \param[in] names - \ru Именователь грани оболочки. \en Generating face names. \~ */ @@ -54,10 +54,10 @@ public : \en \name Common functions of the mathematical object. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -75,7 +75,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual void SetYourVersion( VERSION version ); /** \} */ @@ -94,7 +94,7 @@ public : /** \} */ /** \brief \ru Создать оболочку на поверхности переменного сечения. - \en Create a shell on swept mutable section surface. \~ + \en Create a shell on mutable section surface. \~ \details \ru Построить оболочку путём движения образующей кривой по направляющей кривой и выполнить булеву операцию с оболочкой, если последняя задана. \n Одновременно с построением оболочки функция создаёт её строитель.\n @@ -106,7 +106,7 @@ public : \param[in] sameShell - \ru Способ копирования граней. \en The method of copying faces. \~ \param[in] data - \ru Данные о поверхности переменного сечения. - \en Data about swept mutable section surface. \~ + \en Data about mutable section surface. \~ \param[in] names - \ru Именователь грани оболочки. \en Generating face names. \~ \param[out] res - \ru Код результата операции. diff --git a/C3d/Include/cr_sheet_bend_any_solid.h b/C3d/Include/cr_sheet_bend_any_solid.h index e1e4136..09eb4bb 100644 --- a/C3d/Include/cr_sheet_bend_any_solid.h +++ b/C3d/Include/cr_sheet_bend_any_solid.h @@ -47,15 +47,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -65,7 +65,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/cr_sheet_bend_by_edge_solid.h b/C3d/Include/cr_sheet_bend_by_edge_solid.h index ebda627..2786936 100644 --- a/C3d/Include/cr_sheet_bend_by_edge_solid.h +++ b/C3d/Include/cr_sheet_bend_by_edge_solid.h @@ -58,14 +58,14 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -76,7 +76,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbBendByEdgeValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_sheet_bend_over_seg_solid.h b/C3d/Include/cr_sheet_bend_over_seg_solid.h index be76c67..8617fdc 100644 --- a/C3d/Include/cr_sheet_bend_over_seg_solid.h +++ b/C3d/Include/cr_sheet_bend_over_seg_solid.h @@ -49,15 +49,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -69,7 +69,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbBendOverSegValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_sheet_bend_unbend_solid.h b/C3d/Include/cr_sheet_bend_unbend_solid.h index e012990..a6be1a7 100644 --- a/C3d/Include/cr_sheet_bend_unbend_solid.h +++ b/C3d/Include/cr_sheet_bend_unbend_solid.h @@ -50,15 +50,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -68,7 +68,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. @@ -122,7 +122,7 @@ MATH_FUNC (MbCreator *) CreateBendUnbend( SPtr & init const MbSNameMaker & names, MbResultType & res, MbFaceShell *& shell, - RPArray * ribContours = NULL ); + RPArray * ribContours = c3d_null ); diff --git a/C3d/Include/cr_sheet_builder_solid.h b/C3d/Include/cr_sheet_builder_solid.h index a0d52e1..6f551b9 100644 --- a/C3d/Include/cr_sheet_builder_solid.h +++ b/C3d/Include/cr_sheet_builder_solid.h @@ -1,114 +1,114 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель оболочки из листового материала на основе произвольного тела. - \en Constructor of the sheet metal shell based on an arbitrary solid. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SHEET_BUILDER_SOLID_H -#define __CR_SHEET_BUILDER_SOLID_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала на основе произвольного тела. - \en Constructor of the sheet metal shell based on an arbitrary solid. \~ - \details \ru Строитель оболочки из листового материала на основе граней и ребер произвольного тела.\n - Оболочка строится на базе исходной плоской грани и указанных ребер сгиба и разреза. - \en Constructor of the sheet metal shell based on faces and edges of an arbitrary solid. \n - Shell builds based on initial planar face and given edges of bend and corner enclosure. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbBuildSheetMetalSolid : public MbCreator { -private: - MbItemIndex faceIndex; ///< \ru Индекс исходной грани для построения листового тела. \en Index of initial face for sheet metal solid creation. - bool sense; ///< \ru Признак совпадения придания толщины с нормалью исходной грани. \en Attribute of coincidence of extrusion direction to the normal of the initial face. - MbSolidToSheetMetalValues parameters; ///< \ru Параметры построения листового тела по произвольному телу. \en The parameters of sheet metal solid building based on an arbitrary solid. - -public : - MbBuildSheetMetalSolid( const MbItemIndex & faceIndex, - const bool sense, - const MbSolidToSheetMetalValues & params, - const MbSNameMaker & names ); -private: - MbBuildSheetMetalSolid( const MbBuildSheetMetalSolid &, MbRegDuplicate * iReg ); - -public: - virtual ~MbBuildSheetMetalSolid(); - - // \ru Общие функции математического объекта. \en Common functions of the mathematical object. - - virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию. \en Create a copy. - - virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? - virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным. \en Make equal. - - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. - - virtual void GetProperties ( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties ( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - - // \ru Общие функции твердого тела. \en Common functions of solid. - - // \ru Построение оболочки листового тела. \en Construction of a sheet metal shell. - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, RPArray *items = NULL ); - // \ru Получить параметры. \en Get the parameters. - void GetParameters( MbSolidToSheetMetalValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbSolidToSheetMetalValues & params ) { parameters = params; } - -private: - OBVIOUS_PRIVATE_COPY( MbBuildSheetMetalSolid ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBuildSheetMetalSolid ) -}; - -IMPL_PERSISTENT_OPS( MbBuildSheetMetalSolid ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала на основе произвольного тела. - \en Constructor of the sheet metal shell based on an arbitrary solid. \~ - \details \ru На базе исходной произвольной оболочки построить оболочку из листового материала. \n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en A shell is to be constructed on the basis of the source arbitary shell. \n - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] solid - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the source shell. \~ - \param[in] initFace - \ru Исходная грань для построения листового тела. - \en The initial face for sheet metal solid construction. \~ - \param[in] sense - \ru Признак совпадения направления придания толщины с нормалью исходной грани. - \en Attribute of coincidence of extrusion direction to the normal of the initial face. \~ - \param[in] params - \ru Параметры построения листового тела по произвольному телу. - \en The parameters of sheet metal solid building based on an arbitrary solid. \~ - \param[in] nameMaker - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующее тело. - \en The resultant solid. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) ConvertShellToSheetMetall( MbFaceShell * initialShell, // Исходная оболочка, - const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, - const MbFace & initFace, // базовая грань, относительно которой будет строиться листовое тело, - bool sense, // признак совпадения придания толщины с нормалью базовой грани, - MbSolidToSheetMetalValues & params, // параметры построения листового тела, - const MbSNameMaker & nameMaker, // именователь, - MbResultType & res, // флаг успешности операции, - SPtr & resultShell ); // результирующая оболочка. - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель оболочки из листового материала на основе произвольного тела. + \en Constructor of the sheet metal shell based on an arbitrary solid. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SHEET_BUILDER_SOLID_H +#define __CR_SHEET_BUILDER_SOLID_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала на основе произвольного тела. + \en Constructor of the sheet metal shell based on an arbitrary solid. \~ + \details \ru Строитель оболочки из листового материала на основе граней и ребер произвольного тела.\n + Оболочка строится на базе исходной плоской грани и указанных ребер сгиба и разреза. + \en Constructor of the sheet metal shell based on faces and edges of an arbitrary solid. \n + Shell builds based on initial planar face and given edges of bend and corner enclosure. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbBuildSheetMetalSolid : public MbCreator { +private: + MbItemIndex faceIndex; ///< \ru Индекс исходной грани для построения листового тела. \en Index of initial face for sheet metal solid creation. + bool sense; ///< \ru Признак совпадения придания толщины с нормалью исходной грани. \en Attribute of coincidence of extrusion direction to the normal of the initial face. + MbSolidToSheetMetalValues parameters; ///< \ru Параметры построения листового тела по произвольному телу. \en The parameters of sheet metal solid building based on an arbitrary solid. + +public : + MbBuildSheetMetalSolid( const MbItemIndex & faceIndex, + const bool sense, + const MbSolidToSheetMetalValues & params, + const MbSNameMaker & names ); +private: + MbBuildSheetMetalSolid( const MbBuildSheetMetalSolid &, MbRegDuplicate * iReg ); + +public: + virtual ~MbBuildSheetMetalSolid(); + + // \ru Общие функции математического объекта. \en Common functions of the mathematical object. + + virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию. \en Create a copy. + + virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? + virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным. \en Make equal. + + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + + virtual void GetProperties ( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual void SetProperties ( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + // \ru Общие функции твердого тела. \en Common functions of solid. + + // \ru Построение оболочки листового тела. \en Construction of a sheet metal shell. + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, RPArray *items = c3d_null ); + // \ru Получить параметры. \en Get the parameters. + void GetParameters( MbSolidToSheetMetalValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbSolidToSheetMetalValues & params ) { parameters = params; } + +private: + OBVIOUS_PRIVATE_COPY( MbBuildSheetMetalSolid ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBuildSheetMetalSolid ) +}; + +IMPL_PERSISTENT_OPS( MbBuildSheetMetalSolid ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала на основе произвольного тела. + \en Constructor of the sheet metal shell based on an arbitrary solid. \~ + \details \ru На базе исходной произвольной оболочки построить оболочку из листового материала. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en A shell is to be constructed on the basis of the source arbitary shell. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] solid - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] initFace - \ru Исходная грань для построения листового тела. + \en The initial face for sheet metal solid construction. \~ + \param[in] sense - \ru Признак совпадения направления придания толщины с нормалью исходной грани. + \en Attribute of coincidence of extrusion direction to the normal of the initial face. \~ + \param[in] params - \ru Параметры построения листового тела по произвольному телу. + \en The parameters of sheet metal solid building based on an arbitrary solid. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующее тело. + \en The resultant solid. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) ConvertShellToSheetMetall( MbFaceShell * initialShell, // Исходная оболочка, + const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, + const MbFace & initFace, // базовая грань, относительно которой будет строиться листовое тело, + bool sense, // признак совпадения придания толщины с нормалью базовой грани, + MbSolidToSheetMetalValues & params, // параметры построения листового тела, + const MbSNameMaker & nameMaker, // именователь, + MbResultType & res, // флаг успешности операции, + SPtr & resultShell ); // результирующая оболочка. + + #endif // __CR_SHEET_BUILDER_SOLID_H \ No newline at end of file diff --git a/C3d/Include/cr_sheet_closed_corner_solid.h b/C3d/Include/cr_sheet_closed_corner_solid.h index 3dc6773..fa86c6c 100644 --- a/C3d/Include/cr_sheet_closed_corner_solid.h +++ b/C3d/Include/cr_sheet_closed_corner_solid.h @@ -50,15 +50,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -68,7 +68,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbClosedCornerValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_sheet_joint_bend_solid.h b/C3d/Include/cr_sheet_joint_bend_solid.h index 45c4b60..1e7dc69 100644 --- a/C3d/Include/cr_sheet_joint_bend_solid.h +++ b/C3d/Include/cr_sheet_joint_bend_solid.h @@ -57,15 +57,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -74,7 +74,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbJointBendValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_sheet_metal_solid.h b/C3d/Include/cr_sheet_metal_solid.h index 8e9dadb..0b96d9f 100644 --- a/C3d/Include/cr_sheet_metal_solid.h +++ b/C3d/Include/cr_sheet_metal_solid.h @@ -82,10 +82,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -101,7 +101,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual MbFaceShell * InitShell( bool in ); diff --git a/C3d/Include/cr_sheet_restored_edges_solid.h b/C3d/Include/cr_sheet_restored_edges_solid.h index 8066fc3..08839eb 100644 --- a/C3d/Include/cr_sheet_restored_edges_solid.h +++ b/C3d/Include/cr_sheet_restored_edges_solid.h @@ -45,15 +45,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -63,7 +63,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/cr_sheet_simplified_flat_solid.h b/C3d/Include/cr_sheet_simplified_flat_solid.h index d3d9c96..0e73ead 100644 --- a/C3d/Include/cr_sheet_simplified_flat_solid.h +++ b/C3d/Include/cr_sheet_simplified_flat_solid.h @@ -42,15 +42,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -60,7 +60,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/cr_sheet_union_solid.h b/C3d/Include/cr_sheet_union_solid.h index fb19969..18b4a26 100644 --- a/C3d/Include/cr_sheet_union_solid.h +++ b/C3d/Include/cr_sheet_union_solid.h @@ -43,10 +43,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * ireg = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -62,7 +62,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual void SetYourVersion( VERSION version, bool forAll ); diff --git a/C3d/Include/cr_simple_creator.h b/C3d/Include/cr_simple_creator.h index 638eb1e..23a94c6 100644 --- a/C3d/Include/cr_simple_creator.h +++ b/C3d/Include/cr_simple_creator.h @@ -68,10 +68,10 @@ public : \en \name Common functions of the shell creator. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -85,7 +85,7 @@ public : virtual bool SetEqual( const MbCreator & ); // \ru Сделать равным \en Make equal virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction /** \} */ const MbFaceShell * GetShell() const { return outer; } /// \ru Дать оболочку. \en Get a shell. @@ -158,7 +158,7 @@ bool MbSimpleCreator::DeleteShellCopies( const CreatorsVector & creators ) size_t i; for ( i = 0; i < creatorsCnt; ++i ) { MbCreator * creator = creators[i]; - if ( creator != NULL ) { + if ( creator != c3d_null ) { if ( creator->IsA() == ct_SimpleCreator ) { MbSimpleCreator * simpleCreator = static_cast(creator); simpleShells.push_back( std::make_pair( i, simpleCreator->GetShell() ) ); @@ -184,7 +184,7 @@ bool MbSimpleCreator::DeleteShellCopies( const CreatorsVector & creators ) if ( shell1 && shell2 && (shell1 != shell2) ) { if ( shell1->IsSame( *shell2, LENGTH_EPSILON ) ) { sc2.SetShell( *shell1 ); - simpleShells[j].second = NULL; + simpleShells[j].second = c3d_null; isReplaced = true; } } @@ -194,7 +194,7 @@ bool MbSimpleCreator::DeleteShellCopies( const CreatorsVector & creators ) std::sort( simpleShells.begin(), simpleShells.end(), ::SortByShellPointers ); simpleShells.erase( std::unique( simpleShells.begin(), simpleShells.end(), ::AreEqualShellPointers ), simpleShells.end() ); if ( simpleShells.size() > 1 ) { - if ( simpleShells.front().second == NULL ) + if ( simpleShells.front().second == c3d_null ) simpleShells.erase( simpleShells.begin() ); } } @@ -215,7 +215,7 @@ bool MbSimpleCreator::IsThisShell( const MbFaceShell & shell, const CreatorsVect if ( creators.size() > 0 ) { for ( size_t i = creators.size(); i--; ) { const MbCreator * creator = creators[i]; - if ( (creator != NULL) && (creator->IsA() == ct_SimpleCreator) ) { + if ( (creator != c3d_null) && (creator->IsA() == ct_SimpleCreator) ) { const MbSimpleCreator & simpleCreator = static_cast(*creator); if ( simpleCreator.GetShell() == &shell ) { res = true; @@ -253,10 +253,10 @@ public : \en \name Common functions of the shell creator. \{ */ virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -267,7 +267,7 @@ public : virtual bool IsSimilar ( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction /** \} */ DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReverseCreator ) diff --git a/C3d/Include/cr_smooth_solid.h b/C3d/Include/cr_smooth_solid.h index 3956d04..d41ce33 100644 --- a/C3d/Include/cr_smooth_solid.h +++ b/C3d/Include/cr_smooth_solid.h @@ -42,10 +42,10 @@ public : virtual MbeCreatorType IsA() const = 0; // \ru Тип элемента \en A type of element virtual MbeCreatorType Type() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate *iReg = NULL ) const = 0; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate *iReg = c3d_null ) const = 0; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ) = 0; // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ) = 0; // \ru Записать свойства объекта \en Set properties of the object @@ -58,7 +58,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = NULL ) = 0; // \ru Построение \en Construction + RPArray * items = c3d_null ) = 0; // \ru Построение \en Construction /// \ru Дать параметры. \en Get the parameters. void GetParameters( SmoothValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_split_data.h b/C3d/Include/cr_split_data.h index ea8a9a5..b1d4102 100644 --- a/C3d/Include/cr_split_data.h +++ b/C3d/Include/cr_split_data.h @@ -91,7 +91,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { } /// \ru Конструктор по двумерному контуру в локальной системе координат. \en Constructor by two-dimensional contour in the local coordinate system. @@ -103,7 +103,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { SPtr sketchContour; sketchContour = same ? const_cast(&item) : static_cast(&item.Duplicate()); @@ -118,7 +118,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); @@ -136,7 +136,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { ::AddRefItems( items, same, sketchContours ); } @@ -150,7 +150,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); @@ -165,7 +165,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { ::AddRefItems( items, same, spaceCurves ); } @@ -178,7 +178,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { ::AddRefItems( items, same, spaceCurves ); } @@ -191,7 +191,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { SPtr surface; surface = same ? const_cast(&item) : static_cast(&item.Duplicate()); @@ -206,7 +206,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { ::AddRefItems( items, same, surfaces ); } @@ -219,7 +219,7 @@ public: , spaceCurves ( ) , surfaces ( ) , creators ( ) - , solidShell ( NULL ) + , solidShell ( c3d_null ) { ::AddRefItems( items, same, surfaces ); } @@ -322,12 +322,12 @@ public: DeleteItems(); size_t creatorsCnt = solidCreators.size(); if ( creatorsCnt > 0 ) { - MbRegDuplicate * iReg = NULL; + MbRegDuplicate * iReg = c3d_null; MbAutoRegDuplicate autoReg( iReg ); SPtr creator; creators.reserve( creatorsCnt ); for ( size_t k = 0; k < creatorsCnt; ++k ) { - if ( solidCreators[k] != NULL ) { + if ( solidCreators[k] != c3d_null ) { creator = sameCreators ? &const_cast( *solidCreators[k] ) : static_cast( &solidCreators[k]->Duplicate( iReg ) ); creators.push_back( creator ); ::DetachItem( creator ); @@ -343,17 +343,17 @@ public: /// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. bool IsSimilar( const MbSplitData & ) const; /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть по вектору. \en Shift by a vector. - void Move ( const MbVector3D &, MbRegTransform * = NULL ); + void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть вокруг оси. \en Rotate about an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /// \ru Отсутствуют ли объекты? \en Are the objects absent? bool IsEmpty() const { return ( sketchContours.empty() && spaceCurves.empty() && surfaces.empty() && - (creators.empty() && (solidShell == NULL)) ); } + (creators.empty() && (solidShell == c3d_null)) ); } /// \ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MbSplitData &, double accuracy ) const; @@ -377,9 +377,9 @@ public: /// \ru Установить направление выдавливания двумерных кривых. \en Set extrusion direction of two-dimensional curves. void SetSketchSense( MbeSenseValue zdir ) { sense = zdir; } /// \ru Получить двумерную кривую по индексу. \en Get two-dimensional curve by index. - const MbContour * GetSketchCurve( size_t k ) const { return ((k < sketchContours.size()) ? sketchContours[k].get() : NULL ); } + const MbContour * GetSketchCurve( size_t k ) const { return ((k < sketchContours.size()) ? sketchContours[k].get() : c3d_null ); } /// \ru Получить двумерную кривую по индексу. \en Get two-dimensional curve by index. - MbContour * SetSketchCurve( size_t k ) { return ((k < sketchContours.size()) ? sketchContours[k].get() : NULL ); } + MbContour * SetSketchCurve( size_t k ) { return ((k < sketchContours.size()) ? sketchContours[k].get() : c3d_null ); } /// \ru Получить все двумерные кривые. \en Get all two-dimensional curves. template void GetSketchCurves( PlaneContoursVector & curvs ) const @@ -401,9 +401,9 @@ public: /// \ru Выдать количество пространственных кривых. \en Get number of spatial curves. size_t GetSpaceCurvesCount() const { return spaceCurves.size(); } /// \ru Получить пространственную кривую по индексу. \en Get a spatial curve by index. - const MbCurve3D * GetSpaceCurve( size_t k ) const { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : NULL ); } + const MbCurve3D * GetSpaceCurve( size_t k ) const { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : c3d_null ); } /// \ru Получить пространственную кривую по индексу. \en Get a spatial curve by index. - MbCurve3D * SetSpaceCurve( size_t k ) { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : NULL ); } + MbCurve3D * SetSpaceCurve( size_t k ) { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : c3d_null ); } /// \ru Получить все пространственные кривые. \en Get all spatial curves. template void GetSpaceCurves( SpaceCurvesVector & curvs ) const @@ -425,9 +425,9 @@ public: /// \ru Выдать количество поверхностей. \en Get number of surfaces. size_t GetSurfacesCount() const { return surfaces.size(); } /// \ru Получить поверхность по индексу. \en Get a surface by index. - const MbSurface * GetSurface( size_t k ) const { return ((k < surfaces.size()) ? surfaces[k].get() : NULL); } + const MbSurface * GetSurface( size_t k ) const { return ((k < surfaces.size()) ? surfaces[k].get() : c3d_null); } /// \ru Получить поверхность по индексу. \en Get a surface by index. - MbSurface * SetSurface( size_t k ) { return ((k < surfaces.size()) ? surfaces[k].get() : NULL); } + MbSurface * SetSurface( size_t k ) { return ((k < surfaces.size()) ? surfaces[k].get() : c3d_null); } /// \ru Получить все поверхности. \en Get all surfaces. template void GetSurfaces( SurfacesVector & surfs ) const @@ -449,9 +449,9 @@ public: /// \ru Выдать количество строителей тела. \en Get number of solid creators. size_t GetCreatorsCount() const { return creators.size(); } /// \ru Получить строитель по индексу. \en Get constructor by index. - const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? creators[k].get() : NULL ); } + const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? creators[k].get() : c3d_null ); } /// \ru Получить строитель по индексу. \en Get constructor by index. - MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? creators[k].get() : NULL ); } + MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? creators[k].get() : c3d_null ); } /// \ru Получить все строители. \en Get all creators. template void GetCreators( CreatorsVector & crs ) const @@ -468,17 +468,17 @@ public: template void GetCreatorsCopies( CreatorsVector & crs ) const { - MbRegDuplicate * iReg = NULL; + MbRegDuplicate * iReg = c3d_null; MbAutoRegDuplicate autoReg( iReg ); crs.reserve( crs.size() + creators.size() ); c3d::CreatorSPtr creator; for ( size_t k = 0, addCnt = creators.size(); k < addCnt; ++k ) { - if ( creators[k] != NULL ) + if ( creators[k] != c3d_null ) creator = static_cast( &creators[k]->Duplicate( iReg ) ); crs.push_back( creator ); ::DetachItem( creator ); - creator = NULL; + creator = c3d_null; } } /// \ru Получить все строители. \en Get all creators. diff --git a/C3d/Include/cr_split_shell.h b/C3d/Include/cr_split_shell.h index 04fcadb..bf977ee 100644 --- a/C3d/Include/cr_split_shell.h +++ b/C3d/Include/cr_split_shell.h @@ -41,10 +41,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -58,7 +58,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Не реализовано \en Not implemented // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. diff --git a/C3d/Include/cr_stamp_bead_solid.h b/C3d/Include/cr_stamp_bead_solid.h index 7aaf46d..d75828a 100644 --- a/C3d/Include/cr_stamp_bead_solid.h +++ b/C3d/Include/cr_stamp_bead_solid.h @@ -67,15 +67,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties ( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -87,7 +87,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbBeadValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_stamp_jalousie_solid.h b/C3d/Include/cr_stamp_jalousie_solid.h index 492280f..5173b53 100644 --- a/C3d/Include/cr_stamp_jalousie_solid.h +++ b/C3d/Include/cr_stamp_jalousie_solid.h @@ -66,13 +66,13 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties ( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties ( const MbProperties &properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -84,7 +84,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbJalousieValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_stamp_jog_solid.h b/C3d/Include/cr_stamp_jog_solid.h index d65403c..b3ce5c2 100644 --- a/C3d/Include/cr_stamp_jog_solid.h +++ b/C3d/Include/cr_stamp_jog_solid.h @@ -63,13 +63,13 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -82,7 +82,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbJogValues & params ) const { params = jogParameters; } diff --git a/C3d/Include/cr_stamp_remove_solid.h b/C3d/Include/cr_stamp_remove_solid.h index ee56931..d555811 100644 --- a/C3d/Include/cr_stamp_remove_solid.h +++ b/C3d/Include/cr_stamp_remove_solid.h @@ -43,15 +43,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -61,7 +61,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. diff --git a/C3d/Include/cr_stamp_rib_solid.h b/C3d/Include/cr_stamp_rib_solid.h index 1f945cb..615d611 100644 --- a/C3d/Include/cr_stamp_rib_solid.h +++ b/C3d/Include/cr_stamp_rib_solid.h @@ -46,10 +46,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA () const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy - virtual void Transform ( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual void Transform ( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -62,7 +62,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction + RPArray *items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( SheetRibValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_stamp_ruled_solid.h b/C3d/Include/cr_stamp_ruled_solid.h index c30dbc7..6ddb86a 100644 --- a/C3d/Include/cr_stamp_ruled_solid.h +++ b/C3d/Include/cr_stamp_ruled_solid.h @@ -49,15 +49,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -69,7 +69,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать базовые объекты. \en Get the base objects. virtual void GetBasisItems( RPArray & s ); diff --git a/C3d/Include/cr_stamp_solid.h b/C3d/Include/cr_stamp_solid.h index 8f4950d..546710c 100644 --- a/C3d/Include/cr_stamp_solid.h +++ b/C3d/Include/cr_stamp_solid.h @@ -65,15 +65,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties ( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties ( const MbProperties &properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -85,7 +85,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction + RPArray *items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbStampingValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_stamp_spherical_solid.h b/C3d/Include/cr_stamp_spherical_solid.h index 7dd0871..f83ff7e 100644 --- a/C3d/Include/cr_stamp_spherical_solid.h +++ b/C3d/Include/cr_stamp_spherical_solid.h @@ -60,15 +60,15 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties ( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties ( const MbProperties &properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -80,7 +80,7 @@ public: // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction + RPArray *items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( MbStampingValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_stamp_user_solid.h b/C3d/Include/cr_stamp_user_solid.h index 4e1f13f..d27ee72 100644 --- a/C3d/Include/cr_stamp_user_solid.h +++ b/C3d/Include/cr_stamp_user_solid.h @@ -60,15 +60,15 @@ public: // \ru Общие функции математического объекта. \en Common functions of the mathematical object. virtual MbeCreatorType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию. \en Create a copy. + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию. \en Create a copy. virtual bool IsSame ( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & item ) const; // \ru Являются ли объекты подобными? \en Determine whether an object is similar? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties ( MbProperties &properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties ( const MbProperties &properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -77,7 +77,7 @@ public: // \ru Общие функции твердого тела. \en Common functions of solid. virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение оболочки штамповки. \en Construction of a stamping shell. + RPArray *items = c3d_null ); // \ru Построение оболочки штамповки. \en Construction of a stamping shell. // \ru Получить параметры. \en Get the parameters. void GetParameters( MbToolStampingValues & params ) const { params = parameters; } @@ -124,18 +124,59 @@ IMPL_PERSISTENT_OPS( MbUserStampSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateUserStamp( MbFaceShell * initialShell, // Исходная оболочка, - const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, - const MbFace & targetFace, // грань штамповки, - const RPArray & creatorsTool, // журнал построения инструмента, - MbFaceShell & toolShell, // оболочка тела-инструмента, - const MbeCopyMode sameShellTool, // флаг способа использования оболочки инструмента, - bool isPunch, // является инструмент пуансоном или матрицей, - const RPArray & pierceFaces, // вскрываемые для вырубки грани инструмента, - const MbToolStampingValues & params, // параметры штамповки, - const MbSNameMaker & nameMaker, // именователь, - MbResultType & res, // флаг успешности операции, - SPtr & resultShell ); // результирующая оболочка. +MATH_FUNC (MbCreator *) CreateUserStamp( MbFaceShell * initialShell, // Исходная оболочка, + const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, + const MbFace & targetFace, // грань штамповки, + const RPArray & creatorsTool, // журнал построения инструмента, + MbFaceShell & toolShell, // оболочка тела-инструмента, + const MbeCopyMode sameShellTool, // флаг способа использования оболочки инструмента, + bool isPunch, // является инструмент пуансоном или матрицей, + const RPArray & pierceFaces, // вскрываемые для вырубки грани инструмента, + const MbToolStampingValues & params, // параметры штамповки, + const MbSNameMaker & nameMaker, // именователь, + MbResultType & res, // флаг успешности операции, + SPtr & resultShell ); // результирующая оболочка + +//------------------------------------------------------------------------------ +/** \brief \ru Построение результирующей оболочки. + \en Construction of result shell. \~ + \details \ru На базе исходной оболочки из листового материала построить оболочку методом закрытой или открытой штамповки. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en A shell is to be constructed on the basis of the source shell by the method of closed or open stamping. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] initialShell - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] targetFace - \ru Грань штамповки. + \en The face for stamping. \~ + \param[in] toolShell - \ru Оболочка тела-инструмента. + \en A shell of tool solid. \~ + \param[in] sameShellTool - \ru Режим копирования оболочки тела-инструмента. + \en Mode of copying the tool shell. \~ + \param[in] isPunch - \ru Является тело-инструмент пуансоном или матрицей. + \en Is tool body a punch or a die. \~ + \param[in] pierceFaces - \ru Вскрываемые для вырубки грани инструмента, + \en Pierce faces of tool body. \~ + \param[in] params - \ru Параметры штамповки. + \en The parameters of stamping. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \result \ru - тело со штамповкой. + \en - The solid with stamping. \~ + \ingroup Model_Creators +*/ +// --- +MbFaceShell * MakeUserStampShellForStampParts ( MbFaceShell * initialShell, // Исходная оболочка, + const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, + const MbFace & targetFace, // грань штамповки, + MbFaceShell & toolShell, // оболочка тела-инструмента, + const MbeCopyMode sameShellTool, // флаг способа использования оболочки инструмента, + bool isPunch, // является инструмент пуансоном или матрицей, + const RPArray & pierceFaces, // вскрываемые для вырубки грани инструмента, + const MbToolStampingValues & params, // параметры штамповки, + const MbSNameMaker & nameMaker ); // именователь, + #endif // __CR_USERSTAMP_SOLID_H diff --git a/C3d/Include/cr_stitch_solid.h b/C3d/Include/cr_stitch_solid.h index 94f6894..656074d 100644 --- a/C3d/Include/cr_stitch_solid.h +++ b/C3d/Include/cr_stitch_solid.h @@ -78,11 +78,11 @@ public : size_t estSimpleCnt = 0; for ( i = 0; i < setsCnt; ++i ) { Creators * creatorsSet = creatorsData[i]; - if ( creatorsSet != NULL ) { + if ( creatorsSet != c3d_null ) { size_t count = creatorsSet->size(); for ( size_t j = 0; j < count; ++j ) { MbCreator * creator = (*creatorsSet)[j]; - if ( creator != NULL ) + if ( creator != c3d_null ) estSimpleCnt += creator->GetCreatorsCount( ct_SimpleCreator ); } } @@ -93,13 +93,13 @@ public : c3d::CreatorSPtr creator; for ( i = 0; i < setsCnt; ++i ) { Creators * creatorsSet = creatorsData[i]; - if ( creatorsSet != NULL ) { + if ( creatorsSet != c3d_null ) { size_t count = creatorsSet->size(); RPArray * creators = new RPArray( count, 1 ); creatorsArray.push_back( creators ); for ( size_t j = 0; j < count; ++j ) { // важен порядок перебора creator = (*creatorsSet)[j]; - if ( creator != NULL ) { + if ( creator != c3d_null ) { creators->push_back( creator ); if ( creator->IsA() == ct_SimpleCreator ) simpleCreators.push_back( creator ); @@ -125,12 +125,12 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -146,7 +146,7 @@ public: virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual void SetYourVersion( VERSION version, bool forAll ); diff --git a/C3d/Include/cr_surface_spline.h b/C3d/Include/cr_surface_spline.h index ccbe886..20e3008 100644 --- a/C3d/Include/cr_surface_spline.h +++ b/C3d/Include/cr_surface_spline.h @@ -31,12 +31,12 @@ class MATH_CLASS MbSurface; // --- class MATH_CLASS MbSurfaceSplineCreator : public MbCreator { private: - MbSurface * surface; // \ru Поверхность \en Surface - bool throughPnts; // \ru через точки \en Through points - SArray paramPnts; // \ru Параметрические точки \en Parametric points - SArray paramWts; // \ru Веса параметрических точек \en Parametric points weights - bool paramClosed; // \ru Замкнуть параметрический сплайн \en Make the parametric spline close - RPArray< MbPntMatingData > spaceTransitions; // \ru Сопряжения в точках \en Tangents at the points + MbSurface * surface; // \ru Поверхность \en Surface + bool throughPnts; // \ru через точки \en Through points + SArray paramPnts; // \ru Параметрические точки \en Parametric points + SArray paramWts; // \ru Веса параметрических точек \en Parametric points weights + bool paramClosed; // \ru Замкнуть параметрический сплайн \en Make the parametric spline close + RPArray spaceTransitions; // \ru Сопряжения в точках \en Tangents at the points protected: MbSurfaceSplineCreator( const MbSurfaceSplineCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor @@ -44,25 +44,28 @@ protected: MbSurfaceSplineCreator(); // \ru Не реализовано \en Not implemented public: - MbSurfaceSplineCreator( const MbSurface &, bool sameSurf, bool thrPnts, - const SArray & pnts, - const SArray & wts, bool parCls, - RPArray< MbPntMatingData > & transitions, - const MbSNameMaker & snMaker ); + MbSurfaceSplineCreator( const MbSurface & surface, + bool sameSurf, + bool thrPnts, + const SArray & pnts, + const SArray & wts, + bool parCls, + RPArray & transitions, + const MbSNameMaker & snMaker ); public : virtual ~MbSurfaceSplineCreator(); // \ru Общие функции строителя. \en The common functions of the creator. virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame ( const MbCreator &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual MbePrompt GetPropertyName(); // \ru Дать имя свойства объекта \en Get the object property name virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -72,7 +75,7 @@ public : virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. // \ru Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = c3d_null ); /** \} */ @@ -127,15 +130,15 @@ IMPL_PERSISTENT_OPS( MbSurfaceSplineCreator ) \ingroup Curve3D_Modeling */ //--- -MATH_FUNC (MbCreator *) CreateSurfaceSpline( const MbSurface & surface, - bool throughPoints, - SArray & paramPnts, - SArray & paramWts, - bool paramClosed, - RPArray< MbPntMatingData > & spaceTransitions, - const MbSNameMaker & snMaker, - MbResultType & resType, - RPArray & resCurves ); +MATH_FUNC (MbCreator *) CreateSurfaceSpline( const MbSurface & surface, + bool throughPoints, + SArray & paramPnts, + SArray & paramWts, + bool paramClosed, + RPArray & spaceTransitions, + const MbSNameMaker & snMaker, + MbResultType & resType, + RPArray & resCurves ); #endif // __CR_SURFACE_SPLINE_H diff --git a/C3d/Include/cr_swept_solid.h b/C3d/Include/cr_swept_solid.h index bcd499c..fc14a99 100644 --- a/C3d/Include/cr_swept_solid.h +++ b/C3d/Include/cr_swept_solid.h @@ -78,10 +78,10 @@ public : \{ */ virtual MbeCreatorType IsA() const = 0; // \ru Тип элемента \en A type of element virtual MbeCreatorType Type() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси \en Rotate around an axis virtual bool IsSame( const MbCreator &, double accuracy ) const = 0; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSimilar( const MbCreator & ) const = 0; // \ru Являются ли объекты подобными. \en Whether the objects are similar @@ -99,7 +99,7 @@ public : \en \name Common functions of the rigid solid (forming operations). \{ */ virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual MbFaceShell * InitShell( bool in ) = 0; virtual void InitBasis( RPArray & ) = 0; diff --git a/C3d/Include/cr_symmetry_solid.h b/C3d/Include/cr_symmetry_solid.h index 0044ef6..03e8f13 100644 --- a/C3d/Include/cr_symmetry_solid.h +++ b/C3d/Include/cr_symmetry_solid.h @@ -44,10 +44,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -60,7 +60,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction private : // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. @@ -105,15 +105,15 @@ IMPL_PERSISTENT_OPS( MbSymmetrySolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateSymmetry( MbFaceShell * solid, - MbeCopyMode sameShell, +MATH_FUNC (MbCreator *) CreateSymmetry( MbFaceShell * solid, + MbeCopyMode sameShell, const MbCartPoint3D & origin, - const MbVector3D & axisX, - const MbVector3D & axisY, - int side, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); + const MbVector3D & axisX, + const MbVector3D & axisY, + int side, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); #endif // __CR_SYMMETRY_SOLID_H diff --git a/C3d/Include/cr_thin_sheet.h b/C3d/Include/cr_thin_sheet.h index c6bf0d3..160fc0b 100644 --- a/C3d/Include/cr_thin_sheet.h +++ b/C3d/Include/cr_thin_sheet.h @@ -31,10 +31,10 @@ protected : SimpleName name; ///< \ru Имя операции. \en Operation name. public : - MbThinShellCreator( const MbSurface & surf, bool sense, SweptValues p, + MbThinShellCreator( const MbSurface & surf, bool sense, const SweptValues & p, bool same, const MbSNameMaker & n, SimpleName & m ); private : - MbThinShellCreator( const MbThinShellCreator &, MbRegDuplicate *ireg ); + MbThinShellCreator( const MbThinShellCreator &, MbRegDuplicate * ); // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. MbThinShellCreator( const MbThinShellCreator & ); public : @@ -43,15 +43,15 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis - virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties &properties ); // \ru Записать свойства объекта \en Set properties of the object + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property - virtual void GetBasisItems ( RPArray & s ); // \ru Дать базовые объекты \en Get the base objects + virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты \en Get the base objects virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. @@ -62,7 +62,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid solid virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction // \ru Дать параметры. \en Get the parameters. void GetParameters( SweptValues & params ) const { params = parameters; } @@ -78,6 +78,7 @@ private : IMPL_PERSISTENT_OPS( MbThinShellCreator ) + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку по поверхности. \en Construct a shell from a surface. \~ @@ -106,14 +107,14 @@ IMPL_PERSISTENT_OPS( MbThinShellCreator ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateThinShell( const MbSurface & surface, - bool sense, - const SweptValues & parameters, - bool same, +MATH_FUNC (MbCreator *) CreateThinShell( const MbSurface & surface, + bool sense, + const SweptValues & parameters, + bool same, const MbSNameMaker & operNames, - SimpleName & name, - MbResultType & res, - MbFaceShell *& shell ); + SimpleName & name, + MbResultType & res, + MbFaceShell *& shell ); //------------------------------------------------------------------------------ @@ -141,10 +142,10 @@ MATH_FUNC (MbCreator *) CreateThinShell( const MbSurface & surface, */ // --- MATH_FUNC (MbCreator *) CreateLoftedShell( const RPArray< SArray > & points, - const MbSNameMaker & operNames, - SimpleName & name, - MbResultType & res, - MbFaceShell *& shell ); + const MbSNameMaker & operNames, + SimpleName & name, + MbResultType & res, + MbFaceShell *& shell ); //------------------------------------------------------------------------------ @@ -172,10 +173,10 @@ MATH_FUNC (MbCreator *) CreateLoftedShell( const RPArray< SArray */ // --- MATH_FUNC (MbCreator *) CreateLoftedShell( const RPArray & curves, - const MbSNameMaker & operNames, - SimpleName & name, - MbResultType & res, - MbFaceShell *& shell ); + const MbSNameMaker & operNames, + SimpleName & name, + MbResultType & res, + MbFaceShell *& shell ); #endif // __CR_THIN_SHEET_H diff --git a/C3d/Include/cr_thin_shell_solid.h b/C3d/Include/cr_thin_shell_solid.h index 564eb75..9ff8943 100644 --- a/C3d/Include/cr_thin_shell_solid.h +++ b/C3d/Include/cr_thin_shell_solid.h @@ -64,10 +64,10 @@ private : public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -79,7 +79,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction /// \ru Дать параметры. \en Get the parameters. void GetParameters( SweptValues & params ) const { params = parameters; } diff --git a/C3d/Include/cr_transformed_solid.h b/C3d/Include/cr_transformed_solid.h index d7b1c5f..938c151 100644 --- a/C3d/Include/cr_transformed_solid.h +++ b/C3d/Include/cr_transformed_solid.h @@ -43,12 +43,12 @@ public: // \ru Деструктор \en Destructor public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy virtual bool IsSame( const MbCreator & other, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool SetEqual ( const MbCreator & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать по матрице \en Transform according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг по вектору \en Translation by a vector - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать по матрице \en Transform according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг по вектору \en Translation by a vector + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -58,7 +58,7 @@ public: // \ru Общие функции математического объе /// \ru Построение оболочки \en Creation of a shell virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); virtual void Refresh( MbFaceShell & ); ///< \ru Обновить форму оболочки \en Update shape of the shell // \ru Добавить модификацию по матрице \en Add a modification by a matrix void AddMatrix( MbFaceShell &, const MbMatrix3D & ); diff --git a/C3d/Include/cr_truncated_shell.h b/C3d/Include/cr_truncated_shell.h index 8f4da09..ca2993a 100644 --- a/C3d/Include/cr_truncated_shell.h +++ b/C3d/Include/cr_truncated_shell.h @@ -43,20 +43,20 @@ class MATH_CLASS MbTruncatedShell : public MbCreator { private : std::vector selIndices; ///< \ru Идентификаторы выбранных граней усекаемой оболочки. \en Identifiers of selected faces of the shell being truncated. MbSplitData splitItems; ///< \ru Усекающие элементы c ориентациями. \en Truncating elements with orientations. - SArray orients; ///< \ru Ориентация усекающих элементов. \en Orientation of truncating elements. + c3d::BoolVector orients; ///< \ru Ориентация усекающих элементов. \en Orientation of truncating elements. bool mergeFaces; ///< \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). public: /// \ru Конструктор по двумерным кривым. \en Constructor by two-dimensional curves. MbTruncatedShell( const MbPlacement3D &, const RPArray &, bool same, - const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); + const c3d::BoolVector & orients, const MbMergingFlags &, const MbSNameMaker & ); /// \ru Конструктор по трехмерным кривым. \en Constructor by three-dimensional curves. MbTruncatedShell( const RPArray &, bool same, - const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); + const c3d::BoolVector & orients, const MbMergingFlags &, const MbSNameMaker & ); /// \ru Конструктор по поверхностям. \en Constructor by surfaces. MbTruncatedShell( const RPArray &, bool same, - const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); + const c3d::BoolVector & orients, const MbMergingFlags &, const MbSNameMaker & ); /// \ru Конструктор по строителям тела. \en Constructor by solid creators. MbTruncatedShell( const MbSolid &, bool same, bool keepShell, bool orient, const MbMergingFlags &, const MbSNameMaker & ); @@ -68,11 +68,11 @@ private: public: virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию \en Create a copy + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -90,7 +90,7 @@ public: // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); // \ru Установить номера выбраных граней усекаемого тела \en Set indices of selected faces of the solid being truncated. void SetSelIndices( const std::vector & selInds ); @@ -139,18 +139,18 @@ IMPL_PERSISTENT_OPS( MbTruncatedShell ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) TruncateSurfacesSol( MbSolid & initSolid, - SArray & selIndices, - MbeCopyMode sameShell, - const MbSNameMaker & operNames, - RPArray & items, - SArray & orients, - bool curvesSplitMode, - MbeCopyMode solidsCopyMode, - const MbMergingFlags & mergeFlags, // флаги слияния граней и ребер - MbResultType & res, - MbFaceShell *& resShell, - MbPlacement3D *& resDir ); +MATH_FUNC (MbCreator *) TruncateSurfacesSol( MbSolid & initSolid, + SArray & selIndices, + MbeCopyMode sameShell, + const MbSNameMaker & operNames, + RPArray & items, + c3d::BoolVector & orients, + bool curvesSplitMode, + MbeCopyMode solidsCopyMode, + const MbMergingFlags & mergeFlags, // флаги слияния граней и ребер + MbResultType & res, + MbFaceShell *& resShell, + MbPlacement3D *& resDir ); #endif // __TRUNCATED_SHELL_H diff --git a/C3d/Include/cr_union_solid.h b/C3d/Include/cr_union_solid.h index b0851e5..0dd7d06 100644 --- a/C3d/Include/cr_union_solid.h +++ b/C3d/Include/cr_union_solid.h @@ -79,10 +79,10 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeCreatorType IsA() const; // \ru Тип элемента \en A type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию \en Create a copy - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbCreator & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию \en Create a copy + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -102,7 +102,7 @@ public : // \ru Общие функции твердого тела \en Common functions of solid virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction + RPArray * items = c3d_null ); // \ru Построение \en Construction virtual void SetYourVersion( VERSION version, bool forAll ); @@ -115,7 +115,9 @@ public: /// \ru Общее количество строителей. \en Total count of creators. size_t GetCreatorsCount() const { return creators.size(); } /// \ru Дать строитель. \en Get the creator. - const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? &(*creators[k]) : NULL); } + const MbCreator * GetCreator( size_t k ) const { return ((k < creators.size()) ? &(*creators[k]) : c3d_null); } + /// \ru Дать строитель. \en Get the creator. + MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? &(*creators[k]) : c3d_null); } public: /// \ru Собрать группы общих строителей тел. \en Collect groups of shared creators. @@ -140,8 +142,8 @@ IMPL_PERSISTENT_OPS( MbUnionSolid ) Before the operation a shell set is united into a single shell which contains all the faces of shell set. Union of the intersected shells is performed if necessary. The function simultaneously constructs the shell and creates its constructor. \n \~ - \param[in] solid - \ru Оболочка, с которой выполняется булева операция объединённого множества оболочек (может быть NULL). - \en The shell the Boolean operation of the united shell set is performed with (can be NULL). \~ + \param[in] solid - \ru Оболочка, с которой выполняется булева операция объединённого множества оболочек (может быть c3d_null). + \en The shell the Boolean operation of the united shell set is performed with (can be c3d_null). \~ \param[in] sameShell - \ru Способ копирования граней оболочки. \en Method of shell faces copying. \~ \param[in] creators - \ru Строители набора оболочек. @@ -186,7 +188,7 @@ MATH_FUNC (MbCreator *) CreateUnion( MbFaceShell * solid, bool isArray, // \ru Флаг массива \en Flag of array MbResultType & res, MbFaceShell *& shell, - RPArray * notGluedShells = NULL ); + RPArray * notGluedShells = c3d_null ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/creator.h b/C3d/Include/creator.h index 2526f85..0f2af4b 100644 --- a/C3d/Include/creator.h +++ b/C3d/Include/creator.h @@ -69,6 +69,10 @@ enum MbeCreatorType { ct_Undefined = 0, ///< \ru Неизвестный объект. \en Unknown object. ct_Creator = 1, ///< \ru Строитель объекта. \en Constructor of object. \n + ct_DisplaceMaker = 10, ///< \ru Строитель изменённого объекта. \en Constructor of a changed object. \n + ct_MotionMaker = 11, ///< \ru Строитель перемещенного объекта. \en Constructor of a moved object. \n + ct_RotationMaker = 12, ///< \ru Строитель Повёрнутого вокруг оси объекта. \en Constructor of a rotated object. \n + ct_TransformationMaker = 13, ///< \ru Строитель трансформированного объекта. \en Constructor of a transformed object. \n // \ru Строители точек. \en Creators of points. ct_PointsCreator = 101, ///< \ru Строитель точечного каркаса. \en Constructor of point-frame. \n @@ -247,7 +251,7 @@ public : \return \ru Копия объекта. \en The object copy. \~ */ - virtual MbCreator & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; + virtual MbCreator & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; /** \brief \ru Преобразовать согласно матрице. \en Transform according to the matrix. \~ @@ -270,7 +274,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. \~ */ - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ) = 0; + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Сдвинуть вдоль вектора. \en Translate along a vector. \~ @@ -293,7 +297,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. \~ */ - virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ) = 0; + virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Повернуть объект вокруг оси. \en Rotate an object about the axis. \~ @@ -318,7 +322,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. \~ */ - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ) = 0; + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Являются ли объекты равными? \en Determine whether an object is equal? \~ @@ -356,13 +360,13 @@ public : \en A shell to be modified or a new shell. \~ \param[in] sameShell - \ru Полнота копирования элементов при построении. \en Whether to perform complete copying of elements while constructing. \~ - \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть NULL). - \en Container for the elements of not performed constructions (can be NULL). \~ + \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть c3d_null). + \en Container for the elements of not performed constructions (can be c3d_null). \~ \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); /** \brief \ru Построить оболочку по исходным данным. \en Create a shell from the initial data. \~ @@ -372,13 +376,13 @@ public : \en A shell to be modified or a new shell. \~ \param[in] sameShell - \ru Полнота копирования элементов при построении. \en Whether to perform complete copying of elements while constructing. \~ - \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть NULL). - \en Container for the elements of not performed constructions (can be NULL). \~ + \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть c3d_null). + \en Container for the elements of not performed constructions (can be c3d_null). \~ \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ bool CreateShell( c3d::ShellSPtr & shell, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); /** \brief \ru Построить проволочный каркас по исходным данным. \en Create a wire-frame from the source data. \~ @@ -388,13 +392,13 @@ public : \en A frame to be modified or a new frame. \~ \param[in] sameShell - \ru Полнота копирования элементов при построении. \en Whether to perform complete copying of elements while constructing. \~ - \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть NULL). - \en Container for the elements of not performed constructions (can be NULL). \~ + \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть c3d_null). + \en Container for the elements of not performed constructions (can be c3d_null). \~ \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ virtual bool CreateWireFrame( MbWireFrame *& frame, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); /** \brief \ru Построить проволочный каркас по исходным данным. \en Create a wire-frame from the source data. \~ @@ -417,13 +421,13 @@ public : \en A frame to be modified or a new frame. \~ \param[in] sameShell - \ru Полнота копирования элементов при построении. \en Whether to perform complete copying of elements while constructing. \~ - \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть NULL). - \en Container for the elements of not performed constructions (can be NULL). \~ + \param[in] items - \ru Контейнер для складывания элементов невыполненных построений (может быть c3d_null). + \en Container for the elements of not performed constructions (can be c3d_null). \~ \return \ru Выполнено ли построение. \en Whether the construction is performed. \~ */ virtual bool CreatePointFrame( MbPointFrame *& frame, MbeCopyMode sameShell, - RPArray * items = NULL ); + RPArray * items = c3d_null ); /** \brief \ru Построить точечный каркас по исходным данным. \en Create a point-frame from the source data. \~ @@ -455,11 +459,13 @@ public : /// \ru Изменить объект по контрольным точкам. \en Change the object by control points. virtual void SetBasisPoints( const MbControlData3D & ); /// \ru Посчитать внутренние построители по типу. \en Count internal creators by type. - virtual size_t GetCreatorsCount( MbeCreatorType ct ) const { return (IsA() == ct) ? 1 : 0; } + virtual size_t GetCreatorsCount( MbeCreatorType ct ) const; // { return (IsA() == ct) ? 1 : 0; } /// \ru Получить внутренние построители по типу. \en Get internal creators by type. - virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const { return false; } + virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; /// \ru Получить внутренние построители по типу. \en Get internal creators by type. - virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ) { return false; } + virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ); + /// \ru Переместить/Изменить строитель. \en Displace/Change the creator. + virtual bool Perform( MbCreator * ) const; /// \ru Установить версию объектов. \en Set the objects version. virtual void SetYourVersion( VERSION version, bool forAll ); diff --git a/C3d/Include/creator_transaction.h b/C3d/Include/creator_transaction.h index b241d19..bb5a16b 100644 --- a/C3d/Include/creator_transaction.h +++ b/C3d/Include/creator_transaction.h @@ -68,7 +68,7 @@ public: transactions.reserve( iCount ); for ( size_t i = 0; i < iCount; i++ ) { MbCreator * creator = const_cast( creators[i] ); - if ( creator != NULL ) { + if ( creator != c3d_null ) { creator->AddRef(); transactions.push_back( creator ); } @@ -84,19 +84,21 @@ public: virtual bool RebuildItem( MbeCopyMode sameShell, RPArray * items, IProgressIndicator * progInd ); /// \ru Очистить присланный журнал и скопировать в него строители. \en Clear the given history tree and copy the creators to it. - void CreatorsCopy ( MbTransactions & other, MbRegDuplicate * iReg = NULL ) const; + void CreatorsCopy ( MbTransactions & other, MbRegDuplicate * iReg = c3d_null ) const; /// \ru Очистить журнал и скопировать в него строители из присланного журнала. \en Clear the history tree and copy the creators from the given history tree to it. void CreatorsAssign ( const MbTransactions & other ); /// \ru Сделать строители равными соответствующим строителям присланного журнала, если строители подобны. \en Make the creators equal to the creators from the given history tree if the creators are similar. bool SetCreatorsEqual ( const MbTransactions & other ); /// \ru Проверить, являются ли соответствующие строители присланного журнала подобными. \en Check whether the corresponding creators of the given history tree are similar. bool IsCreatorsSimilar( const MbTransactions & other ) const; + // Посчитать внутренние построители по типу. \en Count internal creators by type. + size_t GetCreatorsCount( MbeCreatorType ct ) const; /// \ru Преобразовать согласно матрице строители. \en Transform the creators according to the matrix. - void CreatorsTransform( const MbMatrix3D &, MbRegTransform * = NULL ); + void CreatorsTransform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть вдоль вектора строители. \en Move creators along the vector. - void CreatorsMove ( const MbVector3D &, MbRegTransform * = NULL ); + void CreatorsMove ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть вокруг оси строители на заданный угол. \en Rotate the creators about the axis by the given angle. - void CreatorsRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void CreatorsRotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /// \ru Выдать количество строителей. \en Get the creators count. size_t GetCreatorsCount() const { return transactions.size(); } /// \ru Зарезервировать место для строителей. \en Reserve space for creators. @@ -111,7 +113,7 @@ public: virtual bool GetCreators( c3d::CreatorsSPtrVector & ) const; /// \ru Добавить копии своих строителей в присланный массив. \en Add copies of your own creators to the given array. template - bool GetCreatorsCopies( CreatorsVector & creators ) const + bool GetCreatorsCopies( CreatorsVector & creators, MbRegDuplicate * iReg ) const { bool res = false; size_t addCnt = transactions.size(); @@ -119,8 +121,8 @@ public: c3d::CreatorSPtr creator; creators.reserve( creators.size() + addCnt ); for ( size_t i = 0; i < addCnt; ++i ) { - if ( transactions[i] != NULL ) { - creator = static_cast(&transactions[i]->Duplicate()); + if ( transactions[i] != c3d_null ) { + creator = static_cast(&transactions[i]->Duplicate( iReg )); creators.push_back( creator ); ::DetachItem( creator ); res = true; @@ -143,7 +145,7 @@ public: c3d::CreatorSPtr creator; for ( size_t i = 0, addCnt = creators.size(); i < addCnt; ++i ) { creator = creators[i]; - if ( creator != NULL ) { + if ( creator != c3d_null ) { creator->AddRef(); transactions.push_back( creator ); ::DetachItem( creator ); diff --git a/C3d/Include/cur_arc.h b/C3d/Include/cur_arc.h index b622cb6..ca20731 100644 --- a/C3d/Include/cur_arc.h +++ b/C3d/Include/cur_arc.h @@ -377,12 +377,12 @@ public : \en \name Common functions of a geometric object. \{ */ virtual MbePlaneType IsA() const; // \ru Тип элемента \en A type of element - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать согласно матрице \en Transform according to the matrix - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать согласно матрице \en Transform according to the matrix + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual double DistanceToPoint( const MbCartPoint & ) const;// \ru Расстояние до точки \en Distance to a point virtual bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const; // \ru Расстояние до точки, если оно меньше d \en Distance to a point if it is less than 'd' virtual void AddYourGabaritTo( MbRect & r ) const; // \ru Добавь свой габарит в прямой прям-к \en Add own bounding rectangle to an upright bounding rectangle @@ -445,7 +445,7 @@ public : /** \ru \name Общие функции кривой \en \name Common functions of the curve \{ */ - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Выдать метрическую длину кривой \en Get the metric length of the curve virtual double CalculateMetricLength() const; // \ru Посчитать метрическую длину \en Calculate metric length @@ -459,7 +459,7 @@ public : virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на кривую \en Projection of a point onto the curve virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Projection of the point onto the curve or its extension in the projection region + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Projection of the point onto the curve or its extension in the projection region // \ru Вычисление всех касательных к кривой из данной точки \en Calculation of all the tangents to the curve from a given point virtual void TangentPoint( const MbCartPoint & pnt, SArray & tFind ) const; // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all the perpendiculars to the curve from a given point @@ -949,15 +949,15 @@ public : void Init( const MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); // \ru Инициализация по начальной и конечной точкам и 1/2 угла раствора дуги \en Initialization by the starting and end points and 1/2 of the arc opening angle - // \ru Если diskrData != NULL, то округлить радиус и скорректировать первую \en If diskrData != NULL, then round the radius and correct the first + // \ru Если diskrData != c3d_null, то округлить радиус и скорректировать первую \en If diskrData != c3d_null, then round the radius and correct the first // \ru Или вторую точку (зависит от correctFirstPnt) \en Or the second point (depends on correctFirstPnt) /** \brief \ru Инициализировать дугу окружность. \en Initialize a circular arc. \~ \details \ru Инициализация происходит по начальной и конечной точкам и 1/2 угла раствора дуги. - Если diskrData != NULL, радиус округляется и корректируется первая + Если diskrData != c3d_null, радиус округляется и корректируется первая или вторая точка (зависит от correctFirstPnt). \en The initialization is performed by the starting and end points and 1/2 of the arc opening angle. - If diskrData != NULL, the radius is rounded and the first + If diskrData != c3d_null, the radius is rounded and the first or the second point is corrected (depends on correctFirstPnt). \~ \param[in] a2 - \ru 1/2 угла раствора дуги окружности. \en 1/2 of the circular arc opening angle. \~ @@ -973,7 +973,7 @@ public : correctFirstPnt == true - the first point is to be corrected. \~ */ void Init( double a2, MbCartPoint & p1, MbCartPoint & p2, - const DiskreteLengthData * diskrData = NULL, + const DiskreteLengthData * diskrData = c3d_null, bool correctFirstPnt = true ); // \ru Инициализация эллипса \en Ellipse initialization /** \brief \ru Инициализировать эллипс. diff --git a/C3d/Include/cur_arc3d.h b/C3d/Include/cur_arc3d.h index f9c35e1..3af393d 100644 --- a/C3d/Include/cur_arc3d.h +++ b/C3d/Include/cur_arc3d.h @@ -300,10 +300,10 @@ public : \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual double DistanceToPoint( const MbCartPoint3D & ) const;// \ru Расстояние до точки \en Distance to a point @@ -356,13 +356,13 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; /** \} */ - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. virtual double MetricStep ( double t, double length ) const; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. // \ru Все проекции точки на кривую \en All the projections of a point onto the curve - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The closest projection of a point onto the curve + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The closest projection of a point onto the curve virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить Nurbs-копию кривой \en Construct NURBS-copy of the curve @@ -377,15 +377,15 @@ public : virtual size_t GetCount() const; virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; // \ru Выдать n точек кривой с равными интервалами по длине дуги \en Get n points of curves equally spaced by the arc length - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = NULL ) const; + MbRect1D * pRgn = c3d_null ) const; virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis ( MbAxis3D & ) const; // \ru Дать ось кривой \en Get the axis of the curve // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called on a three-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой \en Calculate bounding box of curve virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to local coordinate system @@ -413,9 +413,9 @@ public : void AlignXAxis(); ///< \ru Повернуть плейсмент круговой дуги так, чтобы ось ox указывала в начальную точку дуги. \en Rotate the placement of a circular arc so as the ox-axis points to the start point of the arc. /// \ru Является ли кривая плоской? \en Whether the curve is planar? - virtual bool IsPlanar() const; + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; /// \ru Заполнить плейсемент, если кривая плоская. \en Fill the placement if a curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; const MbPlacement3D & GetPlacement() const { return position; } MbPlacement3D & SetPlacement() { return position; } diff --git a/C3d/Include/cur_b_spline.h b/C3d/Include/cur_b_spline.h index 199e50e..3f5ed6f 100644 --- a/C3d/Include/cur_b_spline.h +++ b/C3d/Include/cur_b_spline.h @@ -56,12 +56,12 @@ public: // \ru Общие функции математического объекта \en The common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -87,7 +87,7 @@ public: virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction void CalculateOnePolygon( size_t i, const MbStepData & stepData, MbPolygon3D * polygon ) const; // \ru Pассчитать полигон по параметру T \en Calculate polygon of the parameter T // \ru Расчет весовых функций и их первых, вторых и третьих производных \en Calculation of the weight functions and their first, second and third derivatives diff --git a/C3d/Include/cur_bezier.h b/C3d/Include/cur_bezier.h index be2e5c9..04e1d93 100644 --- a/C3d/Include/cur_bezier.h +++ b/C3d/Include/cur_bezier.h @@ -220,10 +220,10 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en A type of element virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element /** \} */ /** \ru \name Функции инициализации сплайна. \en \name Spline initialization functions. @@ -310,7 +310,7 @@ public : virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; virtual MbContour * NurbsContour() const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -472,7 +472,7 @@ public : virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, VERSION version = Math::DefaultMathVersion() ) const; - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_bezier3d.h b/C3d/Include/cur_bezier3d.h index 445a1ca..6695acf 100644 --- a/C3d/Include/cur_bezier3d.h +++ b/C3d/Include/cur_bezier3d.h @@ -112,12 +112,12 @@ public : // \ru Общие функции математического объекта \en The common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Поворот \en Rotation virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -137,7 +137,7 @@ public : virtual double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculate step of approximation virtual double DeviationStep( double t, double angle ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual bool Break( MbBezier3D &, double t1, double t2 ) const; // \ru Разбить на две части \en Split into two parts @@ -147,7 +147,7 @@ public : virtual MbCurve3D * TrimmBreak( double t1, double t2, int sense ) const; // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) // \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ @@ -180,8 +180,8 @@ public : ptrdiff_t GetSplinesCount() const { return splinesCount; } // \ru Количество сплайнов \en The number of splines // \ru Функции только 3D кривой \en Function for 3D-curve - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve virtual size_t GetCount() const; @@ -191,7 +191,7 @@ public : virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, VERSION version = Math::DefaultMathVersion() ) const; - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_bridge3d.h b/C3d/Include/cur_bridge3d.h index fecd521..a3db18c 100644 --- a/C3d/Include/cur_bridge3d.h +++ b/C3d/Include/cur_bridge3d.h @@ -67,13 +67,13 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Сделать элементы равными \en Make the elements equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб \en Add own bounding box into a bounding box virtual void Refresh(); // \ru Сбросить все временные данные \en Flush all the temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -97,7 +97,7 @@ public: virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculation of the approximation step virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/cur_character_curve.h b/C3d/Include/cur_character_curve.h index ce9dccb..630c735 100644 --- a/C3d/Include/cur_character_curve.h +++ b/C3d/Include/cur_character_curve.h @@ -71,12 +71,12 @@ public: // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbePlaneType IsA() const; // \ru Тип элемента \en A type of element - virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Кривая есть копия этой кривой ? \en Is a curve a copy of this curve? virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void AddYourGabaritTo( MbRect & ) const; // \ru Добавь в прям-к свой габарит \en Add own bounding rectangle to the bounding rectangle virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -103,7 +103,7 @@ public: virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Metric length evaluation of a curve virtual void CalculateGabarit( MbRect & ) const; // \ru Определить габаритный прямоугольник кривой. - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual size_t GetCount () const; // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. virtual MbNurbs * NurbsCurve ( const MbCurveIntoNurbsInfo & ) const; diff --git a/C3d/Include/cur_character_curve3d.h b/C3d/Include/cur_character_curve3d.h index 84382ba..2fd24e3 100644 --- a/C3d/Include/cur_character_curve3d.h +++ b/C3d/Include/cur_character_curve3d.h @@ -79,12 +79,12 @@ public: VISITING_CLASS( MbCharacterCurve3D ) virtual MbeSpaceType IsA () const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Кривая есть копия этой кривой ? \en Is a curve a copy of this curve? virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform ( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform ( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void AddYourGabaritTo( MbCube & ) const; virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -110,16 +110,16 @@ public: virtual double Step ( double t, double sag ) const; ///< \ru Вычисление шага параметра по величине прогиба кривой \en Calculation of parameter step by value of sag of the curve virtual double DeviationStep( double t, double ang ) const; ///< \ru Вычисление шага параметра по углу отклонения касательной \en Calculation of parameter by the angle of tangent deviation - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve virtual double GetLengthEvaluation() const; - virtual bool IsPlanar() const; // \ru Является ли кривая плоской \en Whether the curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if curve is planar + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether the curve is planar + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if curve is planar // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called on a three-dimensional curve) - virtual bool GetPlaneCurve ( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; - virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + virtual bool GetPlaneCurve ( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; + virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. virtual size_t GetCount() const; virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; diff --git a/C3d/Include/cur_cone_spiral.h b/C3d/Include/cur_cone_spiral.h index dc5b0c2..61cd5da 100644 --- a/C3d/Include/cur_cone_spiral.h +++ b/C3d/Include/cur_cone_spiral.h @@ -197,7 +197,7 @@ public: public: // \ru Общие функции математического объекта. \en The common functions of the mathematical object. virtual MbeSpaceType IsA() const; // \ru Получить тип. \en Get a type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. virtual bool IsSame( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -223,18 +223,18 @@ public: virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. virtual double MetricStep ( double t, double length ) const; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой. \en Creation of a trimmed curve. - virtual void Inverse( MbRegTransform * = NULL ); // \ru Изменить направление. \en Change the direction. + virtual void Inverse( MbRegTransform * = c3d_null ); // \ru Изменить направление. \en Change the direction. virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual double CalculateLength( double t1, double t2 ) const; // \ru Ближайшая проекция точки на спираль. \en The nearest point projection on the spiral. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D & p, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Частные функции спирали. \en Special functions for spiral. virtual bool SetStep( double s ); // \ru Изменить шаг. \en Change the step. diff --git a/C3d/Include/cur_contour.h b/C3d/Include/cur_contour.h index 6d6e66c..abeef2f 100644 --- a/C3d/Include/cur_contour.h +++ b/C3d/Include/cur_contour.h @@ -102,13 +102,13 @@ public: virtual MbePlaneType IsA() const; // \ru Тип элемента \en A type of element virtual MbePlaneType Type() const; // \ru Тип элемента \en A type of element - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element. + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element. virtual bool IsSimilar ( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar. virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements. virtual bool IsSame( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the curve "curve" is a copy of a given curve? - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix. - virtual void Move( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation. - virtual void Rotate( const MbCartPoint &, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation. + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix. + virtual void Move( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation. + virtual void Rotate( const MbCartPoint &, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation. /** \brief \ru Построить эквидистантную кривую, смещённую на заданное расстояние. \en Construct the equidistant curve which is shifted by the given value. \~ @@ -128,8 +128,8 @@ public: You can use the OffsetContour function instead this function. \~ \param[in] rad - \ru Величина эквидистантного смещения. \en Equidistant offset. \~ - \return \ru Возвращает эквидистантный контур, если получилось его построить, иначе - NULL. - \en Returns the equidistant curve if it's possible to build it, otherwise - NULL. \~ + \return \ru Возвращает эквидистантный контур, если получилось его построить, иначе - c3d_null. + \en Returns the equidistant curve if it's possible to build it, otherwise - c3d_null. \~ */ virtual MbCurve * Offset( double rad ) const; // \ru Смещение контура. \en Shift of a contour @@ -300,7 +300,7 @@ public: virtual double PointProjection( const MbCartPoint & ) const; // \ru Проекция точки на кривую \en Point projection on the curve virtual bool NearPointProjection( const MbCartPoint &, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area /** \brief \ru Параметрическое расстояние до ближайшей границы. \en Parametric distance to the nearest boundary. @@ -416,7 +416,7 @@ public: void SetSense( int sense ); // \ru Изменить направление обхода контура \en Change the traverse direction of the contour - virtual void Inverse( MbRegTransform * = NULL ); + virtual void Inverse( MbRegTransform * = c3d_null ); // \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion. bool NormalizeReparametrization(); virtual size_t GetCount() const; // \ru Количество разбиений для прохода в операциях \en The number of partitions for passage in the operations @@ -464,7 +464,7 @@ public: \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы производных по длине в стыках сегментов. \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. @@ -778,13 +778,13 @@ void MbContour::GetCornerParams( Params & params ) const double pLength = 0.0; const MbCurve * segment = GetSegment( 0 ); - if ( segment != NULL ) + if ( segment != c3d_null ) pLength = segment->GetParamLength(); for ( size_t segInd = 1; segInd < segCount; ++segInd ) { params.push_back( pLength ); segment = GetSegment( segInd ); - if ( segment != NULL ) + if ( segment != c3d_null ) pLength += segment->GetParamLength(); } } diff --git a/C3d/Include/cur_contour3d.h b/C3d/Include/cur_contour3d.h index 9ea1a2f..08acdf2 100644 --- a/C3d/Include/cur_contour3d.h +++ b/C3d/Include/cur_contour3d.h @@ -92,13 +92,13 @@ public: virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element virtual MbeSpaceType Type() const; // \ru Групповой тип элемента \en Group element type - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Расстояние до точки \en Distance to a point virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -172,7 +172,7 @@ public: virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve // \ru Изменить направление \en Change direction - virtual void Inverse( MbRegTransform * iReg = NULL ); + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Согласовать параметризацию сегментов, если до инвертации она была согласованной. \en Agree on segment parameterization, if it was consistent before inversion. bool NormalizeReparametrization(); /// \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar. @@ -180,7 +180,7 @@ public: // \ru Все проекции точки на кривую \en All point projections on the curve // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; virtual double CalculateMetricLength() const; // \ru Посчитать метрическую длину \en Calculate the metric length virtual double CalculateLength( double t1, double t2 ) const; @@ -190,18 +190,18 @@ public: virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой \en Calculate the bounding box of curve - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve virtual MbCurve * GetProjection( const MbPlacement3D & place, VERSION version ) const; // \ru Дать проекцию ребра на плоскость. \en Get the edge projection onto plane. virtual size_t GetCount() const; virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether the curve is planar? - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether the curve is planar? + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called on a three-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; virtual void GetWeightCentre( MbCartPoint3D & ) const; @@ -229,7 +229,7 @@ public: \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы производных по длине в стыках сегментов. \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. @@ -403,11 +403,11 @@ MbContour3D::MbContour3D( const CurvesVector & initSegments, bool sameCurves ) const size_t count = initSegments.size(); if ( count > 0 ) { - MbRegDuplicate * ireg = NULL; + MbRegDuplicate * ireg = c3d_null; MbAutoRegDuplicate autoreg( ireg ); for ( size_t i = 0; i < count; ++i ) { const MbCurve3D * initSegment = initSegments[i]; - if ( initSegment != NULL ) { + if ( initSegment != c3d_null ) { C3D_ASSERT( initSegment->GetSubstrate().Type() != st_Contour3D ); // \ru Использование контура не по назначению. \en Wrong contour use as contours container. MbCurve3D * segment = sameCurves ? const_cast(initSegment) : static_cast(&initSegment->Duplicate( ireg )); segments.push_back( segment ); @@ -430,7 +430,7 @@ bool MbContour3D::Init( const CurvesVector & initSegments, bool sameCurves, bool ::AddRefItems( initSegments ); DeleteSegments(); for ( size_t i = 0; i < count; ++i ) { - if ( initSegments[i] != NULL ) { + if ( initSegments[i] != c3d_null ) { C3D_ASSERT( initSegments[i]->GetSubstrate().Type() != st_Contour3D ); // \ru Использование контура не по назначению. \en Wrong contour use as contours container. MbCurve3D * initSegment = &const_cast( *initSegments[i] ); MbCurve3D * segment = sameCurves ? initSegment : static_cast(&initSegment->Duplicate()); @@ -481,7 +481,7 @@ void MbContour3D::GetSegments( CurvesVector & curves ) const SPtr curve; for ( size_t k = 0; k < segmentsCnt; ++k ) { curve = const_cast(segments[k]); - if ( curve != NULL ) { + if ( curve != c3d_null ) { curves.push_back( curve ); ::DetachItem( curve ); } diff --git a/C3d/Include/cur_contour_on_plane.h b/C3d/Include/cur_contour_on_plane.h index ed15544..dfa9009 100644 --- a/C3d/Include/cur_contour_on_plane.h +++ b/C3d/Include/cur_contour_on_plane.h @@ -63,7 +63,7 @@ public : // \ru Общие функции математического объекта. \en The common functions of the mathematical object. virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get a type of the element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. virtual MbContourOnSurface & CurvesDuplicate() const; // \ru Сделать копию со старой подложкой. \en Make a copy with old substrate. virtual bool IsSame( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, является ли копией данного объекта? \en Determine whether the object is copy of a given object. @@ -98,11 +98,11 @@ public : virtual bool ChangeSurface( const MbSurface & newsurf ); // \ru Заменить поверхность контура. \en Replace the surface of contour. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменить носителя. \en Change the carrier. - virtual bool IsPlanar() const; // \ru Является ли кривая плоской? \en Whether the curve is planar? + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской? \en Whether the curve is planar? // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis( MbAxis3D & ) const; // \ru Дать ось кривой. \en Get the curve axis. @@ -112,8 +112,8 @@ public : virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Определить, является ли линия прямолинейной? \en Determine whether the line is straight. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D *pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D *pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; // \ru Выдать n точек кривой с равными интервалами по длине дуги. \en Get n points of curve with equal intervals along the length of the arc. @@ -129,7 +129,7 @@ public : /// \ru Заменить локальную систему координат плоскости. \en Replace the local coordinate system of a plane. void SetPlacement( const MbPlacement3D & ); /// \ru Инвертировать нормаль плоскости. \en Invert the normal of plane. - void InvertNormal( MbRegTransform * = NULL ); + void InvertNormal( MbRegTransform * = c3d_null ); private: void operator = ( const MbContourOnPlane & ); // \ru Не реализовано !!! \en Not implemented !!! diff --git a/C3d/Include/cur_contour_on_surface.h b/C3d/Include/cur_contour_on_surface.h index 8c969f2..bf11c49 100644 --- a/C3d/Include/cur_contour_on_surface.h +++ b/C3d/Include/cur_contour_on_surface.h @@ -44,8 +44,8 @@ class MbSegmentsSearchTree; class MATH_CLASS MbContourOnSurface : public MbCurve3D { protected : - MbSurface * surface; ///< \ru Указатель на базовую поверхность (всегда не NULL). \en The pointer to the base surface (this value is never NULL). - MbContour * contour; ///< \ru Указатель на 2D-контур в плоскости параметров поверхности (всегда не NULL). \en The pointer to 2D-contour in the plane of the surface parameters (this value is never NULL). + MbSurface * surface; ///< \ru Указатель на базовую поверхность (всегда не c3d_null). \en The pointer to the base surface (this value is never c3d_null). + MbContour * contour; ///< \ru Указатель на 2D-контур в плоскости параметров поверхности (всегда не c3d_null). \en The pointer to 2D-contour in the plane of the surface parameters (this value is never c3d_null). mutable double area; ///< \ru Площадь 2D-контура со знаком. \en The area of 2D-contour with sign. mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. mutable double metricLength; ///< \ru Метрическая длина. \en The metric length. @@ -99,15 +99,15 @@ public : virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get a type of the element. virtual MbeSpaceType Type() const; // \ru Дать тип элемента. \en Get a type of the element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. /// \ru Сделать копию на той же поверхности. \en Create a copy on the same surface. virtual MbContourOnSurface & CurvesDuplicate() const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, является ли копией данного объекта? \en Determine whether the object is copy of a given object. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube &r ) const; // \ru Добавить габарит в куб. \en Add bounding box into a cube. virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. @@ -140,7 +140,7 @@ public : MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; /// \ru Изменить ориентацию контура относительно поверхности. \en Change the contour orientation relative to a surface. - virtual void Inverse( MbRegTransform * iReg = NULL ); + virtual void Inverse( MbRegTransform * iReg = c3d_null ); virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; // \ru Установить параметры NURBS. \en Set the NURBS parameters. @@ -167,25 +167,25 @@ public : virtual bool ChangeSurface( const MbSurface & ); /// \ru Заменить двумерный контур. \en Replace the two-dimensional contour. void ChangeContour( MbContour & ); - virtual bool IsPlanar() const; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar. virtual bool IsSmoothConnected( double angleEps ) const; // \ru Определить, является ли контур гладким. \en Define whether the contour is smooth. // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Вычислить ближайшую проекцию точки на кривую. \en Calculate the nearest projection of the point on the curve. + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Вычислить ближайшую проекцию точки на кривую. \en Calculate the nearest projection of the point on the curve. virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Определить, является ли линия прямолинейной. \en Determine whether the line is straight. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. /// \ru Найти все особые точки функции кривизны кривой. /// \en Find all the special points of the curvature function of the curve. virtual void GetCurvatureSpecialPoints( std::vector & points ) const; - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); @@ -211,6 +211,9 @@ public : /// \ru Вычислить нормали к поверхности по параметру кривой. \en Calculate normals to the surface in the curve parameter. void SurfaceNormal( double t, MbVector3D & n ) const; + /// \ru Кривизна поверхности в поперечном направлении к вектору tau. \en The surface curvature in the transverse direction to the vector tau. + double SurfaceTransversalCurvature( double t, const MbVector3D & tau ) const; + /** \brief \ru Найти сегмент контура. \en Find a contour segment. \~ \details \ru Найти сегмент контура по параметру контура. \n diff --git a/C3d/Include/cur_contour_with_breaks.h b/C3d/Include/cur_contour_with_breaks.h index 456155e..173d886 100644 --- a/C3d/Include/cur_contour_with_breaks.h +++ b/C3d/Include/cur_contour_with_breaks.h @@ -84,10 +84,10 @@ public : \en \name Common functions of a geometric object. \{ */ virtual MbePlaneType IsA() const; // \ru Тип элемента. \en A type of element. - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот. \en Rotation. - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот. \en Rotation. + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. /** \} */ /**\ru \name Функции доступа к данным: разрывы. \en \name Functions for access to data: breaks. @@ -160,11 +160,11 @@ public : \en Invisible part by the number of break. \~ \details \ru Невидимая часть по номеру разрыва.\n Номер проверяется на корректность. - В случае, если номер не меньше числа разрывов, функция вернет NULL.\n + В случае, если номер не меньше числа разрывов, функция вернет c3d_null.\n После использования полученный контур нужно удалить. \en Invisible part by the number of break. \n A number Is checked for correctness. - If the number is not less than the number of breaks, the function returns NULL. \n + If the number is not less than the number of breaks, the function returns c3d_null. \n The resulting contour is to be deleted after use. \~ \param[in] i - \ru Номер разрыва, должен быть меньше количества видимых частей. \en The number of break must be less than the number of visible parts. \~ diff --git a/C3d/Include/cur_cosinusoid.h b/C3d/Include/cur_cosinusoid.h index b9fb77b..5c745cd 100644 --- a/C3d/Include/cur_cosinusoid.h +++ b/C3d/Include/cur_cosinusoid.h @@ -90,11 +90,11 @@ public: virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal virtual bool IsBounded () const { return true; } // \ru Ограниченность кривой \en Bounded curve - virtual void Transform ( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual void Transform ( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; - virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -124,7 +124,7 @@ public: virtual bool HasLength ( double & length ) const; virtual double GetMetricLength() const; // \ru Метрическая длина \en The metric length - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; @@ -140,7 +140,7 @@ public: virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на кривую \en Point projection on the curve virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object @@ -173,10 +173,10 @@ public: void Init1( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle ); void Init2( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, double & angle ); void Init3( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, double & len, const double & angle, - const DiskreteLengthData * = NULL ); + const DiskreteLengthData * = c3d_null ); void Init4( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, double & angle ); void Init5( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, double & len, const double & angle, - const DiskreteLengthData * = NULL ); + const DiskreteLengthData * = c3d_null ); void Init6( CosinusoidPar & par, const MbCartPoint & p1, MbCartPoint & p2, const double & len, const double & angle ); void Init7( CosinusoidPar & par, MbCartPoint & p1, const MbCartPoint & p2, const double & len, const double & angle ); void Init8( CosinusoidPar & par, MbCartPoint & p1, MbCartPoint & p2, double & len, double & angle, diff --git a/C3d/Include/cur_crooked_spiral.h b/C3d/Include/cur_crooked_spiral.h index a01898f..e45da06 100644 --- a/C3d/Include/cur_crooked_spiral.h +++ b/C3d/Include/cur_crooked_spiral.h @@ -57,7 +57,7 @@ class MATH_CLASS MbCrookedSpiral : public MbSpiral { typedef std::vector CurveParams; protected: - MbCurve * curve; ///< \ru Кривая, задающая ось спирали, (не может быть NULL). \en The curve which determines the axis of the spiral, (can not be NULL). + MbCurve * curve; ///< \ru Кривая, задающая ось спирали, (не может быть c3d_null). \en The curve which determines the axis of the spiral, (can not be c3d_null). double radius; ///< \ru Радиус спирали. \en A spiral radius. double wMin; ///< \ru Минимальное значение параметра curve. \en Minimal value of parameter "curve". double wMax; ///< \ru Максимальное значение параметра curve. \en Maximal value of parameter "curve". @@ -84,7 +84,7 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal @@ -108,7 +108,7 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve virtual double CalculateLength( double t1, double t2 ) const; diff --git a/C3d/Include/cur_cubic_spline.h b/C3d/Include/cur_cubic_spline.h index 29a8393..183e803 100644 --- a/C3d/Include/cur_cubic_spline.h +++ b/C3d/Include/cur_cubic_spline.h @@ -194,11 +194,11 @@ public : \{ */ virtual MbePlaneType IsA () const; // \ru Тип элемента \en Type of element virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements - virtual bool IsSame ( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой \en Whether the curve "curve" is a copy of a given curve - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbCartPoint &, const MbDirection &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual bool IsSame ( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой \en Whether the curve "curve" is a copy of a given curve + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbCartPoint &, const MbDirection &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element /** \} */ /** \ru \name Функции описания области определения кривой. @@ -246,7 +246,7 @@ public : \{ */ virtual void Rebuild (); // \ru Пересчитать Безье кривую \en Recalculate Bezier curve virtual void SetClosed( bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve /** \brief \ru Построить усеченную кривую. \en Construct a trimmed curve. \~ diff --git a/C3d/Include/cur_cubic_spline3d.h b/C3d/Include/cur_cubic_spline3d.h index 5253207..6954681 100644 --- a/C3d/Include/cur_cubic_spline3d.h +++ b/C3d/Include/cur_cubic_spline3d.h @@ -247,13 +247,13 @@ public: void Init( const MbCubicSpline &, const MbPlacement3D & ); // \ru Общие функции математического объекта \en Common functions of the mathematical object - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -277,19 +277,19 @@ public: virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const; - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual size_t GetCount() const; virtual void Rebuild (); // \ru Перестроить кривую \en Rebuild the curve virtual void SetClosed( bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. virtual bool IsDegenerate( double eps = METRIC_PRECISION ) const; virtual MbCurve3D * TrimmBreak( double t1, double t2, int sense ) const; // \ru Создать усеченную кривую \en Create the trimmed curve - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether a curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Посчитать метрическую длину \en Calculate the metric length virtual double CalculateMetricLength() const; diff --git a/C3d/Include/cur_curve_spiral.h b/C3d/Include/cur_curve_spiral.h index 31e391a..2c539f4 100644 --- a/C3d/Include/cur_curve_spiral.h +++ b/C3d/Include/cur_curve_spiral.h @@ -88,7 +88,7 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal @@ -112,7 +112,7 @@ public: virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve diff --git a/C3d/Include/cur_hermit.h b/C3d/Include/cur_hermit.h index 28f5186..f99372f 100644 --- a/C3d/Include/cur_hermit.h +++ b/C3d/Include/cur_hermit.h @@ -211,11 +211,11 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element /** \} */ /** \ru \name Общие функции кривой @@ -246,7 +246,7 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of approximation step with consideration of curvature radius virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага аппроксимации по угловой толерантности \en Calculation of approximation step by angular tolerance virtual void IntersectHorizontal( double y, SArray & ) const; // \ru Пересечение кривой с горизонтальной прямой \en Intersection of a curve with a horizontal line @@ -254,7 +254,7 @@ public : virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на кривую \en Point projection on the curve virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area virtual double CalculateMetricLength() const; // \ru Посчитать метрическую длину разомкнутой \en Calculate the open metric length virtual bool GetWeightCentre( MbCartPoint & wc ) const; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve virtual void CalculateGabarit( MbRect & r ) const; // \ru Определить габариты \en Calculate bounding box @@ -305,7 +305,10 @@ public : const MbHermit & init, double t1, double w1, double koef, bool checkClosed ) const; size_t GetVectorListCount() const { return vectorList.Count(); } - void GetVectorList( SArray & vectors ) const { vectors = vectorList; } + + template + void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } + const MbVector & _GetVectorList( size_t i ) const { return vectorList[i]; } MbVector & _SetVectorList( size_t i ) { MbPolyCurve::Refresh(); return vectorList[i]; } diff --git a/C3d/Include/cur_hermit3d.h b/C3d/Include/cur_hermit3d.h index 9a53d3f..cf7a5c5 100644 --- a/C3d/Include/cur_hermit3d.h +++ b/C3d/Include/cur_hermit3d.h @@ -211,12 +211,12 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать \en Transform. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать \en Transform. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Поворот \en Rotation virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -236,7 +236,7 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculation of approximation step virtual double DeviationStep( double t, double angle ) const; @@ -246,12 +246,12 @@ public : virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve virtual MbCurve3D * TrimmBreak( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether a curve is planar. + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar. virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Признак прямолинейности кривой \en An attribute of curve straightness - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Получить границы участков кривой, которые описываются одной аналитической функцией. /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ @@ -276,7 +276,7 @@ public : virtual bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const; // \ru Загнать параметр получить локальный индексы и параметры \en Move parameter into domain, get local indices and parameters virtual double GetParam( ptrdiff_t i ) const; // \ru Выдать параметр для точки с номером \en Get parameter for point with index - virtual bool NearPointProjection ( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve + virtual bool NearPointProjection ( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve virtual double CalculateMetricLength() const; // \ru Посчитать метрическую длину \en Calculate the metric length virtual void GetWeightCentre( MbCartPoint3D &wc ) const; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve virtual void CalculateGabarit( MbCube & gab ) const; // \ru Вычислить габарит кривой \en Calculate the bounding box of curve @@ -284,8 +284,8 @@ public : VERSION version = Math::DefaultMathVersion() ) const; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction // \ru Функции только 3D кривой \en Function for 3D-curve - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve virtual size_t GetCount() const; // \ru Установить область изменения параметра. \en Set range of parameter. @@ -294,7 +294,10 @@ public : void SetLimitVector( ptrdiff_t n, const MbVector3D & v ); size_t GetVectorListCount() const { return vectorList.size(); } - void GetVectorList( SArray & vectors ) const { vectors = vectorList; } + + template + void GetVectorList( VectorsVector & vectors ) const { vectors.assign( vectorList.begin(), vectorList.end() ); } + const MbVector3D & _GetVectorList( size_t i ) const { return vectorList[i]; } MbVector3D & _SetVectorList( size_t i ) { MbPolyCurve3D::Refresh(); return vectorList[i]; } diff --git a/C3d/Include/cur_line.h b/C3d/Include/cur_line.h index 86b5356..b7e086b 100644 --- a/C3d/Include/cur_line.h +++ b/C3d/Include/cur_line.h @@ -71,11 +71,11 @@ public : virtual bool IsSimilar( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual void AddYourGabaritTo ( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add bounding box into a straight box virtual void AddYourGabaritMtr( MbRect &, const MbMatrix & ) const; // \ru Добавь в прям-к свой габарит с учетом матрицы \en Add bounding rectangle into a box with consideration of the matrix @@ -149,7 +149,7 @@ public : // \ru Вычисление минимальной длины кривой между двумя точками на ней \en Calculation of minimal length of a curve between two points on it virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, - MbCartPoint * pc = NULL ) const; + MbCartPoint * pc = c3d_null ) const; virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, VERSION version = Math::DefaultMathVersion() ) const; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction @@ -166,7 +166,7 @@ public : virtual MbeItemLocation PointRelative ( const MbCartPoint & p, double eps = Math::LengthEps ) const; virtual double PointProjection ( const MbCartPoint & ) const; // \ru Проекция точки на кривую \en Point projection on the curve virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point virtual void PerpendicularPoint( const MbCartPoint & pnt, SArray & tFind ) const; @@ -186,7 +186,7 @@ public : virtual void IntersectHorizontal( double y, SArray & cross ) const; // \ru Пересечение с горизонтальной прямой \en Intersection with the horizontal line virtual void IntersectVertical ( double x, SArray & cross ) const; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve virtual bool IsClosed() const; // \ru Проверка замкнутости \en Check for closedness virtual bool IsBounded() const; // \ru Определить, является ли кривая ограниченной. \en Define whether the curve is bounded. virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Признак прямолинейности кривой \en An attribute of curve straightness @@ -308,6 +308,11 @@ inline bool LineLineCrossParams( const MbCartPoint & origin1, const MbVector & d return true; } + if ( origin1.IsSame(origin2, EPSILON) ) { // KOMPAS-41917 + t1 = 0.0; + t2 = 0.0; + return true; + } // \ru Для параллельных прямых определяем параметры точки по середине между origin1 и origin2. \en Definition the parameters for the middle point between origin 1 and origin 2 for parallel lines. MbCartPoint middle; middle.Set( origin1, 0.5, origin2, 0.5 ); diff --git a/C3d/Include/cur_line3d.h b/C3d/Include/cur_line3d.h index d6e8904..6f0b635 100644 --- a/C3d/Include/cur_line3d.h +++ b/C3d/Include/cur_line3d.h @@ -56,12 +56,12 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать \en Transform - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать \en Transform + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Расстояние до точки \en Distance to a point virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить габарит кривой в куб. \en Add a bounding box of a curve to a cube. @@ -98,7 +98,7 @@ public : virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, VERSION version = Math::DefaultMathVersion() ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. @@ -110,7 +110,7 @@ public : virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; bool operator == ( const MbLine3D & with ) const; // \ru Проверка на равенство \en Check for equality bool operator != ( const MbLine3D & with ) const; // \ru Проверка на неравенство \en Check for inequality @@ -118,16 +118,16 @@ public : virtual void GetCentre ( MbCartPoint3D & c ) const; // \ru Выдать центр кривой \en Get the center of curve virtual void GetWeightCentre( MbCartPoint3D & wc ) const; // \ru Выдать центр тяжести кривой \en Get the center of gravity of the curve virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether a curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar virtual double GetParamToUnit() const; // \ru Дать приращение параметра, осреднённо соответствующее единичной длине в пространстве \en Get increment of parameter, corresponding to the unit length in space virtual double GetParamToUnit( double t ) const; // \ru Дать приращение параметра, соответствующее единичной длине в пространстве \en Get increment of parameter, corresponding to the unit length in space // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = NULL ) const; + MbRect1D * pRgn = c3d_null ) const; virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & ) const; // \ru pассчитать полигон \en Calculate a polygon virtual bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar diff --git a/C3d/Include/cur_line_segment.h b/C3d/Include/cur_line_segment.h index f27ab7d..4d67a2d 100644 --- a/C3d/Include/cur_line_segment.h +++ b/C3d/Include/cur_line_segment.h @@ -68,10 +68,10 @@ public : void Init1( const MbCartPoint &p1, const MbCartPoint &p2, double &len, double &angle ); void Init2( const MbCartPoint &p1, MbCartPoint &p2, const double &len, double &angle ); void Init3( const MbCartPoint &p1, MbCartPoint &p2, double &len, const double &angle, - const DiskreteLengthData * diskrData = NULL ); + const DiskreteLengthData * diskrData = c3d_null ); void Init4( MbCartPoint &p1, const MbCartPoint &p2, const double &len, double &angle ); void Init5( MbCartPoint &p1, const MbCartPoint &p2, double &len, const double &angle, - const DiskreteLengthData * diskrData = NULL ); + const DiskreteLengthData * diskrData = c3d_null ); void Init6( const MbCartPoint &p1, MbCartPoint &p2, const double &len, const double &angle ); void Init7( MbCartPoint &p1, const MbCartPoint &p2, const double &len, const double &angle ); void Init8( MbCartPoint &p1, MbCartPoint &p2, double &len, double &angle, @@ -86,10 +86,10 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual void AddYourGabaritTo ( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add bounding box into a straight box virtual void CalculateGabarit ( MbRect & ) const; // \ru Определить габариты кривой \en Determine the bounding box of the curve virtual void CalculateLocalGabarit( const MbMatrix & into, MbRect & local ) const ; // \ru Добавь в прям-к свой габарит с учетом матрицы \en Add bounding box into a box with consideration of the matrix @@ -155,7 +155,7 @@ public : \en \name Common function of curve. \{ */ virtual double Curvature( double t ) const; // \ru Кривизна усеченной кривой \en Curvature of a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление кривой \en Change direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление кривой \en Change direction of a curve virtual MbCurve * Offset( double rad ) const; // \ru Смещение отрезка \en Shift of a line segment virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; @@ -179,7 +179,7 @@ public : virtual MbeItemLocation PointRelative( const MbCartPoint & pnt, double eps = Math::LengthEps ) const; virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на отрезок \en Point projection on the line segment virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area virtual void PerpendicularPoint( const MbCartPoint & pnt, SArray & tFind ) const; // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all perpendiculars to the curve from a given point virtual void IntersectHorizontal( double y, SArray & cross ) const; // \ru Пересечение с горизонтальной прямой \en Intersection with the horizontal line virtual void IntersectVertical ( double x, SArray & cross ) const; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line @@ -188,7 +188,7 @@ public : virtual double GetMetricLength() const; // \ru Метрическая длина \en The metric length virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Evaluation of the metric length of the curve // \ru Вычисление минимальной длины кривой между двумя точками на ней \en Calculation of minimal length of a curve between two points on it - virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = NULL ) const; + virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = c3d_null ) const; virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, VERSION version = Math::DefaultMathVersion() ) const; diff --git a/C3d/Include/cur_line_segment3d.h b/C3d/Include/cur_line_segment3d.h index 29532ea..2797dc0 100644 --- a/C3d/Include/cur_line_segment3d.h +++ b/C3d/Include/cur_line_segment3d.h @@ -64,12 +64,12 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -100,7 +100,7 @@ public : virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить Nurbs-копию кривой \en Construct NURBS copy of the curve virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double CalculateMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve virtual double GetLengthEvaluation() const; virtual double CalculateLength( double t1, double t2 ) const; @@ -111,19 +111,19 @@ public : virtual void GetCentre ( MbCartPoint3D & wc ) const; // \ru Посчитать центр кривой \en Calculate a center of curve virtual void GetWeightCentre( MbCartPoint3D & wc ) const; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve virtual double Curvature( double t ) const; // \ru Кривизна усеченной кривой \en Curvature of a trimmed curve - virtual bool NearPointProjection ( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve + virtual bool NearPointProjection ( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. virtual double MetricStep ( double t, double length ) const; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. - virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = NULL ) const; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of curve. + virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = c3d_null ) const; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of curve. virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight virtual size_t GetCount () const; - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether a curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, VERSION version = Math::DefaultMathVersion() ) const; // \ru Сдвинуть параметр t на расстояние len по направлению \en Shift the parameter t by the distance 'len' in the direction virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & polygon ) const; // \ru Рассчитать полигон \en Calculate a polygon diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index e9786a2..524e4e8 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -399,7 +399,7 @@ public : uppIndex = (ptrdiff_t)initPoints.size() - 1; pointList.assign( initPoints.begin(), initPoints.end() ); - if ( initWeights != NULL ) { + if ( initWeights != c3d_null ) { if ( (ptrdiff_t)initWeights->size() == uppIndex + 1 ) weights.assign( initWeights->begin(), initWeights->end() ); else { @@ -477,6 +477,7 @@ public : */ bool Init( size_t degree, bool cls, const CcArray & points, const CcArray & knots, ptrdiff_t nPoints, ptrdiff_t nKnots ); + /** \brief \ru Инициализация. \en Initialization. \~ \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n @@ -492,8 +493,29 @@ public : \param[in] params - \ru Последовательность узловых параметров. \en Sequence of knot parameters. \~ */ - bool InitThrough( size_t degree, bool cls, const SArray & points, - const SArray & params ); + bool InitThrough( size_t degree, + bool cls, + const SArray & points, + const SArray & params ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through given points at given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const c3d::ParamPointsVector & points, + const c3d::DoubleVector & params ); /** \brief \ru Инициализация. \en Initialization. \~ @@ -535,16 +557,16 @@ public : /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. static MbNurbs * CreateNURBS4( const SArray &, MbeSplineParamType spType, - const MbPntMatingData & begData, - const MbPntMatingData & endData ); + const c3d::PntMatingData2D & begData, + const c3d::PntMatingData2D & endData ); /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. static MbNurbs * CreateNURBS4( const SArray &, MbeSplineParamType spType, bool closed, - RPArray< MbPntMatingData > & ); + RPArray & ); /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. static MbNurbs * CreateNURBS4( const SArray &, const SArray &, bool closed, - RPArray< MbPntMatingData > & ); + RPArray & ); /** \brief \ru Интерполяция. \en Interpolation. \~ \details \ru Создать плоский сплайн четвертого порядка по точкам, признаку замкнутости и типу параметризации.\n @@ -607,14 +629,42 @@ public : static MbNurbs * CreateNURBS4( const MbBezier & ); /// \ru Установить сопряжение на конце. \en Set conjugation at the end. - bool AttachG( MbPntMatingData & connectData, bool beg ); + bool AttachG( c3d::PntMatingData2D & connectData, bool beg ); - /// \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \en Increase order of curve without changing its geometric shape and parametrization. - bool RaiseDegree ( size_t, double relEps = Math::paramEpsilon ); - /// \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \en Decrease order of curve by 1 without changing its geometric shape and parametrization. + /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of curve without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of curve without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en New order of spline. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); + /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ + \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ bool ReductionDegree( double relEps = Math::paramEpsilon ); - /// \ru Задать порядок сплайна. \en Set the spline order. - void SetDegree( size_t newDegree ); + /** \brief \ru Задать порядок сплайна. + \en Set the spline order. \~ + \details \ru Задать порядок сплайна. \n + При изменении порядка параметризация сплайна сбрасывается на равномерную, форма сплайна меняется. \n + \en Set the spline order. \n + When you change the order, the parameterization of the spline is reset to uniform, the shape of the spline changes. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en A new spline order. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool SetDegree( size_t newDegree ); /// \ru Увеличить порядок на 1. \en Increase the order by 1. void DegreeIncrease(); /// \ru Установить тип формы. \en Set the type of shape. @@ -627,12 +677,12 @@ public : \en \name Common functions of geometric object. \{ */ virtual MbePlaneType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая other копией данной кривой? \en Whether the curve is duplicate of current curve. virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными. \en Make elements equal. - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот. \en Rotation. + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот. \en Rotation. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -705,7 +755,7 @@ public : virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное. \en Set the opposite direction of curve. + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное. \en Set the opposite direction of curve. // \ru Определить, является ли кривая репараметризованно такой же. \en Define whether a reparameterized curve is the same. virtual bool IsReparamSame( const MbCurve & curve, double & factor ) const; @@ -766,9 +816,9 @@ public : virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Найти проекцию точки на кривую. \en Find the point projection to the curve. virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); @@ -831,11 +881,11 @@ public : /// \ru Установить признак замкнутости. \en Set the closedness attribute. void LtSetClosed( bool cls ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( form == ncf_Unspecified ) { closed = cls; } } /// \ru Изменить степень, замкнутость и тип формы. \en Change degree, closedness and type of shape. - void LtSetData( size_t d, bool c, MbeNurbsCurveForm f ); + void LtSetData( size_t d, bool c, MbeNurbsCurveForm f ); /// \ru Перестроить сплайн после накачки из библиотеки. \en Rebuild the spline. bool LtRebuild(); /// \ru Инициализация. \en Initialization. - void LtInit(); + void LtInit(); // \ru Преобразование кусочно степенной формы в NURBS-кривую. \en Convert a piecewise exponential form to a NURBS-curve. bool LtInitPowerArc(); bool LtTrimmed( double t1, double t2, int sense = 1 ); @@ -850,7 +900,7 @@ public : void SetWeight( ptrdiff_t pointNumber, double newWeight ); /// \ru Получить кратность узла. \en Get the knot multiplicity. - size_t KnotMultiplicity( ptrdiff_t knotIndex ) const; + size_t KnotMultiplicity( ptrdiff_t knotIndex ) const; /// \ru Определение базисного узлового вектора. \en Determination of basis knot vector. void DefineKnotsVector(); /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. @@ -888,7 +938,7 @@ public : void AddCurves( NurbsCurves & curves ) { for ( size_t i = 0, icount = curves.size(); i < icount; ++i ) { - if ( curves[i] != NULL ) + if ( curves[i] != c3d_null ) AddCurve( *curves[i] ); } } @@ -907,7 +957,7 @@ public : /// \ru Расширить незамкнутую NURBS-кривую по касательным. \en Extend open NURBS-curve by tangents. bool ExtendNurbs( double, double, bool bmerge = false ); - /** \brief \ru Замкнуть кривую. + /** \brief \ru Замкнуть кривую. \en Make curve closed. \~ \details \ru Замкнуть фактически замкнутую кривую.\n То есть если первая и последняя точки кривой совпадают, но она реализована как незамкнутая, @@ -932,6 +982,27 @@ private: // \ru Системные методы. \en System methods. void CalculateSplineWeight( double & t, ptrdiff_t n, MbNurbsAuxiliaryData * cache ) const; bool InitSegments( MbNurbsAuxiliaryData * cache ) const; + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through given points at given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + */ + template + bool InitThroughTempl( size_t degree, + bool cls, + const PointsVector & points, + const ParamsVector & params ); + // \ru Служебные аналоги публичных функций, которые используют заданный кэш. \en Service analogs of public functions that use a given cache. void PointOn( double & t, MbCartPoint & pnt, MbNurbsAuxiliaryData * ucache ) const; // \ru Точка на кривой. \en Point on the curve. void FirstDer( double & t, MbVector & fd, MbNurbsAuxiliaryData * ucache ) const; // \ru Первая производная. \en First derivative. @@ -946,7 +1017,7 @@ private: // \ru Системные методы. \en System methods. // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and its first derivatives. ptrdiff_t WeightFunctions( double & x, CcArray & ) const; // \ru Вычисление шага аппроксимации в обе стороны. \en Calculation of approximation step in both directions. - double StepD( double & t, double sag, bool checkAngle = false, double angle = 0.0, MbNurbsAuxiliaryData * cache = NULL ) const; + double StepD( double & t, double sag, bool checkAngle = false, double angle = 0.0, MbNurbsAuxiliaryData * cache = c3d_null ) const; // \ru Вычисление шага аппроксимации сплайна второго порядка. \en Calculation of approximation step of second order spline. double PolylineStep( double t, bool half, MbNurbsAuxiliaryData * cache ) const; // \ru Уточнить проекцию \en Specify projection. @@ -981,12 +1052,12 @@ MbNurbs::MbNurbs( size_t initDegree, bool initClosed, const PointsVector & initP closed = initClosed; degree = initDegree; // Степень В-сплайна. - if ( initWeights != NULL ) + if ( initWeights != c3d_null ) weights.assign( initWeights->begin(), initWeights->end() ); else weights.assign( initPoints.size(), 1.0 ); - if ( initKnots != NULL ) { + if ( initKnots != c3d_null ) { knots.assign( initKnots->begin(), initKnots->end() ); uppKnotsIndex = (ptrdiff_t)knots.size() - 1; } @@ -1019,15 +1090,13 @@ bool IsStraightNurbs( const Nurbs & nurbs, double mEps = METRIC_EPSILON ) bool isStraight = false; if ( !nurbs.IsClosed() ) { - SArray wts( 0, 1 ); - nurbs.GetWeights( wts ); - size_t wtsCnt = wts.size(); + size_t wtsCnt = nurbs.GetWeightsCount(); isStraight = true; if ( wtsCnt > 1 ) { - double wt0 = wts[0]; + double wt0 = nurbs.GetWeight(0); for ( size_t k = 1; k < wtsCnt; k++ ) { - double wt = wts[k]; + double wt = nurbs.GetWeight(k); if ( ::fabs(wt0 - wt) > EXTENT_EQUAL ) { isStraight = false; break; @@ -1036,8 +1105,8 @@ bool IsStraightNurbs( const Nurbs & nurbs, double mEps = METRIC_EPSILON ) } if ( isStraight ) { isStraight = false; - SArray pnts( 0, 1 ); - nurbs.GetPointList( pnts ); + std::vector pnts; + pnts.reserve( nurbs.GetPointsCount() ); if ( c3d::ArePointsOnLine( pnts, mEps ) ) isStraight = true; } diff --git a/C3d/Include/cur_nurbs3d.h b/C3d/Include/cur_nurbs3d.h index 442bec4..25925f0 100644 --- a/C3d/Include/cur_nurbs3d.h +++ b/C3d/Include/cur_nurbs3d.h @@ -127,7 +127,7 @@ protected: */ MbNurbs3D( size_t deg, bool cls, const SArray & points, - const SArray * weights = NULL, const SArray * knots = NULL ); + const SArray * weights = c3d_null, const SArray * knots = c3d_null ); MbNurbs3D( const MbNurbs3D & ); public : virtual ~MbNurbs3D(); @@ -171,7 +171,7 @@ public : \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs3D * Create( size_t degree, const SArray & points, bool closed, - const SArray * weights = NULL ); + const SArray * weights = c3d_null ); /** \brief \ru Создать сплайн. \en Create spline. \~ \details \ru Создать сплайн и установить параметры сплайна.\n @@ -238,7 +238,28 @@ public : \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs3D * CreateThrough( size_t degree, bool cls, const SArray & points, - const SArray & params, SArray * aKnots = NULL ); + const SArray & params, SArray * aKnots = c3d_null ); + /** \brief \ru Создать сплайн. + \en Create spline. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] aKnots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbNurbs3D * CreateThrough( size_t degree, bool cls, const c3d::SpacePointsVector & points, + const c3d::DoubleVector & params, c3d::DoubleVector * aKnots = c3d_null ); /** \brief \ru Заполнить NURBS по данным parasolid. \en Fill NURBS by parasolid data. \~ \details \ru Заполнить NURBS по данным parasolid.\n @@ -294,7 +315,7 @@ public: \en Closedness attribute. \~ */ bool Init( size_t degree, const SArray & points, bool closed, - const SArray * weights = NULL ); + const SArray * weights = c3d_null ); /** \brief \ru Инициализация. \en Initialization. \~ \details \ru Установить параметры сплайна.\n @@ -386,9 +407,11 @@ public: \param[in] endData - \ru Параметр сопряжения в конечной точке сплайна. \en Parameter of conjugation at the end point of the spline. \~ */ - bool Init( size_t degree, const SArray & points, const SArray & weights, - MbPntMatingData & begData, - MbPntMatingData & endData ); + bool Init( size_t degree, + const SArray & points, + const SArray & weights, + c3d::PntMatingData3D & begData, + c3d::PntMatingData3D & endData ); /** \brief \ru Инициализация. \en Initialization. \~ \details \ru Установить параметры сплайна.\n @@ -422,29 +445,55 @@ public: \en Set of points which the spline passes through. \~ \param[in] params - \ru Последовательность узловых параметров. \en Sequence of knot parameters. \~ - \param[in] aKnots - \ru Неубывающая последовательность узлов. + \param[in] knots - \ru Неубывающая последовательность узлов. \en Nondecreasing sequence of knots. \~ */ - bool InitThrough( size_t degree, bool cls, const SArray & points, - const SArray & params, SArray * aKnots = NULL ); + bool InitThrough( size_t degree, + bool cls, + const SArray & points, + const SArray & params, + SArray * aKnots = c3d_null ); + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + bool InitThrough( size_t degree, + bool cls, + const c3d::SpacePointsVector & points, + const c3d::DoubleVector & params, + c3d::DoubleVector * knots = c3d_null ); + /// \ru Установить тип формы. \en Set the type of shape. void SetFormType( MbeNurbsCurveForm f ) { form = f; } // \ru Общие функции математического объекта. \en The common functions of the mathematical object. virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая копией данной кривой? \en Whether the curve is a duplicate of the current curve. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void GetControlPoints( SArray & s ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + void GetControlPoints( SArray & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. // \ru Общие функции кривой. \en Common functions of curve. @@ -475,12 +524,12 @@ public: virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis ( MbAxis3D & ) const; // \ru Дать ось кривой \en Get the axis of the curve // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Ближайшая проекция точки на кривую. \en The nearest projection of a point onto the curve. - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление. \en Change the direction. + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление. \en Change the direction. // \ru Определить, является ли кривая репараметризованно такой же. \en Determine whether a reparameterized curve is the same. virtual bool IsReparamSame( const MbCurve3D & curve, double & factor ) const; @@ -521,7 +570,7 @@ public: virtual double GetParam( ptrdiff_t i ) const; // \ru Выдать параметр для точки с заданным номером. \en Get parameter for a point with the given index. virtual void ResetTCalc() const; // \ru Сбросить текущее значение параметра \en Reset the current value of the parameter - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); @@ -550,9 +599,27 @@ public: /// \ru Преобразовать данный NURBS в форму кривой Безье. \en Transform current NURBS into Bezier curve. bool DecomposeCurve(); - /// \ru Увеличить порядок NURBS-кривой, не меняя ее геометрическую форму и парамеризацию. \en Increase the order of a NURBS-curve without changing its geometric shape and parameterization. - bool RaiseDegree ( size_t, double relEps = Math::paramEpsilon ); - /// \ru Уменьшить порядок кривой на 1. \en Decrease the order of a curve by 1. + /** \brief \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. + \en Increase order of curve without changing its geometric shape and parametrization. \~ + \details \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \n + \en Increase order of curve without changing its geometric shape and parametrization. \n \~ + \param[in] newDegree - \ru Новый порядок сплайна. + \en New order of spline. \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ + bool RaiseDegree( size_t newDegree, double relEps = Math::paramEpsilon ); + /** \brief \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \~ + \details \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \n + \en Decrease order of nurbs curve by 1 without changing its geometric shape and parametrization. \n \~ + \param[in] relEps - \ru Допустимая погрешность изменения формы. + \en Permissible shape error. \~ + \return \ru Возвращает true, если порядок сплайна был изменен. + \en Returns true if the order of the spline was changed. \~ + */ bool ReductionDegree( double relEps = Math::paramEpsilon ); /// \ru Получить кратность узла с заданным номером. \en Get multiplicity of a knot with a given index. @@ -605,28 +672,30 @@ public: // \ru Функции только 3D кривой. \en Functions of 3D curve only. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. virtual size_t GetCount() const; // \ru Количество разбиений для прохода в операциях с поверхностями. \en Count of subdivisions for pass in operations with surfaces. /// \ru Установить сопряжение на конце. \en Set conjugation at the end. - bool AttachG( MbPntMatingData & connectData, bool beg, bool isWrongAttachG1_K12 = false ); + bool AttachG( c3d::PntMatingData3D & connectData, bool beg, bool isWrongAttachG1_K12 = false ); /// \ru Создать кубический NURBS по точкам, через которые он проходит, и параметрам сопряжения. \en Create cubic NURBS by parameters of conjugation and points which it passes through. - static MbNurbs3D * CreateNURBS4( const SArray &, MbeSplineParamType spType, - const MbPntMatingData & begData, - const MbPntMatingData & endData, - MbeSplineCreateType useInitThrough ); + static MbNurbs3D * CreateNURBS4( const SArray & points, + MbeSplineParamType spType, + const c3d::PntMatingData3D & begData, + const c3d::PntMatingData3D & endData, + MbeSplineCreateType useInitThrough ); /// \ru Создать кубический NURBS по интерполяционным точкам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points and data of conjugation at each point. - static MbNurbs3D * CreateNURBS4( const SArray &, MbeSplineParamType spType, - bool closed, - RPArray< MbPntMatingData > &, - MbeSplineCreateType useInitThrough ); + static MbNurbs3D * CreateNURBS4( const SArray & points, + MbeSplineParamType spType, + bool closed, + RPArray & matingData, + MbeSplineCreateType useInitThrough ); /// \ru Создать кубический NURBS по интерполяционным точкам, их параметрам и данным сопряжения в каждой точке. \en Create cubic NURBS by interpolation points, parameters and data of conjugation at each point. static MbNurbs3D * CreateNURBS4( const SArray &, const SArray &, bool closed, - RPArray< MbPntMatingData > &, + RPArray &, MbeSplineCreateType useInitThrough ); /// \ru Создать кубический NURBS по точкам, через которые он проходит, и признаку замкнутости. \en Create a cubic NURBS by the attribute of closedness and points which it passes through. static MbNurbs3D * CreateNURBS4( const SArray &, bool cls, MbeSplineParamType spType, @@ -690,9 +759,11 @@ public: \details \ru Создать сплайн произвольного порядка через точки, с управлением касательными и кривизной в этих точках. \en Create a spline of any order containing the given points with managing of tangent and curvature at these points.\~ */ - static MbNurbs3D * CreateNURBS( size_t initDegree, const SArray & initPoints, - const SArray & initParams, bool initClosed, - RPArray> & matingData ); + static MbNurbs3D * CreateNURBS( size_t initDegree, + const SArray & initPoints, + const SArray & initParams, + bool initClosed, + RPArray & matingData ); /** \brief \ru Разбить кривую. \en Split the curve. \~ \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n @@ -745,41 +816,68 @@ private: MbNurbs3D * NurbsPlus( double tin, double tax ) const; + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n + В случае замкнутости нужно передавать массив с совпадением первой и последней точек.\n + \en Spline passing through the given points at the given parameters.\n + In case of closedness it is necessary to pass the array with coincidence of the first and the last points.\n \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline order. \~ + \param[in] cls - \ru Признак замкнутости. + \en Closedness attribute. \~ + \param[in] points - \ru Набор точек, через которые проходит сплайн. + \en Set of points which the spline passes through. \~ + \param[in] params - \ru Последовательность узловых параметров. + \en Sequence of knot parameters. \~ + \param[in] knots - \ru Неубывающая последовательность узлов. + \en Nondecreasing sequence of knots. \~ + */ + template + bool InitThroughTempl( size_t degree, + bool cls, + const PointsVector & points, + const ParamsVector & params, + ParamsVector * knots ); + // \ru BEG: Внутренние функции CreateNURBS4 по двум сопряжениям. \en BEG: Internal CreateNURBS4 functions by two conjugations. // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения по касательным. \en Create an interpolation cubic NURBS meeting conditions of conjugation by tangents. - bool AttachG1_NURBS4( const SArray &, const SArray & params, - const MbPntMatingData & begData, - const MbPntMatingData & endData ); + bool AttachG1_NURBS4( const SArray & points, + const SArray & params, + const c3d::PntMatingData3D & begData, + const c3d::PntMatingData3D & endData ); // \ru Создать интерполяционный кубический NURBS, удовлетворяющий условиям сопряжения со вторым порядком гладкости. \en Create an interpolation cubic NURBS meeting conditions of conjugation with the second order of smoothness. - bool AttachG2_NURBS4( const SArray &, const SArray & params, - const MbPntMatingData & begData, - const MbPntMatingData & endData ); + bool AttachG2_NURBS4( const SArray & points, + const SArray & params, + const c3d::PntMatingData3D & begData, + const c3d::PntMatingData3D & endData ); // \ru END: Внутренние функции CreateNURBS4 по двум сопряжениям. \en END: Internal CreateNURBS4 functions by two conjugations. // \ru BEG: Внутренние функции CreateNURBS4 по массиву сопряжений. \en BEG: Internal CreateNURBS4 functions by an array of conjugations. // \ru Построение интерполяционного NURBS4 с возможными заданными управляющими параметрами. \en Create an interpolation NURBS4 with possibly given driving parameters. - bool CreateC2_NURBS4( const SArray &, MbeSplineParamType spType, - RPArray< MbPntMatingData > &, - const SArray &, - MbeSplineCreateType useInitThrough, - bool cls = false ); + bool CreateC2_NURBS4( const SArray & points, + MbeSplineParamType spType, + RPArray & inferredData, + const SArray & params, + MbeSplineCreateType useInitThrough, + bool cls = false ); // \ru Построение интерполяционного незамкнутого NURBS4 в общем случае \en Create an interpolation open NURBS4 in general case // \ru С возможными заданными управляющими параметрами в средних точках. \en With possibly given driving parameters at middle points. // \ru Считаем, что данные для сопряжений заданы корректно. Этот факт проверяется до запуска функции. \en Consider that the given data for conjugations is correct. This fact is checked before calling the function. - static MbNurbs3D * CreateC2Nurbs4Common( const SArray & arPoints, - RPArray< MbPntMatingData > & inferredData, - const SArray & arParams, - const SArray & arKnots, - size_t addCount, - bool cls, - MbeSplineCreateType useInitThrough, - size_t deg = 4 ); + static MbNurbs3D * CreateC2Nurbs4Common( const SArray & points, + RPArray & inferredData, + const SArray & params, + const SArray & knots, + size_t addCount, + bool cls, + MbeSplineCreateType useInitThrough, + size_t deg = 4 ); // \ru END: Внутренние функции CreateNURBS4 по массиву сопряжений. \en END: Internal CreateNURBS4 functions by an array of conjugations. // \ru Расчет весовых функций и их первых производных. \en Calculation of weight functions and their first derivatives. ptrdiff_t WeightFunctions ( double & x, CcArray & m ) const; /// \ru Вычисление шага аппроксимации. \en Calculation of a step of approximation. - double StepD( double t, double sag, bool checkAngle, double angle = Math::lowRenderAng, MbNurbs3DAuxiliaryData * cache = NULL ) const; + double StepD( double t, double sag, bool checkAngle, double angle = Math::lowRenderAng, MbNurbs3DAuxiliaryData * cache = c3d_null ) const; // \ru Вычисление шага аппроксимации сплайна второго порядка. \en Calculation of approximation step of second order spline. double PolylineStep( double t, bool half, MbNurbs3DAuxiliaryData * cache ) const; // \ru Уточнить проекцию \en Specify projection. diff --git a/C3d/Include/cur_nurbs_vector.h b/C3d/Include/cur_nurbs_vector.h index 2832663..fb15fd8 100644 --- a/C3d/Include/cur_nurbs_vector.h +++ b/C3d/Include/cur_nurbs_vector.h @@ -29,7 +29,7 @@ public: double * w; public: - MbNURBSVector2D() : x( NULL ), y( NULL ), w( NULL ) {} + MbNURBSVector2D() : x( c3d_null ), y( c3d_null ), w( c3d_null ) {} ~MbNURBSVector2D(); // \ru освободить память \en free memory public: @@ -51,7 +51,7 @@ private: // // --- inline void MbNURBSVector2D::Init( ptrdiff_t i, const MbCartPoint &ip, double iw ) { - if ( w != NULL ) { + if ( w != c3d_null ) { x[i] = ( ip.x * iw ); y[i] = ( ip.y * iw ); w[i] = iw; @@ -69,7 +69,7 @@ inline void MbNURBSVector2D::Init( ptrdiff_t i, const MbCartPoint &ip, double iw inline void MbNURBSVector2D::SetZero( ptrdiff_t i ) { x[i] = 0.0; y[i] = 0.0; - if ( w != NULL ) + if ( w != c3d_null ) w[i] = 0.0; } @@ -80,7 +80,7 @@ inline void MbNURBSVector2D::SetZero( ptrdiff_t i ) { inline void MbNURBSVector2D::Set( ptrdiff_t i, const MbNURBSVector2D &p, ptrdiff_t ip ) { x[i] = p.x[ip]; y[i] = p.y[ip]; - if ( w != NULL ) + if ( w != c3d_null ) w[i] = p.w[ip]; } @@ -95,7 +95,7 @@ inline void MbNURBSVector2D::Dec( ptrdiff_t i, { x[i] = ( (p2.x[ip2] - p1.x[ip1]) * kk ); y[i] = ( (p2.y[ip2] - p1.y[ip1]) * kk ); - if ( w != NULL ) + if ( w != c3d_null ) w[i] = ( (p2.w[ip2] - p1.w[ip1]) * kk ); } @@ -107,7 +107,7 @@ inline void MbNURBSVector2D::Set( ptrdiff_t i, const MbNURBSVector2D & p, ptrdif { x[i] = ( p.x[ip] * kk ); y[i] = ( p.y[ip] * kk ); - if ( w != NULL ) + if ( w != c3d_null ) w[i] = ( p.w[ip] * kk ); } diff --git a/C3d/Include/cur_nurbs_vector3d.h b/C3d/Include/cur_nurbs_vector3d.h index 0476a22..2a2c85f 100644 --- a/C3d/Include/cur_nurbs_vector3d.h +++ b/C3d/Include/cur_nurbs_vector3d.h @@ -212,7 +212,7 @@ inline void MbNURBSVector::Set( ptrdiff_t i, const MbNURBSVector & p, ptrdiff_t inline void MbNURBSVector::Set( ptrdiff_t i, const DoubleTriple * t, double * ww, ptrdiff_t ip ) { _vec[i].Init( t[ip].x , t[ip].y , t[ip].z ); - if ( useWeights && ww != NULL ) + if ( useWeights && ww != c3d_null ) w(i) = ww[ip]; } diff --git a/C3d/Include/cur_offset_curve.h b/C3d/Include/cur_offset_curve.h index 00e0471..7ef7470 100644 --- a/C3d/Include/cur_offset_curve.h +++ b/C3d/Include/cur_offset_curve.h @@ -40,7 +40,7 @@ class MbRegTransform; // --- class MATH_CLASS MbOffsetCurve : public MbCurve { protected : - MbCurve * basisCurve; ///< \ru Базовая кривая (всегда не NULL) \en Base curve (always not NULL). + MbCurve * basisCurve; ///< \ru Базовая кривая (всегда не c3d_null) \en Base curve (always not c3d_null). double tmin; ///< \ru Начальный параметр basisCurve. \en Start parameter of basisCurve. double tmax; ///< \ru Конечный параметр basisCurve. \en End parameter of basisCurve. bool closed; ///< \ru Замкнутость basisCurve. \en Closedness of basisCurve. @@ -102,10 +102,10 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool IsSimilar ( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. virtual void AddYourGabaritTo( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add bounding box into a straight box @@ -192,7 +192,7 @@ public : \{ */ virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight virtual MbCurve * Offset( double rad ) const; // \ru Смещение смещенной кривой \en Offset of the offset curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -237,7 +237,7 @@ public : virtual void GetBasisPoints( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_offset_curve3d.h b/C3d/Include/cur_offset_curve3d.h index 2cf0a1a..0a7938e 100644 --- a/C3d/Include/cur_offset_curve3d.h +++ b/C3d/Include/cur_offset_curve3d.h @@ -12,6 +12,7 @@ #include +#include #include #include @@ -62,14 +63,40 @@ public : \en Constructor. \~ \details \ru Конструктор эквидистантной кривой по спайну и вектору.\n \en Constructor by a curve and offset vector in start point.\n \~ - \param[in] c - \ru Базовая кривая. \en The base curve. \~ - \param[in] off - \ru Вектор смещения начальной точки кривой. \en Offset in start point. \~ - \param[in] same - \ru Использовать присланную кривую (true) или ее копию (false). - \en Use same curve (true) or copy (false). \~ - \param[in] ort - \ru Ортогонализовать вектор к касательной кривой в начальной точке. - \en Ortogonalize offset vector (true) or same vector (false). \~ + \param[in] baseCurve - \ru Базовая кривая. + \en The base curve. \~ + \param[in] offsetVector - \ru Вектор смещения начальной точки кривой. + \en Offset in start point. \~ + \param[in] sameCurve - \ru Использовать присланную кривую (true) или ее копию (false). + \en Use same curve (true) or copy (false). \~ + \param[in] ort - \ru Ортогонализовать вектор к касательной кривой в начальной точке. + \en Ortogonalize offset vector (true) or same vector (false). \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ */ - MbOffsetCurve3D( const MbCurve3D & c, const MbVector3D & off, bool same, bool ort, VERSION version = Math::DefaultMathVersion() ); + MbOffsetCurve3D( const MbCurve3D & baseCurve, const MbVector3D & offsetVector, bool sameCurve, bool ort, VERSION version = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор эквидистантной кривой по спайну и вектору в режим по нормали к поверхности. \n + Если кривая не является поверхностной кривой, то будет выполнена инициализация без использования поверхности. \n + Поверхность в аргументах нужна для выбора нужной поверхности, если кривая является кривой пересечения двух разных поверхностей. \n + \en Constructor by a surface curve and offset vector in start point.\n + If the curve is not a curve on surface, it will be initialized without using the surface. \n + A surface in arguments is needed to select the desired surface if the curve is a curve of intersection of two different surfaces. \n \~ + \param[in] baseCurve - \ru Базовая кривая. + \en The base curve. \~ + \param[in] sameCurve - \ru Использовать присланную кривую (true) или ее копию (false). + \en Use same curve (true) or copy (false). \~ + \param[in] surface - \ru Поверхность кривой или поверхность, подобная поверхности кривой. + \en Curve surface or surface similar to curve surface. \~ + \param[in] offsetVector - \ru Вектор смещения начальной точки кривой. + \en Offset in start point. \~ + \param[in] ort - \ru Ортогонализовать вектор к касательной кривой в начальной точке. + \en Ortogonalize offset vector (true) or same vector (false). \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + */ + MbOffsetCurve3D( const MbCurve3D & baseCurve, bool sameCurve, c3d::ConstSurfaceSPtr & surface, const MbVector3D & offsetVector, bool ort, VERSION version = Math::DefaultMathVersion() ); private : MbOffsetCurve3D( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. protected: @@ -103,7 +130,7 @@ public: // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar @@ -147,16 +174,16 @@ public: virtual const MbCurve3D & GetBasisCurve() const; virtual MbCurve3D & SetBasisCurve(); //virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual size_t GetCount() const; virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether a curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if curve is planar - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_plane_curve.h b/C3d/Include/cur_plane_curve.h index fef1f09..c5b1632 100644 --- a/C3d/Include/cur_plane_curve.h +++ b/C3d/Include/cur_plane_curve.h @@ -36,7 +36,7 @@ class MATH_CLASS MbContour; class MATH_CLASS MbPlaneCurve : public MbCurve3D { protected : MbPlacement3D position; ///< \ru Локальная система координат, в плоскости XY которой расположена кривая. \en The local coordinate system in XY plane of which the curve is located. - MbCurve * curve; ///< \ru Двумерная кривая (не может быть NULL). \en A two-dimensional uv-curve (can not be NULL). + MbCurve * curve; ///< \ru Двумерная кривая (не может быть c3d_null). \en A two-dimensional uv-curve (can not be c3d_null). public : /// \ru same = false - копировать кривую init. \en Same = false - copy the curve "init". @@ -55,13 +55,13 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать \en Transform. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать \en Transform. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Расстояние до точки \en Distance to a point virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -101,8 +101,8 @@ public : virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Creation of a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve virtual double Curvature( double ) const; // \ru Кривизна кривой \en Curvature of the curve virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. @@ -119,15 +119,15 @@ public : /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ virtual void GetAnalyticalFunctionsBounds( std::vector & params ) const; - virtual bool IsPlanar() const; // \ru Является ли кривая плоской \en Whether a curve is planar + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether a curve is planar virtual bool IsSmoothConnected( double angleEps ) const; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of contour\curve are smooth. // \ru Ближайшая точка кривой к плейсменту \en The nearest point of a curve by the placement virtual double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const; - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of curve virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, - MbRect1D * pRgn = NULL ) const; + MbRect1D * pRgn = c3d_null ) const; virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis ( MbAxis3D & ) const; // \ru Дать ось кривой \en Get the curve axis @@ -141,11 +141,11 @@ public : virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Give a planar curve and placement, if the spatial curve is planar (after using the DeleteItem must be called for a two-dimensional curve) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы) \en Get a surface curve if spatial curve is lying on the surface (after the using call DeleteItem for arguments) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; MbCurve * GetCurve ( const MbPlacement3D & , MbMatrix & ) const; // \ru Дать плоскую кривую \en Get the plane curve MbCurve * MakeCurve( const MbPlacement3D & ) const; @@ -163,7 +163,7 @@ public : virtual bool IsShift( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const; virtual bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves are similar for merge (joining) - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_point_curve.h b/C3d/Include/cur_point_curve.h index 3488e36..44908b9 100644 --- a/C3d/Include/cur_point_curve.h +++ b/C3d/Include/cur_point_curve.h @@ -65,10 +65,10 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make equal elements - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); virtual void AddYourGabaritTo ( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add bounding box into a straight box virtual void CalculateLocalGabarit( const MbMatrix & into, MbRect & local ) const; // \ru Добавь в прям-к свой габарит с учетом матрицы \en Add bounding box into a box with consideration of the matrix virtual double DistanceToPoint( const MbCartPoint & to ) const; // \ru Расстояние до точки \en Distance to a point @@ -131,7 +131,7 @@ public : \en \name Common function of curve \{ */ virtual double Curvature( double t ) const; // \ru Кривизна усеченной кривой \en Curvature of a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление кривой \en Change direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление кривой \en Change direction of a curve virtual bool IsDegenerate( double eps = Math::LengthEps ) const; // \ru Проверка вырожденности \en Check for degeneracy virtual bool HasLength( double & length ) const; @@ -154,7 +154,7 @@ public : virtual MbeItemLocation PointRelative( const MbCartPoint & pnt, double eps = Math::LengthEps ) const; virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на отрезок \en Point projection on the line segment virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Point projection on the curve or its extension in the projection search area virtual void IntersectHorizontal( double y, SArray & cross ) const; // \ru Пересечение с горизонтальной прямой \en Intersection with the horizontal line virtual void IntersectVertical ( double x, SArray & cross ) const; // \ru Пересечение с вертикальной прямой \en Intersection with the vertical line diff --git a/C3d/Include/cur_polycurve.h b/C3d/Include/cur_polycurve.h index b0e9227..e267ea7 100644 --- a/C3d/Include/cur_polycurve.h +++ b/C3d/Include/cur_polycurve.h @@ -54,10 +54,10 @@ public : virtual MbePlaneType Type() const; // \ru Тип элемента \en Type of element virtual bool SetEqual( const MbPlaneItem & ) = 0; // \ru Сделать элементы равными \en Make the elements equal virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element virtual void AddYourGabaritTo( MbRect & r ) const; // \ru Добавь свой габарит в прямой прям-к \en Add your own gabarit into the given bounding rectangle virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -94,7 +94,7 @@ public : virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Признак прямолинейности кривой \en An attribute of curve straightness. virtual bool HasLength( double & length ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one virtual MbeState Deformation( const MbRect &, const MbMatrix & ); // \ru Деформация \en Deformation virtual bool IsInRectForDeform( const MbRect & r ) const; // \ru Виден ли объект в заданном прямоугольнике для деформации \en Whether the object is visible in the given rectangle for deformation @@ -298,9 +298,12 @@ public : size_t GetPointListCount() const { return pointList.Count(); } ///< \ru Выдать количество характерный точек. \en Get count of control points. ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } ///< \ru Выдать максимальный индекс массива контрольных точек. \en Get maximal index of array of control points. - template - void GetPoints( Points & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - void GetPointList( SArray & pnts ) const { pnts = pointList; } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + + template + void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( c3d::ParamPointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + bool ReplacePoints( const SArray & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. bool ReplacePoints( const std::vector & pnts ); ///< \ru Заменить набор контрольных точек. \en Replace the set of control points. diff --git a/C3d/Include/cur_polycurve3d.h b/C3d/Include/cur_polycurve3d.h index a5bdf62..99d259a 100644 --- a/C3d/Include/cur_polycurve3d.h +++ b/C3d/Include/cur_polycurve3d.h @@ -47,12 +47,12 @@ public : virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента \en Type of element virtual MbeSpaceType Type() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси \en Rotate about an axis virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб \en Add your own bounding box into the cube virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -82,15 +82,15 @@ public : virtual double GetTMax() const = 0; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter virtual double GetTMin() const = 0; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter virtual bool IsClosed() const; // \ru Замкнутость кривой \en A curve closedness - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Выдать метрическую длину ограниченной кривой \en Get metric length of bounded curve virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Estimation of metric length of the curve - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether the curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if the curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether the curve is planar + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if the curve is planar // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const = 0; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const = 0; // \ru Общие функции полигональной кривой \en Common functions of polygonal curve @@ -119,9 +119,12 @@ public : size_t GetPointListCount() const { return pointList.Count(); } ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } - template - void GetPoints( Points & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. - void GetPointList( SArray & pnts ) const { pnts = pointList; } // \ru Получить характерные точки \en Get control points + + template + void GetPoints( PointsVector & pnts ) const { std::copy( pointList.begin(), pointList.end(), std::back_inserter( pnts ) ); } ///< \ru Вернуть массив контрольных точек. \en Get array of control points. + void GetPointList( SArray & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points + void GetPointList( c3d::SpacePointsVector & pnts ) const { pnts.assign( pointList.begin(), pointList.end() ); } // \ru Получить характерные точки \en Get control points + const MbCartPoint3D & GetPointList( size_t i ) const { return pointList[i]; } // \ru Характерные точки \en Control points MbCartPoint3D & SetPointList( size_t i ) { return pointList[i]; } // \ru Характерные точки \en Control points diff --git a/C3d/Include/cur_polyline.h b/C3d/Include/cur_polyline.h index 616db77..9087c8c 100644 --- a/C3d/Include/cur_polyline.h +++ b/C3d/Include/cur_polyline.h @@ -51,7 +51,7 @@ public : MbPolyline( const MbCartPoint & p1, const MbCartPoint & p2 ) : MbPolyCurve() , segmentsCount( 1 ) - , searchTree( NULL ) + , searchTree( c3d_null ) { pointList.reserve( 2 ); pointList.push_back( p1 ); @@ -64,7 +64,7 @@ public : MbPolyline( const Points & initList, bool cls ) : MbPolyCurve() , segmentsCount( UNDEFINED_INT_T ) - , searchTree( NULL ) + , searchTree( c3d_null ) { Init( initList, cls ); } @@ -87,10 +87,10 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool SetEqual( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. - virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix & matr, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data /** \} */ @@ -189,7 +189,7 @@ public : virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Признак прямолинейности кривой \en An attribute of curve straightness. - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one virtual double CalculateMetricLength() const; // \ru Посчитать метрическую длину \en Calculate the metric length virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Estimation of metric length of the curve @@ -253,7 +253,7 @@ public : virtual bool IsDegenerate( double eps = Math::LengthEps ) const; // \ru Проверка вырожденности кривой \en Check for curve degeneracy virtual bool IsSmoothConnected( double angleEps ) const; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth. - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_polyline3d.h b/C3d/Include/cur_polyline3d.h index 25dfea8..a9168e2 100644 --- a/C3d/Include/cur_polyline3d.h +++ b/C3d/Include/cur_polyline3d.h @@ -99,12 +99,12 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать \en Transform - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать \en Transform + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const;// \ru Расстояние до точки \en Distance to a point virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object @@ -130,7 +130,7 @@ public : virtual double GetTMin() const; // \ru Вернуть минимальное значение параметра \en Get the minimum value of the parameter virtual double GetTMax() const; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; // \ru Шаг параметра с учетом радиуса кривизны \en Step of parameter with consideration of curvature virtual double DeviationStep( double t, double angle ) const; // \ru Шаг параметра по заданному углу отклонения касательной \en Step of parameter by a given angle of deviation of tangent @@ -144,7 +144,7 @@ public : virtual void GetCentre ( MbCartPoint3D & wc ) const; // \ru Посчитать центр кривой \en Calculate the center of a curve virtual void GetWeightCentre( MbCartPoint3D & wc ) const; // \ru Посчитать центр тяжести кривой \en Calculate the gravity center of the curve // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Общие функции полигональной кривой \en Common functions of polygonal curve @@ -152,7 +152,7 @@ public : virtual void GetRuleInterval( ptrdiff_t index, double & t1, double & t2 ) const; // \ru Выдать интервал влияния точки кривой \en Get the interval of point influence // \ru Функции только 3D кривой \en Functions of 3D curve only - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The nearest point projection to the curve virtual void InsertPoint( ptrdiff_t index, const MbCartPoint3D & ); // \ru Добавить точку \en Add a point virtual void InsertPoint( double t, const MbCartPoint3D &, double ); // \ru Добавить точку \en Add a point virtual bool CheckParam ( double & t, ptrdiff_t & i0, ptrdiff_t & i1, double & t0, double & t1 ) const; // \ru Установить параметр \en Set parameter @@ -162,14 +162,14 @@ public : //virtual bool GoThroughPoint( double t, MbCartPoint3D & p ); // \ru Пройти через точку \en Pass through point - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. - virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = NULL ) const; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of a curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. + virtual MbCurve * GetMapPsp( const MbMatrix3D &, double zNear, MbRect1D * pRgn = c3d_null ) const; // \ru Дать перспективную плоскую проекцию кривой. \en Get a planar geometric projection of a curve. virtual size_t GetCount() const; virtual bool IsSmoothConnected( double angleEps ) const; // \ru Являются ли стыки контура\кривой гладкими? \en Whether the joints of a contour\curve are smooth. - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_projection_curve.h b/C3d/Include/cur_projection_curve.h index a49155c..a4d679a 100644 --- a/C3d/Include/cur_projection_curve.h +++ b/C3d/Include/cur_projection_curve.h @@ -43,9 +43,9 @@ class MbCurveIntoNurbsInfo; // --- class MATH_CLASS MbProjCurve : public MbCurve { private : - MbCurve3D * spaceCurve; ///< \ru Пространственная кривая (всегда не NULL). \en Spatial curve (always not NULL). - MbSurface * surface; ///< \ru Поверхность (всегда не NULL). \en Surface (always not NULL). - MbCurve * curve; ///< \ru Проекция пространственной кривой на поверхность (служит начальным приближением), всегда не NULL. \en Projection of a spatial curve onto a surface (is used as initial approximation), always not NULL. + MbCurve3D * spaceCurve; ///< \ru Пространственная кривая (всегда не c3d_null). \en Spatial curve (always not c3d_null). + MbSurface * surface; ///< \ru Поверхность (всегда не c3d_null). \en Surface (always not c3d_null). + MbCurve * curve; ///< \ru Проекция пространственной кривой на поверхность (служит начальным приближением), всегда не c3d_null. \en Projection of a spatial curve onto a surface (is used as initial approximation), always not c3d_null. MbMatrix3D * into; ///< \ru Матрица пересчета в систему координат плоскости. Для случая плоской поверхности surface. Вычисляется заново при изменении поверхности. \en A matrix of transformation to the plane coordinate system. In case of planar surface 'surface'. Recalculated at surface change. bool belong; ///< \ru Проецируемая кривая лежит на поверхности. \en Projecting curve lies on the surface. @@ -117,7 +117,7 @@ public : MbProjCurve( const MbCurve3D & sCurve, bool sameSpaceCurve, const MbSurface & surface, const MbCurve & pCurve, bool samePlaneCurve, - MbRegDuplicate * iReg = NULL ); + MbRegDuplicate * iReg = c3d_null ); private: MbProjCurve( const MbProjCurve &, MbRegDuplicate * ireg ); @@ -136,13 +136,13 @@ public : virtual bool IsSimilar ( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -204,7 +204,7 @@ public : \{ */ virtual double PointProjection( const MbCartPoint & pnt ) const; // \ru Проекция точки на кривую. \en Point projection on the curve. virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции. \en Projection of a point onto the curve or its extension in the projection region. + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции. \en Projection of a point onto the curve or its extension in the projection region. virtual bool HasLength( double & ) const; // \ru Метрическая длина кривой. \en Metric length of a curve. virtual double GetMetricLength() const; // \ru Метрическая длина кривой. \en Metric length of a curve. @@ -216,7 +216,7 @@ public : virtual bool GetMiddlePoint( MbCartPoint & ) const; // \ru Вычислить среднюю точку кривой. \en Calculate mid-point of curve. - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; @@ -238,12 +238,12 @@ public : bool IsBelong() const { return belong; } ///< \ru Лежит ли проецируемая кривая на поверхности. \en Whether the projecting curve lies on the surface. - bool InvertNormal( MbRegTransform * = NULL ); ///< \ru Инвертировать нормаль, если поверхность - плоскость. \en Invert normal if the surface is a plane. + bool InvertNormal( MbRegTransform * = c3d_null ); ///< \ru Инвертировать нормаль, если поверхность - плоскость. \en Invert normal if the surface is a plane. bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); ///< \ru Изменение носителя. \en Change a carrier. /// \ru Получить 2d сплайн с данной относительной точностью аппроксимирующий данную кривую. \en Get 2d spline which approximates given curve with a given relative tolerance. - MbCurve * CreateSpline( double relEps, MbRect1D * pRgn = NULL ) const; + MbCurve * CreateSpline( double relEps, MbRect1D * pRgn = c3d_null ) const; /// \ru Создать кривую путём сращивания части данной кривой с частью другой кривой. \en Create a curve by joining a part of this curve with a part of other curve. MbProjCurve * AddCurve( const MbProjCurve &, double accuracy, VERSION version = Math::DefaultMathVersion() ) const; diff --git a/C3d/Include/cur_reparam_curve.h b/C3d/Include/cur_reparam_curve.h index 5a28df2..33c4cf7 100644 --- a/C3d/Include/cur_reparam_curve.h +++ b/C3d/Include/cur_reparam_curve.h @@ -80,12 +80,12 @@ public : virtual MbePlaneType IsA() const; // \ru Тип элемента \en Type of element virtual bool IsSimilar( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal - virtual void Transform( const MbMatrix &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbCartPoint &, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation + virtual void Transform( const MbMatrix &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbCartPoint &, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation virtual bool IsSame( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const; virtual MbCurve * Offset( double rad ) const; // \ru Смещение усеченной кривой \en Shift of a trimmed curve - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; virtual MbContour * NurbsContour() const; // \ru Построить контур \en Create a contour virtual void AddYourGabaritTo( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add your own gabarit into the given bounding rectangle @@ -153,7 +153,7 @@ public : /** \ru \name Общие функции кривой \en \name Common functions of curve \{ */ - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменение направления кривой на противоположное \en Change curve direction to the opposite one virtual double DistanceToPoint( const MbCartPoint & toP ) const; // \ru Расстояние до точки \en Distance to a point virtual bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const; // \ru Расстояние до точки, если оно меньше d \en Distance to a point if it is less than 'd' virtual MbeState Deformation( const MbRect &, const MbMatrix & ); // \ru Деформация \en Deformation @@ -188,7 +188,7 @@ public : virtual double PointProjection( const MbCartPoint & ) const; // \ru Проекция точки на кривую \en Point projection on the curve virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Projection of a point onto the curve or its extension in the projection region + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Проекция точки на кривую или её продолжение в области поиска проекции \en Projection of a point onto the curve or its extension in the projection region // \ru Вычисление всех перпендикуляров к кривой из данной точки \en Calculation of all the perpendiculars to the curve from a given point virtual void PerpendicularPoint( const MbCartPoint & pnt, SArray & tFind ) const; virtual bool SmallestPerpendicular( const MbCartPoint & pnt, double & tProj ) const; // \ru Нахождение ближайшего перпендикуляра к кривой из данной точки \en Calculation of the closest perpendicular to the curve from the given point @@ -202,7 +202,7 @@ public : virtual bool GetMiddlePoint( MbCartPoint & ) const; // \ru Выдать среднюю точку кривой \en Get mid-point of a curve virtual bool GoThroughPoint( MbCartPoint & p0 ); // \ru Вычисление минимальной длины кривой между двумя точками на ней \en Calculate the minimal curve length between two points on it - virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = NULL ) const; + virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = c3d_null ) const; virtual bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const; // \ru Выдать характерную точку кривой если она ближе чем dmax \en Get control point of curve if it is closer than 'dmax' virtual bool GetWeightCentre( MbCartPoint & c ) const; // \ru Выдать центр тяжести кривой \en Get the center of gravity of the curve virtual bool GetCentre( MbCartPoint & c ) const; // \ru Выдать центр кривой \en Get center of curve @@ -227,7 +227,7 @@ public : virtual const MbCurve & GetBasisCurve() const; virtual MbCurve & SetBasisCurve(); - bool SetBasisCurve( const MbCurve &, const MbRect1D * tRange = NULL ); ///< \ru Заменить плоскую кривую \en Replace the planar curve + bool SetBasisCurve( const MbCurve &, const MbRect1D * tRange = c3d_null ); ///< \ru Заменить плоскую кривую \en Replace the planar curve double Tmin() const; ///< \ru Начальный параметр. \en Start parameter. double Tmax() const; ///< \ru Конечный параметр. \en End parameter. double Dt() const; ///< \ru Производная параметра кривой basisCurve по параметру. \en Derivative of parameter of 'basisCurve' curve by parameter. @@ -249,7 +249,7 @@ public : virtual void GetBasisPoints( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_reparam_curve3d.h b/C3d/Include/cur_reparam_curve3d.h index 412260d..042a5d0 100644 --- a/C3d/Include/cur_reparam_curve3d.h +++ b/C3d/Include/cur_reparam_curve3d.h @@ -75,13 +75,13 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Расстояние до точки \en Distance to a point virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -122,7 +122,7 @@ public : virtual MbCurve3D & SetBasisCurve(); virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Create a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve virtual double CalculateMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve @@ -148,7 +148,7 @@ public : virtual void GetPointsByEvenLengthDelta( size_t n, std::vector & pnts ) const; // \ru Выдать n точек кривой с равными интервалами по длине дуги \en Get n points of curve equally spaced by the arc length // \ru Ближайшая проекция точки на кривую \en The nearest projection of a point onto the curve - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Определение точек касания изоклины \en Determination of tangent points of isocline virtual void GetIsoclinal( const MbVector3D & nor, SArray & tIso ) const; /// \ru Найти все особые точки функции кривизны кривой. @@ -160,12 +160,12 @@ public : // \ru Касание кривой через точку с заданной производной \en Tangent of curve through point with the given derivative //virtual bool GoThroughPointWithDerive( double t, MbCartPoint3D & p0, MbVector3D & v0 ); - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve virtual size_t GetCount() const; virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Change a carrier - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether the curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether the curve is planar virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis ( MbAxis3D & ) const; // \ru Дать ось кривой \en Get axis of curve @@ -188,9 +188,9 @@ public : virtual void SubstrateToCurve( double & ) const; // \ru Преобразовать параметр подложки в параметр кривой \en Transform a substrate parameter to the curve parameter virtual void CurveToSubstrate( double & ) const; // \ru Преобразовать параметр кривой в параметр подложки \en Transform a curve parameter to the substrate parameter // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if the curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы) \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after using ) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; @@ -198,7 +198,7 @@ public : virtual bool IsShift( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const; virtual bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_silhouette_curve.h b/C3d/Include/cur_silhouette_curve.h index fff5ad0..ee87c17 100644 --- a/C3d/Include/cur_silhouette_curve.h +++ b/C3d/Include/cur_silhouette_curve.h @@ -77,7 +77,7 @@ public : const MbMatrix3D & m, bool p ); /// \ru Конструктор по поверхности, двумерной кривой, типу кривой, вектору взгляда и флагу перспективы. \en Constructor by surface, two-dimensional curve, type of curve, vector of view and flag of perspective. MbSilhouetteCurve( const MbSurface & surf, const MbCurve & crv, MbeCurveBuildType _species, - const MbVector3D & e, bool p, const MbAxis3D * axis = NULL ); + const MbVector3D & e, bool p, const MbAxis3D * axis = c3d_null ); protected: /// \ru Конструктор копирования. \en Copy-constructor. MbSilhouetteCurve( const MbSilhouetteCurve &, MbRegDuplicate * ); @@ -92,13 +92,13 @@ public: // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get element type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, являются ли объекты одинаковыми. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -125,19 +125,19 @@ public: // \ru Вычислить габарит кривой. \en Calculate bounding box of a curve. virtual void CalculateGabarit( MbCube & ) const; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar. - virtual bool IsPlanar() const; + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if the curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using ). - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after use). virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; // \ru Создать усеченную кривую. \en Create a trimmed curve virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Дать плоскую проекцию кривой(локальная система координат, шаг, параметрическая область). \en Get the planar projection of a curve (local coordinate system, step, parametric region). - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; virtual double GetMetricLength() const; // \ru Метрическая длина кривой \en Metric length of a curve virtual double GetLengthEvaluation() const; // \ru Оценить метрическую длину кривой. \en Estimate the metric length of a curve. @@ -145,16 +145,16 @@ public: virtual double GetParamToUnit() const; // \ru Дать приращение параметра, осреднённо соответствующее единичной длине в пространстве. \en Get parameter increment which averagingly corresponds to the unit length in space. virtual double GetParamToUnit( double t ) const; // \ru Дать приращение параметра, соответствующее единичной длине в пространстве. \en Get parameter increment which corresponds to the unit length in space. - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление. \en Change the direction. + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление. \en Change the direction. virtual MbeCurveBuildType GetBuildType() const; // \ru Дать тип кривой. \en Get type of curve. virtual bool InsertPoint( double & t ); // \ru Вставить точку и выдать её параметр. \en Insert point and get its parameter. virtual bool IsSimilarToCurve( const MbCurve3D & curve, double precision = METRIC_PRECISION ) const; // \ru Определить, подобные ли кривые для объединения (слива). \en Determine whether the curves for union (joining) are similar. /// \ru Определить, существует ли точное пространственное представление линии очерка. \en Determine whether the exact spatial representation of isocline curve exists. - bool IsExactSpaceCurve() const { return (approxExact && approxCurve != NULL); } + bool IsExactSpaceCurve() const { return (approxExact && approxCurve != c3d_null); } /// \ru Получить указатель на кривую точного пространственное представление линии очерка. (Может и не быть). \en Get a pointer to the curve of exact spatial representation of isocline curve. (Can be absent). - const MbCurve3D * GetExactSpaceCurve() const { return approxExact ? approxCurve : NULL; } + const MbCurve3D * GetExactSpaceCurve() const { return approxExact ? approxCurve : c3d_null; } /// \ru Дать пространственную копию линии очерка. \en Construct a new spatial copy of isocline curve. const MbCurve3D * GetApproxCurve() const { return approxCurve; } diff --git a/C3d/Include/cur_spiral.h b/C3d/Include/cur_spiral.h index bca6c0d..e605fa4 100644 --- a/C3d/Include/cur_spiral.h +++ b/C3d/Include/cur_spiral.h @@ -95,12 +95,12 @@ public : virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента \en Type of element virtual MbeSpaceType Type() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб \en Add your own bounding box into the cube virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -125,7 +125,7 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const = 0; - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; // \ru Изменить направление \en Change direction virtual double GetMetricLength() const; // \ru Выдать метрическую длину ограниченной кривой \en Get metric length of bounded curve virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Estimation of metric length of the curve @@ -140,7 +140,7 @@ public : double GetSpiralPeriod() const; // \ru Вернуть период \en Get period // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if the curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Является ли объект смещением \en Whether the object is a shift virtual bool IsShift( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const; diff --git a/C3d/Include/cur_surface_curve.h b/C3d/Include/cur_surface_curve.h index 6c3fba6..7256023 100644 --- a/C3d/Include/cur_surface_curve.h +++ b/C3d/Include/cur_surface_curve.h @@ -61,8 +61,8 @@ class MbCurveIntoNurbsInfo; // --- class MATH_CLASS MbSurfaceCurve : public MbCurve3D { protected : - MbCurve * curve; ///< \ru Плоская кривая в uv-пространстве (всегда не NULL). \en Planar curve in uv-space (always not NULL). - MbSurface * surface; ///< \ru Указатель на поверхность (всегда не NULL). \en Pointer to the surface (always not NULL). + MbCurve * curve; ///< \ru Плоская кривая в uv-пространстве (всегда не c3d_null). \en Planar curve in uv-space (always not c3d_null). + MbSurface * surface; ///< \ru Указатель на поверхность (всегда не c3d_null). \en Pointer to the surface (always not c3d_null). bool closed; ///< \ru Флаг замкнутости поверхностной кривой. \en An attribute of closedness of surface of curve. /** \brief \ru Вспомогательные данные. @@ -105,7 +105,7 @@ protected : public : /// \ru Конструктор кривой на поверхности. \en Constructor of curve on surface. - MbSurfaceCurve( const MbSurface &, const MbCurve &, bool sameCurve, MbRegDuplicate * iReg = NULL ); + MbSurfaceCurve( const MbSurface &, const MbCurve &, bool sameCurve, MbRegDuplicate * iReg = c3d_null ); /// \ru Конструктор отрезка прямой на поверхности. \en Constructor of a line segment on surface. MbSurfaceCurve( const MbSurface &, const MbCartPoint & p0, const MbCartPoint & p1, MbePlaneType type = pt_Curve ); /// \ru Конструктор граничной кривой поверхности. \en Constructor of boundary curve of surface. @@ -131,15 +131,15 @@ public: virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get element type. virtual MbeSpaceType Type() const; // \ru Дать тип элемента. \en Get element type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. /// \ru Копия кривой с той же поверхностью. \en Copy of curve with the same surface. MbSurfaceCurve & CurvesDuplicate() const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, являются ли объекты одинаковыми. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавить свой габарит в куб. \en Add your own bounding box into a cube. virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -180,16 +180,16 @@ public: virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создать усеченную кривую. \en Create a trimmed curve // \ru Вычислить ближайшую проекцию точки на кривую. \en Calculate the nearest projection of a point onto the curve. - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление. \en Change the direction. + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление. \en Change the direction. virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. void SetTesselation( const MbContourOnSurface & contour, size_t indSegment ); // \ru Установить разбиение из контура. \en Set tessellation from contour. virtual double MetricStep ( double t, double length ) const; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой. \en Get a planar projection of a curve. /// \ru Вычислить плоскую проекцию кривой в частных случаях. \en Calculate planar projection of a curve in special cases. MbCurve * GetParticularMap( const MbMatrix3D & into, MbRect1D * pRgn, VERSION version ) const; @@ -197,7 +197,7 @@ public: virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Определить, является ли линия прямолинейной. \en Determine whether the line is straight. virtual void ChangeCarrier ( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменить носитель. \en Change the carrier. virtual bool ChangeCarrierBorne( const MbSpaceItem &, MbSpaceItem &, const MbMatrix & matr ); // \ru Изменить носимые элементы. \en Change a carrier elements. - virtual bool IsPlanar() const; // \ru Определить, является ли кривая плоской. Прямолинейные кривые являются плоскими, но без определённой ЛСК. \en Determine whether the curve is planar. Straight lines is planar but without certain placement. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Определить, является ли кривая плоской. Прямолинейные кривые являются плоскими, но без определённой ЛСК. \en Determine whether the curve is planar. Straight lines is planar but without certain placement. virtual bool IsSmoothConnected( double angleEps ) const; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth. virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой. \en Calculate bounding box of a curve. virtual double GetMetricLength() const; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. @@ -210,11 +210,11 @@ public: // \ru Вычислить ближайшую точку кривой к плейсменту. \en Calculate the curve point nearest to a placement. virtual double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const; // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using ). - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after use). virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if the curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать тип кривой. \en Get type of curve. virtual MbeCurveBuildType GetBuildType() const; @@ -242,7 +242,7 @@ public: /// \en Get the boundaries of the curve sections that are described by one analytical function. \~ virtual void GetAnalyticalFunctionsBounds( std::vector & params ) const; - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index 0899832..96cd261 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -114,12 +114,33 @@ namespace c3d // namespace C3D // --- class MATH_CLASS MbSurfaceIntersectionCurve : public MbCurve3D { private : + + //------------------------------------------------------------------------------ + /** \brief \ru Кэш для пространственной аппроксимационной кривой. + \en Cache for the spatial approximating curve. \~ + \details \ru Кэш служит для потокобезопасности операций с аппроксимационной кривой. + \en The cache is used for thread-safety of operations with the approximating curve. \n \~ + */ + // --- + struct SpaceCurveAuxiliaryData : public AuxiliaryData + { + MbCurve3D * spaceCurve; ///< \ru Пространственная аппроксимационная кривая. \en The spatial approximating curve. \~ + SpaceCurveAuxiliaryData() : spaceCurve( c3d_null ) {} + SpaceCurveAuxiliaryData( const SpaceCurveAuxiliaryData & c ) : spaceCurve( c3d_null ) { + if ( c.spaceCurve != c3d_null ) { + spaceCurve = static_cast( &c.spaceCurve->Duplicate() ); + spaceCurve->AddRef(); + } + } + ~SpaceCurveAuxiliaryData() { ::ReleaseItem( spaceCurve ); } + }; + mutable CacheManager spaceCurveCache; ///< \ru Кэш пространственной аппроксимационной кривой. \en Cache of a spatial approximating curve. \~ + MbSurfaceCurve curveOne; ///< \ru Кривая на первой поверхности. \en Curve on the first surface. MbSurfaceCurve curveTwo; ///< \ru Кривая на второй поверхности. \en Curve on the second surface. MbeCurveBuildType buildType; ///< \ru Тип кривой по построению. \en A curve type by construction. mutable MbeCurveGlueType glueType; ///< \ru Тип кривой по топологии. \en A curve type by topology. - mutable MbCurve3D * spaceCurve; ///< \ru Пространственная аппроксимационная кривая. \en The spatial approximating curve. \~ mutable double tolerance; ///< \ru Погрешность построения кривой. \en The tolerance of curve construction. \~ mutable MbCube cube; ///< \ru Габаритный куб кривой. \en Bounding box of a curve. \~ mutable double metricLength; ///< \ru Метрическая длина кривой. \en Metric length of a curve. \~ @@ -146,7 +167,7 @@ private : MbIntersectionCurveAuxiliaryData(); MbIntersectionCurveAuxiliaryData( const MbIntersectionCurveAuxiliaryData & ); - virtual ~MbIntersectionCurveAuxiliaryData(); + virtual ~MbIntersectionCurveAuxiliaryData() {} void Init(); void Init( const MbIntersectionCurveAuxiliaryData & ); @@ -180,7 +201,7 @@ public : MbSurfaceIntersectionCurve( const MbSurface & surf1, const MbCurve & curve1, const MbSurface & surf2, const MbCurve & curve2, MbeCurveBuildType buildType, bool sameOne, bool sameTwo, - MbRegDuplicate * iReg = NULL ); + MbRegDuplicate * iReg = c3d_null ); /** \brief \ru Конструктор по поверхностям и двумерным точкам. \en Constructor by surfaces and two-dimensional points. \~ \details \ru Конструктор кривой пересечения по поверхностям и двумерным точкам. \n @@ -284,15 +305,15 @@ public: \{ */ virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get element type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. /// \ru Сделать копию кривой на тех же поверхностях. \en Create a copy of a curve on the same surfaces. - MbSurfaceIntersectionCurve & CurvesDuplicate() const; + MbSurfaceIntersectionCurve & CurvesDuplicate() const { return *new MbSurfaceIntersectionCurve( this ); } virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, равны ли объекты. \en Determine whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавить свой габарит в куб. \en Add your own bounding box into a cube. virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. @@ -330,7 +351,7 @@ public: // \ru Функции приближённого быстрого вычисления точки и производных на кривой. \en Functions of approximate fast calculation of point and derivatives on the curve. virtual void FastApproxExplore( double & t, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление. \en Change the direction. + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление. \en Change the direction. // \ru Функции движения по кривой. \en Functions of moving along the curve. // \ru Вычислить шаг параметра по величине прогиба кривой. \en Calculate step of parameter by value of sag of curve. @@ -377,8 +398,8 @@ public: virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D &polygon ) const; // \ru Рассчитать полигон. \en Calculate a polygon. // \ru Построить плоскую проекцию некоторой части пространственной кривой. \en Construct a planar projection of a piece of a space curve. - virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать проекцию ребра на плоскость. \en Get the edge projection onto plane. virtual MbCurve * GetProjection( const MbPlacement3D & place, VERSION version ) const; @@ -388,14 +409,14 @@ public: virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Определить, является ли линия прямолинейной. \en Determine whether the line is straight. virtual void ChangeCarrier ( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменить носитель. \en Change the carrier. virtual bool ChangeCarrierBorne( const MbSpaceItem & item, MbSpaceItem & init, const MbMatrix & matr ); // \ru Изменение носимые элементы. \en Change a carrier elements. - virtual bool IsPlanar() const; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Определить, является ли кривая плоской. \en Determine whether the curve is planar. virtual bool IsSmoothConnected( double angleEps ) const; // \ru Определить, являются ли стыки контура\кривой гладкими. \en Determine whether the joints of contour\curve are smooth. virtual double DistanceToPlace( const MbPlacement3D & place, double & t0, double & angle ) const; // \ru Вычислить ближайшую точку кривой к плейсменту. \en Calculate the curve point nearest to a placement. // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using ). - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place3d, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Заполнить плейсмент, если кривая плоская. \en Fill the placement if the curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after use). virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; @@ -645,7 +666,7 @@ public: /// \ru Дать точную пространственную копию или себя. \en Get exact spatial copy or itself. const MbCurve3D & GetExactCurve( bool saveParams = true ) const; /// \ru Удалить пространственную кривую. \en Remove a spatial curve. - void ReleaseSpaceCurve(); + void ReleaseSpaceCurve() const; /// \ru Разрезать кривую пересечения на три части по заданным параметрам и вернуть одну из крайних частей в зависимости от sense. \en Cutaway an intersection curve into three pieces by given parameters and return one of end pieces depending on 'sense'. MbSurfaceIntersectionCurve * BreakWithGap( double tt, double ttP, bool sense ); // \ru Используется в конвертерах. \en Used in converters. @@ -682,7 +703,7 @@ private: // \ru Вычислить толерантность кривой. \en Calculate tolerance of the curve. void CalculateTolerance() const; // \ru Создать пространственную кривую по проекционной кривой. \en Create a spatial curve from a projection curve. - void TryProjection() const; + bool TryProjection() const; // \ru Создать явную пространственную кривую. \en Create an explicit spatial curve. bool CreateSpaceCurve( VERSION version = Math::DefaultMathVersion() ) const; // \ru Создать аппроксимационную кривую по кривой пересечения \en Create an approximating curve by an intersection curve @@ -742,9 +763,14 @@ inline bool MbSurfaceIntersectionCurve::CopyReadyMutable( const MbSurfaceInterse cube = s.cube; changed = true; } - if ( spaceCurve == NULL && s.spaceCurve != NULL ) { - spaceCurve = (MbCurve3D *)&s.spaceCurve->Duplicate(); - spaceCurve->AddRef(); + MbCurve3D * sspaceCurve = s.spaceCurveCache()->spaceCurve; + if ( sspaceCurve != c3d_null && spaceCurveCache.LongTerm()->spaceCurve == c3d_null ) { + { + ScopedLock cacheLock( spaceCurveCache.GetLock() ); + spaceCurveCache.LongTerm()->spaceCurve = (MbCurve3D *)&sspaceCurve->Duplicate(); + } + spaceCurveCache.LongTerm()->spaceCurve->AddRef(); + spaceCurveCache.Reset(); changed = true; } @@ -809,5 +835,66 @@ inline void MbSurfaceIntersectionCurve::GetFirstDer( double & t, MbVector3D & fd fd.Set( vect1, 0.5, vect2, 0.5 ); } +//------------------------------------------------------------------------------ +// \ru Конструктор вспомогательных данных. \en Auxiliary data constructor. +// --- +inline MbSurfaceIntersectionCurve::MbIntersectionCurveAuxiliaryData::MbIntersectionCurveAuxiliaryData() + : AuxiliaryData() + , t( UNDEFINED_DBL ) + , res( false ) + , uv1( UNDEFINED_DBL, 0 ) + , uv2( UNDEFINED_DBL, 0 ) + , pnt( UNDEFINED_DBL, 0, 0 ) + , fder( UNDEFINED_DBL, 0, 0 ) + , sder( UNDEFINED_DBL, 0, 0 ) + , tder( UNDEFINED_DBL, 0, 0 ) +{ +} + +//------------------------------------------------------------------------------ +// \ru Конструктор копирования вспомогательных данных. \en Copy constructor of auxiliary data. +// --- +inline MbSurfaceIntersectionCurve::MbIntersectionCurveAuxiliaryData::MbIntersectionCurveAuxiliaryData( const MbIntersectionCurveAuxiliaryData & init ) + : AuxiliaryData() + , t( init.t ) + , res( init.res ) + , uv1( init.uv1 ) + , uv2( init.uv2 ) + , pnt( init.pnt ) + , fder( init.fder ) + , sder( init.sder ) + , tder( init.tder ) +{ +} + +//------------------------------------------------------------------------------ +// \ru Инициализация вспомогательных данных. \en Initialization of auxiliary data. +// --- +inline void MbSurfaceIntersectionCurve::MbIntersectionCurveAuxiliaryData::Init() +{ + t = UNDEFINED_DBL; + res = false; + uv1.Init( UNDEFINED_DBL, 0 ); + uv2.Init( UNDEFINED_DBL, 0 ); + pnt.Init( UNDEFINED_DBL, 0, 0 ); + fder.Init( UNDEFINED_DBL, 0, 0 ); + sder.Init( UNDEFINED_DBL, 0, 0 ); + tder.Init( UNDEFINED_DBL, 0, 0 ); +} + +//------------------------------------------------------------------------------ +// \ru Инициализация вспомогательных данных. \en Initialization of auxiliary data. +// --- +inline void MbSurfaceIntersectionCurve::MbIntersectionCurveAuxiliaryData::Init( const MbIntersectionCurveAuxiliaryData & init ) +{ + t = init.t; + res = init.res; + uv1.Init( init.uv1 ); + uv2.Init( init.uv2 ); + pnt.Init( init.pnt ); + fder.Init( init.fder ); + sder.Init( init.sder ); + tder.Init( init.tder ); +} #endif // __CUR_SURFACE_INTERSECTION_H diff --git a/C3d/Include/cur_trimmed_curve.h b/C3d/Include/cur_trimmed_curve.h index e981bf8..c9921b2 100644 --- a/C3d/Include/cur_trimmed_curve.h +++ b/C3d/Include/cur_trimmed_curve.h @@ -42,7 +42,7 @@ class MbRegTransform; class MATH_CLASS MbTrimmedCurve : public MbCurve { // \ru Усечение может быть на продолжении кривой (внесенные изменения помечены как E13865) \en Trimming can be on curve extension (made changes are marked as E13865) protected : - MbCurve * basisCurve; ///< \ru Базовая кривая (не может быть NULL). \en Base curve (can't be NULL). + MbCurve * basisCurve; ///< \ru Базовая кривая (не может быть c3d_null). \en Base curve (can't be c3d_null). double trim1; ///< \ru Параметры начальной точки \en Parameters of start point double trim2; ///< \ru Параметры конечной точки \en Parameters of end point int sense; ///< \ru Флаг совпадения направления с направлением базовой кривой (sense==0 не допускается) \en Flag of coincidence of the direction with the direction of the base curve (sense==0 isn't allowed) @@ -75,10 +75,10 @@ public : virtual bool IsSimilar( const MbPlaneItem & ) const; // \ru Являются ли элементы подобными \en Whether the elements are similar virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать элементы равными \en Make the elements equal virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether curve 'curve' is a duplicate of the current curve. - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Поворот \en Rotation - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Поворот \en Rotation + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual void AddYourGabaritTo( MbRect & ) const; // \ru Добавь свой габарит в прямой прям-к \en Add your own gabarit into the given bounding rectangle virtual void CalculateGabarit( MbRect & ) const; // \ru Определить габаритный прямоугольник кривой. \en Detect the bounding box of a curve. virtual bool IsInRectForDeform( const MbRect & r ) const; // \ru Виден ли объект в заданном прямоугольнике для деформации \en Whether the object is visible in the given rectangle for deformation @@ -189,7 +189,7 @@ public : void SetTrim1( double t ) { trim1 = t; InitParam( trim1, trim2, sense ); } void SetTrim2( double t ) { trim2 = t; InitParam( trim1, trim2, sense ); } - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление кривой \en Change direction of a curve + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление кривой \en Change direction of a curve virtual bool GetAxisPoint( MbCartPoint & p ) const; // \ru Точка для построения оси \en Point for the axis construction virtual bool IsSimilarToCurve( const MbCurve & curve, double precision = PARAM_PRECISION ) const; // \ru Подобные ли кривые для объединения (слива) \en Whether the curves for union (joining) are similar virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. diff --git a/C3d/Include/cur_trimmed_curve3d.h b/C3d/Include/cur_trimmed_curve3d.h index a8dcdfd..651c99a 100644 --- a/C3d/Include/cur_trimmed_curve3d.h +++ b/C3d/Include/cur_trimmed_curve3d.h @@ -59,13 +59,13 @@ public : // \ru Общие функции математического объекта \en Common functions of the mathematical object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией \en Whether the object is a copy virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -104,18 +104,18 @@ public : virtual MbCurve3D & SetBasisCurve(); virtual MbCurve3D * Trimmed( double t1, double t2, int sense ) const; // \ru Создание усеченной кривой \en Create a trimmed curve - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Curvature ( double ) const; // \ru Кривизна усеченной кривой \en Curvature of a trimmed curve virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. virtual double MetricStep ( double t, double length ) const; // \ru Вычисление шага параметра по длине. \en Calculation of parameter step by the given length. virtual bool IsDegenerate( double eps = METRIC_PRECISION ) const; // \ru Проверка вырожденности кривой \en Check for curve degeneracy - virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve + virtual MbCurve * GetMap( const MbMatrix3D &, MbRect1D * pRgn = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; // \ru Дать плоскую проекцию кривой \en Get a planar projection of a curve virtual size_t GetCount() const; virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Change a carrier - virtual bool IsPlanar () const; // \ru Является ли кривая плоской \en Whether the curve is planar + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; // \ru Является ли кривая плоской \en Whether the curve is planar virtual bool IsStraight( bool ignoreParams = false ) const; // \ru Является ли линия прямолинейной \en Whether the line is straight virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool GetCircleAxis ( MbAxis3D & ) const; // \ru Дать ось кривой \en Get axis of curve @@ -137,7 +137,7 @@ public : bool IsBaseParamOn( double t ) const; // \ru Находится ли параметр базовой кривой в диапазоне усеченной кривой \en Whether the parameter of base curve is in range of a trimmed curve // \ru Ближайшая проекция точки на кривую. \en The nearest projection of a point onto the curve. - virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Ближайшая проекция точки на кривую \en The nearest projection of a point onto the curve + virtual bool NearPointProjection( const MbCartPoint3D &, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Ближайшая проекция точки на кривую \en The nearest projection of a point onto the curve /// \ru Найти все особые точки функции кривизны кривой. /// \en Find all the special points of the curvature function of the curve. virtual void GetCurvatureSpecialPoints( std::vector & points ) const; @@ -153,9 +153,9 @@ public : virtual void CurveToSubstrate( double & ) const; // \ru Преобразовать параметр кривой в параметр подложки \en Transform a curve parameter to the substrate parameter // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if the curve is planar - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую) \en Get the planar curve and placement if the spatial curve is planar (call DeleteItem for two-dimensional curve after using) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; // \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы) \en Get a surface curve if a spatial curve is on a surface (call DeleteItem for arguments after using ) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; diff --git a/C3d/Include/curve.h b/C3d/Include/curve.h index 7c6659f..9203c64 100644 --- a/C3d/Include/curve.h +++ b/C3d/Include/curve.h @@ -61,15 +61,19 @@ typedef std::vector ConstPlaneCurvesSPtrVector; для плоского моделирования,\n для описания области определения параметров поверхности,\n для построения кривых на поверхностях,\n - для построения кривых пересечения поверхностей. + для построения кривых пересечения поверхностей.\n + Нормаль к кривой - это перпендикуляр к касательной. \n + Для вычисления направления нормали с учётом кривизны нужно умножить нормаль на знак кривизны. \en A curve in two-dimensional space is a vector function of a scalar parameter, given on a finite one-dimensional space. A curve is continuous mapping of some piece of numeric axis to two-dimensional space.\n - Two-dimensional curve is used:\n - for planar modeling,\n - for description of surface parameters domain,\n - for construction of curves on surfaces,\n - for constructing of surfaces intersection curves. \~ + Two-dimensional curve is used: \n + for planar modeling, \n + for description of surface parameters domain, \n + for construction of curves on surfaces, \n + for constructing of surfaces intersection curves. \n + Normal vector to a curve is perpendicular to tangent. \n + To calculate the direction of normal according curvature, multiply this normal vector by the curvature sign. \~ \ingroup Curves_2D */ // --- @@ -94,10 +98,10 @@ public : virtual MbePlaneType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbePlaneType Type() const; // \ru Групповой тип элемента. \en Group element type. virtual MbePlaneType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Поворот вокруг точки на угол. \en Rotation at angle around a point. + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix &, MbRegTransform * ireg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; // \ru Поворот вокруг точки на угол. \en Rotation at angle around a point. virtual bool SetEqual( const MbPlaneItem & ) = 0; // \ru Сделать объект равным данному. \en Make an object equal to a given one. virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Является ли кривая curve копией данной кривой? \en Is a curve a copy of a given curve? virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. @@ -331,9 +335,9 @@ public : \param[out] fir - \ru Производная. \en Derivative with respect to t. \~ \param[out] sec - \ru Вторая производная по t, если не ноль. - \en Second derivative with respect to t, if not NULL. \~ + \en Second derivative with respect to t, if not c3d_null. \~ \param[out] thir - \ru Третья производная по t, если не ноль. - \en Third derivative with respect to t, if not NULL. \~ + \en Third derivative with respect to t, if not c3d_null. \~ \ingroup Curves_3D */ virtual void Explore( double & t, bool ext, @@ -472,7 +476,7 @@ public : /// \ru Сбросить текущее значение параметра. \en Reset the current value of parameter. virtual void ResetTCalc() const; /// \ru Изменить направления кривой на противоположное. \en Set the opposite direction of curve. - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; /// \ru Построить эквидистантную кривую, смещённую на заданное расстояние. \en Construct the equidistant curve which is shifted by the given value. virtual MbCurve * Offset( double rad ) const; @@ -545,10 +549,10 @@ public : \en A constructed NURBS-curve. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ - MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo * nInfo = NULL ) const; + MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo * nInfo = c3d_null ) const; /** \brief \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. \~ @@ -570,8 +574,8 @@ public : 'sense' > 0 - direction coincide. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & nInfo ) const = 0; @@ -585,8 +589,8 @@ public : If the flag of accurate approximation is not set in parameters then NURBS without multiple knots is constructed. \~ \param[in] tParameters - \ru Параметры построения NURBS копии кривой. \en Parameters for the construction of a NURBS copy of the curve. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ virtual MbCurve * NurbsCurve( const MbNurbsParameters & tParameters ) const; @@ -703,10 +707,10 @@ public : \en End parameter of trimming. \~ \param[in, out] part2 - \ru Может заполниться результатом усечения, если не смогли изменить саму кривую. В этом случае возвращаемый результат dp_Degenerated. - Иначе = NULL. + Иначе = c3d_null. \en This may be filled by a result of trimming if the curve was not changed. In this case the returned value is dp_Degenerated. - Otherwise NULL is returned. \~ + Otherwise c3d_null is returned. \~ \result \ru Состояние кривой после модификации:\n dp_Degenerated - кривая выродилась, может быть три варианта: кривая не была изменена, так как в результате преобразования она бы выродилась, @@ -798,7 +802,7 @@ public : \en True - if there is found a projection which satisfies to all input conditions. \~ */ virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, - double & t, bool ext, MbRect1D * tRange = NULL ) const; + double & t, bool ext, MbRect1D * tRange = c3d_null ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ @@ -1046,7 +1050,7 @@ public : \en A length of a curve between points. \~ */ virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, - MbCartPoint * pc = NULL ) const; + MbCartPoint * pc = c3d_null ) const; /// \ru Вычислить центр тяжести кривой. \en Calculate the center of gravity of a curve. virtual bool GetWeightCentre ( MbCartPoint & ) const; @@ -1263,7 +1267,7 @@ public : \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. @@ -1431,7 +1435,7 @@ inline void MbCurve::Normal( double & t, MbVector & v ) const //------------------------------------------------------------------------------ // \ru Вычислить нормальный вектор. \en Calculate the normal vector. // --- -inline void MbCurve::Normal( double &t, MbDirection &norm ) const { +inline void MbCurve::Normal( double & t, MbDirection & norm ) const { Tangent( t, norm ); norm.Perpendicular(); } diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index 60f3190..e4266a0 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -69,12 +69,18 @@ typedef std::pair ConstSpaceCurvesSetRet; принимающего значения на конечной одномерной области. Координаты точки кривой являются однозначными непрерывными функциями параметра кривой. Кривая представляет собой непрерывное отображение некоторого участка числовой оси в трёхмерное пространство.\n - Кривые используются для построения поверхностей. + Кривые используются для построения поверхностей. \n + Нормаль к кривой вычисляется с учетом кривизны (второй производной). \n + Для прямолинейных кривых это вектор нулевой за исключением плоских прямолинейных кривых, + где он перпендикулярен нормали плоскости этой кривой. \en A curve in space is a vector function of a scalar parameter, which is set on a finite one-dimensional space. Coordinates of the point are single-valued continuous functions of curve parameter. A curve is continuous mapping from a piece of numeric axis to the three-dimensional space.\n - Curves are used to construct surfaces. \~ + Curves are used to construct surfaces. \n + Normal to a curve is calculated taking into account curvature (second derivative). \n + For rectilinear curves it's a zero vector except for flat rectilinear curves, + where it's perpendicular to a normal of curve plane. \~ \ingroup Curves_3D */ // --- @@ -101,14 +107,14 @@ public : virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbeSpaceType Type() const; // \ru Групповой тип элемента. \en Group element type. virtual MbeSpaceType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. /// \ru Сделать копию с измененным направлением. \en Create a copy with changed direction. virtual MbCurve3D & InverseDuplicate() const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить габарит кривой в куб. \en Add a bounding box of a curve to a cube. /// \ru Перевести все временные (mutable) данные объекта в неопределённое (исходное) состояние. \en Translate all the time (mutable) data objects in an inconsistent (initial) state. @@ -256,9 +262,9 @@ public : \param[out] fir - \ru Производная. \en Derivative with respect to t. \~ \param[out] sec - \ru Вторая производная по t, если не ноль. - \en Second derivative with respect to t, if not NULL. \~ + \en Second derivative with respect to t, if not c3d_null. \~ \param[out] thir - \ru Третья производная по t, если не ноль. - \en Third derivative with respect to t, if not NULL. \~ + \en Third derivative with respect to t, if not c3d_null. \~ \ingroup Curves_3D */ virtual void Explore( double & t, bool ext, @@ -267,9 +273,9 @@ public : /** \brief \ru Вычислить точку и производные на кривой. \en Calculate point and derivatives on the curve. \~ \details \ru Функция перегружена у MbSurfaceIntersectionCurve и MbSilhouetteCurve для приближённого быстрого вычисления точки и производных. - В остальных поверхностях эквивалентна функции Explore(t,false,pnt,fir,sec,NULL). + В остальных поверхностях эквивалентна функции Explore(t,false,pnt,fir,sec,c3d_null). \en The function is overloaded in MbSurfaceIntersectionCurve and MbSilhouetteCurve for the fast approximated calculation of a point and derivatives. - In other surfaces it is equivalent to the function Explore(t,false,pnt,fir,sec,NULL). \~ + In other surfaces it is equivalent to the function Explore(t,false,pnt,fir,sec,c3d_null). \~ \param[in] t - \ru Параметр. \en Parameter. \~ \param[out] pnt - \ru Вычисленная точка. @@ -277,7 +283,7 @@ public : \param[out] fir - \ru Производная. \en Derivative with respect to t. \~ \param[out] sec - \ru Вторая производная по t, если не ноль. - \en Second derivative with respect to t, if not NULL. \~ + \en Second derivative with respect to t, if not c3d_null. \~ \ingroup Curves_3D */ virtual void FastApproxExplore( double & t, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec ) const; @@ -362,7 +368,7 @@ public : /// \ru Сбросить текущее значение параметра. \en Reset the current value of parameter. virtual void ResetTCalc() const; /// \ru Изменить направление кривой. \en Change direction of a curve. - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; /// \ru Вернуть базовую кривую, если есть, или себя \en Returns the base curve if exists or itself virtual const MbCurve3D & GetBasisCurve() const; /// \ru Вернуть базовую кривую, если есть, или себя \en Returns the base curve if exists or itself @@ -382,10 +388,10 @@ public : The number of knots for NURBS is defined depending on the curve. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ - MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo * nInfo = NULL ) const; + MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo * nInfo = c3d_null ) const; /** \brief \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. \~ @@ -405,8 +411,8 @@ public : 'sense' > 0 - direction coincide. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & nInfo ) const; @@ -420,8 +426,8 @@ public : If the flag of accurate approximation is not set in parameters then NURBS without multiple knots is constructed. \~ \param[in] tParameters - \ru Параметры построения NURBS копии кривой. \en Parameters for the construction of a NURBS copy of the curve. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ \ingroup Curves_3D */ virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & tParameters ) const; @@ -434,8 +440,8 @@ public : \en Parameters for the construction of a NURBS copy of the curve. \~ \param[in] epsilon - \ru Точность аппроксимации. \en The tolerance of approximation. \~ - \result \ru Построенная NURBS кривая или NULL при неуспешном построении. - \en The constructed NURBS curve or NULL in a case of failure. \~ + \result \ru Построенная NURBS кривая или c3d_null при неуспешном построении. + \en The constructed NURBS curve or c3d_null in a case of failure. \~ */ virtual size_t NurbsCurveMinPoints( const MbNurbsParameters & tParameters, double epsilon = c3d::METRIC_DELTA ) const; @@ -552,7 +558,7 @@ public : /// \ru Является ли линия прямолинейной? \en Whether the line is straight? virtual bool IsStraight( bool ignoreParams = false ) const; /// \ru Является ли кривая плоской? \en Is a curve planar? - virtual bool IsPlanar () const; + virtual bool IsPlanar ( double accuracy = METRIC_EPSILON ) const; /// \ru Являются ли стыки контура/кривой гладкими? \en Are joints of contour/curve smooth? virtual bool IsSmoothConnected( double angleEps ) const; /// \ru Изменить носитель. Для поверхностных кривых. \en Change the carrier. For surface curves. @@ -588,19 +594,20 @@ public : Если кривая представляет собой контур, то узловые точки контура дублируются. \en Get an array of drawn points with a given sag. If the cure is a contour then knots of a contour are duplicated. \~ - \param[in] sag - \ru Максимальная величина прогиба. - \en Maximal value of sag. \~ - \param[in, out] poligon - \ru Полигон рассчитанных точек на кривой. + \param[in] stepData - \ru Данные для вычисления шага. + \en Data for step calculation. \~ + \param[in, out] polygon - \ru Полигон рассчитанных точек на кривой. \en A polygon of calculated points on a curve. \~ \ingroup Curves_3D */ - virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & poligon ) const; // \ru Рассчитать полигон. \en Calculate a polygon. - void CalculatePolygon( double sag, MbPolygon3D & poligon ) const; // The method deprecated. It will be removed at 2018. Use CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \~ + virtual void CalculatePolygon( const MbStepData & stepData, MbPolygon3D & polygon ) const; // \ru Рассчитать полигон. \en Calculate a polygon. + + DEPRECATE_DECLARE void CalculatePolygon( double, MbPolygon3D & ) const; // The method deprecated. It will be removed at 2018. Use CalculatePolygon( MbStepData(ist_SpaceStep,sag), poligon ); \~ /// \ru Выдать центр кривой. \en Give the curve center. - virtual void GetCentre ( MbCartPoint3D & c ) const; + virtual void GetCentre ( MbCartPoint3D & ) const; /// \ru Выдать центр тяжести кривой. \en Give the gravity center of a curve. - virtual void GetWeightCentre( MbCartPoint3D & wc ) const; + virtual void GetWeightCentre( MbCartPoint3D & ) const; // \ru Проекция точки на кривую (метод Ньютона). \en Point projection on a curve (the Newton method). /** \brief \ru Найти проекцию точки на кривую. @@ -644,7 +651,7 @@ public : \en True - if there is found a projection which satisfies to all input conditions. \~ \ingroup Curves_3D */ - virtual bool NearPointProjection ( const MbCartPoint3D &pnt, double & t, bool ext, MbRect1D * tRange = NULL ) const; + virtual bool NearPointProjection ( const MbCartPoint3D &pnt, double & t, bool ext, MbRect1D * tRange = c3d_null ) const; // \ru Изоклины кривой (метод Ньютона). \en Isoclines of a curve (Newton method). /** \brief \ru Найти изоклины кривой. @@ -716,17 +723,17 @@ public : \param[in] version - \ru Версия, по умолчанию - последняя. \en Version, last by default. \~ \param[in, out] coincParams - \ru Флаг совпадения параметризации исходной кривой и ее проекции \n - если coincParams != NULL, функция попытается сделать проекцию с совпадающей параметризацией \n + если coincParams != c3d_null, функция попытается сделать проекцию с совпадающей параметризацией \n если в результате *coincParams = true, у проекции параметризация совпадает с параметрицацией исходной кривой. \en A flag of coincidence between parameterization of initial curve and its projection \n - if coincParams != NULL then the function tries to create a projection with coincident parameterization \n + if coincParams != c3d_null then the function tries to create a projection with coincident parameterization \n if *coincParams = true then parameterization of projection coincides with parameterization of initial curve. \~ \return \ru Двумерная проекция кривой. \en Two-dimensional projection of a curve \~ \ingroup Curves_3D */ - virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = NULL, - VERSION version = Math::DefaultMathVersion(), bool * coincParams = NULL ) const; + virtual MbCurve * GetMap( const MbMatrix3D & into, MbRect1D * pRegion = c3d_null, + VERSION version = Math::DefaultMathVersion(), bool * coincParams = c3d_null ) const; /** \brief \ru Построить плоскую проекцию некоторой части пространственной кривой. \en Construct a planar projection of a piece of a space curve. \~ @@ -743,7 +750,7 @@ public : \ingroup Curves_3D */ virtual MbCurve * GetMapPsp( const MbMatrix3D & into, double zNear, - MbRect1D * pRegion = NULL ) const; + MbRect1D * pRegion = c3d_null ) const; /** \brief \ru Построить плоскую проекцию пространственной кривой на плоскость. \en Construct a planar projection of a space curve to a plane. \~ @@ -783,7 +790,7 @@ public : \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ - virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; + virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = c3d_null, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. @@ -975,11 +982,11 @@ public : virtual void CurveToSubstrate( double & ) const; /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlaneCurve( MbCurve *& curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, VERSION version = Math::DefaultMathVersion() ) const; + bool GetPlaneCurve( SPtr & curve2d, MbPlacement3D & place, bool saveParams, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) virtual bool GetSurfaceCurve( MbCurve *& curve2d, MbSurface *& surface, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) @@ -987,7 +994,7 @@ public : /// \ru Дать поверхностную кривую, если пространственная кривая поверхностная (после использования вызывать DeleteItem на аргументы). \en Get surface curve if the space curve is surface (after the using call DeleteItem for arguments) bool GetSurfaceCurve( SPtr & curve2d, SPtr & surface, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Заполнить плейсемент, если кривая плоская. \en Fill the placement if a curve is planar. - virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; + virtual bool GetPlacement( MbPlacement3D & place, PlanarCheckParams params = PlanarCheckParams() ) const; /// \ru Является ли объект смещением. \en Is the object is a shift? virtual bool IsShift( const MbSpaceItem &, MbVector3D &, bool & isSame, double accuracy = LENGTH_EPSILON ) const; /// \ru Подобные ли кривые для объединения (слива). \en Whether the curves to union (joining) are similar. @@ -1117,15 +1124,16 @@ MATH_FUNC (MbeNewtonResult) CurveCrossNewton( const MbCurve3D & curve1, bool ext \en Calculate polygon points of curve. \n \~ \param[in] curve - \ru Кривая. \en Curve. \~ - \param[in] sag - \ru Максимальная величина прогиба. - \en Maximal value of sag. \~ + \param[in] stepData - \ru Данные для вычисления шага. + \en Data for step calculation. \~ \param[out] paramPoints - \ru Массив параметров и точек. \en Array of parameters and points. \~ \ingroup Curves_3D */ // --- MATH_FUNC (void) CalculatePolygon( const MbCurve3D & curve, const MbStepData & stepData, std::vector< std::pair > & paramPoints ); -DEPRECATE_DECLARE MATH_FUNC (void) CalculatePolygon( const MbCurve3D & curve, double sag, std::vector< std::pair > & paramPoints ); // The method deprecated. It will be removed at 2018. Use ::CalculatePolygon( curve, MbStepData(ist_SpaceStep,sag), paramPoints ); \~ + +DEPRECATE_DECLARE MATH_FUNC (void) CalculatePolygon( const MbCurve3D &, double, std::vector< std::pair > & ); // The method deprecated. It will be removed at 2018. Use ::CalculatePolygon( curve, MbStepData(ist_SpaceStep,sag), paramPoints ); \~ #endif // __CURVE3D_H diff --git a/C3d/Include/dxf_converter.h b/C3d/Include/dxf_converter.h index 7f16a81..99f0093 100644 --- a/C3d/Include/dxf_converter.h +++ b/C3d/Include/dxf_converter.h @@ -1,463 +1,463 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru DXF - конвертер. - \en DXF - converter. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __DXF_CONVERTER_H -#define __DXF_CONVERTER_H - -#include -#include -#include -#include -#include - - -class IConvertorProperty3D; -class IProgressIndicator; -class ColorProperties; -class ItModelInstanceProperties; -class ItModelDocument; -class ItModelInstance; -class DXFConverter; -class DXFCompositeRef; -class MbGrid; - - -//------------------------------------------------------------------------------ -/** \brief \ru Уникальный (в пределах документа) идентификатор объекта. - \en Unique (in the document) object identifier. \~ - \ingroup DXF_Exchange -*/ -class CONV_CLASS DXFHandle { - -private: - int64 thisId; ///< \ru Уникальное 64-битное число, соответствующее модельному объекту. \en Unique 64-bit number corresponding to the model object. - -public: - DXFHandle ( ); - DXFHandle ( int64 & id ); - DXFHandle ( const unsigned char id[8] ); - ~DXFHandle(); - - const DXFHandle & operator = ( const DXFHandle & id ); - - bool IsDefined() const { return thisId != -1 ; } - - // \ru операторы сравнения \en compare operators - friend bool operator > ( const DXFHandle & left, const DXFHandle & right ); - friend bool operator == ( const DXFHandle & left, const DXFHandle & right ); -}; - - -//------------------------------------------------------------------------------ -/// \ru Сравнение thisId. \en Comparison of thisId. -//--- -inline -bool operator > ( const DXFHandle & left, const DXFHandle & right ) { - return left.thisId > right.thisId; -} - - -//------------------------------------------------------------------------------ -/// \ru Равенство thisId. \en Equality of thisId. -//--- -inline -bool operator ==( const DXFHandle & left, const DXFHandle & right ) { - return left.IsDefined() && right.IsDefined() && left.thisId == right.thisId; -} - - -/** - \addtogroup DXF_Exchange - \{ -*/ - - -//------------------------------------------------------------------------------ -// \ru Тело. \en A solid. -//--- -class CONV_CLASS DXFSolidBody { -private: - MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. - std::vector > solids; ///< \ru Тела. \en Solids. - std::vector< SPtr > faces; ///< \ru Грани. \en Faces. - -public: - DXFSolidBody( MbPlacement3D & placement ); - DXFSolidBody( const DXFSolidBody &); - ~DXFSolidBody(); - -public: - bool IsEmpty () const; - - bool IsSingle () const; - MbPlacement3D GetPlacement() const; - - void MakePlacementIdentical( const MbPlacement3D& ownComponentLocation = MbPlacement3D::global ); - void FillSolids ( std::vector > & solids ) const; - void Flush (); - void AddSolids ( const std::vector > & mSolids ); - void AddFaces ( const std::vector< SPtr > & mFaces ); - void SetPlacement ( const MbPlacement3D & place ); - - size_t GetSolidsCount() const { return solids.size(); } - void GetSolids ( std::vector > & mSolids ) const; - - size_t GetFacesCount () const { return faces.size(); } - void GetFaces ( std::vector< SPtr > & mFaces ) const; -private: - //DXFSolidBody ( const DXFSolidBody & ); // \ru не реализовано \en not implemented - DXFSolidBody & operator = ( const DXFSolidBody & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -// -// --- -inline -void DXFSolidBody::SetPlacement( const MbPlacement3D & place ) { - placement = place; -} - - -//------------------------------------------------------------------------------ -// \ru Поверхность. \en The surface. -//--- -class CONV_CLASS DXFSurfaceBody { -private: - MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. - std::vector< SRef > faces; ///< \ru Грани. \en Faces. - SPtr mesh; - -public: - DXFSurfaceBody(); - DXFSurfaceBody( MbPlacement3D & placement ); - ~DXFSurfaceBody(); - -public: - bool IsEmpty () const; - bool IsSingle () const; - MbPlacement3D GetPlacement() const; - - void Flush(); - void AddFace ( MbFace & face ); - void AddGrid ( MbGrid & grid ); - void AddFaces( const std::vector< SPtr > & mFaces ); - - size_t GetFacesCount() const { return faces.size(); } - -private: - void FillFaces( RPArray & faces ) const; - void GetFaces( std::vector< SPtr > & mFaces ) const; -public: - - SPtr GetMesh(); - - std::vector > GenerateItems( bool stitch ); - -private: - - - DXFSurfaceBody ( const DXFSurfaceBody & ); // \ru не реализовано \en not implemented - DXFSurfaceBody & operator = ( const DXFSurfaceBody & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойства блока. - \en Block properties. \~ -\ingroup DXF_Exchange -*/ -class CONV_CLASS DXFCompositeData { -private: - DXFHandle thisId; ///< \ru Идентификатор блока. \en Block identifier. - MbVector3D m_scalesId; ///< \ru Масштабы блока по осям координат, (нужны только для идентификация блока с thisId); связано с отказом от использования левых плейсментов в подсборках (err. 56646). \en Block scales by coordinate axes, (they are necessary only for the identification of the block with thisId); this is related with the decision not to use left placements in subassemblies (err. 56646). 56646). - c3d::string_t name; ///< \ru Имя блока. \en Block name. - MbVector3D scales; ///< \ru Масштабы блока по осям координат (нужны при создании сборки). \en Scales of block by coordinate axes (they are necessary for assembly creation). - - MbMatrix3D m_TranslateRotate; ///< \ru Преобразование блока для текущей вставки блока, но без учета масштабных коэффициентов самой вставки блока. \en Transformation of a block for the current block insertion without taking into account the scale factors of this block insertion. - MbMatrix3D m_sumTransform; ///< \ru Преобразование всех внешних блоков. \en Transformation of all external blocks. - -public: - DXFCompositeData(); - DXFCompositeData( const DXFHandle & chandle, const TCHAR * cname ); - DXFCompositeData( const DXFHandle & chandle, const TCHAR * cname, - const MbVector3D &, - const MbMatrix3D & tr, - const MbMatrix3D & sumTr ); - // DXFCompositeData( const TCHAR * cname ); - DXFCompositeData( const DXFCompositeData & cname ); - ~DXFCompositeData(); - -public: - const TCHAR * GetName() const { return name.c_str(); } - std::string Name() const { return c3d::ToSTDstring( name ); } - c3d::string_t NamePath() const { return c3d::string_t( name.c_str() ); } - const DXFHandle & ThisId () const { return thisId; } - const MbVector3D & Scales () const { return scales; } - MbVector3D & Scales () { return scales; } - size_t NameLength() const { return name.length(); } - MbVector3D & ScalesId() { return m_scalesId; } - MbVector3D GetScalesId()const { return m_scalesId; } - const MbMatrix3D & GetTranslateRotate() const { return m_TranslateRotate; } - const MbMatrix3D & GetSumTransform () const { return m_sumTransform; } - - /// \ru Cравнение с другими данными. \en Comparison with other data. - bool operator == ( const DXFCompositeData & ) const ; - - DXFCompositeData & operator=( const DXFCompositeData & ) { C3D_ASSERT_UNCONDITIONAL( false ); return *this; } -}; - - -//------------------------------------------------------------------------------ -/// \ru Cравнение с другими данными по thisId. \en Comparison with other data by thisId. -//---- -inline -bool DXFCompositeData::operator == ( const DXFCompositeData & comp ) const { - // \ru для различения блока используется идентификационный номер и масштабный коэффициент \en an identification number and a scale factor are used to distinguish the block - return thisId == comp.thisId && m_scalesId == comp.m_scalesId; - // return thisId == comp.thisId && scales == comp.scales; -} - - -/////////////////////////////////////////////////////////////////////////////// -// -/** - \ingroup DXF_Exchange - */ -// -/////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -// \ru Блок \en Block -//--- -class CONV_CLASS DXFComposite : public MbRefItem { -private: - PArray composites; ///< \ru Составляющие. \en Components. - PArray solid_bodies; ///< \ru Тела. \en Solids. - std::vector< SPtr > space_curves; ///< \ru Кривые. \en Curves. - DXFSurfaceBody surface_body; ///< \ru Поверхностное тело. \en Surface solid. - DXFCompositeData data; ///< \ru Данные для слива блока. \en Data of the block for union. - SPtr insert; ///< \ru Готовая вставка блока в модельный документ. \en Prepared insert of the block to the model document. - -public: - DXFComposite(); - DXFComposite( const DXFCompositeData & data ); - ~DXFComposite(); - -public: - bool IsEmpty () const; - void Complete ( DXFConverter & converter ); - void AddComposite ( DXFCompositeRef * composite ); - ptrdiff_t GetObjectsCount (); - void FlushSolidBodies (); - - void AddFace ( MbFace & m_face ); - void AddGrid ( MbGrid & m_grid ); - void AddSpaceCurve ( MbCurve3D & space_curves ); - void AddSolidBody ( MbPlacement3D & placement, const std::vector > & m_solids, - const std::vector< SPtr > & m_faces ); - - size_t GetSolidBodiesCount() const { return solid_bodies.Count(); } - const DXFSolidBody * GetSolidBody( size_t k ) const { return ((k < solid_bodies.Count()) ? solid_bodies[k] : NULL); } - DXFSolidBody * SetSolidBody( size_t k ) { return ((k < solid_bodies.Count()) ? solid_bodies[k] : NULL); } - - const DXFCompositeData & GetData() const { return data;} - - bool SetToModel( const MbPlacement3D & where, - ItModelInstance & instance ); - /// \ru Высвободить и обнулить вставку. \en Free the insert and set it to null. - void ReleaseInsert(); - - /// \ru Добавить геометрию (solid_bodies и surface_body) из ob. \en Add to geometry (solid_bodies and surface_body) from ob. - void AddGeometryFrom( const DXFComposite & ob ); -private: - friend class DXFConverter; - friend class DXFCompositeRef; - void CompleteDocument ( ItModelDocument & model_document, DXFConverter & converter ); - void CompleteInstance ( ItModelInstance & model_instance, DXFConverter & converter, - MbPlacement3D * place, MbVector3D & scales ); - - void CompleteComponent( const MbPlacement3D & place, - ItModelInstance & model_instance, - DXFConverter & converter, const MbVector3D& scalesBase ); - - DXFComposite * FindObj( const DXFCompositeData & ); - void CheckPlacementsByGabarits( MbPlacement3D & ); - - void CheckIdenticalBaserSurfaces(); // Контроль одинаковых поверхностей в гранях. - void CollectOwnItems( std::vector >& ownItems ); // Собрать собственные элементы комопнента -private: - DXFComposite ( const DXFComposite & ); // \ru не реализовано \en not implemented - DXFComposite & operator = ( const DXFComposite & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -// \ru Ссылка на блок \en Reference to a block -//--- -class CONV_CLASS DXFCompositeRef { -private: - MbPlacement3D place; ///< \ru Локальная система координат. \en Local coordinate system. - DXFComposite * composite; ///< \ru Блок. \en Block. -public: - DXFCompositeRef ( ); - DXFCompositeRef ( DXFComposite & composite , const MbPlacement3D & cplace ); - DXFCompositeRef ( DXFComposite & composite ); - ~DXFCompositeRef( ); - - /// \ru Заполнить документ модели. \en Fill the model document. - void CompleteInstance ( ItModelInstance & model_instance, - DXFConverter & converter, - MbVector3D & overallScales ); - /// \ru Создать документ \en Create a document - void CompleteDocument ( ItModelDocument & model_document, DXFConverter & converter ); - - const MbPlacement3D & GetPlacement() const { return place; } - void SetPlacement( const MbPlacement3D & pl ) { place = pl; } - DXFComposite * operator->() { return composite; } - DXFComposite * operator* () { return composite; } - - /// \ru Для явной записи. \en For explicit record. - DXFComposite * GetComposite() const { return composite; } -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru DXF-конвертер. - \en DXF - converter. \~ -*/ -class CONV_CLASS DXFConverter { -private: - PArray composites; ///< \ru Составляющие блок подблоки, тела, поверхности. \en Subblocks, solids, surfaces forming the block. - DXFCompositeRef * model_space; ///< \ru Корневой блок. \en Root block. - PArraySort readComposites; ///< \ru Идентификаторы прочтенных блоков. \en Identifiers of read blocks. - IConvertorProperty3D * property; ///< \ru Свойства конвертера. \en Converter properties. - int stitch; ///< \ru Нет информации. \en No information. - double factor; ///< \ru Нет информации. \en No information. - IProgressIndicator * indicator; ///< \ru Индикатор хода процесса преобразования. \en Transformation progress indicator. - ptrdiff_t indicator_delta; ///< \ru Приращение индикатора на одну условную операцию. \en Increment of the indicator by one unit operation. - ptrdiff_t indicator_count; ///< \ru Значение счётчика индикатора. \en Value of the indicator counter. - -#ifdef C3D_DEBUG - uint32 prev_mili_sec; - uint32 current_mili_sec; - uint32 delta_mili_sec; -#endif // C3D_DEBUG - -public: - DXFConverter(); - ~DXFConverter(); - - /// \ru Задать признак сшивки. \en Set a flag of stitching. - void SetStitch ( bool stitch ); - /// \ru Получить признак сшивки. \en Get flag of stitching. - bool IsStitch () const; - /// \ru Задать значение множителя. \en Set a value of multiplier. - void SetFactor ( double factor ); - /// \ru Получить значение множителя. \en Get value of multiplier. - double GetFactor () const; - /// \ru Задать свойства конвертера. \en Specify converter properties. - void SetProperty ( IConvertorProperty3D * property ); - /// \ru Получить свойства конвертера. \en Get converter properties. - IConvertorProperty3D * GetProperty (); - /// \ru Инициировать пустой блок. \en Initialize an empty block. - void BeginComposite (); - /**\brief \ru Инициировать блок с данными. - \en Initialize block with data. \~ - \param[in] matr - \ru Матрица, преобразующая данные блока к СК объемлющего блока. - \en Matrix transforming block data to coordinate system of the enclosing block. \~ - \param[in] data - \ru Данные самого блока. - \en Data of the block. \~ - */ - bool BeginComposite ( MbMatrix3D &matr, const DXFCompositeData & data ); - - /** \brief \ru Завершить создание составного элемента. - \en Complete creation of a composite element. \~ - \details \ru Если у последнего составного элемента:\n - - нет идентификатора;\n - - внутри нет вставок,\n - то это признак того, что этот блок создан только для сшивки геометрии. - В этом случае последний блок объединяется с предпоследним: - в предпоследний переносится геометрия, последний удаляется. - \en If the last composite element has:\n - - no identifier;\n - - no inserts,\n - then it is a creterion that the block is created only for stitching the geometry. - In this case the last block is united with the last but one: - the geometry is moved to the last but one, the last one is deleted. \~ - */ - bool EndComposite (); - /// \ru Очистить конвертер. \en Clear the converter. - void Reset (); - /// \ru Отобразить текующее состояние хода операции. \en Show the current state of operation progress. - bool Indicate ( ptrdiff_t count ); - - /** \brief \ru Завершить создание документа. - \en Complete the document creation. \~ - */ - void CompleteDocument ( ItModelDocument & model_document, - IProgressIndicator * indicator = NULL ); - - /// \ru Отобразить текующее состояние хода операции. \en Show the current state of operation progress. - void ConvertLastComposite( uint32 defaultColor ); - - /// \ru Добавить модельную грань. \en Add the model face. - void AddFace ( MbFace & m_face ); - - /// \ru Добавить модельную грань. \en Add the model face. - void AddGrid ( MbGrid & m_grid ); - - /**\brief \ru Добавить тело. - \en Add a solid. \~ - \param[in] placement - \ru Положение тела в ЛСК. - \en Position of the solid in LCS. \~ - \param[in] model_solids - \ru Модельные тела. - \en Model solids. \~ - \param[in] model_faces - \ru Модельные грани. - \en Model solids. \~ - */ - void AddSolidBody ( MbPlacement3D & placement, - const std::vector > & m_solids, - const std::vector< SPtr > & m_faces ); - /// \ru Добавить пространственную кривую. \en Add a spatial curves. - void AddSpaceCurve ( MbCurve3D & spaceCurve ); - /// \ru Удалить значение из списка прочитанных идентификатров. \en Delete a value from the list of read identifiers. - void RemoveData ( const DXFCompositeData & data ); - -private: - /**\brief \ru Cоздать модельные грани по свойствам старых модельных тел. - \en Create model faces from properties of old model solids. \~ - \param[in] solids - \ru Положение тела в ЛСК. - \en Position of the solid in LCS. \~ - \param[in] stitchedSolids - \ru Модельные тела. - \en Model solids. \~ - \param[in] defaultColor - \ru Цвет по умолчанию. - \en Default color. \~ - \param[in] model_faces - \ru Модельные грани. - \en Model solids. \~ - */ - void CreateModelFacesFromOldSolids( const std::vector > & solids, - const std::vector< SPtr > & stitchedSolids, - uint32 defaultColor, - std::vector< SPtr > & modelFaces ) ; - private: - DXFConverter ( const DXFConverter & ); // \ru не реализовано \en not implemented - DXFConverter & operator = ( const DXFConverter & ); // \ru не реализовано \en not implemented - -}; - - -/** \} */ - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru DXF - конвертер. + \en DXF - converter. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXF_CONVERTER_H +#define __DXF_CONVERTER_H + +#include +#include +#include +#include +#include + + +class IConvertorProperty3D; +class IProgressIndicator; +class ColorProperties; +class ItModelInstanceProperties; +class ItModelDocument; +class ItModelInstance; +class DXFConverter; +class DXFCompositeRef; +class MbGrid; + + +//------------------------------------------------------------------------------ +/** \brief \ru Уникальный (в пределах документа) идентификатор объекта. + \en Unique (in the document) object identifier. \~ + \ingroup DXF_Exchange +*/ +class CONV_CLASS DXFHandle { + +private: + int64 thisId; ///< \ru Уникальное 64-битное число, соответствующее модельному объекту. \en Unique 64-bit number corresponding to the model object. + +public: + DXFHandle ( ); + DXFHandle ( int64 & id ); + DXFHandle ( const unsigned char id[8] ); + ~DXFHandle(); + + const DXFHandle & operator = ( const DXFHandle & id ); + + bool IsDefined() const { return thisId != -1 ; } + + // \ru операторы сравнения \en compare operators + friend bool operator > ( const DXFHandle & left, const DXFHandle & right ); + friend bool operator == ( const DXFHandle & left, const DXFHandle & right ); +}; + + +//------------------------------------------------------------------------------ +/// \ru Сравнение thisId. \en Comparison of thisId. +//--- +inline +bool operator > ( const DXFHandle & left, const DXFHandle & right ) { + return left.thisId > right.thisId; +} + + +//------------------------------------------------------------------------------ +/// \ru Равенство thisId. \en Equality of thisId. +//--- +inline +bool operator ==( const DXFHandle & left, const DXFHandle & right ) { + return left.IsDefined() && right.IsDefined() && left.thisId == right.thisId; +} + + +/** + \addtogroup DXF_Exchange + \{ +*/ + + +//------------------------------------------------------------------------------ +// \ru Тело. \en A solid. +//--- +class CONV_CLASS DXFSolidBody { +private: + MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. + std::vector > solids; ///< \ru Тела. \en Solids. + std::vector< SPtr > faces; ///< \ru Грани. \en Faces. + +public: + DXFSolidBody( MbPlacement3D & placement ); + DXFSolidBody( const DXFSolidBody &); + ~DXFSolidBody(); + +public: + bool IsEmpty () const; + + bool IsSingle () const; + MbPlacement3D GetPlacement() const; + + void MakePlacementIdentical( const MbPlacement3D& ownComponentLocation = MbPlacement3D::global ); + void FillSolids ( std::vector > & solids ) const; + void Flush (); + void AddSolids ( const std::vector > & mSolids ); + void AddFaces ( const std::vector< SPtr > & mFaces ); + void SetPlacement ( const MbPlacement3D & place ); + + size_t GetSolidsCount() const { return solids.size(); } + void GetSolids ( std::vector > & mSolids ) const; + + size_t GetFacesCount () const { return faces.size(); } + void GetFaces ( std::vector< SPtr > & mFaces ) const; +private: + //DXFSolidBody ( const DXFSolidBody & ); // \ru не реализовано \en not implemented + DXFSolidBody & operator = ( const DXFSolidBody & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +// +// --- +inline +void DXFSolidBody::SetPlacement( const MbPlacement3D & place ) { + placement = place; +} + + +//------------------------------------------------------------------------------ +// \ru Поверхность. \en The surface. +//--- +class CONV_CLASS DXFSurfaceBody { +private: + MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. + std::vector< SRef > faces; ///< \ru Грани. \en Faces. + SPtr mesh; + +public: + DXFSurfaceBody(); + DXFSurfaceBody( MbPlacement3D & placement ); + ~DXFSurfaceBody(); + +public: + bool IsEmpty () const; + bool IsSingle () const; + MbPlacement3D GetPlacement() const; + + void Flush(); + void AddFace ( MbFace & face ); + void AddGrid ( MbGrid & grid ); + void AddFaces( const std::vector< SPtr > & mFaces ); + + size_t GetFacesCount() const { return faces.size(); } + +private: + void FillFaces( RPArray & faces ) const; + void GetFaces( std::vector< SPtr > & mFaces ) const; +public: + + SPtr GetMesh(); + + std::vector > GenerateItems( bool stitch ); + +private: + + + DXFSurfaceBody ( const DXFSurfaceBody & ); // \ru не реализовано \en not implemented + DXFSurfaceBody & operator = ( const DXFSurfaceBody & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойства блока. + \en Block properties. \~ +\ingroup DXF_Exchange +*/ +class CONV_CLASS DXFCompositeData { +private: + DXFHandle thisId; ///< \ru Идентификатор блока. \en Block identifier. + MbVector3D m_scalesId; ///< \ru Масштабы блока по осям координат, (нужны только для идентификация блока с thisId); связано с отказом от использования левых плейсментов в подсборках (err. 56646). \en Block scales by coordinate axes, (they are necessary only for the identification of the block with thisId); this is related with the decision not to use left placements in subassemblies (err. 56646). 56646). + c3d::string_t name; ///< \ru Имя блока. \en Block name. + MbVector3D scales; ///< \ru Масштабы блока по осям координат (нужны при создании сборки). \en Scales of block by coordinate axes (they are necessary for assembly creation). + + MbMatrix3D m_TranslateRotate; ///< \ru Преобразование блока для текущей вставки блока, но без учета масштабных коэффициентов самой вставки блока. \en Transformation of a block for the current block insertion without taking into account the scale factors of this block insertion. + MbMatrix3D m_sumTransform; ///< \ru Преобразование всех внешних блоков. \en Transformation of all external blocks. + +public: + DXFCompositeData(); + DXFCompositeData( const DXFHandle & chandle, const TCHAR * cname ); + DXFCompositeData( const DXFHandle & chandle, const TCHAR * cname, + const MbVector3D &, + const MbMatrix3D & tr, + const MbMatrix3D & sumTr ); + // DXFCompositeData( const TCHAR * cname ); + DXFCompositeData( const DXFCompositeData & cname ); + ~DXFCompositeData(); + +public: + const TCHAR * GetName() const { return name.c_str(); } + std::string Name() const { return c3d::ToSTDstring( name ); } + c3d::string_t NamePath() const { return c3d::string_t( name.c_str() ); } + const DXFHandle & ThisId () const { return thisId; } + const MbVector3D & Scales () const { return scales; } + MbVector3D & Scales () { return scales; } + size_t NameLength() const { return name.length(); } + MbVector3D & ScalesId() { return m_scalesId; } + MbVector3D GetScalesId()const { return m_scalesId; } + const MbMatrix3D & GetTranslateRotate() const { return m_TranslateRotate; } + const MbMatrix3D & GetSumTransform () const { return m_sumTransform; } + + /// \ru Cравнение с другими данными. \en Comparison with other data. + bool operator == ( const DXFCompositeData & ) const ; + + DXFCompositeData & operator=( const DXFCompositeData & ) { C3D_ASSERT_UNCONDITIONAL( false ); return *this; } +}; + + +//------------------------------------------------------------------------------ +/// \ru Cравнение с другими данными по thisId. \en Comparison with other data by thisId. +//---- +inline +bool DXFCompositeData::operator == ( const DXFCompositeData & comp ) const { + // \ru для различения блока используется идентификационный номер и масштабный коэффициент \en an identification number and a scale factor are used to distinguish the block + return thisId == comp.thisId && m_scalesId == comp.m_scalesId; + // return thisId == comp.thisId && scales == comp.scales; +} + + +/////////////////////////////////////////////////////////////////////////////// +// +/** + \ingroup DXF_Exchange + */ +// +/////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +// \ru Блок \en Block +//--- +class CONV_CLASS DXFComposite : public MbRefItem { +private: + PArray composites; ///< \ru Составляющие. \en Components. + PArray solid_bodies; ///< \ru Тела. \en Solids. + std::vector< SPtr > space_curves; ///< \ru Кривые. \en Curves. + DXFSurfaceBody surface_body; ///< \ru Поверхностное тело. \en Surface solid. + DXFCompositeData data; ///< \ru Данные для слива блока. \en Data of the block for union. + SPtr insert; ///< \ru Готовая вставка блока в модельный документ. \en Prepared insert of the block to the model document. + +public: + DXFComposite(); + DXFComposite( const DXFCompositeData & data ); + ~DXFComposite(); + +public: + bool IsEmpty () const; + void Complete ( DXFConverter & converter ); + void AddComposite ( DXFCompositeRef * composite ); + ptrdiff_t GetObjectsCount (); + void FlushSolidBodies (); + + void AddFace ( MbFace & m_face ); + void AddGrid ( MbGrid & m_grid ); + void AddSpaceCurve ( MbCurve3D & space_curves ); + void AddSolidBody ( MbPlacement3D & placement, const std::vector > & m_solids, + const std::vector< SPtr > & m_faces ); + + size_t GetSolidBodiesCount() const { return solid_bodies.Count(); } + const DXFSolidBody * GetSolidBody( size_t k ) const { return ((k < solid_bodies.Count()) ? solid_bodies[k] : c3d_null); } + DXFSolidBody * SetSolidBody( size_t k ) { return ((k < solid_bodies.Count()) ? solid_bodies[k] : c3d_null); } + + const DXFCompositeData & GetData() const { return data;} + + bool SetToModel( const MbPlacement3D & where, + ItModelInstance & instance ); + /// \ru Высвободить и обнулить вставку. \en Free the insert and set it to null. + void ReleaseInsert(); + + /// \ru Добавить геометрию (solid_bodies и surface_body) из ob. \en Add to geometry (solid_bodies and surface_body) from ob. + void AddGeometryFrom( const DXFComposite & ob ); +private: + friend class DXFConverter; + friend class DXFCompositeRef; + void CompleteDocument ( ItModelDocument & model_document, DXFConverter & converter ); + void CompleteInstance ( ItModelInstance & model_instance, DXFConverter & converter, + MbPlacement3D * place, MbVector3D & scales ); + + void CompleteComponent( const MbPlacement3D & place, + ItModelInstance & model_instance, + DXFConverter & converter, const MbVector3D& scalesBase ); + + DXFComposite * FindObj( const DXFCompositeData & ); + void CheckPlacementsByGabarits( MbPlacement3D & ); + + void CheckIdenticalBaserSurfaces(); // Контроль одинаковых поверхностей в гранях. + void CollectOwnItems( std::vector >& ownItems ); // Собрать собственные элементы комопнента +private: + DXFComposite ( const DXFComposite & ); // \ru не реализовано \en not implemented + DXFComposite & operator = ( const DXFComposite & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +// \ru Ссылка на блок \en Reference to a block +//--- +class CONV_CLASS DXFCompositeRef { +private: + MbPlacement3D place; ///< \ru Локальная система координат. \en Local coordinate system. + DXFComposite * composite; ///< \ru Блок. \en Block. +public: + DXFCompositeRef ( ); + DXFCompositeRef ( DXFComposite & composite , const MbPlacement3D & cplace ); + DXFCompositeRef ( DXFComposite & composite ); + ~DXFCompositeRef( ); + + /// \ru Заполнить документ модели. \en Fill the model document. + void CompleteInstance ( ItModelInstance & model_instance, + DXFConverter & converter, + MbVector3D & overallScales ); + /// \ru Создать документ \en Create a document + void CompleteDocument ( ItModelDocument & model_document, DXFConverter & converter ); + + const MbPlacement3D & GetPlacement() const { return place; } + void SetPlacement( const MbPlacement3D & pl ) { place = pl; } + DXFComposite * operator->() { return composite; } + DXFComposite * operator* () { return composite; } + + /// \ru Для явной записи. \en For explicit record. + DXFComposite * GetComposite() const { return composite; } +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru DXF-конвертер. + \en DXF - converter. \~ +*/ +class CONV_CLASS DXFConverter { +private: + PArray composites; ///< \ru Составляющие блок подблоки, тела, поверхности. \en Subblocks, solids, surfaces forming the block. + DXFCompositeRef * model_space; ///< \ru Корневой блок. \en Root block. + PArraySort readComposites; ///< \ru Идентификаторы прочтенных блоков. \en Identifiers of read blocks. + IConvertorProperty3D * property; ///< \ru Свойства конвертера. \en Converter properties. + int stitch; ///< \ru Нет информации. \en No information. + double factor; ///< \ru Нет информации. \en No information. + IProgressIndicator * indicator; ///< \ru Индикатор хода процесса преобразования. \en Transformation progress indicator. + ptrdiff_t indicator_delta; ///< \ru Приращение индикатора на одну условную операцию. \en Increment of the indicator by one unit operation. + ptrdiff_t indicator_count; ///< \ru Значение счётчика индикатора. \en Value of the indicator counter. + +#ifdef C3D_DEBUG + uint32 prev_mili_sec; + uint32 current_mili_sec; + uint32 delta_mili_sec; +#endif // C3D_DEBUG + +public: + DXFConverter(); + ~DXFConverter(); + + /// \ru Задать признак сшивки. \en Set a flag of stitching. + void SetStitch ( bool stitch ); + /// \ru Получить признак сшивки. \en Get flag of stitching. + bool IsStitch () const; + /// \ru Задать значение множителя. \en Set a value of multiplier. + void SetFactor ( double factor ); + /// \ru Получить значение множителя. \en Get value of multiplier. + double GetFactor () const; + /// \ru Задать свойства конвертера. \en Specify converter properties. + void SetProperty ( IConvertorProperty3D * property ); + /// \ru Получить свойства конвертера. \en Get converter properties. + IConvertorProperty3D * GetProperty (); + /// \ru Инициировать пустой блок. \en Initialize an empty block. + void BeginComposite (); + /**\brief \ru Инициировать блок с данными. + \en Initialize block with data. \~ + \param[in] matr - \ru Матрица, преобразующая данные блока к СК объемлющего блока. + \en Matrix transforming block data to coordinate system of the enclosing block. \~ + \param[in] data - \ru Данные самого блока. + \en Data of the block. \~ + */ + bool BeginComposite ( MbMatrix3D &matr, const DXFCompositeData & data ); + + /** \brief \ru Завершить создание составного элемента. + \en Complete creation of a composite element. \~ + \details \ru Если у последнего составного элемента:\n + - нет идентификатора;\n + - внутри нет вставок,\n + то это признак того, что этот блок создан только для сшивки геометрии. + В этом случае последний блок объединяется с предпоследним: + в предпоследний переносится геометрия, последний удаляется. + \en If the last composite element has:\n + - no identifier;\n + - no inserts,\n + then it is a creterion that the block is created only for stitching the geometry. + In this case the last block is united with the last but one: + the geometry is moved to the last but one, the last one is deleted. \~ + */ + bool EndComposite (); + /// \ru Очистить конвертер. \en Clear the converter. + void Reset (); + /// \ru Отобразить текующее состояние хода операции. \en Show the current state of operation progress. + bool Indicate ( ptrdiff_t count ); + + /** \brief \ru Завершить создание документа. + \en Complete the document creation. \~ + */ + void CompleteDocument ( ItModelDocument & model_document, + IProgressIndicator * indicator = c3d_null ); + + /// \ru Отобразить текующее состояние хода операции. \en Show the current state of operation progress. + void ConvertLastComposite( uint32 defaultColor ); + + /// \ru Добавить модельную грань. \en Add the model face. + void AddFace ( MbFace & m_face ); + + /// \ru Добавить модельную грань. \en Add the model face. + void AddGrid ( MbGrid & m_grid ); + + /**\brief \ru Добавить тело. + \en Add a solid. \~ + \param[in] placement - \ru Положение тела в ЛСК. + \en Position of the solid in LCS. \~ + \param[in] model_solids - \ru Модельные тела. + \en Model solids. \~ + \param[in] model_faces - \ru Модельные грани. + \en Model solids. \~ + */ + void AddSolidBody ( MbPlacement3D & placement, + const std::vector > & m_solids, + const std::vector< SPtr > & m_faces ); + /// \ru Добавить пространственную кривую. \en Add a spatial curves. + void AddSpaceCurve ( MbCurve3D & spaceCurve ); + /// \ru Удалить значение из списка прочитанных идентификатров. \en Delete a value from the list of read identifiers. + void RemoveData ( const DXFCompositeData & data ); + +private: + /**\brief \ru Cоздать модельные грани по свойствам старых модельных тел. + \en Create model faces from properties of old model solids. \~ + \param[in] solids - \ru Положение тела в ЛСК. + \en Position of the solid in LCS. \~ + \param[in] stitchedSolids - \ru Модельные тела. + \en Model solids. \~ + \param[in] defaultColor - \ru Цвет по умолчанию. + \en Default color. \~ + \param[in] model_faces - \ru Модельные грани. + \en Model solids. \~ + */ + void CreateModelFacesFromOldSolids( const std::vector > & solids, + const std::vector< SPtr > & stitchedSolids, + uint32 defaultColor, + std::vector< SPtr > & modelFaces ) ; + private: + DXFConverter ( const DXFConverter & ); // \ru не реализовано \en not implemented + DXFConverter & operator = ( const DXFConverter & ); // \ru не реализовано \en not implemented + +}; + + +/** \} */ + + #endif // __DXF_CONVERTER_H \ No newline at end of file diff --git a/C3d/Include/dxf_data.h b/C3d/Include/dxf_data.h index fe772cf..41825a2 100644 --- a/C3d/Include/dxf_data.h +++ b/C3d/Include/dxf_data.h @@ -1,339 +1,339 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru DXF - конвертер. - \en DXF - converter. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __DXF_DATA_H -#define __DXF_DATA_H - -#include -#include -#include -#include -#include -#include -#include - - -class MbCartPoint; -class MbCurve; -class MbCartPoint3D; -class MbVector3D; -class MbPlacement3D; -class MbCurve3D; -class MbSolid; -class MbFace; -class MbGrid; -class DXFConverter; - - -//------------------------------------------------------------------------------ -/** \brief \ru Объект формата DXF. - \en Object of DXF format. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFEntity { -protected: - MbAttributeContainer attributes; ///< \ru Атрибуты. \en Attributes. - -protected: - // \ru Конструктор. \en Constructor. - DXFEntity(); - // \ru Деструктор. \en Destructor. - virtual ~DXFEntity(); - -public: - /// \ru Установить цветовые атрибуты. \en Set color attributes. - void SetAttributes( MbAttributeContainer & attribs ); - virtual bool Convert ( DXFConverter & converter ) = 0; - -private: - DXFEntity ( const DXFEntity & ); // \ru не реализовано \en not implemented - DXFEntity & operator = ( const DXFEntity & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Анализатор потока SAT. - \en SAT stream analyzer. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFModelerGeometry : public DXFEntity { -private: - std::iostream & out; ///< \ru анализируемый поток. \en stream being analyzed. - -public: - DXFModelerGeometry( std::iostream & out ); - virtual ~DXFModelerGeometry(); - - virtual bool Convert( DXFConverter & converter ); - -private: - DXFModelerGeometry ( const DXFModelerGeometry & ); // \ru не реализовано \en not implemented - DXFModelerGeometry & operator = ( const DXFModelerGeometry & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Грань. - \en Face. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFFace : public DXFEntity { -private: - /** \brief \ru Цикл. - \en Loop. \~ - \details \ru Цикл объявлен внутри DXFFace. - \en The Loop is declared inside DXFFace. \~ - \ingroup DXF_Exchange -*/ - class CONV_CLASS DXFLoop { - public: - SArray points; ///< \ru Набор точек. \en Point set. - - public: - DXFLoop( const SArray & points ); - ~DXFLoop(); - - private: - DXFLoop ( const DXFLoop & ); // \ru не реализовано \en not implemented - DXFLoop & operator = ( const DXFLoop & ); // \ru не реализовано \en not implemented - - }; - -private: - PArray loops; ///< \ru Набор циклов. \en Loop set. - -public: - DXFFace( const SArray & points ); - virtual ~DXFFace(); - - virtual bool Convert ( DXFConverter & converter ); - MbFace * MakeFace( ) const; - MbGrid* MakeGrid( ) const; - void AddHole ( const SArray & points ); - void Scale ( double factor ); - -private: - DXFFace ( const DXFFace & ); // \ru не реализовано \en not implemented - DXFFace & operator = ( const DXFFace & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Сеть на основе граней. - \en Mesh on the base of faces. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFPolyfaceMesh : public DXFEntity { -private: - const PArray & faces; ///< \ru Набор граней. \en Face set. - -public: - DXFPolyfaceMesh( const PArray & faces ); - virtual ~DXFPolyfaceMesh(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFPolyfaceMesh ( const DXFPolyfaceMesh & ); // \ru не реализовано \en not implemented - DXFPolyfaceMesh & operator = ( const DXFPolyfaceMesh & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Сеть на основе вершин DXF. - \en Mesh on the base of DXF vertices. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFPolygonMesh : public DXFEntity { -private: - Array2 & points; ///< \ru Набор вершин. \en Vertex set. - bool uclosed; ///< \ru Признак замкнутости по u. \en Flag of closedness by u. - bool vclosed; ///< \ru Признак замкнутости по v. \en Flag of closedness by v. - -public: - DXFPolygonMesh( Array2 & points, bool uclosed, bool vclosed ); - virtual ~DXFPolygonMesh(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFPolygonMesh ( const DXFPolygonMesh & ); // \ru не реализовано \en not implemented - DXFPolygonMesh & operator = ( const DXFPolygonMesh & ); // \ru не реализовано \en not implemented -}; - - -//------------------------------------------------------------------------------ -/**\brief \ru Составная кривая. - \en Polyline. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFPolyline : public DXFEntity { -public: - /**\brief \ru Сегмент составной кривой. - \en Polyline segment. \~ - \details \ru Класс объявлен внутри DXFPolyline; - \en The class is declared inside DXFPolyline; \~ - \ingroup DXF_Exchange -*/ - class CONV_CLASS DXFSegment { - private: - MbCurve & curve; ///< \ru Кривая. \en A curve. - double width1; ///< \ru Толщина. \en The thickness. - double width2; ///< \ru Толщина. \en The thickness. - - mutable SPtr left; - mutable SPtr right; - mutable SPtr top; - mutable SPtr bottom; - - public: - DXFSegment( MbCurve & _curve, double _width1, double _width2 ); - ~DXFSegment(); - - const MbCurve & Curve () const { return curve; } - double Width1 () const { return width1; } - double Width2 () const { return width2; } - bool IsWidth1Zero() const { return (width1 < NULL_EPSILON); } - bool IsWidth2Zero() const { return (width2 < NULL_EPSILON); } - void ChangeLeft ( MbCurve & left ) const; - void ChangeRight ( MbCurve & right ) const; - void ChangeTop ( MbCurve & top ) const; - void ChangeBottom( MbCurve & bottom ) const; - const MbCurve * GetLeft () const { return left; } - const MbCurve * GetRight () const { return right; } - const MbCurve * GetTop () const { return top; } - const MbCurve * GetBottom () const { return bottom; } - void MakeContours( std::vector< SPtr > & contours ) const; - - private: - DXFSegment ( const DXFSegment & ); // \ru не реализовано \en not implemented - DXFSegment & operator = ( const DXFSegment & ); // \ru не реализовано \en not implemented - - }; - -private: - const PArray & segments; ///< \ru Сегменты. \en Segments. - bool closed; ///< \ru Признак замкнутости. \en Flag of closedness. - MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. - MbVector3D direction; ///< \ru Направление. \en Direction. - -public: - DXFPolyline( const PArray & _segments, bool _closed, const MbPlacement3D & _placement, const MbVector3D & _direction ); - virtual ~DXFPolyline(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFPolyline ( const DXFPolyline & ); // \ru не реализовано \en not implemented - DXFPolyline & operator = ( const DXFPolyline & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Кривая. - \en A curve. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFCurve : public DXFEntity { -private: - MbCurve3D & curve; ///< \ru Кривая. \en A curve. - MbVector3D direction; ///< \ru Направление. \en Direction. - -public: - DXFCurve( MbCurve3D & _curve, const MbVector3D & _direction ); - virtual ~DXFCurve(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFCurve ( const DXFCurve & ); // \ru не реализовано \en not implemented - DXFCurve & operator = ( const DXFCurve & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Пространственная кривая. - \en A space curve. \~ - \details \ru Используется для передачи каркасных моделей. - \en Used for wireframe models transfer. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFCurve3D : public DXFEntity { -private: - MbCurve3D & curve; ///< \ru Кривая. \en A curve. - -public: - DXFCurve3D( MbCurve3D & _curve ); - virtual ~DXFCurve3D(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFCurve3D ( const DXFCurve3D & ); // \ru не реализовано \en not implemented - DXFCurve3D & operator = ( const DXFCurve3D & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Точка. - \en Point. \~ - \ingroup DXF_Exchange -*/ -// --- -class CONV_CLASS DXFPoint : public DXFEntity { -private: - MbCartPoint3D point; ///< \ru Точка. \en A point. - MbVector3D direction; ///< \ru Направление. \en Direction. - -public: - DXFPoint( const MbCartPoint3D & _point, const MbVector3D & _direction ); - virtual ~DXFPoint(); - - virtual bool Convert( DXFConverter & converter ); - void Scale ( double factor ); - -private: - DXFPoint ( const DXFPoint & ); // \ru не реализовано \en not implemented - DXFPoint & operator = ( const DXFPoint & ); // \ru не реализовано \en not implemented - -}; - - -//------------------------------------------------------------------------------ -// -// --- -void StitchFacesAndCreateSolids( const RPArray & faces, std::vector< SPtr > & solids ); - - -//------------------------------------------------------------------------------ -// -// --- -void UnStitchFacesAndCreateSolids( const RPArray & faces, std::vector< SPtr > & solids ); - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru DXF - конвертер. + \en DXF - converter. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXF_DATA_H +#define __DXF_DATA_H + +#include +#include +#include +#include +#include +#include +#include + + +class MbCartPoint; +class MbCurve; +class MbCartPoint3D; +class MbVector3D; +class MbPlacement3D; +class MbCurve3D; +class MbSolid; +class MbFace; +class MbGrid; +class DXFConverter; + + +//------------------------------------------------------------------------------ +/** \brief \ru Объект формата DXF. + \en Object of DXF format. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFEntity { +protected: + MbAttributeContainer attributes; ///< \ru Атрибуты. \en Attributes. + +protected: + // \ru Конструктор. \en Constructor. + DXFEntity(); + // \ru Деструктор. \en Destructor. + virtual ~DXFEntity(); + +public: + /// \ru Установить цветовые атрибуты. \en Set color attributes. + void SetAttributes( MbAttributeContainer & attribs ); + virtual bool Convert ( DXFConverter & converter ) = 0; + +private: + DXFEntity ( const DXFEntity & ); // \ru не реализовано \en not implemented + DXFEntity & operator = ( const DXFEntity & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Анализатор потока SAT. + \en SAT stream analyzer. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFModelerGeometry : public DXFEntity { +private: + std::iostream & out; ///< \ru анализируемый поток. \en stream being analyzed. + +public: + DXFModelerGeometry( std::iostream & out ); + virtual ~DXFModelerGeometry(); + + virtual bool Convert( DXFConverter & converter ); + +private: + DXFModelerGeometry ( const DXFModelerGeometry & ); // \ru не реализовано \en not implemented + DXFModelerGeometry & operator = ( const DXFModelerGeometry & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Грань. + \en Face. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFFace : public DXFEntity { +private: + /** \brief \ru Цикл. + \en Loop. \~ + \details \ru Цикл объявлен внутри DXFFace. + \en The Loop is declared inside DXFFace. \~ + \ingroup DXF_Exchange +*/ + class CONV_CLASS DXFLoop { + public: + SArray points; ///< \ru Набор точек. \en Point set. + + public: + DXFLoop( const SArray & points ); + ~DXFLoop(); + + private: + DXFLoop ( const DXFLoop & ); // \ru не реализовано \en not implemented + DXFLoop & operator = ( const DXFLoop & ); // \ru не реализовано \en not implemented + + }; + +private: + PArray loops; ///< \ru Набор циклов. \en Loop set. + +public: + DXFFace( const SArray & points ); + virtual ~DXFFace(); + + virtual bool Convert ( DXFConverter & converter ); + MbFace * MakeFace( ) const; + MbGrid* MakeGrid( ) const; + void AddHole ( const SArray & points ); + void Scale ( double factor ); + +private: + DXFFace ( const DXFFace & ); // \ru не реализовано \en not implemented + DXFFace & operator = ( const DXFFace & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Сеть на основе граней. + \en Mesh on the base of faces. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFPolyfaceMesh : public DXFEntity { +private: + const PArray & faces; ///< \ru Набор граней. \en Face set. + +public: + DXFPolyfaceMesh( const PArray & faces ); + virtual ~DXFPolyfaceMesh(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFPolyfaceMesh ( const DXFPolyfaceMesh & ); // \ru не реализовано \en not implemented + DXFPolyfaceMesh & operator = ( const DXFPolyfaceMesh & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Сеть на основе вершин DXF. + \en Mesh on the base of DXF vertices. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFPolygonMesh : public DXFEntity { +private: + Array2 & points; ///< \ru Набор вершин. \en Vertex set. + bool uclosed; ///< \ru Признак замкнутости по u. \en Flag of closedness by u. + bool vclosed; ///< \ru Признак замкнутости по v. \en Flag of closedness by v. + +public: + DXFPolygonMesh( Array2 & points, bool uclosed, bool vclosed ); + virtual ~DXFPolygonMesh(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFPolygonMesh ( const DXFPolygonMesh & ); // \ru не реализовано \en not implemented + DXFPolygonMesh & operator = ( const DXFPolygonMesh & ); // \ru не реализовано \en not implemented +}; + + +//------------------------------------------------------------------------------ +/**\brief \ru Составная кривая. + \en Polyline. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFPolyline : public DXFEntity { +public: + /**\brief \ru Сегмент составной кривой. + \en Polyline segment. \~ + \details \ru Класс объявлен внутри DXFPolyline; + \en The class is declared inside DXFPolyline; \~ + \ingroup DXF_Exchange +*/ + class CONV_CLASS DXFSegment { + private: + MbCurve & curve; ///< \ru Кривая. \en A curve. + double width1; ///< \ru Толщина. \en The thickness. + double width2; ///< \ru Толщина. \en The thickness. + + mutable SPtr left; + mutable SPtr right; + mutable SPtr top; + mutable SPtr bottom; + + public: + DXFSegment( MbCurve & _curve, double _width1, double _width2 ); + ~DXFSegment(); + + const MbCurve & Curve () const { return curve; } + double Width1 () const { return width1; } + double Width2 () const { return width2; } + bool IsWidth1Zero() const { return (width1 < NULL_EPSILON); } + bool IsWidth2Zero() const { return (width2 < NULL_EPSILON); } + void ChangeLeft ( MbCurve & left ) const; + void ChangeRight ( MbCurve & right ) const; + void ChangeTop ( MbCurve & top ) const; + void ChangeBottom( MbCurve & bottom ) const; + const MbCurve * GetLeft () const { return left; } + const MbCurve * GetRight () const { return right; } + const MbCurve * GetTop () const { return top; } + const MbCurve * GetBottom () const { return bottom; } + void MakeContours( std::vector< SPtr > & contours ) const; + + private: + DXFSegment ( const DXFSegment & ); // \ru не реализовано \en not implemented + DXFSegment & operator = ( const DXFSegment & ); // \ru не реализовано \en not implemented + + }; + +private: + const PArray & segments; ///< \ru Сегменты. \en Segments. + bool closed; ///< \ru Признак замкнутости. \en Flag of closedness. + MbPlacement3D placement; ///< \ru Локальная система координат. \en Local coordinate system. + MbVector3D direction; ///< \ru Направление. \en Direction. + +public: + DXFPolyline( const PArray & _segments, bool _closed, const MbPlacement3D & _placement, const MbVector3D & _direction ); + virtual ~DXFPolyline(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFPolyline ( const DXFPolyline & ); // \ru не реализовано \en not implemented + DXFPolyline & operator = ( const DXFPolyline & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Кривая. + \en A curve. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFCurve : public DXFEntity { +private: + MbCurve3D & curve; ///< \ru Кривая. \en A curve. + MbVector3D direction; ///< \ru Направление. \en Direction. + +public: + DXFCurve( MbCurve3D & _curve, const MbVector3D & _direction ); + virtual ~DXFCurve(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFCurve ( const DXFCurve & ); // \ru не реализовано \en not implemented + DXFCurve & operator = ( const DXFCurve & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Пространственная кривая. + \en A space curve. \~ + \details \ru Используется для передачи каркасных моделей. + \en Used for wireframe models transfer. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFCurve3D : public DXFEntity { +private: + MbCurve3D & curve; ///< \ru Кривая. \en A curve. + +public: + DXFCurve3D( MbCurve3D & _curve ); + virtual ~DXFCurve3D(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFCurve3D ( const DXFCurve3D & ); // \ru не реализовано \en not implemented + DXFCurve3D & operator = ( const DXFCurve3D & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Точка. + \en Point. \~ + \ingroup DXF_Exchange +*/ +// --- +class CONV_CLASS DXFPoint : public DXFEntity { +private: + MbCartPoint3D point; ///< \ru Точка. \en A point. + MbVector3D direction; ///< \ru Направление. \en Direction. + +public: + DXFPoint( const MbCartPoint3D & _point, const MbVector3D & _direction ); + virtual ~DXFPoint(); + + virtual bool Convert( DXFConverter & converter ); + void Scale ( double factor ); + +private: + DXFPoint ( const DXFPoint & ); // \ru не реализовано \en not implemented + DXFPoint & operator = ( const DXFPoint & ); // \ru не реализовано \en not implemented + +}; + + +//------------------------------------------------------------------------------ +// +// --- +void StitchFacesAndCreateSolids( const RPArray & faces, std::vector< SPtr > & solids ); + + +//------------------------------------------------------------------------------ +// +// --- +void UnStitchFacesAndCreateSolids( const RPArray & faces, std::vector< SPtr > & solids ); + + #endif // __DXF_DATA_H \ No newline at end of file diff --git a/C3d/Include/func_analytical_function.h b/C3d/Include/func_analytical_function.h index 8b19060..c946b99 100644 --- a/C3d/Include/func_analytical_function.h +++ b/C3d/Include/func_analytical_function.h @@ -77,7 +77,7 @@ public : virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; @@ -162,7 +162,7 @@ public : virtual double SecondDer ( double & t ) const; // \ru Вторая производная по t \en The second derivative with respect to t virtual double ThirdDer ( double & t ) const; // \ru Третья производная по t \en The third derivative with respect to t - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step ( double t, double sag ) const; virtual double DeviationStep ( double t, double angle ) const; diff --git a/C3d/Include/func_const_function.h b/C3d/Include/func_const_function.h index 559a468..9fcb2ba 100644 --- a/C3d/Include/func_const_function.h +++ b/C3d/Include/func_const_function.h @@ -61,7 +61,7 @@ public: virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; - virtual void Inverse ( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse ( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_cubic_function.h b/C3d/Include/func_cubic_function.h index 73a3667..5c4cae7 100644 --- a/C3d/Include/func_cubic_function.h +++ b/C3d/Include/func_cubic_function.h @@ -54,6 +54,8 @@ public: /// \ru Инициализация по точкам, параметрам и признаку замкнутости. \en Initialization by points, parameters and an attribute of closedness. void Init( const SArray & values, const SArray & params, bool cls ); + /// \ru Инициализация монотонного сплайна. \en Monotone spline initialization. + bool InitMonotonic( const SArray & values, const SArray & params, bool valClosed ); public: // \ru Общие функции математического объекта \en Common functions of mathematical object virtual MbeFunctionType IsA () const; // \ru Тип элемента \en A type of element @@ -83,7 +85,7 @@ public: // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. virtual double Argument( double & val ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_cubic_spline_function.h b/C3d/Include/func_cubic_spline_function.h index efd89b7..5294a29 100644 --- a/C3d/Include/func_cubic_spline_function.h +++ b/C3d/Include/func_cubic_spline_function.h @@ -72,7 +72,7 @@ public: virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_line_function.h b/C3d/Include/func_line_function.h index 137012d..17897c2 100644 --- a/C3d/Include/func_line_function.h +++ b/C3d/Include/func_line_function.h @@ -67,7 +67,7 @@ public: // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. virtual double Argument( double & val ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_mono_smooth_function.h b/C3d/Include/func_mono_smooth_function.h new file mode 100644 index 0000000..6ff8c53 --- /dev/null +++ b/C3d/Include/func_mono_smooth_function.h @@ -0,0 +1,159 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Монотонная сплайн интерполяция класса c2 на основе + однопараметрических групп диффеоморфизмов (Н.В.Осадченко). + \en Monotone spline interpolation class c2 based + one-parameter groups of diffeomorphisms (N.V. Osadchenko). \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __FUNC_MONO_SMOOTH_FUNCTION_H +#define __FUNC_MONO_SMOOTH_FUNCTION_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Монотонная сплайн интерполяция класса c2 на основе + однопараметрических групп диффеоморфизмов (Н.В.Осадченко). + \en Monotone spline interpolation class c2 based + one-parameter groups of diffeomorphisms (N.V. Osadchenko). \~ + \details \ru Класс описывает сплайн-функцию, которая строится по возрастающему \n + набору параметров и монотонно возрастающему/убывающему набору значений. \n + Функция гарантирует однозначное соответствие параметр-значение. При этом \n + аналичиские функции, описывающие сплайн на каждом участке, стыкуются \n + между собой с сохранением непрерывности первой и второй производной. \n + (Если от функции не требуется второй порядок непрерывности, то монотонную функцию \n + можно построить с помощью кубической функции MbCubicFunction через инициализацию \n + InitMonotonic). Данная функция может быть использована, как функция репараметризации. \n + При этом, если репараметризуемый объект обладает свойством замкнутости, то \n + функция может учесть это свойство, обеспечив также второй порядок непрерывности \n + через шов. Функция принимает на вход при инициализации массив параметров и \n + значений, имеющих одинаковую размерность вне зависимости от параметра \n + замкнутости. Репараметризующая функция построена в виде 3х вложенных друг в друга \n + рациональных функций y(x)=y1+(y2-y1)*Fb(Fg(Fb((x-x1)/(x2-x1)))). Подробно ознакомится \n + с данным типом сплайна можно по ссылке. + http://www.stfi.ru/journal/STFI_2017_03/STFI_2017_03_Osadchenko.pdf + \en The class describes a spline function, which is built from an increasing set \n + of parameters and a monotonically increasing / decreasing set of values. The \n + function guarantees a one-to-one parameter-value match. In this case, the \n + analytical functions describing the spline in each section are joined together \n + while maintaining the continuity of the first and second derivatives. (If the \n + function does not require the second order of continuity, then a monotonic \n + function can be built using the MbCubicFunction cubic function through the \n + InitMonotonic initialization). This function can be used as a reparameterization \n + function. Moreover, if the reparameterizable object has the property of being \n + closed, then the function can take this property into account, providing also \n + the second order of continuity through the seam. During initialization, the \n + function accepts an array of parameters and values ​​that have the same dimension, \n + regardless of the closure parameter. The reparametrizing function is built in \n + the form of 3 nested rational functions \n + y (x) = y1 + (y2-y1) * Fb (Fg (Fb ((x-x1) / (x2-x1)))). \n + You can learn more about this type of spline here. \n + http://www.stfi.ru/journal/STFI_2017_03/STFI_2017_03_Osadchenko.pdf \~ + \ingroup Functions +*/ +// --- +class MATH_CLASS MbMonoSmoothFunction : public MbFunction { +protected: + c3d::DoubleVector x; ///< \ru Возрастающий набор параметров. \en Increasing set of parameters. + c3d::DoubleVector y; ///< \ru Монотонный набор значений. \en Monotonic set of values. + c3d::DoubleVector bet; ///< \ru Параметры beta-функций. \en Parameters of beta functions. + c3d::DoubleVector gam; ///< \ru Параметры gamma-функций. \en Parameters of gamma functions. + bool cls; ///< \ru Периодичность набора значений.\en Periodicity of the set of values. + +private: + /// \ru Конструктор. \en Constructor. + MbMonoSmoothFunction(); + /// \ru Конструктор копии. \en Copy constructor. + MbMonoSmoothFunction( const MbMonoSmoothFunction & ); +public : + virtual ~MbMonoSmoothFunction(); + +public: + /// \ru Создание объекта. \en Object creation. + static MbFunction * Create( const c3d::DoubleVector & pars, const c3d::DoubleVector & vals, bool yCls ); + /** \brief \ru Инициализация сплайна. + \en Spline initialization. \~ + \param[in] pars - \ru Возрастающий набор параметров. + \en Increasing set of parameters. \~ + \param[in] vals - \ru Монотонный набор значений. + \en Monotonic set of values. \~ + \param[in] valCls - \ru Периодичность набора значений. + \en Periodicity of the set of values. \~ + \return \ru Статус операции. + \en Operation status. \~ + */ + bool Init ( const c3d::DoubleVector & pars, const c3d::DoubleVector & vals, bool valCls ); +public: + // \ru Общие функции математического объекта \en Common functions of mathematical object + virtual MbeFunctionType IsA () const; // \ru Тип элемента \en A type of element + virtual MbFunction & Duplicate() const; // \ru Сделать копию элемента \en Create a copy of the element + virtual bool IsSame ( const MbFunction & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными \en Determine whether objects are equal + virtual bool SetEqual ( const MbFunction & ); // \ru Сделать равным \en Make equal + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of object + + virtual double GetTMax () const; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter + virtual double GetTMin () const; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter + virtual bool IsClosed () const; // \ru Замкнутость кривой \en A curve closeness + virtual void SetClosed( bool ); // \ru Замкнутость функции \en A function closeness + + virtual double Value ( double & t ) const; // \ru Значение функции для t \en The value of function for a given t + virtual double FirstDer ( double & t ) const; // \ru Первая производная по t \en The first derivative with respect to t + virtual double SecondDer ( double & t ) const; // \ru Вторая производная по t \en The second derivative with respect to t + virtual double ThirdDer ( double & t ) const; // \ru Третья производная по t \en The third derivative with respect to t + + virtual double _Value ( double t ) const; // \ru Значение функции для t \en The value of function for a given t + virtual double _FirstDer ( double t ) const; // \ru Первая производная по t \en The first derivative with respect to t + virtual double _SecondDer ( double t ) const; // \ru Вторая производная по t \en The second derivative with respect to t + virtual double _ThirdDer ( double t ) const; // \ru Третья производная по t \en The third derivative with respect to t + // \ru Вычислить значение и производные. \en Calculate value and derivatives of object for given parameter. \~ + virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; + + size_t GetListCount() const { return x.size(); } // \ru Количество точек в наборе \en Number of points in a set. + double GetValue(size_t ind ) const { return y[ind]; } // \ru Получить значение по индексу. \en Get value by index. + double GetParam(size_t ind ) const { return x[ind]; } // \ru Получить параметр по индексу. \en Get parameter by index. + + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction + virtual double Step( double t, double sag ) const; + virtual double DeviationStep( double t, double angle ) const; + + virtual double MinValue ( double & t ) const; // \ru Минимальное значение функции \en The minimum value of function + virtual double MaxValue ( double & t ) const; // \ru Максимальное значение функции \en The maximum value of function + virtual double MidValue () const; // \ru Среднее значение функции \en The middle value of function + virtual bool IsGood () const; // \ru Корректность функции \en Correctness of function + + virtual bool IsConst() const; + virtual bool IsLine () const; + + virtual void SetOffsetFunc( double distOld, double distNew ); // \ru Сместить функцию \en Shift a function + virtual bool SetLimitParam( double, double ); // \ru Установить область изменения параметра \en Set range of parameter + virtual void SetLimitValue( size_t n, double); // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at start point, 2 - at end point) + virtual double GetLimitValue( size_t n ) const; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at start point, 2 - at end point) + virtual bool InsertValue( double x, double y); // \ru Установить значение для параметра t. \en Set the value for the pdrdmeter t. + + // \ru Создать функцию из части функции между параметрами t1 и t2 c выбором направления sense. \en Create a function in part of the function between the parameters t1 and t2 choosing the direction. + virtual MbFunction * Trimmed( double t1, double t2, int sense ) const; + // \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. + virtual MbFunction * BreakFunction( double t, bool beg ); + MbFunction * Break( double t1, double t2 ) const; ///< \ru Выделить часть функции. \en Select a part of a function. + +private: + void CheckParam( double & t ) const; // \ru Установить параметр в область определения. \en Set the parameter to the domain. + void DivExplore( size_t ord, double( &P )[4], double( &T )[4], double( &res )[4] ) const; // \ru Найти производные частного P/T. \en Find the derivatives of the quotient P / T. + void ExploreBet( double b, size_t ord, double( &res )[4] ) const; // \ru Расчитать производные beta функции. \en Calculate the derivatives of the beta function. + void ExploreGam( double b, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные gamma функции. \en Calculate the derivatives of the gamma function. + void Explore( double x, size_t ord, double( &res )[4] ) const;// \ru Расчитать производные сплайна. \en Calculate the derivatives of the spline. + void operator = ( const MbMonoSmoothFunction & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMonoSmoothFunction ) +}; + +IMPL_PERSISTENT_OPS( MbCubicSplineFunction ) + +#endif // __FUNC_MONO_SMOOTH_FUNCTION_H diff --git a/C3d/Include/func_power_function.h b/C3d/Include/func_power_function.h index c00ee31..3018514 100644 --- a/C3d/Include/func_power_function.h +++ b/C3d/Include/func_power_function.h @@ -67,7 +67,7 @@ public: virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_serve_function.h b/C3d/Include/func_serve_function.h index 3c4072d..c199777 100644 --- a/C3d/Include/func_serve_function.h +++ b/C3d/Include/func_serve_function.h @@ -32,10 +32,10 @@ public : public : ///< \ru Конструктор по умолчанию. \en Default constructor. - MbServeFunction(); + MbServeFunction(); private: ///< \ru Конструктор по параметрам. \en Constructor by parameters. - MbServeFunction( double ka, double kb, double kc, double t1, double t2 ); + MbServeFunction( double ka, double kb, double kc, double t1, double t2 ); ///< \ru Конструктор копировния. \en Copy constructor. MbServeFunction( const MbServeFunction & ); public : @@ -48,7 +48,7 @@ public: \param[in] t1, t2 - \ru Область определения репараметризованной кривой \en Parametric region of the reparameterized curve. \~ */ - void InitLinear( double basisTMin, double basisTMax, double t1, double t2 ); + void InitLinear( double basisTMin, double basisTMax, double t1, double t2 ); /** \brief \ru Инициализация переменных для репараметризации с заданной производной в начале. \en Initialization of variables for reparameterization with a given derivative at the beginning. \~ @@ -60,11 +60,11 @@ public: \en The derivative of the base curve parameter at the beginning of the curve. \~ \return - \ru true - если репараметризация выполнена успешно, false - если репараметризация оказалась вырожденной и была сведена к линейной. - \en true - if reparameterization is successful, + \en true - if reparameterization is successful, false - if the reparametrization is degenerate and reduced to linear. \~ */ - bool InitQuadratic( double basisTMin, double basisTMax, double t1, double t2, double begDer ); - + bool InitQuadratic( double basisTMin, double basisTMax, double t1, double t2, double begDer ); + /** \brief \ru Репараметризация, обеспечивающая на концах новой кривой указаные производные параметра. \en Reparametrization providing the indicated derivatives of the parameter at the ends of the new curve. \~ \details \ru Параметрическая ширина будет подобрана автоматически, исходя из значений производных. @@ -75,10 +75,10 @@ public: \en Derivatives of the base curve parameter at the beginning and end of the curve. \~ \return - \ru true - репараметризация выполнена успешно, false - репараметризация оказалась вырожденной и была сведена к линейной. - \en true - reparameterization is successful, + \en true - reparameterization is successful, false - reparametrization is degenerate and reduced to linear. \~ */ - bool InitScaledEnds( double basisTMin, double basisTMax, double dt1, double dt2); + bool InitScaledEnds( double basisTMin, double basisTMax, double dt1, double dt2); public: // \ru Общие функции математического объекта \en Common functions of mathematical object virtual MbeFunctionType IsA() const; // \ru Тип элемента \en A type of element @@ -108,7 +108,7 @@ public: // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. virtual double Argument( double & val ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/func_sinus_function.h b/C3d/Include/func_sinus_function.h index 2a93ef0..0bb33ef 100644 --- a/C3d/Include/func_sinus_function.h +++ b/C3d/Include/func_sinus_function.h @@ -67,7 +67,7 @@ public: virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = c3d_null ); // \ru Изменить направление \en Change direction virtual double Step( double t, double sag ) const; virtual double DeviationStep( double t, double angle ) const; diff --git a/C3d/Include/function.h b/C3d/Include/function.h index 59e88eb..a92065c 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -41,6 +41,7 @@ enum MbeFunctionType { ft_PowerFunction = 6, ///< \ru Степенная функция. \en Power function. ft_SinusFunction = 7, ///< \ru Синусоидальная функция. \en Sinusoidal function. ft_ServeFunction = 8, ///< \ru Служебная функция. \en Service function. + ft_C2MonoSplineFunction= 9, ///< \ru Кубическая сплайновая функция. \en A cubic spline function. ft_CharacterFunction = 101, ///< \ru Символьная функция. \en A symbolic function. ft_AnalyticalFunction = 102, ///< \ru Символьная функция на модельном выражении. \en A symbolic function in model expression. @@ -130,9 +131,9 @@ public: \param[out] fir - \ru Производная. \en Derivative with respect to t. \~ \param[out] sec - \ru Вторая производная по t, если не ноль. - \en Second derivative with respect to t, if not NULL. \~ + \en Second derivative with respect to t, if not c3d_null. \~ \param[out] thr - \ru Третья производная по t, если не ноль. - \en Third derivative with respect to t, if not NULL. \~ + \en Third derivative with respect to t, if not c3d_null. \~ \ingroup Curves_3D */ virtual void Explore( double & t, bool ext, @@ -144,7 +145,7 @@ public: virtual double Argument( double & val ) const; /// \ru Изменить направление. \en Change direction. - virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; + virtual void Inverse( MbRegTransform * iReg = c3d_null ) = 0; /// \ru Вычислить шаг по прогибу для заданного параметра t. \en Calculate a step by the sag for a given parameter t. virtual double Step( double t, double sag ) const = 0; /// \ru Вычислить шаг по угловому отклонению для заданного параметра t. \en Calculate a step by the angular deviation for a given parameter t. @@ -191,6 +192,8 @@ public: virtual void GetCharacteristicParams( std::vector & tSpecific, double t1, double t2 ); /** \} */ + /// \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(); } /// \ru Находится ли параметр в области определения функции. \en Whether the parameter belongs to the function domain. diff --git a/C3d/Include/gce_api.h b/C3d/Include/gce_api.h index 7231e8d..33d1e7a 100644 --- a/C3d/Include/gce_api.h +++ b/C3d/Include/gce_api.h @@ -1,1926 +1,1926 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Программный интерфейс решателя геометрических ограничений. - \en Program interface of geometric constraints solver. \~ - \details \ru Программный интерфейс геометрического решателя представляет - собой набор типов данных и функций, необходимых для решения - задачи геометрических ограничений. Предметная область решателя - предусматривает такие типы, как "геометрический объект", - "геометрическое ограничение", "система ограничений". Базовые типы - решателя объявлены в заголовочном файле . Вызовы функций - и их аргументы подобраны таким образом, что бы наиболее удобно - осуществлять формулировку задачи для решателя в терминах объектов - и ограничений. Названия многих типов данных и вызовов API начинаются - префиксом GCE, сокращенно Geometric Constraint Engine. \n - - Функции API решателя можно подразделить на такие группы: - 1) Функции #GCE_CreateSystem, #GCE_ClearSystem, #GCE_RemoveSystem - позволяют создавать и удалять систему ограничений в целом - (должны вызываться в однопоточном режиме);\n - 2) С помощью функций вида GCE_Add_XXXXXXX осуществляется формулировка - задачи ограничений, с их помощью в систему добавляются объекты и - ограничения (могут использоваться в параллельном режиме);\n - 3) Функции вида GCE_Change_XXXXXXX, GCE_Set_XXXXXXX позволяют менять - размеры и состояние объектов (могут использоваться в параллельном режиме);\n - 4) Функции для запросов такие, как GCE_Get_XXXXXXX, #GCE_SplinePoint, - GCE_IsXXXXX, #GCE_PointDOF и т.д. позволяют осуществлять запросы - о состоянии объектов или их свойств, узнать степень свободы объектов - и прочие характеристики (могут использоваться в параллельном режиме);\n - 5) Метод #GCE_Evaluate вычисляет состояния системы ограничений, в котором - все ограничения удовлетворены, или возвращает код ошибки при невозможности - найти решение (должна вызываться в однопоточном режиме).\n - 6) Другая группа вызовов отвечает за способы управления недоопределенной - системой ограничений. Вызовы #GCE_PrepareDraggingPoint, #GCE_MovePoint - обеспечивают интерактивную манипуляцию объектами чертежа/эскиза.\n - - \en A program interface of geometric solver represents - a set of data types and functions necessary for solution - of a problem of geometric constraints. Subject area of the solver - provides such types as "geometric object", "geometric constraint", - "constraint system". Base types of the solver are declared in the header - file . Calls of functions and their arguments are chosen - in such way that the formulation of the problem for the solver in terms - of objects and constraints could be performed by the most convenient way. - The names of many data types and API calls begins with a prefix 'GCE', - abbreviation for Geometric Constraint Engine. \n - - API functions of solver can be subdivided into the following groups: - 1) Functions #GCE_CreateSystem, GCE_ClearSystem, GCE_RemoveSystem - allow to create and delete the system of constraints in general - (should be called in sequential code);\n - 2) The problems of constraints are formulated with a function of a kind GCE_Add_XXXXXXX, - by using them the objects and constraints are added to the system - (could be called in multi-threaded mode);\n - 3) Functions of a kind GCE_Change_XXXXXXX, GCE_Set_XXXXXXX allow to change dimensions - and objects states (could be called in multi-threaded mode);\n - 4) Functions for requests, such as #GCE_Get_XXXXXXX, #GCE_SplinePoint, - #GCE_IsXXXXX, #GCE_PointDOF etc, allow to perform requests - about the states of objects or their properties, find the objects degree of freedom - and other characteristics could be called in multi-threaded mode;\n - 5) The method #GCE_Evaluate calculates the state of the constraint system, where - all constraints are satisfied or returns an error code if it is not possible - to find a solution (should be called in sequential code). \n - 6) Other group of calls responses for the ways of control of underdetermined - system of constraints. Calls of #GCE_PrepareDraggingPoint, #GCE_MovePoint - provide interactive manipulation with objects of drawing/sketch.\n \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCE_API_H -#define __GCE_API_H - -#include -#include -#include - -class MATH_CLASS MbMatrix; -class MATH_CLASS MbCurve; - -/** - \addtogroup Constraints2D_API - \{ -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Создать пустую систему ограничений. - \en Create a simple constraint system. \~ - \details \ru Вызов создает пустую систему ограничений. Кроме того, в памяти - создаются внутренние структуры данных геометрического решателя, обслуживающего - систему ограничений. Функция возвращает специальный дескриптор, по которому - система ограничений доступна для различных манипуляций: добавление или удаление - геометрических объектов, ограничений, варьирование размеров, драггинг недоопределенных - объектов и т.д. - \en The call creates a simple constraint system. Besides, inside the memory - there are created internal data structures of geometric solver maintaining - the system of constraints. The functions returns a special descriptor by which - the constraint system is available for various manipulations: addition and deletion - of geometric objects, constraints, variation of sizes, dragging underconstrained objects - etc. \~ - - \return \ru Дескриптор системы ограничений. - \en Descriptor of constraint system. \~ -*/ -//--- -GCE_FUNC(GCE_system) GCE_CreateSystem(); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Сделать систему ограничений пустой. - \en Make the constraint system empty. \~ - \details \ru Данный метод делает систему ограничений пустой при этом - дескриптор gSys остается действительным, т.е. можно осуществлять дальнейшую - работу с системой ограничений. - \en This method makes the constraint system empty while - the descriptor gSys remains valid, i.e. it is possible to perform the further - work with the constraint system. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \sa #GCE_RemoveSystem -*/ -//--- -GCE_FUNC(void) GCE_ClearSystem( GCE_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить систему ограничений. - \en Delete system of constraints. \~ - \details \ru Данный метод освобождает память от внутренних структур данных, обслуживающих - систему ограничений. Удаляемая система ограничений становится недействительной после - данного вызова. - \en This method releases memory from internal data structures maintaining - the constraint system. The removed constraint system is invalidated after this call. - \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \sa #GCE_ClearSystem -*/ -//--- -GCE_FUNC(void) GCE_RemoveSystem( GCE_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений точку. - \en Add point to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pVal - \ru Координаты точки. - \en Point coordinates. \~ - \return \ru Дескриптор зарегистрированной точки. - \en Descriptor of registered point. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddPoint( GCE_system gSys, GCE_point pVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений прямую. - \en Add line to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] lVal - \ru Координаты прямой. - \en Line coordinates. \~ - \return \ru Дескриптор зарегистрированной прямой. - \en Descriptor of registered line. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddLine( GCE_system gSys, const GCE_line & lVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений отрезок прямой, заданный парой концевых точек. - \en Add a line segment specified by pair of end points to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] p - \ru Дескрипторы конечных точек отрезка. - \en Descriptors of end points of the line segment. \~ - \return \ru Дескриптор зарегистрированного отрезка. - \en Descriptor of registered segment. \~ - \details \ru Для отрезка, созданного через данный вызов, действительны все типы - ограничений, которые применимы для прямой, создаваемой вызовом GCE_AddLine. - \en All types of constraints which are applicable to the line created by GCE_AddLine - are valid for the segment created by this call. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddLineSeg( GCE_system gSys, geom_item p[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений окружность. - \en Add circle to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cVal - \ru Координаты окружности. - \en Coordinates of a circle. \~ - \return \ru Дескриптор зарегистрированной окружности. - \en Descriptor of the registered circle. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddCircle( GCE_system gSys, const GCE_circle & cVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений эллипс. - \en Add ellipse to the constraint system. \~ - \param[in] \ru gSys Система ограничений. - \en gSys System of constraints. \~ - \param[in] \ru eVal Координаты эллипса. - \en eVal Ellipse coordinates. \~ - \return \ru Дескриптор зарегистрированного эллипса. - \en Descriptor of registered ellipse. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddEllipse( GCE_system gSys, const GCE_ellipse & eVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений сплайн (NURBS) - \en Add spline (NURBS) to the constraint system \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] spl - \ru Координаты сплайна. - \en Spline coordinates. \~ - \return \ru Дескриптор зарегистрированного сплайна. - \en Descriptor of registered spline. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddSpline( GCE_system gSys, const GCE_spline & spl ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений параметрическую кривую. - \en Add parametric curve to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] crv - \ru Математическое описание параметрической кривой. - \en Mathematical description of parametric curve. \~ - \return \ru Дескриптор зарегистрированной параметрической кривой. - \en Descriptor of registered parametric curve. \~ - \attention \ru Время жизни экземпляра класса crv опирается на счетчик ссылок, т.е. - решатель его увеличивает при добавлении параметрической кривой и - декрементирует при удалении кривой из решателя. - \en The lifetime of the instance of the class 'crv' is based on the reference counter, i.e. - the solver increases it when adding a parametric curve and - decreases when deleting a curve from the solver. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddParametricCurve( GCE_system gSys, const MbCurve & crv ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему граничную кривую, ограниченную парой точек. - \en Add a curve bounded by a pair of points to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] crv - \ru Дескриптор базовой геометрической кривой. Базовой кривой может - быть только кривая одного из следующих типов: прямая, окружность, - эллипс, сплайн или параметрическая кривая. - \en Descriptor of base geometric curve. Base curve may - be only one curve from the following types: line, circle, - ellipse, spline or parametric curve. \~ - \param[in] p - \ru Пара дескрипторов начальной и конечной точек участка кривой. - \en A pair of descriptors of the beginning and ending points of curve piece. \~ - \return \ru Дескриптор зарегистрированной ограниченной кривой. - \en Descriptor of registered bounded curve. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_AddBoundedCurve( GCE_system gSys, geom_item curve, geom_item p[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему жёсткое множество геометрических объектов. - \en Add a rigid set of geometric objects to the system. \~ - \details \ru Жёсткое множество - это массив геометрических объектов, зафиксированных друг относительно друга. - Жёсткое множество представляет собой геометрический объект, для которого доступен весь функционал - работы с геометрическими объектами. Например, у него можно спросить тип (#GCE_GeomType -> GCE_SET) или запросить - положение. С помощью вызовов #GCE_GetPoint и #GCE_GetCoordValue можно получить начало координат и направление оси OX - ЛСК жёсткого множества. Чтобы удалить жёсткое множество, надо, как и для любого другого геометрического объекта, - вызвать функцию #GCE_RemoveGeom. При этом составляющие жёсткое множество объекты (geoms) при удалении жёсткого - множества не удаляются и могут далее быть использованы в решателе. С геометрическими объектами, образующими - жёсткое множество, нужно работать точно так же, как и до их добавления в жёсткое множество. Например, для наложения - ограничения между элементом жёсткого множества и любым другим геометрическим объектом необходимо в - качестве аргумента ограничения указывать не дескриптор жёсткого множества, которому данный объект принадлежит, а - дескриптор самого геометрического объекта из массива geoms, на который накладывается ограничение. - \en A rigid set is an array of geometric objects which are fixed relative to each other. It is considered as a - geometric object and hence all the functionality for working with geometric objects is available for it. For - example, it's possible to request its type (#GCE_GeomType -> GCE_SET) or get its position invoking #GCE_GetPoint - and #GCE_GetCoordValue to get the origin and the direction of the OX axis of the LCS of the rigid set. To remove - a rigid set it's necessary to call the function #GCE_RemoveGeom. Geometric objects (geoms) are not deleted together - with a rigid set and can be used in the solver after it will be deleted. With geometric objects that have been - included in a rigid set it is necessary to continue to work just as before adding them to a rigid set. For - instance, to specify a constraint between an element of a rigid set and any other geometric object, it is necessary - to specify as the constraint argument not the descriptor of the rigid set to which the object belongs but the - descriptor of the geometric object from the geoms array on which the constraint is specified.\~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] geoms - \ru Массив дескрипторов геометрических объектов, образующих жёсткое множество. - \en \~ - \return \ru Дескриптор зарегистрированного жёсткого множества объектов. - \en Descriptor of registered bounded curve. \~ -*/ -// --- -GCE_FUNC(geom_item) GCE_AddRigidSet( GCE_system gSys, const std::vector & geoms ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений переменную. - \en Add a variable to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] val - \ru Начальное значение переменной. - \en A start value of the variable. \~ - \return \ru Дескриптор зарегистрированной переменной. - \en Descriptor of registered variable. \~ -*/ -//--- -GCE_FUNC(var_item) GCE_AddVariable( GCE_system gSys, double val ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Тип геометрического объекта. - \en A type of geometric object. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \return \ru Тип геометрического объекта. - \en A type of geometric object. \~ -*/ -//--- -GCE_FUNC(geom_type) GCE_GeomType( GCE_system gSys, geom_item g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Тип геометрической кривой. - \en A type of geometric curve. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор кривой. - \en Descriptor of curve \~ - \return \ru Тип геометрического объекта. - \en A type of geometric object. \~ - \details \ru The function returns geometric type of a curve 'crv' or type - of a base curve if 'crv' has type #GCE_BOUNDED_CURVE. - \en Функция вернет геометрический тип кривой 'crv' либо тип базовой кривой, - если 'crv' имеет тип #GCE_BOUNDED_CURVE. \~ -*/ -//--- -GCE_FUNC(geom_type) GCE_BaseCurveType( GCE_system gSys, geom_item crv ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить переменную из системы ограничений. - \en Delete variable from the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] var - \ru Дескриптор переменной. - \en Descriptor of variable. \~ - \return \ru true, если переменная var действительно удалена. - \en it equals true if the variable var is actually deleted. \~ -*/ -//--- -GCE_FUNC(bool) GCE_RemoveVariable( GCE_system gSys, var_item var ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить геометрический объект из системы ограничений. - \en Delete geometric object from the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \return \ru true, если геометрический объект g действительно удален. - \en it equals true if the geometric object g is actually deleted. \~ -*/ -//--- -GCE_FUNC(bool) GCE_RemoveGeom( GCE_system gSys, geom_item g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить ограничение из системы. - \en Delete a constraint from the system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] con - \ru Дескриптор ограничения. - \en Descriptor of constraint. \~ - \return \ru true, если ограничение con действительно удалено. - \en it equals true if the constraint con is actually deleted. \~ -*/ -//--- -GCE_FUNC(bool) GCE_RemoveConstraint( GCE_system gSys, constraint_item con ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Запросить дескриптор контрольной точки объекта. - \en Request of the object control point descriptor. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор объекта. - \en Descriptor of object. \~ - \param[in] pnt - \ru Имя контрольной точки объекта. - \en Name of the object control point. \~ - \return \ru Дескриптор контрольной точки объекта. - \en Descriptor of the object control point. \~ - - \details \ru Дескриптор, полученный по значению этой функции, имеет автоматическое - время жизни, т.е. нет необходимости вызывать для него метод #GCE_RemoveGeom. - \en Descriptor obtained by the value of this function, it has automatical - lifetime, i.e. there is no reason to call the method #GCE_RemoveGeom for it. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_PointOf( GCE_system gSys, geom_item g, point_type pnt ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Дескриптор контрольной точки сплайна по индексу. - \en Descriptor of spline control point by index \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] spl - \ru Дескриптор сплайна. - \en Descriptor of spline. \~ - \param[in] pntIdx - \ru Индекс контрольной точки. - \en A control point index. \~ - \return \ru Дескриптор контрольной точки сплайна. - \en Descriptor of spline control point. \~ - - \details \ru Дескриптор, полученный по значению этой функции, имеет автоматическое - время жизни, т.е. нет необходимости вызывать для него метод #GCE_RemoveGeom. - \en Descriptor obtained by the value of this function, it has automatical - lifetime, i.e. there is no reason to call the method #GCE_RemoveGeom for it. \~ -*/ -//--- -GCE_FUNC(geom_item) GCE_SplinePoint( GCE_system gSys, geom_item spl, size_t pntIdx ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить текущие координаты вектора. - \en Get the current coordinates of vector. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор вектора или иного геометрического объекта. - \en Descriptor of vector or other geometric object. \~ - \param[in] vType - \ru Идентификатор вектора, принадлежащего объекту (в настоящий момент равен или GCE_DIRECTION, или GCE_ORIENTATION). - GCE_DIRECTION возвращает направляющую прямой, отрезка или главной полуоси эллипса. - \en Identifier of vector belonging to the object (currently it equals GCE_DIRECTION or GCE_ORIENTATION). - In case of GCE_DIRECTION function returns direction vector for line, line segment or ellipse major axis.\~ - \return \ru Координаты вектора. - \en Vector coordinates. \~ -*/ -//--- -GCE_FUNC(GCE_vec2d) GCE_GetVectorValue( GCE_system gSys, geom_item g, query_geom_type vType ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить текущие координаты точки. - \en Get the current coordinates of point. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор точки или иного геометрического объекта. - \en Descriptor of point or other geometric object. \~ - \param[in] pName - \ru Идентификатор точки, принадлежащей объекту. - \en Identifier of a point belonging to the object. \~ - \return \ru Координаты точки. - \en Point coordinates \~ -*/ -//--- -GCE_FUNC(GCE_point) GCE_GetPointXY( GCE_system gSys, geom_item g, point_type pName = GCE_PROPER_POINT ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить текущее значение координаты геометрического объекта. - \en Get the current value of geometric object's coordinate. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор объекта. - \en Descriptor of object. \~ - \param[in] cName - \ru Обозначение параметра объекта. - \en Denotation of object parameter. \~ - \return \ru Координаты точки. - \en Point coordinates \~ - \details \ru Получить текущее значение координаты геометрического объекта. Например, - с помощью данной функции можно узнать текущее значение большой или малой - полуоси эллипса, радиус окружности и т.д. - \en Get the current value of geometric object's coordinate. For example, - by using this function one can find the current value of the major or the minor - semi-axis of ellipse, circle radius etc. \~ -*/ -//--- -GCE_FUNC(double) GCE_GetCoordValue( GCE_system gSys, geom_item g, coord_name cName ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить текущее значение переменной. - \en Get the current value of variable. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] var - \ru Дескриптор переменной. - \en Descriptor of variable. \~ - \return \ru Значение переменной. - \en A value of variable. \~ -*/ -//--- -GCE_FUNC(double) GCE_GetVarValue( GCE_system gSys, var_item var ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать текущие координаты точки. - \en Set the current coordinates of point. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор точки или иного геометрического объекта. - \en Descriptor of point or other geometric object. \~ - \param[in] pName - \ru Идентификатор точки, принадлежащей объекту. - \en Identifier of a point belonging to the object. \~ - \param[in] xyVal - \ru Новое значение координат точки. - \en New value of point coordinates. \~ - \return \ru true, если операция выполнена успешно. - \en true if operation succeeded. \~ - - \details \ru Метод присваивает точке или контрольной точке объекта g c - атрибутом pName новое состояние координат (параметр xyVal). Следует учитывать, - что вызов #GCE_SetPointXY не решает системы ограничений, а только меняет состояние - геометрического объекта. При этом система ограничений может стать неудовлетворенной. - Состояние точки, присвоенное вызовом GCE_SetPointXY не обязано сохранятся после - вызова #GCE_Evaluate, если точка не фиксированная или не замороженная. - \en The method assigns to the point or the control point of the object g with - the attribute pName a new state of coordinates (the parameter xyVal). It should be taken into account - that the call of #GCE_SetPointXY doesn't solve the constraint system but only changes the state - of geometric object. At the same time the constraint system may become unsatisfied. - The state of a point assigned by the call of GCE_SetPointXY should not be saved after - the call of #GCE_Evaluate if the point is not fixed or not frozen. \~ -*/ -//--- -GCE_FUNC(bool) GCE_SetPointXY( GCE_system gSys, geom_item g, point_type pName, GCE_point xyVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать текущее значение координаты геометрического объекта. - \en Set the current value of geometric object's coordinate. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор объекта. - \en Descriptor of object. \~ - \param[in] cName - \ru Обозначение параметра объекта. - \en Denotation of object parameter. \~ - \param[in] crdVal - \ru Новое значение координаты. - \en New value of coordinate. \~ - \return \ru true, если операция выполнена успешно. - \en true if operation succeeded. \~ - - \details \ru Метод присваивает координате объекта g c атрибутом cName новое значение. - Следует учитывать, что вызов #GCE_SetCoordValue не решает системы ограничений, - а только меняет состояние геометрического объекта. При этом система ограничений - может стать неудовлетворенной. Состояние координаты, присвоенное этим методом - не обязано сохранятся после вызова #GCE_Evaluate, если точка не фиксированная - или не замороженная. - \en The method assigns a new value to the coordinate of the object g with the attribute cName. - It should be taken into account that the call of #GCE_SetCoordValue doesn't solve the constraint system - but only changes the state of geometric object. At the same time the constraint system - may become unsatisfied. The state of coordinate assigned by this method - should not be saved after the call of #GCE_Evaluate if the point is not fixed - or not frozen. \~ -*/ -//--- -GCE_FUNC(bool) GCE_SetCoordValue( GCE_system gSys, geom_item g, coord_name cName, double crdVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать текущее значение переменной. - \en Set the current value of variable. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] var - \ru Дескриптор переменной. - \en Descriptor of variable. \~ - \param[in] val - \ru Новое значение переменной. - \en New value of variable. \~ - \return \ru true, если операция выполнена успешно. - \en true if operation succeeded. \~ -*/ -//--- -GCE_FUNC(bool) GCE_SetVarValue( GCE_system gSys, var_item var, double val ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Заморозить геометрический объект. - \en Freeze geometric object. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Геометрический объект. - \en Geometric object. \~ - \return \ru true, если операция выполнена успешно. - \en true if operation succeeded. \~ - - \details - - \ru Функция лишает объект всей степени свободы. Отдельно можно заметить, что - функция GCE_IsConstrainedGeom для замороженного объекта вернет false, если - объект не был связан другими ограничениями. Т.е. заморозка не считается - ограничением.\n - Решатель не может менять замороженную геометрию, но её может поменять - клиентское приложение методами GCE_SetCoordValue или GCE_SetPointXY. - Замороженные объекты следует рассматривать в качестве независимых входных - параметров системы ограничений. - - \en The function deprives the object of all degrees of freedom. Note that - the function GCE_IsConstrainedGeom returns false for the frozen object if - the object was not connected with other constraints. I.e. the freezing is not considered - as a constraint.\n - The solver cannot change the frozen geometry but the user application can change it - with the methods GCE_SetCoordValue or GCE_SetPointXY. Frozen objects should be - considered as independent input parameters of constraint system. \~ - - \note - \ru Обычно на стороне САПР эта команда применяется для фиксации проекционной геометрии - в ассоциативных чертежах или в эскизах с проекциями трехмерных объектов. - \en Usually, in CAD applications this command is used only for fixation of projection - geometry in associative drawings or sketches with projections of 3D-objects. \~ -*/ -//--- -GCE_FUNC(bool) GCE_FreezeGeom( GCE_system gSys, geom_item g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Функция отвечает на вопрос: Связан ли геометрический объект ограничениями? - \en The function answers the question: Is geometric object connected with constraints? \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object. \~ - \return \ru true, если для объекта g задано хотя бы одно ограничение. - \en true if at least one constraint is set for the object g. \~ - \sa GCE_RemoveGeom, GCE_RemoveConstraint -*/ -//--- -GCE_FUNC(bool) GCE_IsConstrainedGeom( GCE_system gSys, geom_item g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выполнить проверку удовлетворенности ограничения. - \en Perform a check that a constraint is satisfied. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cItem - \ru Дескриптор ограничения. - \en Descriptor of constraint. \~ - \return \ru true, если ограничение удовлетворено. - \en true if a constraint is satisfied. \~ -*/ -//--- -GCE_FUNC(bool) GCE_IsSatisfied( GCE_system gSys, constraint_item cItem ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Статус ограничения в системе. - \en Status of constraint inn the system. - \details - \ru Вызов показывает результат диагностики, которая выделяет в системе ограничений - хорошо-обусловленные части и части, содержащие переопределения и противоречия. В результате - диагностики или попытки решения каждое ограничение помечается одним из статусов, - перечисленных в наборе GCE_c_status. - - \en The call shows the result of the diagnostic, which highlights the constraint system - well-conditioned parts and parts containing redundancies and inconsistencies. As a result - diagnosing or evaluating each constraint is marked with one of the statuses enumerated by - GCE_c_status enum. - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cItem - \ru Дескриптор ограничения. - \en Descriptor of constraint. \~ - \return \ru Статус ограничения в результате диагностики на противоречия или переопределения. - \en The status of the constraint as a result of diagnostics on inconsistence and overdefining. \~ - -*/ -// --- -GCE_FUNC(GCE_c_status) GCE_ConstraintStatus( GCE_system gSys, constraint_item cItem ); - -//---------------------------------------------------------------------------------------- -/** - brief \ru Выполнить диагностику геометрических объектов. - \en Diagnose geometry. \~ - \details - \ru Если в ходе решения системы ограничений вырождаются какие-то геометрические объекты - (функция #GCE_Evaluate возвращает GCE_RESULT_InvalidGeometry ), то данная функция возвращает - массив индексов, под которыми эти объекты зарегистрированы в решателе. - Если вырождающихся объектов нет, то функция вернет пустой массив. - \en If some geometrical objects are degenerate in the course of solving the system of constraints - (function #GCE_Evaluate returns GCE_RESULT_InvalidGeometry ), this function returns an array of indices - by which these geometric objects are registered in the solver. - If geometrical objects do not degenerate, then the function returns an empty array. \~ - \param[in] gcSys - \ru Система ограничений. - \en System of constraints. \~ - \return \ru Вектор индексов объектов с вырожденной геометрией. - \en Vector of indices of objects with invalid geometry. \~ -*/// --- -GCE_FUNC(std::vector) GCE_DiagnoseGeometry( GCE_system gcSys ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Вычислить степень свободы точки. - \en Calculate point's degree of freedom. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \param[in] cp - \ru Код контрольной точки объекта g. - \en The code of control point of the object g. \~ - \param[out] dofDir- \ru Угловое направление свободы перемещения точки в радианах. - \en Angular direction of point moving freedom in radians. \~ - \return \ru Функция возвращает степень свободы точки; Если возвращается значение < 0, - то вычислить степень свободы не удалось. - \en The function returns degree of freedom of the point; If a negative value is returned, - then it is failed to calculate the degree of freedom. \~ - - \details \ru Данная функция возвращает степень свободы точки и может принимать - одно из следующих значений:\n - (-1) - Означает, что функция не определила степень свободы;\n - 0 - Означает, что точка неподвижна в системе ограничений;\n - 1 - Означает, что точка имеет свободу перемещения вдоль некоторой траектории, причем - через параметр dofDir возвращается направление тангенциального вектора перемещения - точки;\n - 2 - Означает, что точка имеет свободу перемещения в некоторой 2D-области.\n - Если направление перемещения определить не удалось, то dofDir принимает значение < 0. - - \en This function returns the point's degree of freedom and may take - one of the following values:\n - (-1) - It means that the function didn't determine the degree of freedom;\n - 0 - It means that the point is fixed in constraint system. - 1 - It means that the point has a freedom of movement along some trajectory, besides - the direction of point movement tangent vector is returned via the parameter dotDir;\n - 2 - It means that the point has a movement freedom inside some two-dimensional region.\n - If the direction of movement was not determined, then dotDir takes a negative value. \~ -*/ -//-- -GCE_FUNC(ptrdiff_t) GCE_GetPointDOF( GCE_system gSys, geom_item g, point_type cp, double & dofDir ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Вычислить степень свободы точки. - \en Calculate point's degree of freedom. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pnt - \ru Дескриптор точки. - \en Descriptor of point \~ - \param[out] dofDir- \ru Угловое направление свободы перемещения точки в радианах. - \en Angular direction of point moving freedom in radians. \~ - \return \ru Функция возвращает структуру #GCE_point_dof, которая описывает - степень свободы точки, её целочисленное значение и вектор перемещения. - Если возвращается значение dof < 0, то вычислить степень свободы не удалось. - \en The function returns a structure #GCE_point_dof, which describes degree - of freedom of the point, namely its integral value (dof) and direction - vector of point moving freedom (dir). If a negative value (dof) is returned, - then it is failed to calculate the degree of freedom. \~ - - \details \ru Данная функция возвращает степень свободы точки и может принимать - одно из следующих значений:\n - dof = (-1) - Означает, что функция не определила степень свободы;\n - dof = 0 - Означает, что точка неподвижна в системе ограничений;\n - dof = 1 - Означает, что точка имеет свободу перемещения вдоль некоторой траектории, - причем через параметр "dir" (в структуре #GCE_point_dof ) возвращается направление - тангенциального вектора перемещения точки;\n - dof = 2 - Означает, что точка имеет свободу перемещения в некоторой 2D-области.\n - Если направление перемещения определить не удалось, то "dof" принимает значение < 0. - - \en This function returns the point's degree of freedom and may take - one of the following values:\n - dof = (-1) - It means that the function didn't determine the degree of freedom;\n - dof = 0 - It means that the point is fixed in constraint system. - dof = 1 - It means that the point has a freedom of movement along some trajectory, besides - the direction of point movement tangent vector is returned via the parameter "dir" - of data structure #GCE_point_dof;\n - dof = 2 - It means that the point has a movement freedom inside some two-dimensional region.\n - If the direction of movement was not determined, then "dof" takes a negative value. \~ -*/ -//-- -GCE_FUNC(GCE_point_dof) GCE_PointDOF( GCE_system gSys, geom_item pnt ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать степень свободы геометрической координаты. - \en Get the degree of freedom of geometric coordinate. - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of a geometric object. \~ - \param[in] cName - \ru Обозначение геометрической координаты. - \en Denotation of geometric coordinate. \~ - \return \ru Степень свободы координаты: 1-для недоопределенной координаты, 0-для полно-заданной координаты. - \en Degree of freedom: 1 for underdefined coordinate, 0 for well-defined coordinate.\~ - - \details - \ru Функция возвращает степень свободы координаты, а именно одно из возможных - значений: 1, 0 и -1. Если возвращается значение < 0, то вычислить степень - свободы не удалось. - \en The function returns degree of freedom of the coordinate, namely one of the - possible values: 1, 0 and -1. If a negative value is returned, then it is - failed to calculate the degree of freedom. \~ - -*/ -//--- -GCE_FUNC(int) GCE_CoordDOF( GCE_system gSys, geom_item g, coord_name cName ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение для одного объекта (унарное ограничение). - \en Set a constraint on single object (unary constraint). \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cType - \ru Значение одного из следующих типов ограничений: GCE_FIX_GEOM; GCE_VERTICAL; GCE_HORIZONTAL; GCE_ANGLE_OX; GCE_LENGTH. - \en The value of one of the following types of constraints: GCE_FIX_GEOM; GCE_VERTICAL; GCE_HORIZONTAL; GCE_ANGLE_OX; GCE_LENGTH. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details - \ru Функция задает унарное ограничение, а именно ограничение, относящееся к одному из типов, - действительных для одного геометрического объекта. - \en The function specifies an unary constraint, namely constraint which has one of types - that are valid for single geometric object. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddUnaryConstraint( GCE_system gSys, constraint_type cType, geom_item geom ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Совпадение". - \en Set the constraint "Coincidence". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары геометрических объектов. - \en Descriptors of geom objects pair. \~ - \details - \ru Если ограничение совпадение задано для точки и кривой, то предполагается, что точка - лежит на кривой. Если совпадение задано для геометрических объектов одного и того - же типа, то совпадение подразумевает, что они равны. - \en If a coincident constraint is defined between a point and a curve then this implies - that the point lies on the curve. A coincident constraint defined between two - geometries of the same type implies that they are equal. - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \attention - \ru В текущей версии решателя применение этого ограничения возможно - только для двух точек либо для точки и кривой. На будущее планируется расширить - его применения для других типов. - \en In the current version of solver using of this constraint is possible only for - two points either for a point and a curve. It is planned to extend its application - area for other types. \~ -*/ -// --- -GCE_FUNC(constraint_item) GCE_AddCoincidence( GCE_system gSys, geom_item g[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Ограничение "Точка на участке кривой по коэффициенту его параметрической длины". - \en The constraint "Point on a piece of a curve by the coefficient of its parametric range". \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curve - \ru Дескриптор кривой. - \en Descriptor of a curve. \~ - \param[in] pnt - \ru Дескрипторы точек: две крайние точки участка и точка между. - \en Descriptors of points: two boundary points of a piece and a point between. \~ - \param[in] k - \ru Долевой коэффициент от параметрической длины участка. - \en Coefficient for a part of parametric range of piece. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \details \ru Предполагается, что для кривой curve и точек pnt[0], pnt[1], обеспечивается - инцидентность другими ограничениями, зарегистрированными в решателе, или эти - точки априори принадлежат кривой. Для точки pnt[2] инцидентность с кривой задавать - не требуется, т.к. данное ограничение уже обеспечивает это. Если pnt[0] = pnt[1] = GCE_NULL_G, то участок - кривой, для которого исчисляется процент k, совпадает со всей параметрической - областью кривой. Например, для окружности параметрическая область равна - интервалу [-PI ... PI]. Область значений k из интервала от 0 до 1 отображается - на параметрическую область участка кривой, соответственно k = 0 прикрепит точку - pnt[2] к началу участка, а k = 1.0 к концу участка. - - \en It is assumed that for the curve 'curve' and the points pnt[0], pnt[1] an incidence - is provided with the other constraints registered in solver or these - points a priori belong to a curve. An incidence between pnt[2] and 'curve' is not required because - this constraint already provides an incidence. If pnt[0] = pnt[1] = GCE_NULL_G, then the piece - of a curve for which the percentage k is calculated coincides with the whole parametric - region of a curve. For example, in a case of circle the parametric range is equal - to the interval [-PI ... PI]. The range of values of k from the interval from 0 to 1 is mapped - to the parametric region of curve's piece, k = 0 attaches the point - pnt[2] to the beginning of the piece and k = 1.0 - to the end of the piece. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddPointOnPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], double k ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Ограничение "Точка на участке кривой по коэффициенту его длины". - \en The constraint "Point on a piece of a curve by the coefficient of its length". \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curve - \ru Дескриптор кривой. - \en Descriptor of a curve. \~ - \param[in] pnt - \ru Дескрипторы точек: две крайние и точка между ними. - \en Descriptors of points: two boundary points and a point between them. \~ - \param[in] k - \ru Значение доли от метрической длины между заданными точками. - \en Value of a part (proportion) of the arc length between the two points. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \details \ru Метод создает в системе ограничение, задающее положение точки на - участке кривой, заданное коэффициентом от его длины. Предполагается, - что для кривой curve и точек pnt[0], pnt[1], обеспечивается инцидентность другими, - зарегистрированными в решателе, ограничениями или эти точки априори принадлежат - кривой. Если pnt[0] = pnt[1] = GCE_NULL_G, то участок кривой, для которого - исчисляется процент k, совпадает со всей параметрической областью кривой. - Например, для окружности параметрическая область равна интервалу [-PI ... PI]. - Если k = 0, то ограничение прикрепит точку pnt[2] к началу участка, если k = 1.0, - то ограничение прикрепит точку pnt[2] к концу участка. - - \en The method creates a constraint specifying the point location on - a piece of a curve which is set by the coefficient (proportional) of its arc length. - It is assumed that for the curve 'curve' and the points pnt[0], pnt[1] an incidence - is provided with the other constraints registered in the solver or these points belong to - the curve a priori. If pnt[0] = pnt[1] = GCE_NULL_G, then the piece of a curve for which - the percentage k is calculated coincides with the whole parametric region of a curve. - For example, in a case of circle the parametric range is equal to the interval [-PI ... PI]. - If k = 0, then the constraint attaches the point pnt[2] to the beginning of the piece, if k = 1.0, - then the constraint attaches the point pnt[2] to the end of the piece. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddPointByMetricPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], double k ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Фиксация положения точки, лежащей на кривой". - \en Set the constraint "Fixation of location of the point lying on a curve". \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curve - \ru Дескриптор кривой. - \en Descriptor of a curve. \~ - \param[in] pnt - \ru Дескрипторы точки. - \en Descriptors of a point. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \details \ru Данная функция создает ограничение, прикрепляющее точку к кривой в текущем - месте. Точка локализуется, опираясь на параметрическое представление кривой, с помощью - параметра вдоль кривой, где она расположена. Требуется, что бы к моменту вызова функции, - точка лежала на кривой, а для точки и кривой curve должна обеспечиваться инцидентность - с помощью других ограничений или эта точка априори должна принадлежать кривой. - \en This function creates a constraint attaching a point to the curve in the current - location. The point is localized according to the parametric representation of a curve with a help of - parameter along a curve where it is located. It is required that at the moment when the function is called - the point is lying on the curve, and coincidence between the point and the curve should be provided - by other constraints or this point should belong to the curve a priori. \~ - - \attention \ru В Cad-системе КОМПАС данная функция применяется только для фиксации концов - участка (bounded curve) параметрической кривой, полученной проецированием из 3D-модели. - Для таких ограничений, как "средняя точка" рекомендуется применять более - нативную функцию #GCE_AddMiddlePoint. - \en In CAD system KOMPAS this function is used only for fixation of ends of - a piece ('bounded curve') of a parametric curve obtained by projecting from 3D model. - It is recommended to apply the more native function - #GCE_AddMiddlePoint for such constraints as "middle point". \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddFixCurvePoint( GCE_system gSys, geom_item curve, geom_item pnt ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Точка на параметрическом эллипсе". - \en Set the constraint "Point on parametric ellipse". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pnt - \ru Дескриптор точки. - \en Descriptor of a point. \~ - \param[in] ellipse - \ru Дескриптор эллипса. - \en Descriptor of ellipse. \~ - \param[in] \ru t Значение параметра на эллипсе из области [-PI,PI]. - \en t The value of parameter on ellipse from the region [-PI,PI]. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Данная функция действительна только для кривых, относящихся типу - "эллипс", функция создает ограничение, обеспечивающее совпадение точки pnt с - точкой эллипса, заданной параметром t из параметрической области эллипса, - равной интервалу [-PI,PI]. - \en This function is valid only for curves of the type - "ellipse", the function creates a constraint which provides coincidence between the point pnt and - the ellipse point set by the parameter t from the ellipse parametric region - which is equal to the interval [-PI,PI]. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddPointOnParEllipse( GCE_system gSys, geom_item pnt, geom_item ellipse, double t ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Точка на кривой по параметру". - \en Specify a constraint "Point on curve at a given parameter". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pnt - \ru Дескриптор точки. - \en Descriptor of a point. \~ - \param[in] curve - \ru Дескриптор кривой. - \en Descriptor of a curve. \~ - \param[in] t - \ru Дескриптор параметра кривой. - \en Descriptor of a curve parameter. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Функция отличается от #GCE_AddCoincidence тем, что позволяет связать точку с параметрической - кривой через значение параметра и управлять её положением на кривой через этот параметр. - Ограничение доступно для следующих типов кривой: #GCE_ELLIPSE, #GCE_SPLINE, - #GCE_PARAMETRIC_CURVE и #GCE_BOUNDED_CURVE, основанной на кривой одного из перечисленных - типов. - \en This function differs from #GCE_AddCoincidence in that it allows to link a point with a - parametric curve through a parameter value and control its position on the curve through this - parameter. The constraint is available for the following curve types: #GCE_ELLIPSE, - #GCE_SPLINE, #GCE_PARAMETRIC_CURVE and #GCE_BOUNDED_CURVE, based on the curve of one of the - listed types. -*/ -// --- -GCE_FUNC(constraint_item) GCE_AddParPointOnCurve( GCE_system gSys, geom_item pnt, geom_item curve, var_item t ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Выравнивание точек вдоль заданного направления". - \en Set the constraint "Alignment of points along the given direction". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] p - \ru Дескрипторы пары точек. - \en Descriptors of point pair. \~ - \param[in] ang - \ru Угол, задающий направление выравнивания, радианы. - \en An angle specifying alignment direction, in radians. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddAlignPoints( GCE_system gSys, geom_item p[2], double ang ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Угловой размер между двумя прямыми". - \en Set the constraint "Angular dimension between two lines". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] l1 - \ru Дескриптор первого линейного геометрического объекта. - \en Descriptor of the first linear geometric object. \~ - \param[in] l2 - \ru Дескриптор второго линейного геометрического объекта. - \en Descriptor of the second linear geometric object. \~ - \param[in] dPars - \ru Параметры углового размера (подробности см.#GCE_adim_pars). - \en Parameters of angular dimension (see #GCE_adim_pars). \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Угловой размер для пары линейных геометрических объектов. Аргументами - ограничения могут быть объекты, принадлежащие типам: "прямая", "отрезок" или - "Bounded curve", основанной на прямой. - \en Angular dimension for a pair of linear geometric objects. Arguments - of constraint are objects of the following types: "line", "segment" or - "Bounded curve" based on line. \~ - -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddAngle( GCE_system gSys, geom_item l1, geom_item l2 - , const GCE_adim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Биссектриса". - \en Set the constraint "Bisector of angle". \~ - \param[in] \ru gSys Система ограничений. - \en gSys System of constraints. \~ - \param[in] \ru bl отрезок, биссектриса между двумя прямыми. - \en bl a segment, bisector of angle between two lines. \~ - \param[in] \ru l1, l2 прямые или отрезки, между которыми устанавливается биссектриса. - \en l1, l2 lines or segments a bisector of angle is set between. \~ - \param[in] \ru variant вариант решения для биссектрисы. - \en variant variant of solution for bisector of angle. \~ - \return \ru дескриптор нового ограничения. - \en descriptor of new constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddAngleBisector( GCE_system gSys - , geom_item l1, geom_item l2 - , geom_item bl - , GCE_bisec_variant variant ); - -//---------------------------------------------------------------------------------------- -/// \ru Задать угловой размер для четырех точек. \en Specify angular dimension for four points. -/**\ru Конструируется угловой размер для двух отрезков с точками p1-p2, p3-p4. - \en Angular dimension is constructed for two segments with points p1-p2, p3-p4. \~ - \param[in] \ru gSys - Система ограничений. - \en gSys - System of constraints. \~ - \param[in] \ru fPair - Первая пара точек (первый отрезок). - \en sPair - First pair of points (first segment).\~ - \\param[in] \ru fPair - Вторая пара точек (второй отрезок). - \en sPair - Second pair of points (second segment).\~ - \param[in] dPars - \ru Параметры углового размера (подробности см.#GCE_adim_pars). - \en Parameters of angular dimension (see #GCE_adim_pars). \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddAngle4P( GCE_system gSys, geom_item fPair[2] - , geom_item sPair[2], const GCE_adim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Коллинеарность". - \en Set the constraint "Colinearity". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары линейных объектов. - \en Descriptors of a pair of linear objects. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Ограничение делает пару объектов, принадлежащими общей прямой, применяется - для прямых или отрезков. - \en Constraint makes a pair of objects belonging to the common line, it is used - for lines or segments. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddColinear( GCE_system gSys, geom_item g[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Коллинеарность трех точек". - \en Set the constraint "Colinearity of three points". \~ - \details \ru Задать для трех точек отношение, такое что точки лежат на одной прямой. - \en Set such a constraint for three points that points should lie on the same line. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pnt - \ru Тройка точек, лежащих на одной прямой. - \en A triplet of points lying on the same line. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddColinear3Points( GCE_system gcSys, geom_item pnt[3] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Равенство длин" для отрезков. - \en Set the constraint "Equality of lengths" for segments. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] ls1 - \ru Дескриптор первого отрезка. - \en Descriptor of the first segment. \~ - \param[in] ls2 - \ru Дескриптор второго отрезка. - \en Descriptor of the second segment. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Ограничение применимо для отрезков или участков прямых, созданных с помощью - функции #GCE_AddBoundedCurve или #GCE_AddLineSeg. - \en The constraint is applicable for segments or line pieces created by - the function #GCE_AddBoundedCurve or #GCE_AddLineSeg. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddEqualLength( GCE_system gSys, geom_item ls1, geom_item ls2 ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Равенство радиусов" для двух окружностей (дуг) - \en Set the constraint "Equality of radii" for two circles (arcs) \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] c1 - \ru Дескриптор первой окружности. - \en Descriptor of the first circle. \~ - \param[in] c2 - \ru Дескриптор второй окружности. - \en Descriptor of the second circle. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddEqualRadius( GCE_system gSys, geom_item c1, geom_item c2 ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Равенство кривизны двух кривых в заданных точках". - \en Specify a constraint "Equality of curvature of two curves at given points". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curves - \ru Дескрипторы пары кривых. - \en Descriptors of a pair of curves. \~ - \param[in] tPars - \ru Дескрипторы параметров параметрических кривых, в которых должно выполняется - равенство кривизны. - \en Descriptors of parameters of parametric curves in which the equality of curvature - must be satisfied. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \note \ru Если тип кривой #GCE_CIRCLE или #GCE_BOUNDED_CURVE, базовой кривой которой является окружность, - то соответствующее этой кривой значение tPars[i] может равняться #GCE_NULL_V, т.к. кривизна - окружности одинакова во всех её точках. - \en If curve has a type #GCE_CIRCLE or #GCE_BOUNDED_CURVE which is based on circle then the - corresponding value of tPars[i] may be equal to #GCE_NULL_V because the curvature of circle - is the same in all its points. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddEqualCurvature( GCE_system gSys, geom_item curves[2], var_item tPars[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Радиусный размер". - \en Specify a "Radius dimension" constraint. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cir - \ru Дескриптор окружности. - \en Descriptor of circle. \~ - \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). - \en Parameters of linear dimension (see #GCE_dim_pars). \~ - - \return \ru Дескриптор радиусного ограничения. - \en Descriptor of radius constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddRadiusDimension( GCE_system gSys, geom_item cir, GCE_dim_pars dPar ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Диаметральный размер". - \en Specify a "Diameter dimension" constraint. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cir - \ru Дескриптор окружности. - \en Descriptor of circle. \~ - \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). - \en Parameters of linear dimension (see #GCE_dim_pars). \~ - - \return \ru Дескриптор диаметрального ограничения. - \en Descriptor of diameter constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDiameter( GCE_system gSys, geom_item cir, GCE_dim_pars dPar ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Длина кривой". - \en Specify a "Curve Length" constraint. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curve - \ru Дескриптор кривой. - \en Descriptor of curve. \~ - \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). - \en Parameters of linear dimension (see #GCE_dim_pars). \~ - - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \details \ru У кривой должны быть начальная и конечная точки (#GCE_FIRST_END и #GCE_SECOND_END). - Ограничение поддерживается для линейных объектов и дуг окружностей. - \en The curve must have a start and end points (#GCE_FIRST_END и #GCE_SECOND_END). - Constraint is supported for linear objects and circular arcs.\~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddLength( GCE_system gSys, geom_item curve, GCE_dim_pars dPar ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Управляющий параметр" или "Фиксация переменной" - \en Set the constraint "Driving parameter" or "Fixation of variable" \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] var - \ru Дескриптор переменной. - \en Descriptor of variable. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \note \ru Созданное с помощью этой функции, ограничение может управляться - через вызов GCE_ChangeDrivingDimension. - \en A constraint created with this function can be driven - via the call of GCE_ChangeDrivingDimension. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_FixVariable( GCE_system gSys, var_item var ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Задать ограничение "Фиксация геометрического объекта". - \en Set the constraint "Fixation of geom" \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -// --- -GCE_FUNC(constraint_item) GCE_FixGeom( GCE_system gSys, geom_item g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Фиксированная длина отрезка" - \en Set the constraint "Fixation of segment length" \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] ls - \ru Дескриптор отрезка. - \en Descriptor of segment. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \details \ru У кривой должны быть начальная и конечная точки (#GCE_FIRST_END и #GCE_SECOND_END). - Ограничение поддерживается для линейных объектов и дуг окружностей. - \en The curve must have a start and end points (#GCE_FIRST_END и #GCE_SECOND_END). - Constraint is supported for linear objects and circular arcs.\~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_FixLength( GCE_system gSys, geom_item ls ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Задать ограничение "Фиксированный радиус". - \en Set the constraint "Fixation of radius" \~ - \details \ru Ограничение применимо для фиксации радиуса окружности или полуоси эллипса. - \en The constraint is applicable to fix radius of circle or semiaxis of ellipse. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] circ - \ru Дескриптор окружности или эллипса. - \en Descriptor of circle or ellipse. \~ - \param[in] cName- \ru Тип фиксируемой координаты. Может быть радиус, большая или малая полуось эллипса. - \en Type of fixed coordinate. It can be #GCE_RADIUS, - #GCE_MAJOR_RADIUS or #GCE_MINOR_RADIUS.\~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -// --- -GCE_FUNC(constraint_item) GCE_FixRadius( GCE_system gSys, geom_item circ, coord_name cName = GCE_RADIUS ); - -//---------------------------------------------------------------------------------------- -/** - \brief - \ru Задать ограничение "Зафиксировать производную сплайна в заданной точке". - \en Set the constraint "Fixation of derivative vector of the spline at a given point". \~ - \param[in] gSys - \ru Система ограничений. \en System of constraints. \~ - \param[in] spline - \ru Дескриптор сплайна. \en Descriptor of spline. \~ - \param[in] par - \ru Значение параметра, в котором надо зафиксировать производную. - \ \en Parameter value in which it is necessary to record a derivative. \~ - \param[in] derOrder - \ru Порядок производной, которую надо зафиксировать. \en Order of the derivative which must be fixed. \~ - \param[in] fixVal - \ru Значение, к которому надо приравнять производную. \en The value to which it is necessary to equate the derivative. \~ - \return \ru Дескриптор нового ограничения. \en Descriptor of a new constraint. \~ - \details - \ru Точка фиксации задается через значение параметра, соответствующего ей. \n - Порядок фиксируемой производной может равняться 0 (фиксация точки), 1, 2 или 3. \n - Если fixVal равен NULL, будет зафиксировано текущее значение производной, - иначе фиксируемой производной будет присвоено значение fixVal. - \en - Fixation point is specified via the parameter value corresponding to it. \n - The order of a fixed derivative can be equal 0 (point fixing), 1, 2 or 3. \n - If fixVal is NULL current value of the derivative vector will be fixed. - Otherwise the derivative vector will be fixed at fixVal value. \~ - */ -//--- -GCE_FUNC(constraint_item) GCE_FixSplineDerivative( GCE_system gSys, geom_item spline - , double par, uint derOrder, GCE_vec2d * fixVal = NULL ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Средняя точка". - \en Set the constraint "Middle point". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pnt - \ru Дескрипторы трех точек. - \en Descriptors of point triplet. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Для данных трех точек, задать отношение, связывающее тройку точек, - так, что третья точка лежит на середине отрезка между pnt[0] и pnt[1]. - \en For the given three points set the relation connecting the point triplet - in such way that the third point lies in the middle of points pnt[0] and pnt[1]. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddMiddlePoint( GCE_system gcSys, geom_item pnt[3] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Параллельность". - \en Set the constraint "Parallelism". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары линейных объектов. - \en Descriptors of a pair of linear objects. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Ограничение применяется для прямых или отрезков. - \en The constraint is used for lines or segments. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddParallel( GCE_system gSys, geom_item g[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Перпендикулярность". - \en Set the constraint "Perpendicularity". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары линейных объектов. - \en Descriptors of a pair of linear objects. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Ограничение применяется для прямых или отрезков. - \en The constraint is used for lines or segments. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddPerpendicular( GCE_system gSys, geom_item g[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Симметрия относительно линейного объекта". - \en Set the constraint "Symmetry relative to the linear object". \~ - - \param[in] gSys - \ru Система ограничений. - gSys - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары симметричных объектов. - g - \en Descriptors pair of symmetrical objects.. \~ - \param[in] lObj - \ru Дескриптор оси симметрии. - lObj - \en Descriptor of the axis of symmetry. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - - \attention \ru В настоящий момент данное ограничение применимо только для симметрии точек. - \en Currently, this restriction only applies to the symmetry of the points. \~ - */ -//--- -GCE_FUNC(constraint_item) GCE_AddSymmetry( GCE_system gSys, geom_item g[2], geom_item lObj ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Касание двух кривых". - \en Set the constraint "Tangency of two curves". \~ - \param[in] \ru gSys Система ограничений. - \en gSys System of constraints. \~ - \param[in] \ru g Дескрипторы пары кривых или прямых. - \en g Descriptors of a pair of curves or lines. \~ - \param[in] \ru tPar Дескрипторы параметров касания для параметрических кривых. - \en tPar Descriptors of parameters of tangency for parametric curves. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details - \par \ru Вспомогательные параметры касания - \en Help parameters of tangency - \ru Дескрипторы переменных tPar[0] и tPar[1] задают вспомогательные значения, параметризующие - точку касания на первой и второй кривой. Одна или обе tPar могут быть равными GCE_NULL_V, - если соответствующая кривая не является сплайном или параметрической кривой, либо - пользователь согласен, что точка касания будет локализована автоматически по ближайшему решению. - - \en Variable descriptors tPar[0], tPar[1] specify help values parametrizing a tangent point - on the first and the second curve. One of both tPar can be equal GCE_NULL_V. - - \note \ru tPar[0] или tPar[1] могут быть равными GCE_NULL_V, если параметры - касания не предусмотрены или кривые не имеют параметрического представления. - Параметрическое представление имеют пока только два типа: - GCE_SPLINE и GCE_PARAMETRIC_CURVE. - \en tPar[0] or tPar[1] may be equal to GCE_NULL_V if parameters - of tangency are not provided or curves have no parametric representation. - There are only two types having parametric representation: - GCE_SPLINE and GCE_PARAMETRIC_CURVE. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddTangent( GCE_system gSys, geom_item g[2], var_item tPar[2] ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать размерное ограничение "Расстояние между объектами". - \en Set the dimensional constraint "Distance between objects". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескрипторы пары геометрических объектов. - \en Descriptors of a pair of geometric objects. \~ - \param[in] dPars - \ru Параметры линейного размера (подробности см.#GCE_ldim_pars). - \en Parameters of linear dimension (see #GCE_adim_ldim). \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Задать линейный размер для пары геометрических объектов. - \en Set linear dimension for a pair of geometric objects. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDistance( GCE_system gSys, geom_item g[2], const GCE_ldim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Расстояние между точками". - \en Set the constraint "Distance between points". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] p - \ru Дескрипторы пары точек. - \en Descriptors of point pair. \~ - \param[in] dPars - \ru Параметры размерного ограничения. - \en Parameters of dimensional constraint. \~ - - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDistance2P( GCE_system gSys, geom_item p[2], const GCE_dim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Расстояние от точки до отрезка". - \en Set the constraint "Distance from a point to a segment". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] p - \ru Дескрипторы тройки точек. - \en Descriptors of point triplet. \~ - \param[in] dPars - \ru Параметры размерного ограничения. - \en Parameters of dimensional constraint. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Линейный размер от точки p1 до отрезка . Размер чувствителен к знаку - величины размера. - \en Linear dimension from the point p1 to the segment . - The dimension is sensitive to a sign of its value. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDistancePLs( GCE_system gSys, geom_item p[3] - , const GCE_dim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Ориентированное расстояние между точками". - \en Set the constraint "Directed distance between points". \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] p - \ru Дескрипторы пары точек. - \en Descriptors of point pair. \~ - \param[in] dPars - \ru Параметры размерного ограничения. - \en Parameters of dimensional constraint. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Параметр dPars.dirAngle задает направление размера в радианах. - Управляя dPars.dirAngle, можно задать вертикальный или - горизонтальный размеры. Так размер параметром dPars.dirAngle = 0 - создаст "горизонтальный размер", а dPars.dirAngle, равный PI/2 радиан - будет соответствовать "вертикальному" размеру. - - \en The constraint represents the dimension type that dimensions the - distance between two points in plane when they are projected onto a line - at an angle specified by parameter dPars dirAngle, which sets the direction - of dimension in radians. With driving dPars.dirAngle it is possible to - set the vertical or the horizontal dimension. So a dimension with an angle - equal to 0 radians specifies a "horizontal". The angle equal to PI/2 radians - corresponds to "vertical" dimension. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDirectedDistance( GCE_system gSys, geom_item p[2] - , const GCE_ldim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать линейное уравнение. - \en Set the linear equation. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] a - \ru Вектор коэффициентов линейного уравнения. - \en Vector of coefficients of linear equation. \~ - \param[in] v - \ru Дескрипторы переменных уравнения. - \en Descriptors of variables of equation. \~ - \param[in] n - \ru Количество переменных. - \en Quantity of variables.\~ - \param[in] c - \ru Коэффициент без переменной. - \en Free coefficient. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details \ru Задать линейное уравнение в виде a1*v1 + a2*v2 + .. + an*vn + c = 0. - \en Set a linear equation in form of a1*v1 + a2*v2 + .. + an*vn + c = 0. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddLinearEquation( GCE_system gSys, const double * a - , const var_item * v, size_t n, double c ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Изменить значение управляющего размера. - \en Change the value of driving dimension. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] dItem - \ru Дескриптор размерного ограничения. - \en Descriptor of dimensional constraint. \~ - \param[in] dVal - \ru Требуемое значение размера. - \en Required value of constraint. \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \details \ru Функция применяется только для управляющих размеров или управляющих параметров. - Если управляющий размер или параметр является угловым, то параметр dVal задается в радианах.\n - Следует учитывать, что настоящая функция не осуществляет вычислений, а только - подготавливает изменение размера. Что бы изменения вступили в силу, необходимо вызвать - функцию #GCE_Evaluate. - \en The function is used only for driving dimensions or driving parameters. - If the driving dimension or parameter is angular, then the parameter dVal is specified in radians. \n - It should be taken into account that the function doesn't perform computations but only - prepares the changing of dimension. For the changes to take effect it is required - to call the function #GCE_Evaluate. \~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_ChangeDrivingDimension( GCE_system gSys, constraint_item dItem, double dVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Отклонить ограничение от точки решения. - \en Deviate the constraint from the point of solution. \~ - \param[in] dItem - \ru Дескриптор геометрического ограничения. - \en Descriptor of geometric constraint. \~ - \param[in] delta - \ru Величина отклонения. - \en Deviation value. \~ - \return errCode - \ru Результат решения системы ограничений. - \en Solution of constraint system. \~ - - \details \ru Функция применяется для диагностики избыточности ограничения, основанной - на отклонении области решений ограничения. Работает только для размерных ограничений - и некоторых типов геометрических ограничений, таких как "Выравнивание точек", - "Горизонтальность" и т.д. Применимость к тому или иному типу не задокументирована и - определяется опытным путем. - Если было возвращено значение GCE_RESULT_None, то ограничение не отклонялось. - \en The function is used for the diagnostics of constraints redundancy based - on the deviation of the region of solution of the constraint. It works only for dimensional constraints - and other types of geometric constraints such as "Points alignment", - "Horizontality" etc. The applicability to a certain type was not documented and - it is defined only empirically. - If GCE_RESULT_None is returned, the constraint wasn't deviated. \~ -*/ -// --- -GCE_FUNC(GCE_result) GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Тест избыточности ограничения, основанный на отклонении его от точки решения. - \en Test for redundancy of constraint based on the deviation the constraint from the point of solution. \~ - \param[in] dItem - \ru Дескриптор геометрического ограничения. - \en Descriptor of geometric constraint. \~ - \param[in] delta - \ru Величина отклонения. - \en Deviation value. \~ - \return - \ru Результат решения системы ограничений. - \en Solution of constraint system. \~ - - \details \ru Функция применяется для диагностики избыточности ограничения, основанной - на отклонении области решений ограничения. Работает только для размерных ограничений - и некоторых типов геометрических ограничений, таких как "Выравнивание точек", - "Горизонтальность" и т.д. Применимость к тому или иному типу (кроме размерных) не - задокументирована и определяется опытным путем. - Если было возвращено значение GCE_RESULT_None, то ограничение не отклонялось. - \en The function is used for the diagnostics of constraints redundancy based - on the deviation of the region of solution of the constraint. It works only for dimensional constraints - and other types of geometric constraints such as "Points alignment", - "Horizontality" etc. The applicability to a certain type (for non dimensional) - was not documented and it is defined only empirically. - If GCE_RESULT_None is returned, the constraint wasn't deviated. \~ - - \note \ru В отличии от #GCE_DeviateDimension не меняется состояние системы ограничений. - \en Unlike #GCE_DeviateDimension this function does not change state of geometric constraint system. -*/ -// --- -GCE_FUNC(GCE_result) GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Текущее значение размерного параметра. - \en A current value of the dimension parameter. - \details \ru Функция выдает текущее значение размерного параметра ограничения. Если - ограничение не размерное, то функция вернет GCE_UNDEFINED_DBL. Для управляющих размеров - будет выдано значение управляющего параметра, которое было задано при создании размера - или последним вызовом GCE_ChangeDrivingDimension. - \en The function returns a value of dimension parameter of the constraint. - If the constraint is a driving dimension, the function returns a value of dimension - parameter specified when creating the constraint or last call of #GCE_ChangeDrivingDimension. -*/ -//--- -GCE_FUNC(double) GCE_DimensionParameter( GCE_system gSys, constraint_item dItem ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вычислить систему ограничений. - \en Calculate the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \return \ru Код результата вычислений. - \en Calculation result code. \~ - \details \ru Функция решает задачу ограничений. Задача ограничений формулируется - функциями API геометрического решателя; функции вида GCE_Add_XXXXXXX добавляют новые - объекты, функции вида GCE_Change_XXXXXXX, GCE_Set_XXXXXXX изменяют состояние - объектов. Таким образом, что бы все такие изменения вступили в силу, нужно - вызвать метод #GCE_Evaluate.\n - Алгоритмы GCE_Evaluate учитывают удовлетворенность систем ограничений; если - все ограничения уже решены, то функция не тратит время на вычисления, а - состояние геометрических объектов остается неизменным. - \en The function solves problem of constraints. The problem of constraint is formulated - by API functions of geometric solver; the functions of a kind GCE_Add_XXXXXXX add a new - object, the functions of kinds GCE_Change_XXXXXXX and GCE_Set_XXXXXXX change a state - of objects. Thus, for all changes to take effect it is necessary - to call the method #GCE_Evaluate.\n - The algorithms GCE_Evaluate take into account whether constraint systems are satisfied, if - all constraints have been already solved, then the function doesn't spend time for calculations, and - the state of geometric objects remains unchanged. \~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_Evaluate( GCE_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Инициализировать режим драггинга контрольной точки объекта. - \en Initialize the dragging mode of the object control point. \~ - \param[in] \ru gSys Система ограничений. - \en gSys System of constraints. \~ - \param[in] \ru obj Геометрический объект. - \en obj Geometric object. \~ - \param[in] \ru pntId Обозначение передвигаемой контрольной точки объекта. - \en pntId Denotation of the dragged control point of the object. \~ - \param[in] \ru curXY Координаты курсора, куда следует перемещаемая точка. - \en curXY Coordinates of cursor where the moving point follows. \~ - \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. - \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_PrepareMovingOfPoint( GCE_system gSys, geom_item obj - , point_type pntId, GCE_point curXY ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Инициализировать режим драггинга контрольной точки объекта. - \en Initialize the dragging mode of the object control point. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] drgPnt - \ru Контрольная точка объекта. - \en A geom control point. \~ - \param[in] curXY - \ru Координаты точки драггинга. - \en Coordinates of dragging point. \~ - \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. - \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_PrepareDraggingPoint( GCE_system gSys, GCE_dragging_point drgPnt - , GCE_point curXY ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Инициализировать режим драггинга контрольной точки множества объектов. - \en Initialize the dragging mode of the control point of object set. \~ - \details \ru Этот метод предназначен для группового редактирования (драггинг) - нескольких объектов с "общей" hot-точкой. Под "общей" hot-точкой подразумевается - не обязательно одна точка (с одним дескриптором), а множество точек с разными - дескрипторами, но имеющих одинаковые координаты. - \en This method is intended for the group dragging of few objects with - the "common" hot-point. A "common" hot-point is not necessarily the only point - (with the only descriptor), but a set of points with different descriptors but - with equal coordinates. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cPntArr - \ru Множество геометрически одинаковых контрольных точек. - \en A set of geometrically equal control points. \~ - \param[in] curXY - \ru Координаты точки драггинга. - \en Coordinates of dragging point. \~ - \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. - \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_PrepareDraggingPoint( GCE_system gSys - , const std::vector & cPntArr - , GCE_point curXY ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Инициализировать режим перетаскивания множества объектов. - \en Initialize mode of moving a set of objects. - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param geoms - \ru Множество геометрических объектов. - \en Set of geometric objects. \~ - \param curXY - \ru Координаты точки драггинга. - \en Coordinates of dragging point. \~ - \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. - \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ - -*/ -//--- -GCE_FUNC(GCE_result) GCE_PrepareMovingGeoms( GCE_system gSys - , std::vector & geoms - , GCE_point curXY ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Переместить точку драггинга. - \en Move a dragging point. \~ - \param[in] gcSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curXY - \ru Текущие координаты курсора. - \en Current coordinates of cursor. \~ - \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. - \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ - - \details \ru Процедура обслуживает режим драггинга, с ее помощью геометрический решатель - отслеживает положение курсора. Этот вызов позволяет осуществлять двух-координатное - управление не доопределенной моделью. Если функция возвращает код ошибки, - не равный #GCE_RESULT_Ok, то гарантируется, что состояние геометрических объектов - останется неизменным. Если функция вернула #GCE_RESULT_Ok, то решатель содержит - новое состояние геометрических объектов, удовлетворяющее всем ранее наложенным - ограничениям (новое решение). В этом случае вызывать #GCE_Evaluate для приведения - объектов в решенное состояние не требуется. - \en The procedure services the dragging mode, with a help of it a geometric solver - tracks the cursor location. This call allows to perform a two-coordinate - control of an underdetermined model. If the function returns an error code, - which is not #GCE_RESULT_Ok, then it is guaranteed that the state of geometric objects - will remain the same. If the function returned #GCE_RESULT_Ok, then the solver contains - a new state of geometric objects satisfying to all the constraints created before - (a new solution). In this case it not required to call #GCE_Evaluate for the conversion - of objects to the solved state. \~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_MovePoint( GCE_system gcSys, GCE_point curXY ); - -//---------------------------------------------------------------------------------------- -/** - brief \ru Трансформировать геометрические объекты согласно заданной матрице. - \en Transform geometric objects according to a given matrix. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] geoms - \ru Множество геометрических объектов. - \en Set of geometric objects. \~ - \param[in] mat - \ru Матрица преобразования. - \en Transformation matrix. \~ - \return \ru Код ошибки. \en Error code. \~ - - \details \ru Режим динамической трансформации для данного набора геометрических объектов - включается при первом вызове функции #GCE_DynamicTransform. При этом запоминаются начальные - положения геометрических объектов и далее трансформации при каждом новом вызове - #GCE_DynamicTransform выполняются относительно их первоначального положения до тех пор, пока - режим динамической трансформации не будет выключен. Выключается режим динамической - трансформации геометрических объектов при вызове любой другой функции API или при вызове - функции #GCE_DynamicTransform для другого набора геометрических объектов. - \en The dynamic transformation mode for given set of geometric objects is turned on - after the first time the #GCE_DynamicTransform function is called. In this case, the initial - positions of geometric objects are remembered and then the transformations for each new call - of the #GCE_DynamicTransform are performed relative to their initial position until the dynamic - transformation mode is turned off. The mode of dynamic transformation of geometric objects is - turned off when calling any other API function or when calling the #GCE_DynamicTransform - function for another set of geometric objects. \~ -*/// --- -GCE_FUNC(GCE_result) GCE_DynamicTransform( GCE_system gSys, const std::vector & geoms, const MbMatrix & mat ); - -//---------------------------------------------------------------------------------------- -/** - brief \ru Трансформировать геометрию системы ограничений согласно заданной матрице. - \en Transform the geometry of the constraints system according to a given matrix. \~ - \details \ru Если преобразование несобственное, т.е. включает в себя отражение, то изменится - направление кривых, ограниченных двумя точками, у которых базовая кривая замкнутая. - Это значит, что после преобразования, запрос #GCE_PointOf для таких кривых в качестве #GCE_FIRST_END - будет возвращать точку, которую до преобразования выдавал в качестве #GCE_SECOND_END и наоброт. - \en If the transformation is improper, i.e. includes reflection, direction of bounded curves - for which the base curve is closed will be changed. This means that after transformation, - the request #GCE_PointOf for such curves will return as a #GCE_FIRST_END a point that - before transformation returned as #GCE_SECOND_END and vice versa.\~ - - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] mat - \ru Матрица преобразования. - \en Transformation matrix. \~ - \return \ru Код ошибки. \en Error code. \~ -*/// --- -GCE_FUNC(GCE_result) GCE_Transform( GCE_system gSys, const MbMatrix & mat ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Включить журналирование и назначить файл для записи журнала вызовов API. - \en Switch on the journalling and specify the file for recording a journal of GCE API calls. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] fName - \ru Имя файла назначения с полным путем. - \en Name of destination file with a full path. \~ - \return true, if journalling has been successfully switched on. - \attention - \ru Файл журнала будет записан только после завершения сеанса работы с системой - ограничений, а именно сразу после вызова GCE_RemoveSystem. - \en The journal file will be written only when a session of work with the - constraint system is finished, i.e. immediately after calling the - GCE_RemoveSystem method. -*/ -//--- -GCE_FUNC(bool) GCE_SetJournal( GCE_system gSys, const char * fName ); - -#define FB_NULL_GEOM 0 - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - Рекомендуется использовать новую функцию: #GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta ) - \en An obsolete function. The call will be removed in one of the next versions. - It's recommended to use new version of this function: #GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta )\~ - */ -// --- -GCE_FUNC(bool) GCE_DeviateDimension( GCE_system gSys, constraint_item dItem - , double delta, GCE_result & errCode ); - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - Рекомендуется использовать новую функцию: #GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta ) - \en An obsolete function. The call will be removed in one of the next versions. - It's recommended to use new version of this function: #GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta )\~ - */ -// --- -GCE_FUNC(bool) GCE_DeviationTest( GCE_system gSys, constraint_item dItem - , double delta, GCE_result & errCode ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - \en An obsolete function. The call will be removed in one of the next versions. \~ - - \attention \ru Время жизни экземпляра класса crv опирается на счетчик ссылок, т.е. - решатель его увеличивает при добавлении кривой и декрементирует при удалении кривой из решателя. - \en The lifetime of the instance of the class 'crv' is based on the reference counter, i.e. - the solver increases it when adding a curve and decreases when deleting a curve from the solver. \~ -*/ -//--- -class MbPolyCurve; -GCE_FUNC(geom_item) GCE_AddSpline( GCE_system gSys, const MbPolyCurve & crv ); - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - \en An obsolete function. The call will be removed in one of the next versions. \~ -*/ -//--- -inline geom_item GCE_AddPoint( GCE_system gSys, GCE_point pVal, int ) -{ - return GCE_AddPoint( gSys, pVal ); -} - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - \en An obsolete function. The call will be removed in one of the next versions. \~ -*/ -//--- -GCE_FUNC(GCE_system) GCE_CreateSystem( void * ); - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий (2016). - \en An obsolete function. The call will be removed in one of the next versions (2016). \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddDirectedDistance2P( GCE_system gSys, geom_item p[2] - , const GCE_ldim_pars & dPars ); - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - \en An obsolete function. The call will be removed in one of the next versions. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddAlignPoints( GCE_system gSys, geom_item p[2], bool hor ); - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Функция устарела. Вместо неё применять #GCE_FixLength. - \en The function is obsolete. Use #GCE_FixLength instead. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddFixedLength( GCE_system, geom_item ); - -//---------------------------------------------------------------------------------------- -/** - \attention \ru Функция устарела. Вместо неё применять #GCE_FixVariable. - \en The function is obsolete. Use #GCE_FixVariable instead. \~ -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddFixVariable( GCE_system, var_item ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение "Точка на кривой". - \en Set the constraint "Point on curve". \~ - \attention This call is deprecated. Call #GCE_AddCoincidence instead. -*/ -//--- -GCE_FUNC(constraint_item) GCE_AddIncidence( GCE_system, geom_item, geom_item ); - -//---------------------------------------------------------------------------------------- -/** - \attention - \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. - Используйте #GCE_PrepareMovingOfPoint( GCE_system gSys, const std::vector & cPntArr, GCE_point curXY ) - взамен. - \en An obsolete function. The call will be removed in one of the next versions. - Use GCE_PrepareDraggingPoint( GCE_system gSys, const std::vector & cPntArr, GCE_point curXY ) instead of this. \~ -*/ -//--- -GCE_FUNC(GCE_result) GCE_PrepareMovingOfPoint( GCE_system gSys - , const std::vector & cPntArr - , GCE_point curXY ); - -/** \} */ - -#endif // __GCE_API_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Программный интерфейс решателя геометрических ограничений. + \en Program interface of geometric constraints solver. \~ + \details \ru Программный интерфейс геометрического решателя представляет + собой набор типов данных и функций, необходимых для решения + задачи геометрических ограничений. Предметная область решателя + предусматривает такие типы, как "геометрический объект", + "геометрическое ограничение", "система ограничений". Базовые типы + решателя объявлены в заголовочном файле . Вызовы функций + и их аргументы подобраны таким образом, что бы наиболее удобно + осуществлять формулировку задачи для решателя в терминах объектов + и ограничений. Названия многих типов данных и вызовов API начинаются + префиксом GCE, сокращенно Geometric Constraint Engine. \n + + Функции API решателя можно подразделить на такие группы: + 1) Функции #GCE_CreateSystem, #GCE_ClearSystem, #GCE_RemoveSystem + позволяют создавать и удалять систему ограничений в целом + (должны вызываться в однопоточном режиме);\n + 2) С помощью функций вида GCE_Add_XXXXXXX осуществляется формулировка + задачи ограничений, с их помощью в систему добавляются объекты и + ограничения (могут использоваться в параллельном режиме);\n + 3) Функции вида GCE_Change_XXXXXXX, GCE_Set_XXXXXXX позволяют менять + размеры и состояние объектов (могут использоваться в параллельном режиме);\n + 4) Функции для запросов такие, как GCE_Get_XXXXXXX, #GCE_SplinePoint, + GCE_IsXXXXX, #GCE_PointDOF и т.д. позволяют осуществлять запросы + о состоянии объектов или их свойств, узнать степень свободы объектов + и прочие характеристики (могут использоваться в параллельном режиме);\n + 5) Метод #GCE_Evaluate вычисляет состояния системы ограничений, в котором + все ограничения удовлетворены, или возвращает код ошибки при невозможности + найти решение (должна вызываться в однопоточном режиме).\n + 6) Другая группа вызовов отвечает за способы управления недоопределенной + системой ограничений. Вызовы #GCE_PrepareDraggingPoint, #GCE_MovePoint + обеспечивают интерактивную манипуляцию объектами чертежа/эскиза.\n + + \en A program interface of geometric solver represents + a set of data types and functions necessary for solution + of a problem of geometric constraints. Subject area of the solver + provides such types as "geometric object", "geometric constraint", + "constraint system". Base types of the solver are declared in the header + file . Calls of functions and their arguments are chosen + in such way that the formulation of the problem for the solver in terms + of objects and constraints could be performed by the most convenient way. + The names of many data types and API calls begins with a prefix 'GCE', + abbreviation for Geometric Constraint Engine. \n + + API functions of solver can be subdivided into the following groups: + 1) Functions #GCE_CreateSystem, GCE_ClearSystem, GCE_RemoveSystem + allow to create and delete the system of constraints in general + (should be called in sequential code);\n + 2) The problems of constraints are formulated with a function of a kind GCE_Add_XXXXXXX, + by using them the objects and constraints are added to the system + (could be called in multi-threaded mode);\n + 3) Functions of a kind GCE_Change_XXXXXXX, GCE_Set_XXXXXXX allow to change dimensions + and objects states (could be called in multi-threaded mode);\n + 4) Functions for requests, such as #GCE_Get_XXXXXXX, #GCE_SplinePoint, + #GCE_IsXXXXX, #GCE_PointDOF etc, allow to perform requests + about the states of objects or their properties, find the objects degree of freedom + and other characteristics could be called in multi-threaded mode;\n + 5) The method #GCE_Evaluate calculates the state of the constraint system, where + all constraints are satisfied or returns an error code if it is not possible + to find a solution (should be called in sequential code). \n + 6) Other group of calls responses for the ways of control of underdetermined + system of constraints. Calls of #GCE_PrepareDraggingPoint, #GCE_MovePoint + provide interactive manipulation with objects of drawing/sketch.\n \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCE_API_H +#define __GCE_API_H + +#include +#include +#include + +class MATH_CLASS MbMatrix; +class MATH_CLASS MbCurve; + +/** + \addtogroup Constraints2D_API + \{ +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Создать пустую систему ограничений. + \en Create a simple constraint system. \~ + \details \ru Вызов создает пустую систему ограничений. Кроме того, в памяти + создаются внутренние структуры данных геометрического решателя, обслуживающего + систему ограничений. Функция возвращает специальный дескриптор, по которому + система ограничений доступна для различных манипуляций: добавление или удаление + геометрических объектов, ограничений, варьирование размеров, драггинг недоопределенных + объектов и т.д. + \en The call creates a simple constraint system. Besides, inside the memory + there are created internal data structures of geometric solver maintaining + the system of constraints. The functions returns a special descriptor by which + the constraint system is available for various manipulations: addition and deletion + of geometric objects, constraints, variation of sizes, dragging underconstrained objects + etc. \~ + + \return \ru Дескриптор системы ограничений. + \en Descriptor of constraint system. \~ +*/ +//--- +GCE_FUNC(GCE_system) GCE_CreateSystem(); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Сделать систему ограничений пустой. + \en Make the constraint system empty. \~ + \details \ru Данный метод делает систему ограничений пустой при этом + дескриптор gSys остается действительным, т.е. можно осуществлять дальнейшую + работу с системой ограничений. + \en This method makes the constraint system empty while + the descriptor gSys remains valid, i.e. it is possible to perform the further + work with the constraint system. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \sa #GCE_RemoveSystem +*/ +//--- +GCE_FUNC(void) GCE_ClearSystem( GCE_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить систему ограничений. + \en Delete system of constraints. \~ + \details \ru Данный метод освобождает память от внутренних структур данных, обслуживающих + систему ограничений. Удаляемая система ограничений становится недействительной после + данного вызова. + \en This method releases memory from internal data structures maintaining + the constraint system. The removed constraint system is invalidated after this call. + \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \sa #GCE_ClearSystem +*/ +//--- +GCE_FUNC(void) GCE_RemoveSystem( GCE_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений точку. + \en Add point to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pVal - \ru Координаты точки. + \en Point coordinates. \~ + \return \ru Дескриптор зарегистрированной точки. + \en Descriptor of registered point. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddPoint( GCE_system gSys, GCE_point pVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений прямую. + \en Add line to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] lVal - \ru Координаты прямой. + \en Line coordinates. \~ + \return \ru Дескриптор зарегистрированной прямой. + \en Descriptor of registered line. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddLine( GCE_system gSys, const GCE_line & lVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений отрезок прямой, заданный парой концевых точек. + \en Add a line segment specified by pair of end points to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] p - \ru Дескрипторы конечных точек отрезка. + \en Descriptors of end points of the line segment. \~ + \return \ru Дескриптор зарегистрированного отрезка. + \en Descriptor of registered segment. \~ + \details \ru Для отрезка, созданного через данный вызов, действительны все типы + ограничений, которые применимы для прямой, создаваемой вызовом GCE_AddLine. + \en All types of constraints which are applicable to the line created by GCE_AddLine + are valid for the segment created by this call. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddLineSeg( GCE_system gSys, geom_item p[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений окружность. + \en Add circle to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cVal - \ru Координаты окружности. + \en Coordinates of a circle. \~ + \return \ru Дескриптор зарегистрированной окружности. + \en Descriptor of the registered circle. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddCircle( GCE_system gSys, const GCE_circle & cVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений эллипс. + \en Add ellipse to the constraint system. \~ + \param[in] \ru gSys Система ограничений. + \en gSys System of constraints. \~ + \param[in] \ru eVal Координаты эллипса. + \en eVal Ellipse coordinates. \~ + \return \ru Дескриптор зарегистрированного эллипса. + \en Descriptor of registered ellipse. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddEllipse( GCE_system gSys, const GCE_ellipse & eVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений сплайн (NURBS) + \en Add spline (NURBS) to the constraint system \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] spl - \ru Координаты сплайна. + \en Spline coordinates. \~ + \return \ru Дескриптор зарегистрированного сплайна. + \en Descriptor of registered spline. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddSpline( GCE_system gSys, const GCE_spline & spl ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений параметрическую кривую. + \en Add parametric curve to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] crv - \ru Математическое описание параметрической кривой. + \en Mathematical description of parametric curve. \~ + \return \ru Дескриптор зарегистрированной параметрической кривой. + \en Descriptor of registered parametric curve. \~ + \attention \ru Время жизни экземпляра класса crv опирается на счетчик ссылок, т.е. + решатель его увеличивает при добавлении параметрической кривой и + декрементирует при удалении кривой из решателя. + \en The lifetime of the instance of the class 'crv' is based on the reference counter, i.e. + the solver increases it when adding a parametric curve and + decreases when deleting a curve from the solver. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddParametricCurve( GCE_system gSys, const MbCurve & crv ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему граничную кривую, ограниченную парой точек. + \en Add a curve bounded by a pair of points to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] crv - \ru Дескриптор базовой геометрической кривой. Базовой кривой может + быть только кривая одного из следующих типов: прямая, окружность, + эллипс, сплайн или параметрическая кривая. + \en Descriptor of base geometric curve. Base curve may + be only one curve from the following types: line, circle, + ellipse, spline or parametric curve. \~ + \param[in] p - \ru Пара дескрипторов начальной и конечной точек участка кривой. + \en A pair of descriptors of the beginning and ending points of curve piece. \~ + \return \ru Дескриптор зарегистрированной ограниченной кривой. + \en Descriptor of registered bounded curve. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_AddBoundedCurve( GCE_system gSys, geom_item curve, geom_item p[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему жёсткое множество геометрических объектов. + \en Add a rigid set of geometric objects to the system. \~ + \details \ru Жёсткое множество - это массив геометрических объектов, зафиксированных друг относительно друга. + Жёсткое множество представляет собой геометрический объект, для которого доступен весь функционал + работы с геометрическими объектами. Например, у него можно спросить тип (#GCE_GeomType -> GCE_SET) или запросить + положение. С помощью вызовов #GCE_GetPoint и #GCE_GetCoordValue можно получить начало координат и направление оси OX + ЛСК жёсткого множества. Чтобы удалить жёсткое множество, надо, как и для любого другого геометрического объекта, + вызвать функцию #GCE_RemoveGeom. При этом составляющие жёсткое множество объекты (geoms) при удалении жёсткого + множества не удаляются и могут далее быть использованы в решателе. С геометрическими объектами, образующими + жёсткое множество, нужно работать точно так же, как и до их добавления в жёсткое множество. Например, для наложения + ограничения между элементом жёсткого множества и любым другим геометрическим объектом необходимо в + качестве аргумента ограничения указывать не дескриптор жёсткого множества, которому данный объект принадлежит, а + дескриптор самого геометрического объекта из массива geoms, на который накладывается ограничение. + \en A rigid set is an array of geometric objects which are fixed relative to each other. It is considered as a + geometric object and hence all the functionality for working with geometric objects is available for it. For + example, it's possible to request its type (#GCE_GeomType -> GCE_SET) or get its position invoking #GCE_GetPoint + and #GCE_GetCoordValue to get the origin and the direction of the OX axis of the LCS of the rigid set. To remove + a rigid set it's necessary to call the function #GCE_RemoveGeom. Geometric objects (geoms) are not deleted together + with a rigid set and can be used in the solver after it will be deleted. With geometric objects that have been + included in a rigid set it is necessary to continue to work just as before adding them to a rigid set. For + instance, to specify a constraint between an element of a rigid set and any other geometric object, it is necessary + to specify as the constraint argument not the descriptor of the rigid set to which the object belongs but the + descriptor of the geometric object from the geoms array on which the constraint is specified.\~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] geoms - \ru Массив дескрипторов геометрических объектов, образующих жёсткое множество. + \en \~ + \return \ru Дескриптор зарегистрированного жёсткого множества объектов. + \en Descriptor of registered bounded curve. \~ +*/ +// --- +GCE_FUNC(geom_item) GCE_AddRigidSet( GCE_system gSys, const std::vector & geoms ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений переменную. + \en Add a variable to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] val - \ru Начальное значение переменной. + \en A start value of the variable. \~ + \return \ru Дескриптор зарегистрированной переменной. + \en Descriptor of registered variable. \~ +*/ +//--- +GCE_FUNC(var_item) GCE_AddVariable( GCE_system gSys, double val ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Тип геометрического объекта. + \en A type of geometric object. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \return \ru Тип геометрического объекта. + \en A type of geometric object. \~ +*/ +//--- +GCE_FUNC(geom_type) GCE_GeomType( GCE_system gSys, geom_item g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Тип геометрической кривой. + \en A type of geometric curve. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор кривой. + \en Descriptor of curve \~ + \return \ru Тип геометрического объекта. + \en A type of geometric object. \~ + \details \ru The function returns geometric type of a curve 'crv' or type + of a base curve if 'crv' has type #GCE_BOUNDED_CURVE. + \en Функция вернет геометрический тип кривой 'crv' либо тип базовой кривой, + если 'crv' имеет тип #GCE_BOUNDED_CURVE. \~ +*/ +//--- +GCE_FUNC(geom_type) GCE_BaseCurveType( GCE_system gSys, geom_item crv ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить переменную из системы ограничений. + \en Delete variable from the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] var - \ru Дескриптор переменной. + \en Descriptor of variable. \~ + \return \ru true, если переменная var действительно удалена. + \en it equals true if the variable var is actually deleted. \~ +*/ +//--- +GCE_FUNC(bool) GCE_RemoveVariable( GCE_system gSys, var_item var ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить геометрический объект из системы ограничений. + \en Delete geometric object from the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \return \ru true, если геометрический объект g действительно удален. + \en it equals true if the geometric object g is actually deleted. \~ +*/ +//--- +GCE_FUNC(bool) GCE_RemoveGeom( GCE_system gSys, geom_item g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить ограничение из системы. + \en Delete a constraint from the system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] con - \ru Дескриптор ограничения. + \en Descriptor of constraint. \~ + \return \ru true, если ограничение con действительно удалено. + \en it equals true if the constraint con is actually deleted. \~ +*/ +//--- +GCE_FUNC(bool) GCE_RemoveConstraint( GCE_system gSys, constraint_item con ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Запросить дескриптор контрольной точки объекта. + \en Request of the object control point descriptor. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор объекта. + \en Descriptor of object. \~ + \param[in] pnt - \ru Имя контрольной точки объекта. + \en Name of the object control point. \~ + \return \ru Дескриптор контрольной точки объекта. + \en Descriptor of the object control point. \~ + + \details \ru Дескриптор, полученный по значению этой функции, имеет автоматическое + время жизни, т.е. нет необходимости вызывать для него метод #GCE_RemoveGeom. + \en Descriptor obtained by the value of this function, it has automatical + lifetime, i.e. there is no reason to call the method #GCE_RemoveGeom for it. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_PointOf( GCE_system gSys, geom_item g, point_type pnt ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Дескриптор контрольной точки сплайна по индексу. + \en Descriptor of spline control point by index \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] spl - \ru Дескриптор сплайна. + \en Descriptor of spline. \~ + \param[in] pntIdx - \ru Индекс контрольной точки. + \en A control point index. \~ + \return \ru Дескриптор контрольной точки сплайна. + \en Descriptor of spline control point. \~ + + \details \ru Дескриптор, полученный по значению этой функции, имеет автоматическое + время жизни, т.е. нет необходимости вызывать для него метод #GCE_RemoveGeom. + \en Descriptor obtained by the value of this function, it has automatical + lifetime, i.e. there is no reason to call the method #GCE_RemoveGeom for it. \~ +*/ +//--- +GCE_FUNC(geom_item) GCE_SplinePoint( GCE_system gSys, geom_item spl, size_t pntIdx ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить текущие координаты вектора. + \en Get the current coordinates of vector. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор вектора или иного геометрического объекта. + \en Descriptor of vector or other geometric object. \~ + \param[in] vType - \ru Идентификатор вектора, принадлежащего объекту (в настоящий момент равен или GCE_DIRECTION, или GCE_ORIENTATION). + GCE_DIRECTION возвращает направляющую прямой, отрезка или главной полуоси эллипса. + \en Identifier of vector belonging to the object (currently it equals GCE_DIRECTION or GCE_ORIENTATION). + In case of GCE_DIRECTION function returns direction vector for line, line segment or ellipse major axis.\~ + \return \ru Координаты вектора. + \en Vector coordinates. \~ +*/ +//--- +GCE_FUNC(GCE_vec2d) GCE_GetVectorValue( GCE_system gSys, geom_item g, query_geom_type vType ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить текущие координаты точки. + \en Get the current coordinates of point. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор точки или иного геометрического объекта. + \en Descriptor of point or other geometric object. \~ + \param[in] pName - \ru Идентификатор точки, принадлежащей объекту. + \en Identifier of a point belonging to the object. \~ + \return \ru Координаты точки. + \en Point coordinates \~ +*/ +//--- +GCE_FUNC(GCE_point) GCE_GetPointXY( GCE_system gSys, geom_item g, point_type pName = GCE_PROPER_POINT ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить текущее значение координаты геометрического объекта. + \en Get the current value of geometric object's coordinate. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор объекта. + \en Descriptor of object. \~ + \param[in] cName - \ru Обозначение параметра объекта. + \en Denotation of object parameter. \~ + \return \ru Координаты точки. + \en Point coordinates \~ + \details \ru Получить текущее значение координаты геометрического объекта. Например, + с помощью данной функции можно узнать текущее значение большой или малой + полуоси эллипса, радиус окружности и т.д. + \en Get the current value of geometric object's coordinate. For example, + by using this function one can find the current value of the major or the minor + semi-axis of ellipse, circle radius etc. \~ +*/ +//--- +GCE_FUNC(double) GCE_GetCoordValue( GCE_system gSys, geom_item g, coord_name cName ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить текущее значение переменной. + \en Get the current value of variable. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] var - \ru Дескриптор переменной. + \en Descriptor of variable. \~ + \return \ru Значение переменной. + \en A value of variable. \~ +*/ +//--- +GCE_FUNC(double) GCE_GetVarValue( GCE_system gSys, var_item var ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать текущие координаты точки. + \en Set the current coordinates of point. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор точки или иного геометрического объекта. + \en Descriptor of point or other geometric object. \~ + \param[in] pName - \ru Идентификатор точки, принадлежащей объекту. + \en Identifier of a point belonging to the object. \~ + \param[in] xyVal - \ru Новое значение координат точки. + \en New value of point coordinates. \~ + \return \ru true, если операция выполнена успешно. + \en true if operation succeeded. \~ + + \details \ru Метод присваивает точке или контрольной точке объекта g c + атрибутом pName новое состояние координат (параметр xyVal). Следует учитывать, + что вызов #GCE_SetPointXY не решает системы ограничений, а только меняет состояние + геометрического объекта. При этом система ограничений может стать неудовлетворенной. + Состояние точки, присвоенное вызовом GCE_SetPointXY не обязано сохранятся после + вызова #GCE_Evaluate, если точка не фиксированная или не замороженная. + \en The method assigns to the point or the control point of the object g with + the attribute pName a new state of coordinates (the parameter xyVal). It should be taken into account + that the call of #GCE_SetPointXY doesn't solve the constraint system but only changes the state + of geometric object. At the same time the constraint system may become unsatisfied. + The state of a point assigned by the call of GCE_SetPointXY should not be saved after + the call of #GCE_Evaluate if the point is not fixed or not frozen. \~ +*/ +//--- +GCE_FUNC(bool) GCE_SetPointXY( GCE_system gSys, geom_item g, point_type pName, GCE_point xyVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать текущее значение координаты геометрического объекта. + \en Set the current value of geometric object's coordinate. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор объекта. + \en Descriptor of object. \~ + \param[in] cName - \ru Обозначение параметра объекта. + \en Denotation of object parameter. \~ + \param[in] crdVal - \ru Новое значение координаты. + \en New value of coordinate. \~ + \return \ru true, если операция выполнена успешно. + \en true if operation succeeded. \~ + + \details \ru Метод присваивает координате объекта g c атрибутом cName новое значение. + Следует учитывать, что вызов #GCE_SetCoordValue не решает системы ограничений, + а только меняет состояние геометрического объекта. При этом система ограничений + может стать неудовлетворенной. Состояние координаты, присвоенное этим методом + не обязано сохранятся после вызова #GCE_Evaluate, если точка не фиксированная + или не замороженная. + \en The method assigns a new value to the coordinate of the object g with the attribute cName. + It should be taken into account that the call of #GCE_SetCoordValue doesn't solve the constraint system + but only changes the state of geometric object. At the same time the constraint system + may become unsatisfied. The state of coordinate assigned by this method + should not be saved after the call of #GCE_Evaluate if the point is not fixed + or not frozen. \~ +*/ +//--- +GCE_FUNC(bool) GCE_SetCoordValue( GCE_system gSys, geom_item g, coord_name cName, double crdVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать текущее значение переменной. + \en Set the current value of variable. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] var - \ru Дескриптор переменной. + \en Descriptor of variable. \~ + \param[in] val - \ru Новое значение переменной. + \en New value of variable. \~ + \return \ru true, если операция выполнена успешно. + \en true if operation succeeded. \~ +*/ +//--- +GCE_FUNC(bool) GCE_SetVarValue( GCE_system gSys, var_item var, double val ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Заморозить геометрический объект. + \en Freeze geometric object. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Геометрический объект. + \en Geometric object. \~ + \return \ru true, если операция выполнена успешно. + \en true if operation succeeded. \~ + + \details + + \ru Функция лишает объект всей степени свободы. Отдельно можно заметить, что + функция GCE_IsConstrainedGeom для замороженного объекта вернет false, если + объект не был связан другими ограничениями. Т.е. заморозка не считается + ограничением.\n + Решатель не может менять замороженную геометрию, но её может поменять + клиентское приложение методами GCE_SetCoordValue или GCE_SetPointXY. + Замороженные объекты следует рассматривать в качестве независимых входных + параметров системы ограничений. + + \en The function deprives the object of all degrees of freedom. Note that + the function GCE_IsConstrainedGeom returns false for the frozen object if + the object was not connected with other constraints. I.e. the freezing is not considered + as a constraint.\n + The solver cannot change the frozen geometry but the user application can change it + with the methods GCE_SetCoordValue or GCE_SetPointXY. Frozen objects should be + considered as independent input parameters of constraint system. \~ + + \note + \ru Обычно на стороне САПР эта команда применяется для фиксации проекционной геометрии + в ассоциативных чертежах или в эскизах с проекциями трехмерных объектов. + \en Usually, in CAD applications this command is used only for fixation of projection + geometry in associative drawings or sketches with projections of 3D-objects. \~ +*/ +//--- +GCE_FUNC(bool) GCE_FreezeGeom( GCE_system gSys, geom_item g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Функция отвечает на вопрос: Связан ли геометрический объект ограничениями? + \en The function answers the question: Is geometric object connected with constraints? \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object. \~ + \return \ru true, если для объекта g задано хотя бы одно ограничение. + \en true if at least one constraint is set for the object g. \~ + \sa GCE_RemoveGeom, GCE_RemoveConstraint +*/ +//--- +GCE_FUNC(bool) GCE_IsConstrainedGeom( GCE_system gSys, geom_item g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выполнить проверку удовлетворенности ограничения. + \en Perform a check that a constraint is satisfied. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cItem - \ru Дескриптор ограничения. + \en Descriptor of constraint. \~ + \return \ru true, если ограничение удовлетворено. + \en true if a constraint is satisfied. \~ +*/ +//--- +GCE_FUNC(bool) GCE_IsSatisfied( GCE_system gSys, constraint_item cItem ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Статус ограничения в системе. + \en Status of constraint inn the system. + \details + \ru Вызов показывает результат диагностики, которая выделяет в системе ограничений + хорошо-обусловленные части и части, содержащие переопределения и противоречия. В результате + диагностики или попытки решения каждое ограничение помечается одним из статусов, + перечисленных в наборе GCE_c_status. + + \en The call shows the result of the diagnostic, which highlights the constraint system + well-conditioned parts and parts containing redundancies and inconsistencies. As a result + diagnosing or evaluating each constraint is marked with one of the statuses enumerated by + GCE_c_status enum. + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cItem - \ru Дескриптор ограничения. + \en Descriptor of constraint. \~ + \return \ru Статус ограничения в результате диагностики на противоречия или переопределения. + \en The status of the constraint as a result of diagnostics on inconsistence and overdefining. \~ + +*/ +// --- +GCE_FUNC(GCE_c_status) GCE_ConstraintStatus( GCE_system gSys, constraint_item cItem ); + +//---------------------------------------------------------------------------------------- +/** + brief \ru Выполнить диагностику геометрических объектов. + \en Diagnose geometry. \~ + \details + \ru Если в ходе решения системы ограничений вырождаются какие-то геометрические объекты + (функция #GCE_Evaluate возвращает GCE_RESULT_InvalidGeometry ), то данная функция возвращает + массив индексов, под которыми эти объекты зарегистрированы в решателе. + Если вырождающихся объектов нет, то функция вернет пустой массив. + \en If some geometrical objects are degenerate in the course of solving the system of constraints + (function #GCE_Evaluate returns GCE_RESULT_InvalidGeometry ), this function returns an array of indices + by which these geometric objects are registered in the solver. + If geometrical objects do not degenerate, then the function returns an empty array. \~ + \param[in] gcSys - \ru Система ограничений. + \en System of constraints. \~ + \return \ru Вектор индексов объектов с вырожденной геометрией. + \en Vector of indices of objects with invalid geometry. \~ +*/// --- +GCE_FUNC(std::vector) GCE_DiagnoseGeometry( GCE_system gcSys ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Вычислить степень свободы точки. + \en Calculate point's degree of freedom. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \param[in] cp - \ru Код контрольной точки объекта g. + \en The code of control point of the object g. \~ + \param[out] dofDir- \ru Угловое направление свободы перемещения точки в радианах. + \en Angular direction of point moving freedom in radians. \~ + \return \ru Функция возвращает степень свободы точки; Если возвращается значение < 0, + то вычислить степень свободы не удалось. + \en The function returns degree of freedom of the point; If a negative value is returned, + then it is failed to calculate the degree of freedom. \~ + + \details \ru Данная функция возвращает степень свободы точки и может принимать + одно из следующих значений:\n + (-1) - Означает, что функция не определила степень свободы;\n + 0 - Означает, что точка неподвижна в системе ограничений;\n + 1 - Означает, что точка имеет свободу перемещения вдоль некоторой траектории, причем + через параметр dofDir возвращается направление тангенциального вектора перемещения + точки;\n + 2 - Означает, что точка имеет свободу перемещения в некоторой 2D-области.\n + Если направление перемещения определить не удалось, то dofDir принимает значение < 0. + + \en This function returns the point's degree of freedom and may take + one of the following values:\n + (-1) - It means that the function didn't determine the degree of freedom;\n + 0 - It means that the point is fixed in constraint system. + 1 - It means that the point has a freedom of movement along some trajectory, besides + the direction of point movement tangent vector is returned via the parameter dotDir;\n + 2 - It means that the point has a movement freedom inside some two-dimensional region.\n + If the direction of movement was not determined, then dotDir takes a negative value. \~ +*/ +//-- +GCE_FUNC(ptrdiff_t) GCE_GetPointDOF( GCE_system gSys, geom_item g, point_type cp, double & dofDir ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Вычислить степень свободы точки. + \en Calculate point's degree of freedom. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pnt - \ru Дескриптор точки. + \en Descriptor of point \~ + \param[out] dofDir- \ru Угловое направление свободы перемещения точки в радианах. + \en Angular direction of point moving freedom in radians. \~ + \return \ru Функция возвращает структуру #GCE_point_dof, которая описывает + степень свободы точки, её целочисленное значение и вектор перемещения. + Если возвращается значение dof < 0, то вычислить степень свободы не удалось. + \en The function returns a structure #GCE_point_dof, which describes degree + of freedom of the point, namely its integral value (dof) and direction + vector of point moving freedom (dir). If a negative value (dof) is returned, + then it is failed to calculate the degree of freedom. \~ + + \details \ru Данная функция возвращает степень свободы точки и может принимать + одно из следующих значений:\n + dof = (-1) - Означает, что функция не определила степень свободы;\n + dof = 0 - Означает, что точка неподвижна в системе ограничений;\n + dof = 1 - Означает, что точка имеет свободу перемещения вдоль некоторой траектории, + причем через параметр "dir" (в структуре #GCE_point_dof ) возвращается направление + тангенциального вектора перемещения точки;\n + dof = 2 - Означает, что точка имеет свободу перемещения в некоторой 2D-области.\n + Если направление перемещения определить не удалось, то "dof" принимает значение < 0. + + \en This function returns the point's degree of freedom and may take + one of the following values:\n + dof = (-1) - It means that the function didn't determine the degree of freedom;\n + dof = 0 - It means that the point is fixed in constraint system. + dof = 1 - It means that the point has a freedom of movement along some trajectory, besides + the direction of point movement tangent vector is returned via the parameter "dir" + of data structure #GCE_point_dof;\n + dof = 2 - It means that the point has a movement freedom inside some two-dimensional region.\n + If the direction of movement was not determined, then "dof" takes a negative value. \~ +*/ +//-- +GCE_FUNC(GCE_point_dof) GCE_PointDOF( GCE_system gSys, geom_item pnt ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать степень свободы геометрической координаты. + \en Get the degree of freedom of geometric coordinate. + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of a geometric object. \~ + \param[in] cName - \ru Обозначение геометрической координаты. + \en Denotation of geometric coordinate. \~ + \return \ru Степень свободы координаты: 1-для недоопределенной координаты, 0-для полно-заданной координаты. + \en Degree of freedom: 1 for underdefined coordinate, 0 for well-defined coordinate.\~ + + \details + \ru Функция возвращает степень свободы координаты, а именно одно из возможных + значений: 1, 0 и -1. Если возвращается значение < 0, то вычислить степень + свободы не удалось. + \en The function returns degree of freedom of the coordinate, namely one of the + possible values: 1, 0 and -1. If a negative value is returned, then it is + failed to calculate the degree of freedom. \~ + +*/ +//--- +GCE_FUNC(int) GCE_CoordDOF( GCE_system gSys, geom_item g, coord_name cName ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение для одного объекта (унарное ограничение). + \en Set a constraint on single object (unary constraint). \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cType - \ru Значение одного из следующих типов ограничений: GCE_FIX_GEOM; GCE_VERTICAL; GCE_HORIZONTAL; GCE_ANGLE_OX; GCE_LENGTH. + \en The value of one of the following types of constraints: GCE_FIX_GEOM; GCE_VERTICAL; GCE_HORIZONTAL; GCE_ANGLE_OX; GCE_LENGTH. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details + \ru Функция задает унарное ограничение, а именно ограничение, относящееся к одному из типов, + действительных для одного геометрического объекта. + \en The function specifies an unary constraint, namely constraint which has one of types + that are valid for single geometric object. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddUnaryConstraint( GCE_system gSys, constraint_type cType, geom_item geom ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Совпадение". + \en Set the constraint "Coincidence". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары геометрических объектов. + \en Descriptors of geom objects pair. \~ + \details + \ru Если ограничение совпадение задано для точки и кривой, то предполагается, что точка + лежит на кривой. Если совпадение задано для геометрических объектов одного и того + же типа, то совпадение подразумевает, что они равны. + \en If a coincident constraint is defined between a point and a curve then this implies + that the point lies on the curve. A coincident constraint defined between two + geometries of the same type implies that they are equal. + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \attention + \ru В текущей версии решателя применение этого ограничения возможно + только для двух точек либо для точки и кривой. На будущее планируется расширить + его применения для других типов. + \en In the current version of solver using of this constraint is possible only for + two points either for a point and a curve. It is planned to extend its application + area for other types. \~ +*/ +// --- +GCE_FUNC(constraint_item) GCE_AddCoincidence( GCE_system gSys, geom_item g[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Ограничение "Точка на участке кривой по коэффициенту его параметрической длины". + \en The constraint "Point on a piece of a curve by the coefficient of its parametric range". \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curve - \ru Дескриптор кривой. + \en Descriptor of a curve. \~ + \param[in] pnt - \ru Дескрипторы точек: две крайние точки участка и точка между. + \en Descriptors of points: two boundary points of a piece and a point between. \~ + \param[in] k - \ru Долевой коэффициент от параметрической длины участка. + \en Coefficient for a part of parametric range of piece. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \details \ru Предполагается, что для кривой curve и точек pnt[0], pnt[1], обеспечивается + инцидентность другими ограничениями, зарегистрированными в решателе, или эти + точки априори принадлежат кривой. Для точки pnt[2] инцидентность с кривой задавать + не требуется, т.к. данное ограничение уже обеспечивает это. Если pnt[0] = pnt[1] = GCE_NULL_G, то участок + кривой, для которого исчисляется процент k, совпадает со всей параметрической + областью кривой. Например, для окружности параметрическая область равна + интервалу [-PI ... PI]. Область значений k из интервала от 0 до 1 отображается + на параметрическую область участка кривой, соответственно k = 0 прикрепит точку + pnt[2] к началу участка, а k = 1.0 к концу участка. + + \en It is assumed that for the curve 'curve' and the points pnt[0], pnt[1] an incidence + is provided with the other constraints registered in solver or these + points a priori belong to a curve. An incidence between pnt[2] and 'curve' is not required because + this constraint already provides an incidence. If pnt[0] = pnt[1] = GCE_NULL_G, then the piece + of a curve for which the percentage k is calculated coincides with the whole parametric + region of a curve. For example, in a case of circle the parametric range is equal + to the interval [-PI ... PI]. The range of values of k from the interval from 0 to 1 is mapped + to the parametric region of curve's piece, k = 0 attaches the point + pnt[2] to the beginning of the piece and k = 1.0 - to the end of the piece. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddPointOnPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], double k ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Ограничение "Точка на участке кривой по коэффициенту его длины". + \en The constraint "Point on a piece of a curve by the coefficient of its length". \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curve - \ru Дескриптор кривой. + \en Descriptor of a curve. \~ + \param[in] pnt - \ru Дескрипторы точек: две крайние и точка между ними. + \en Descriptors of points: two boundary points and a point between them. \~ + \param[in] k - \ru Значение доли от метрической длины между заданными точками. + \en Value of a part (proportion) of the arc length between the two points. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \details \ru Метод создает в системе ограничение, задающее положение точки на + участке кривой, заданное коэффициентом от его длины. Предполагается, + что для кривой curve и точек pnt[0], pnt[1], обеспечивается инцидентность другими, + зарегистрированными в решателе, ограничениями или эти точки априори принадлежат + кривой. Если pnt[0] = pnt[1] = GCE_NULL_G, то участок кривой, для которого + исчисляется процент k, совпадает со всей параметрической областью кривой. + Например, для окружности параметрическая область равна интервалу [-PI ... PI]. + Если k = 0, то ограничение прикрепит точку pnt[2] к началу участка, если k = 1.0, + то ограничение прикрепит точку pnt[2] к концу участка. + + \en The method creates a constraint specifying the point location on + a piece of a curve which is set by the coefficient (proportional) of its arc length. + It is assumed that for the curve 'curve' and the points pnt[0], pnt[1] an incidence + is provided with the other constraints registered in the solver or these points belong to + the curve a priori. If pnt[0] = pnt[1] = GCE_NULL_G, then the piece of a curve for which + the percentage k is calculated coincides with the whole parametric region of a curve. + For example, in a case of circle the parametric range is equal to the interval [-PI ... PI]. + If k = 0, then the constraint attaches the point pnt[2] to the beginning of the piece, if k = 1.0, + then the constraint attaches the point pnt[2] to the end of the piece. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddPointByMetricPercent( GCE_system gSys, geom_item curve, geom_item pnt[3], double k ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Фиксация положения точки, лежащей на кривой". + \en Set the constraint "Fixation of location of the point lying on a curve". \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curve - \ru Дескриптор кривой. + \en Descriptor of a curve. \~ + \param[in] pnt - \ru Дескрипторы точки. + \en Descriptors of a point. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \details \ru Данная функция создает ограничение, прикрепляющее точку к кривой в текущем + месте. Точка локализуется, опираясь на параметрическое представление кривой, с помощью + параметра вдоль кривой, где она расположена. Требуется, что бы к моменту вызова функции, + точка лежала на кривой, а для точки и кривой curve должна обеспечиваться инцидентность + с помощью других ограничений или эта точка априори должна принадлежать кривой. + \en This function creates a constraint attaching a point to the curve in the current + location. The point is localized according to the parametric representation of a curve with a help of + parameter along a curve where it is located. It is required that at the moment when the function is called + the point is lying on the curve, and coincidence between the point and the curve should be provided + by other constraints or this point should belong to the curve a priori. \~ + + \attention \ru В Cad-системе КОМПАС данная функция применяется только для фиксации концов + участка (bounded curve) параметрической кривой, полученной проецированием из 3D-модели. + Для таких ограничений, как "средняя точка" рекомендуется применять более + нативную функцию #GCE_AddMiddlePoint. + \en In CAD system KOMPAS this function is used only for fixation of ends of + a piece ('bounded curve') of a parametric curve obtained by projecting from 3D model. + It is recommended to apply the more native function + #GCE_AddMiddlePoint for such constraints as "middle point". \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddFixCurvePoint( GCE_system gSys, geom_item curve, geom_item pnt ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Точка на параметрическом эллипсе". + \en Set the constraint "Point on parametric ellipse". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pnt - \ru Дескриптор точки. + \en Descriptor of a point. \~ + \param[in] ellipse - \ru Дескриптор эллипса. + \en Descriptor of ellipse. \~ + \param[in] \ru t Значение параметра на эллипсе из области [-PI,PI]. + \en t The value of parameter on ellipse from the region [-PI,PI]. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Данная функция действительна только для кривых, относящихся типу + "эллипс", функция создает ограничение, обеспечивающее совпадение точки pnt с + точкой эллипса, заданной параметром t из параметрической области эллипса, + равной интервалу [-PI,PI]. + \en This function is valid only for curves of the type + "ellipse", the function creates a constraint which provides coincidence between the point pnt and + the ellipse point set by the parameter t from the ellipse parametric region + which is equal to the interval [-PI,PI]. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddPointOnParEllipse( GCE_system gSys, geom_item pnt, geom_item ellipse, double t ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Точка на кривой по параметру". + \en Specify a constraint "Point on curve at a given parameter". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pnt - \ru Дескриптор точки. + \en Descriptor of a point. \~ + \param[in] curve - \ru Дескриптор кривой. + \en Descriptor of a curve. \~ + \param[in] t - \ru Дескриптор параметра кривой. + \en Descriptor of a curve parameter. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Функция отличается от #GCE_AddCoincidence тем, что позволяет связать точку с параметрической + кривой через значение параметра и управлять её положением на кривой через этот параметр. + Ограничение доступно для следующих типов кривой: #GCE_ELLIPSE, #GCE_SPLINE, + #GCE_PARAMETRIC_CURVE и #GCE_BOUNDED_CURVE, основанной на кривой одного из перечисленных + типов. + \en This function differs from #GCE_AddCoincidence in that it allows to link a point with a + parametric curve through a parameter value and control its position on the curve through this + parameter. The constraint is available for the following curve types: #GCE_ELLIPSE, + #GCE_SPLINE, #GCE_PARAMETRIC_CURVE and #GCE_BOUNDED_CURVE, based on the curve of one of the + listed types. +*/ +// --- +GCE_FUNC(constraint_item) GCE_AddParPointOnCurve( GCE_system gSys, geom_item pnt, geom_item curve, var_item t ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Выравнивание точек вдоль заданного направления". + \en Set the constraint "Alignment of points along the given direction". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] p - \ru Дескрипторы пары точек. + \en Descriptors of point pair. \~ + \param[in] ang - \ru Угол, задающий направление выравнивания, радианы. + \en An angle specifying alignment direction, in radians. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddAlignPoints( GCE_system gSys, geom_item p[2], double ang ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Угловой размер между двумя прямыми". + \en Set the constraint "Angular dimension between two lines". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] l1 - \ru Дескриптор первого линейного геометрического объекта. + \en Descriptor of the first linear geometric object. \~ + \param[in] l2 - \ru Дескриптор второго линейного геометрического объекта. + \en Descriptor of the second linear geometric object. \~ + \param[in] dPars - \ru Параметры углового размера (подробности см.#GCE_adim_pars). + \en Parameters of angular dimension (see #GCE_adim_pars). \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Угловой размер для пары линейных геометрических объектов. Аргументами + ограничения могут быть объекты, принадлежащие типам: "прямая", "отрезок" или + "Bounded curve", основанной на прямой. + \en Angular dimension for a pair of linear geometric objects. Arguments + of constraint are objects of the following types: "line", "segment" or + "Bounded curve" based on line. \~ + +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddAngle( GCE_system gSys, geom_item l1, geom_item l2 + , const GCE_adim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Биссектриса". + \en Set the constraint "Bisector of angle". \~ + \param[in] \ru gSys Система ограничений. + \en gSys System of constraints. \~ + \param[in] \ru bl отрезок, биссектриса между двумя прямыми. + \en bl a segment, bisector of angle between two lines. \~ + \param[in] \ru l1, l2 прямые или отрезки, между которыми устанавливается биссектриса. + \en l1, l2 lines or segments a bisector of angle is set between. \~ + \param[in] \ru variant вариант решения для биссектрисы. + \en variant variant of solution for bisector of angle. \~ + \return \ru дескриптор нового ограничения. + \en descriptor of new constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddAngleBisector( GCE_system gSys + , geom_item l1, geom_item l2 + , geom_item bl + , GCE_bisec_variant variant ); + +//---------------------------------------------------------------------------------------- +/// \ru Задать угловой размер для четырех точек. \en Specify angular dimension for four points. +/**\ru Конструируется угловой размер для двух отрезков с точками p1-p2, p3-p4. + \en Angular dimension is constructed for two segments with points p1-p2, p3-p4. \~ + \param[in] \ru gSys - Система ограничений. + \en gSys - System of constraints. \~ + \param[in] \ru fPair - Первая пара точек (первый отрезок). + \en sPair - First pair of points (first segment).\~ + \\param[in] \ru fPair - Вторая пара точек (второй отрезок). + \en sPair - Second pair of points (second segment).\~ + \param[in] dPars - \ru Параметры углового размера (подробности см.#GCE_adim_pars). + \en Parameters of angular dimension (see #GCE_adim_pars). \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddAngle4P( GCE_system gSys, geom_item fPair[2] + , geom_item sPair[2], const GCE_adim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Коллинеарность". + \en Set the constraint "Colinearity". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары линейных объектов. + \en Descriptors of a pair of linear objects. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Ограничение делает пару объектов, принадлежащими общей прямой, применяется + для прямых или отрезков. + \en Constraint makes a pair of objects belonging to the common line, it is used + for lines or segments. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddColinear( GCE_system gSys, geom_item g[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Коллинеарность трех точек". + \en Set the constraint "Colinearity of three points". \~ + \details \ru Задать для трех точек отношение, такое что точки лежат на одной прямой. + \en Set such a constraint for three points that points should lie on the same line. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pnt - \ru Тройка точек, лежащих на одной прямой. + \en A triplet of points lying on the same line. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddColinear3Points( GCE_system gcSys, geom_item pnt[3] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Равенство длин" для отрезков. + \en Set the constraint "Equality of lengths" for segments. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] ls1 - \ru Дескриптор первого отрезка. + \en Descriptor of the first segment. \~ + \param[in] ls2 - \ru Дескриптор второго отрезка. + \en Descriptor of the second segment. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Ограничение применимо для отрезков или участков прямых, созданных с помощью + функции #GCE_AddBoundedCurve или #GCE_AddLineSeg. + \en The constraint is applicable for segments or line pieces created by + the function #GCE_AddBoundedCurve or #GCE_AddLineSeg. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddEqualLength( GCE_system gSys, geom_item ls1, geom_item ls2 ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Равенство радиусов" для двух окружностей (дуг) + \en Set the constraint "Equality of radii" for two circles (arcs) \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] c1 - \ru Дескриптор первой окружности. + \en Descriptor of the first circle. \~ + \param[in] c2 - \ru Дескриптор второй окружности. + \en Descriptor of the second circle. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddEqualRadius( GCE_system gSys, geom_item c1, geom_item c2 ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Равенство кривизны двух кривых в заданных точках". + \en Specify a constraint "Equality of curvature of two curves at given points". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curves - \ru Дескрипторы пары кривых. + \en Descriptors of a pair of curves. \~ + \param[in] tPars - \ru Дескрипторы параметров параметрических кривых, в которых должно выполняется + равенство кривизны. + \en Descriptors of parameters of parametric curves in which the equality of curvature + must be satisfied. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \note \ru Если тип кривой #GCE_CIRCLE или #GCE_BOUNDED_CURVE, базовой кривой которой является окружность, + то соответствующее этой кривой значение tPars[i] может равняться #GCE_NULL_V, т.к. кривизна + окружности одинакова во всех её точках. + \en If curve has a type #GCE_CIRCLE or #GCE_BOUNDED_CURVE which is based on circle then the + corresponding value of tPars[i] may be equal to #GCE_NULL_V because the curvature of circle + is the same in all its points. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddEqualCurvature( GCE_system gSys, geom_item curves[2], var_item tPars[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Радиусный размер". + \en Specify a "Radius dimension" constraint. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cir - \ru Дескриптор окружности. + \en Descriptor of circle. \~ + \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). + \en Parameters of linear dimension (see #GCE_dim_pars). \~ + + \return \ru Дескриптор радиусного ограничения. + \en Descriptor of radius constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddRadiusDimension( GCE_system gSys, geom_item cir, GCE_dim_pars dPar ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Диаметральный размер". + \en Specify a "Diameter dimension" constraint. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cir - \ru Дескриптор окружности. + \en Descriptor of circle. \~ + \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). + \en Parameters of linear dimension (see #GCE_dim_pars). \~ + + \return \ru Дескриптор диаметрального ограничения. + \en Descriptor of diameter constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDiameter( GCE_system gSys, geom_item cir, GCE_dim_pars dPar ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Длина кривой". + \en Specify a "Curve Length" constraint. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curve - \ru Дескриптор кривой. + \en Descriptor of curve. \~ + \param[in] dPar - \ru Параметры линейного размера (подробности см.#GCE_dim_pars). + \en Parameters of linear dimension (see #GCE_dim_pars). \~ + + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \details \ru У кривой должны быть начальная и конечная точки (#GCE_FIRST_END и #GCE_SECOND_END). + Ограничение поддерживается для линейных объектов и дуг окружностей. + \en The curve must have a start and end points (#GCE_FIRST_END и #GCE_SECOND_END). + Constraint is supported for linear objects and circular arcs.\~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddLength( GCE_system gSys, geom_item curve, GCE_dim_pars dPar ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Управляющий параметр" или "Фиксация переменной" + \en Set the constraint "Driving parameter" or "Fixation of variable" \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] var - \ru Дескриптор переменной. + \en Descriptor of variable. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \note \ru Созданное с помощью этой функции, ограничение может управляться + через вызов GCE_ChangeDrivingDimension. + \en A constraint created with this function can be driven + via the call of GCE_ChangeDrivingDimension. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_FixVariable( GCE_system gSys, var_item var ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Задать ограничение "Фиксация геометрического объекта". + \en Set the constraint "Fixation of geom" \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +// --- +GCE_FUNC(constraint_item) GCE_FixGeom( GCE_system gSys, geom_item g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Фиксированная длина отрезка" + \en Set the constraint "Fixation of segment length" \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] ls - \ru Дескриптор отрезка. + \en Descriptor of segment. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \details \ru У кривой должны быть начальная и конечная точки (#GCE_FIRST_END и #GCE_SECOND_END). + Ограничение поддерживается для линейных объектов и дуг окружностей. + \en The curve must have a start and end points (#GCE_FIRST_END и #GCE_SECOND_END). + Constraint is supported for linear objects and circular arcs.\~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_FixLength( GCE_system gSys, geom_item ls ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Задать ограничение "Фиксированный радиус". + \en Set the constraint "Fixation of radius" \~ + \details \ru Ограничение применимо для фиксации радиуса окружности или полуоси эллипса. + \en The constraint is applicable to fix radius of circle or semiaxis of ellipse. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] circ - \ru Дескриптор окружности или эллипса. + \en Descriptor of circle or ellipse. \~ + \param[in] cName- \ru Тип фиксируемой координаты. Может быть радиус, большая или малая полуось эллипса. + \en Type of fixed coordinate. It can be #GCE_RADIUS, + #GCE_MAJOR_RADIUS or #GCE_MINOR_RADIUS.\~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +// --- +GCE_FUNC(constraint_item) GCE_FixRadius( GCE_system gSys, geom_item circ, coord_name cName = GCE_RADIUS ); + +//---------------------------------------------------------------------------------------- +/** + \brief + \ru Задать ограничение "Зафиксировать производную сплайна в заданной точке". + \en Set the constraint "Fixation of derivative vector of the spline at a given point". \~ + \param[in] gSys - \ru Система ограничений. \en System of constraints. \~ + \param[in] spline - \ru Дескриптор сплайна. \en Descriptor of spline. \~ + \param[in] par - \ru Значение параметра, в котором надо зафиксировать производную. + \ \en Parameter value in which it is necessary to record a derivative. \~ + \param[in] derOrder - \ru Порядок производной, которую надо зафиксировать. \en Order of the derivative which must be fixed. \~ + \param[in] fixVal - \ru Значение, к которому надо приравнять производную. \en The value to which it is necessary to equate the derivative. \~ + \return \ru Дескриптор нового ограничения. \en Descriptor of a new constraint. \~ + \details + \ru Точка фиксации задается через значение параметра, соответствующего ей. \n + Порядок фиксируемой производной может равняться 0 (фиксация точки), 1, 2 или 3. \n + Если fixVal равен c3d_null, будет зафиксировано текущее значение производной, + иначе фиксируемой производной будет присвоено значение fixVal. + \en + Fixation point is specified via the parameter value corresponding to it. \n + The order of a fixed derivative can be equal 0 (point fixing), 1, 2 or 3. \n + If fixVal is c3d_null current value of the derivative vector will be fixed. + Otherwise the derivative vector will be fixed at fixVal value. \~ + */ +//--- +GCE_FUNC(constraint_item) GCE_FixSplineDerivative( GCE_system gSys, geom_item spline + , double par, uint derOrder, GCE_vec2d * fixVal = c3d_null ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Средняя точка". + \en Set the constraint "Middle point". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pnt - \ru Дескрипторы трех точек. + \en Descriptors of point triplet. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Для данных трех точек, задать отношение, связывающее тройку точек, + так, что третья точка лежит на середине отрезка между pnt[0] и pnt[1]. + \en For the given three points set the relation connecting the point triplet + in such way that the third point lies in the middle of points pnt[0] and pnt[1]. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddMiddlePoint( GCE_system gcSys, geom_item pnt[3] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Параллельность". + \en Set the constraint "Parallelism". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары линейных объектов. + \en Descriptors of a pair of linear objects. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Ограничение применяется для прямых или отрезков. + \en The constraint is used for lines or segments. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddParallel( GCE_system gSys, geom_item g[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Перпендикулярность". + \en Set the constraint "Perpendicularity". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары линейных объектов. + \en Descriptors of a pair of linear objects. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Ограничение применяется для прямых или отрезков. + \en The constraint is used for lines or segments. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddPerpendicular( GCE_system gSys, geom_item g[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Симметрия относительно линейного объекта". + \en Set the constraint "Symmetry relative to the linear object". \~ + + \param[in] gSys - \ru Система ограничений. + gSys - \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары симметричных объектов. + g - \en Descriptors pair of symmetrical objects.. \~ + \param[in] lObj - \ru Дескриптор оси симметрии. + lObj - \en Descriptor of the axis of symmetry. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + + \attention \ru В настоящий момент данное ограничение применимо только для симметрии точек. + \en Currently, this restriction only applies to the symmetry of the points. \~ + */ +//--- +GCE_FUNC(constraint_item) GCE_AddSymmetry( GCE_system gSys, geom_item g[2], geom_item lObj ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Касание двух кривых". + \en Set the constraint "Tangency of two curves". \~ + \param[in] \ru gSys Система ограничений. + \en gSys System of constraints. \~ + \param[in] \ru g Дескрипторы пары кривых или прямых. + \en g Descriptors of a pair of curves or lines. \~ + \param[in] \ru tPar Дескрипторы параметров касания для параметрических кривых. + \en tPar Descriptors of parameters of tangency for parametric curves. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details + \par \ru Вспомогательные параметры касания + \en Help parameters of tangency + \ru Дескрипторы переменных tPar[0] и tPar[1] задают вспомогательные значения, параметризующие + точку касания на первой и второй кривой. Одна или обе tPar могут быть равными GCE_NULL_V, + если соответствующая кривая не является сплайном или параметрической кривой, либо + пользователь согласен, что точка касания будет локализована автоматически по ближайшему решению. + + \en Variable descriptors tPar[0], tPar[1] specify help values parametrizing a tangent point + on the first and the second curve. One of both tPar can be equal GCE_NULL_V. + + \note \ru tPar[0] или tPar[1] могут быть равными GCE_NULL_V, если параметры + касания не предусмотрены или кривые не имеют параметрического представления. + Параметрическое представление имеют пока только два типа: + GCE_SPLINE и GCE_PARAMETRIC_CURVE. + \en tPar[0] or tPar[1] may be equal to GCE_NULL_V if parameters + of tangency are not provided or curves have no parametric representation. + There are only two types having parametric representation: + GCE_SPLINE and GCE_PARAMETRIC_CURVE. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddTangent( GCE_system gSys, geom_item g[2], var_item tPar[2] ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать размерное ограничение "Расстояние между объектами". + \en Set the dimensional constraint "Distance between objects". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескрипторы пары геометрических объектов. + \en Descriptors of a pair of geometric objects. \~ + \param[in] dPars - \ru Параметры линейного размера (подробности см.#GCE_ldim_pars). + \en Parameters of linear dimension (see #GCE_adim_ldim). \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Задать линейный размер для пары геометрических объектов. + \en Set linear dimension for a pair of geometric objects. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDistance( GCE_system gSys, geom_item g[2], const GCE_ldim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Расстояние между точками". + \en Set the constraint "Distance between points". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] p - \ru Дескрипторы пары точек. + \en Descriptors of point pair. \~ + \param[in] dPars - \ru Параметры размерного ограничения. + \en Parameters of dimensional constraint. \~ + + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDistance2P( GCE_system gSys, geom_item p[2], const GCE_dim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Расстояние от точки до отрезка". + \en Set the constraint "Distance from a point to a segment". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] p - \ru Дескрипторы тройки точек. + \en Descriptors of point triplet. \~ + \param[in] dPars - \ru Параметры размерного ограничения. + \en Parameters of dimensional constraint. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Линейный размер от точки p1 до отрезка . Размер чувствителен к знаку + величины размера. + \en Linear dimension from the point p1 to the segment . + The dimension is sensitive to a sign of its value. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDistancePLs( GCE_system gSys, geom_item p[3] + , const GCE_dim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Ориентированное расстояние между точками". + \en Set the constraint "Directed distance between points". \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] p - \ru Дескрипторы пары точек. + \en Descriptors of point pair. \~ + \param[in] dPars - \ru Параметры размерного ограничения. + \en Parameters of dimensional constraint. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Параметр dPars.dirAngle задает направление размера в радианах. + Управляя dPars.dirAngle, можно задать вертикальный или + горизонтальный размеры. Так размер параметром dPars.dirAngle = 0 + создаст "горизонтальный размер", а dPars.dirAngle, равный PI/2 радиан + будет соответствовать "вертикальному" размеру. + + \en The constraint represents the dimension type that dimensions the + distance between two points in plane when they are projected onto a line + at an angle specified by parameter dPars dirAngle, which sets the direction + of dimension in radians. With driving dPars.dirAngle it is possible to + set the vertical or the horizontal dimension. So a dimension with an angle + equal to 0 radians specifies a "horizontal". The angle equal to PI/2 radians + corresponds to "vertical" dimension. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDirectedDistance( GCE_system gSys, geom_item p[2] + , const GCE_ldim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать линейное уравнение. + \en Set the linear equation. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] a - \ru Вектор коэффициентов линейного уравнения. + \en Vector of coefficients of linear equation. \~ + \param[in] v - \ru Дескрипторы переменных уравнения. + \en Descriptors of variables of equation. \~ + \param[in] n - \ru Количество переменных. + \en Quantity of variables.\~ + \param[in] c - \ru Коэффициент без переменной. + \en Free coefficient. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details \ru Задать линейное уравнение в виде a1*v1 + a2*v2 + .. + an*vn + c = 0. + \en Set a linear equation in form of a1*v1 + a2*v2 + .. + an*vn + c = 0. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddLinearEquation( GCE_system gSys, const double * a + , const var_item * v, size_t n, double c ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Изменить значение управляющего размера. + \en Change the value of driving dimension. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] dItem - \ru Дескриптор размерного ограничения. + \en Descriptor of dimensional constraint. \~ + \param[in] dVal - \ru Требуемое значение размера. + \en Required value of constraint. \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \details \ru Функция применяется только для управляющих размеров или управляющих параметров. + Если управляющий размер или параметр является угловым, то параметр dVal задается в радианах.\n + Следует учитывать, что настоящая функция не осуществляет вычислений, а только + подготавливает изменение размера. Что бы изменения вступили в силу, необходимо вызвать + функцию #GCE_Evaluate. + \en The function is used only for driving dimensions or driving parameters. + If the driving dimension or parameter is angular, then the parameter dVal is specified in radians. \n + It should be taken into account that the function doesn't perform computations but only + prepares the changing of dimension. For the changes to take effect it is required + to call the function #GCE_Evaluate. \~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_ChangeDrivingDimension( GCE_system gSys, constraint_item dItem, double dVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Отклонить ограничение от точки решения. + \en Deviate the constraint from the point of solution. \~ + \param[in] dItem - \ru Дескриптор геометрического ограничения. + \en Descriptor of geometric constraint. \~ + \param[in] delta - \ru Величина отклонения. + \en Deviation value. \~ + \return errCode - \ru Результат решения системы ограничений. + \en Solution of constraint system. \~ + + \details \ru Функция применяется для диагностики избыточности ограничения, основанной + на отклонении области решений ограничения. Работает только для размерных ограничений + и некоторых типов геометрических ограничений, таких как "Выравнивание точек", + "Горизонтальность" и т.д. Применимость к тому или иному типу не задокументирована и + определяется опытным путем. + Если было возвращено значение GCE_RESULT_None, то ограничение не отклонялось. + \en The function is used for the diagnostics of constraints redundancy based + on the deviation of the region of solution of the constraint. It works only for dimensional constraints + and other types of geometric constraints such as "Points alignment", + "Horizontality" etc. The applicability to a certain type was not documented and + it is defined only empirically. + If GCE_RESULT_None is returned, the constraint wasn't deviated. \~ +*/ +// --- +GCE_FUNC(GCE_result) GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Тест избыточности ограничения, основанный на отклонении его от точки решения. + \en Test for redundancy of constraint based on the deviation the constraint from the point of solution. \~ + \param[in] dItem - \ru Дескриптор геометрического ограничения. + \en Descriptor of geometric constraint. \~ + \param[in] delta - \ru Величина отклонения. + \en Deviation value. \~ + \return - \ru Результат решения системы ограничений. + \en Solution of constraint system. \~ + + \details \ru Функция применяется для диагностики избыточности ограничения, основанной + на отклонении области решений ограничения. Работает только для размерных ограничений + и некоторых типов геометрических ограничений, таких как "Выравнивание точек", + "Горизонтальность" и т.д. Применимость к тому или иному типу (кроме размерных) не + задокументирована и определяется опытным путем. + Если было возвращено значение GCE_RESULT_None, то ограничение не отклонялось. + \en The function is used for the diagnostics of constraints redundancy based + on the deviation of the region of solution of the constraint. It works only for dimensional constraints + and other types of geometric constraints such as "Points alignment", + "Horizontality" etc. The applicability to a certain type (for non dimensional) + was not documented and it is defined only empirically. + If GCE_RESULT_None is returned, the constraint wasn't deviated. \~ + + \note \ru В отличии от #GCE_DeviateDimension не меняется состояние системы ограничений. + \en Unlike #GCE_DeviateDimension this function does not change state of geometric constraint system. +*/ +// --- +GCE_FUNC(GCE_result) GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Текущее значение размерного параметра. + \en A current value of the dimension parameter. + \details \ru Функция выдает текущее значение размерного параметра ограничения. Если + ограничение не размерное, то функция вернет GCE_UNDEFINED_DBL. Для управляющих размеров + будет выдано значение управляющего параметра, которое было задано при создании размера + или последним вызовом GCE_ChangeDrivingDimension. + \en The function returns a value of dimension parameter of the constraint. + If the constraint is a driving dimension, the function returns a value of dimension + parameter specified when creating the constraint or last call of #GCE_ChangeDrivingDimension. +*/ +//--- +GCE_FUNC(double) GCE_DimensionParameter( GCE_system gSys, constraint_item dItem ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вычислить систему ограничений. + \en Calculate the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \return \ru Код результата вычислений. + \en Calculation result code. \~ + \details \ru Функция решает задачу ограничений. Задача ограничений формулируется + функциями API геометрического решателя; функции вида GCE_Add_XXXXXXX добавляют новые + объекты, функции вида GCE_Change_XXXXXXX, GCE_Set_XXXXXXX изменяют состояние + объектов. Таким образом, что бы все такие изменения вступили в силу, нужно + вызвать метод #GCE_Evaluate.\n + Алгоритмы GCE_Evaluate учитывают удовлетворенность систем ограничений; если + все ограничения уже решены, то функция не тратит время на вычисления, а + состояние геометрических объектов остается неизменным. + \en The function solves problem of constraints. The problem of constraint is formulated + by API functions of geometric solver; the functions of a kind GCE_Add_XXXXXXX add a new + object, the functions of kinds GCE_Change_XXXXXXX and GCE_Set_XXXXXXX change a state + of objects. Thus, for all changes to take effect it is necessary + to call the method #GCE_Evaluate.\n + The algorithms GCE_Evaluate take into account whether constraint systems are satisfied, if + all constraints have been already solved, then the function doesn't spend time for calculations, and + the state of geometric objects remains unchanged. \~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_Evaluate( GCE_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Инициализировать режим драггинга контрольной точки объекта. + \en Initialize the dragging mode of the object control point. \~ + \param[in] \ru gSys Система ограничений. + \en gSys System of constraints. \~ + \param[in] \ru obj Геометрический объект. + \en obj Geometric object. \~ + \param[in] \ru pntId Обозначение передвигаемой контрольной точки объекта. + \en pntId Denotation of the dragged control point of the object. \~ + \param[in] \ru curXY Координаты курсора, куда следует перемещаемая точка. + \en curXY Coordinates of cursor where the moving point follows. \~ + \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. + \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_PrepareMovingOfPoint( GCE_system gSys, geom_item obj + , point_type pntId, GCE_point curXY ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Инициализировать режим драггинга контрольной точки объекта. + \en Initialize the dragging mode of the object control point. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] drgPnt - \ru Контрольная точка объекта. + \en A geom control point. \~ + \param[in] curXY - \ru Координаты точки драггинга. + \en Coordinates of dragging point. \~ + \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. + \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_PrepareDraggingPoint( GCE_system gSys, GCE_dragging_point drgPnt + , GCE_point curXY ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Инициализировать режим драггинга контрольной точки множества объектов. + \en Initialize the dragging mode of the control point of object set. \~ + \details \ru Этот метод предназначен для группового редактирования (драггинг) + нескольких объектов с "общей" hot-точкой. Под "общей" hot-точкой подразумевается + не обязательно одна точка (с одним дескриптором), а множество точек с разными + дескрипторами, но имеющих одинаковые координаты. + \en This method is intended for the group dragging of few objects with + the "common" hot-point. A "common" hot-point is not necessarily the only point + (with the only descriptor), but a set of points with different descriptors but + with equal coordinates. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cPntArr - \ru Множество геометрически одинаковых контрольных точек. + \en A set of geometrically equal control points. \~ + \param[in] curXY - \ru Координаты точки драггинга. + \en Coordinates of dragging point. \~ + \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. + \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_PrepareDraggingPoint( GCE_system gSys + , const std::vector & cPntArr + , GCE_point curXY ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Инициализировать режим перетаскивания множества объектов. + \en Initialize mode of moving a set of objects. + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param geoms - \ru Множество геометрических объектов. + \en Set of geometric objects. \~ + \param curXY - \ru Координаты точки драггинга. + \en Coordinates of dragging point. \~ + \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. + \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ + +*/ +//--- +GCE_FUNC(GCE_result) GCE_PrepareMovingGeoms( GCE_system gSys + , std::vector & geoms + , GCE_point curXY ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Переместить точку драггинга. + \en Move a dragging point. \~ + \param[in] gcSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curXY - \ru Текущие координаты курсора. + \en Current coordinates of cursor. \~ + \return \ru Код ошибки. Вернет код GCE_RESULT_Ok, если подготовка режима драггина прошла успешна. + \en Error code. Returns GCE_RESULT_Ok if preparing the dragging mode was successful.\~ + + \details \ru Процедура обслуживает режим драггинга, с ее помощью геометрический решатель + отслеживает положение курсора. Этот вызов позволяет осуществлять двух-координатное + управление не доопределенной моделью. Если функция возвращает код ошибки, + не равный #GCE_RESULT_Ok, то гарантируется, что состояние геометрических объектов + останется неизменным. Если функция вернула #GCE_RESULT_Ok, то решатель содержит + новое состояние геометрических объектов, удовлетворяющее всем ранее наложенным + ограничениям (новое решение). В этом случае вызывать #GCE_Evaluate для приведения + объектов в решенное состояние не требуется. + \en The procedure services the dragging mode, with a help of it a geometric solver + tracks the cursor location. This call allows to perform a two-coordinate + control of an underdetermined model. If the function returns an error code, + which is not #GCE_RESULT_Ok, then it is guaranteed that the state of geometric objects + will remain the same. If the function returned #GCE_RESULT_Ok, then the solver contains + a new state of geometric objects satisfying to all the constraints created before + (a new solution). In this case it not required to call #GCE_Evaluate for the conversion + of objects to the solved state. \~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_MovePoint( GCE_system gcSys, GCE_point curXY ); + +//---------------------------------------------------------------------------------------- +/** + brief \ru Трансформировать геометрические объекты согласно заданной матрице. + \en Transform geometric objects according to a given matrix. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] geoms - \ru Множество геометрических объектов. + \en Set of geometric objects. \~ + \param[in] mat - \ru Матрица преобразования. + \en Transformation matrix. \~ + \return \ru Код ошибки. \en Error code. \~ + + \details \ru Режим динамической трансформации для данного набора геометрических объектов + включается при первом вызове функции #GCE_DynamicTransform. При этом запоминаются начальные + положения геометрических объектов и далее трансформации при каждом новом вызове + #GCE_DynamicTransform выполняются относительно их первоначального положения до тех пор, пока + режим динамической трансформации не будет выключен. Выключается режим динамической + трансформации геометрических объектов при вызове любой другой функции API или при вызове + функции #GCE_DynamicTransform для другого набора геометрических объектов. + \en The dynamic transformation mode for given set of geometric objects is turned on + after the first time the #GCE_DynamicTransform function is called. In this case, the initial + positions of geometric objects are remembered and then the transformations for each new call + of the #GCE_DynamicTransform are performed relative to their initial position until the dynamic + transformation mode is turned off. The mode of dynamic transformation of geometric objects is + turned off when calling any other API function or when calling the #GCE_DynamicTransform + function for another set of geometric objects. \~ +*/// --- +GCE_FUNC(GCE_result) GCE_DynamicTransform( GCE_system gSys, const std::vector & geoms, const MbMatrix & mat ); + +//---------------------------------------------------------------------------------------- +/** + brief \ru Трансформировать геометрию системы ограничений согласно заданной матрице. + \en Transform the geometry of the constraints system according to a given matrix. \~ + \details \ru Если преобразование несобственное, т.е. включает в себя отражение, то изменится + направление кривых, ограниченных двумя точками, у которых базовая кривая замкнутая. + Это значит, что после преобразования, запрос #GCE_PointOf для таких кривых в качестве #GCE_FIRST_END + будет возвращать точку, которую до преобразования выдавал в качестве #GCE_SECOND_END и наоброт. + \en If the transformation is improper, i.e. includes reflection, direction of bounded curves + for which the base curve is closed will be changed. This means that after transformation, + the request #GCE_PointOf for such curves will return as a #GCE_FIRST_END a point that + before transformation returned as #GCE_SECOND_END and vice versa.\~ + + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] mat - \ru Матрица преобразования. + \en Transformation matrix. \~ + \return \ru Код ошибки. \en Error code. \~ +*/// --- +GCE_FUNC(GCE_result) GCE_Transform( GCE_system gSys, const MbMatrix & mat ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Включить журналирование и назначить файл для записи журнала вызовов API. + \en Switch on the journalling and specify the file for recording a journal of GCE API calls. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] fName - \ru Имя файла назначения с полным путем. + \en Name of destination file with a full path. \~ + \return true, if journalling has been successfully switched on. + \attention + \ru Файл журнала будет записан только после завершения сеанса работы с системой + ограничений, а именно сразу после вызова GCE_RemoveSystem. + \en The journal file will be written only when a session of work with the + constraint system is finished, i.e. immediately after calling the + GCE_RemoveSystem method. +*/ +//--- +GCE_FUNC(bool) GCE_SetJournal( GCE_system gSys, const char * fName ); + +#define FB_NULL_GEOM 0 + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + Рекомендуется использовать новую функцию: #GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta ) + \en An obsolete function. The call will be removed in one of the next versions. + It's recommended to use new version of this function: #GCE_DeviateDimension( GCE_system gSys, constraint_item dItem, double delta )\~ + */ +// --- +GCE_FUNC(bool) GCE_DeviateDimension( GCE_system gSys, constraint_item dItem + , double delta, GCE_result & errCode ); + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + Рекомендуется использовать новую функцию: #GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta ) + \en An obsolete function. The call will be removed in one of the next versions. + It's recommended to use new version of this function: #GCE_DeviationTest( GCE_system gSys, constraint_item dItem, double delta )\~ + */ +// --- +GCE_FUNC(bool) GCE_DeviationTest( GCE_system gSys, constraint_item dItem + , double delta, GCE_result & errCode ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + \en An obsolete function. The call will be removed in one of the next versions. \~ + + \attention \ru Время жизни экземпляра класса crv опирается на счетчик ссылок, т.е. + решатель его увеличивает при добавлении кривой и декрементирует при удалении кривой из решателя. + \en The lifetime of the instance of the class 'crv' is based on the reference counter, i.e. + the solver increases it when adding a curve and decreases when deleting a curve from the solver. \~ +*/ +//--- +class MbPolyCurve; +GCE_FUNC(geom_item) GCE_AddSpline( GCE_system gSys, const MbPolyCurve & crv ); + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + \en An obsolete function. The call will be removed in one of the next versions. \~ +*/ +//--- +inline geom_item GCE_AddPoint( GCE_system gSys, GCE_point pVal, int ) +{ + return GCE_AddPoint( gSys, pVal ); +} + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + \en An obsolete function. The call will be removed in one of the next versions. \~ +*/ +//--- +GCE_FUNC(GCE_system) GCE_CreateSystem( void * ); + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий (2016). + \en An obsolete function. The call will be removed in one of the next versions (2016). \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddDirectedDistance2P( GCE_system gSys, geom_item p[2] + , const GCE_ldim_pars & dPars ); + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + \en An obsolete function. The call will be removed in one of the next versions. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddAlignPoints( GCE_system gSys, geom_item p[2], bool hor ); + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Функция устарела. Вместо неё применять #GCE_FixLength. + \en The function is obsolete. Use #GCE_FixLength instead. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddFixedLength( GCE_system, geom_item ); + +//---------------------------------------------------------------------------------------- +/** + \attention \ru Функция устарела. Вместо неё применять #GCE_FixVariable. + \en The function is obsolete. Use #GCE_FixVariable instead. \~ +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddFixVariable( GCE_system, var_item ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение "Точка на кривой". + \en Set the constraint "Point on curve". \~ + \attention This call is deprecated. Call #GCE_AddCoincidence instead. +*/ +//--- +GCE_FUNC(constraint_item) GCE_AddIncidence( GCE_system, geom_item, geom_item ); + +//---------------------------------------------------------------------------------------- +/** + \attention + \ru Устаревшая функция. Вызов будет удален в одной из следующих версий. + Используйте #GCE_PrepareMovingOfPoint( GCE_system gSys, const std::vector & cPntArr, GCE_point curXY ) + взамен. + \en An obsolete function. The call will be removed in one of the next versions. + Use GCE_PrepareDraggingPoint( GCE_system gSys, const std::vector & cPntArr, GCE_point curXY ) instead of this. \~ +*/ +//--- +GCE_FUNC(GCE_result) GCE_PrepareMovingOfPoint( GCE_system gSys + , const std::vector & cPntArr + , GCE_point curXY ); + +/** \} */ + +#endif // __GCE_API_H + +// eof diff --git a/C3d/Include/gce_callback.h b/C3d/Include/gce_callback.h index e994b3b..939838a 100644 --- a/C3d/Include/gce_callback.h +++ b/C3d/Include/gce_callback.h @@ -1,96 +1,96 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Функции и типы данных для обратных вызовов двухмерного геометрического решателя. - \en Functions and data types for callbacks of the 2D-solver. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCE_CALLBACK_H -#define __GCE_CALLBACK_H - -#include - -/** - \addtogroup Constraints2D_API - \{ -*/ - -/* - Application data types for callback queries -*/ -typedef void* GCE_app_geom; ///< Geometric object of the application using the solver -//typedef void* GCE_app_client; -const GCE_app_geom GCE_NOGEOM = 0; ///< \en Specifies an undefined object of the user's app. \ru Означает неопределенный объект пользовательского приложения. - -/* - Callback enquiries -*/ -typedef void ( *GCE_geom_registered )( GCE_app_geom ag ); ///< Application geom was registered in the solver. -typedef void ( *GCE_geom_unregistered )( GCE_app_geom ag ); -typedef bool ( *GCE_allow_zero_radius )( GCE_app_geom ag ); ///< -typedef bool ( *GCE_abort )(); ///< Query to interrupt calculations - -//---------------------------------------------------------------------------------------- -/** \brief \ru Структура, объединяющая обратные вызовы двухмерного решателя. - \en The structure uniting 2D-solver callbacks. - \details \ru Таблица функций, определяемых на стороне пользовательского приложения - для "тонкой настройки" решателя. - \en Table of user-defined callbacks tuning the 2D-solver. \~ -*/ -//--- -typedef struct -{ - /* - General system callbacks; - */ - GCE_geom_registered gRegister; - GCE_geom_unregistered gUnregister; - GCE_abort abortFunc; - - /* - Geometry properties - */ - GCE_allow_zero_radius allowZeroRadius; ///< Permit circle to have zero radius. -} GCE_callback_table; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Установить и вернуть структуру с функциями обратного вызова по умолчанию. - \en Set and return default callback functions. \~ - \details \ru GCE_callback_table - простая структура в стиле C, не имеющая конструктора. - Функция GCE_InitCallbacks позволяет придать структуре начальное значение - что бы избежать некорректных значений в памяти. - \en GCE_callback_table is a plain old data structure with no constructor. - The function is able to set an initial value of the structure to avoid - incorrect work with memory. -*/ -//--- -GCE_FUNC(GCE_callback_table&) GCE_InitCallbacks( GCE_callback_table & ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Зарегистрировать таблицу обратных вызовов для новой системы ограничений. - \en Register callback table for new constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en Constraint system. \~ - \param[in] cbTable - \ru Таблица обратных вызовов. - \en Table of callbacks. \~ - \return \ru Вернет GCE_RESULT_Ok, если регистрация выполнена. - \en Returns GCE_RESULT_Ok if the registration fulfilled. \~ - -*/ -//--- -GCE_FUNC(GCE_result) GCE_Register( GCE_system gSys, const GCE_callback_table & cbTable ); - -//---------------------------------------------------------------------------------------- -/// Associate an application geometry and a solver's descriptor. -//--- -GCE_FUNC(void) GCE_Bind( GCE_system, geom_item, GCE_app_geom ); - -/** - \} - Constraints2D_API -*/ - -#endif // __GCE_CALLBACK_H - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Функции и типы данных для обратных вызовов двухмерного геометрического решателя. + \en Functions and data types for callbacks of the 2D-solver. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCE_CALLBACK_H +#define __GCE_CALLBACK_H + +#include + +/** + \addtogroup Constraints2D_API + \{ +*/ + +/* + Application data types for callback queries +*/ +typedef void* GCE_app_geom; ///< Geometric object of the application using the solver +//typedef void* GCE_app_client; +const GCE_app_geom GCE_NOGEOM = 0; ///< \en Specifies an undefined object of the user's app. \ru Означает неопределенный объект пользовательского приложения. + +/* + Callback enquiries +*/ +typedef void ( *GCE_geom_registered )( GCE_app_geom ag ); ///< Application geom was registered in the solver. +typedef void ( *GCE_geom_unregistered )( GCE_app_geom ag ); +typedef bool ( *GCE_allow_zero_radius )( GCE_app_geom ag ); ///< +typedef bool ( *GCE_abort )(); ///< Query to interrupt calculations + +//---------------------------------------------------------------------------------------- +/** \brief \ru Структура, объединяющая обратные вызовы двухмерного решателя. + \en The structure uniting 2D-solver callbacks. + \details \ru Таблица функций, определяемых на стороне пользовательского приложения + для "тонкой настройки" решателя. + \en Table of user-defined callbacks tuning the 2D-solver. \~ +*/ +//--- +typedef struct +{ + /* + General system callbacks; + */ + GCE_geom_registered gRegister; + GCE_geom_unregistered gUnregister; + GCE_abort abortFunc; + + /* + Geometry properties + */ + GCE_allow_zero_radius allowZeroRadius; ///< Permit circle to have zero radius. +} GCE_callback_table; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Установить и вернуть структуру с функциями обратного вызова по умолчанию. + \en Set and return default callback functions. \~ + \details \ru GCE_callback_table - простая структура в стиле C, не имеющая конструктора. + Функция GCE_InitCallbacks позволяет придать структуре начальное значение + что бы избежать некорректных значений в памяти. + \en GCE_callback_table is a plain old data structure with no constructor. + The function is able to set an initial value of the structure to avoid + incorrect work with memory. +*/ +//--- +GCE_FUNC(GCE_callback_table&) GCE_InitCallbacks( GCE_callback_table & ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Зарегистрировать таблицу обратных вызовов для новой системы ограничений. + \en Register callback table for new constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en Constraint system. \~ + \param[in] cbTable - \ru Таблица обратных вызовов. + \en Table of callbacks. \~ + \return \ru Вернет GCE_RESULT_Ok, если регистрация выполнена. + \en Returns GCE_RESULT_Ok if the registration fulfilled. \~ + +*/ +//--- +GCE_FUNC(GCE_result) GCE_Register( GCE_system gSys, const GCE_callback_table & cbTable ); + +//---------------------------------------------------------------------------------------- +/// Associate an application geometry and a solver's descriptor. +//--- +GCE_FUNC(void) GCE_Bind( GCE_system, geom_item, GCE_app_geom ); + +/** + \} + Constraints2D_API +*/ + +#endif // __GCE_CALLBACK_H + // eof \ No newline at end of file diff --git a/C3d/Include/gce_geom.h b/C3d/Include/gce_geom.h index 6665a79..c7d41bd 100644 --- a/C3d/Include/gce_geom.h +++ b/C3d/Include/gce_geom.h @@ -1,329 +1,309 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Программный интерфейс для системы КОМПАС - \en Program interface for KOMPAS system. \~ - \details \ru Данный файл содержит классы и методы, ориентированные на типы - данных CAD-системы КОМПАС. Для других приложений это API может оказаться - не удобным, а его методы могут быть удалены или изменены в будущих - версиях. Рекомендуется применять эту часть API решателя, только если - не удасться найти требуемую функциональность в заголовочных файлах - gce_api.h или gce_types.h. - \en This file contains classes and methods oriented to - data types of CAD-system KOMPAS. For other applications this API can be - inconvenient and its methods can be deleted or modified in future - versions. It is recommended to apply this part of solver API only if - the required functionality is not found in header files - gce_api.h or gce_types.h. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCE_GEOM_H -#define __GCE_GEOM_H -// -#include -#include -#include -// -#include "gce_types.h" - - -class MATH_CLASS MbPolyCurve; -struct IfGeomPoint2d; - -//---------------------------------------------------------------------------------------- -// \ru Перечисление параметрических объектов \en Enumeration of parametric objects. -//--- -enum GcGeomType -{ - vt_NULL, ///< \ru Несуществующий тип. \en Nonexistent type. - gt_Point2d, ///< \ru Точка. \en Point. - gt_Line2d, ///< \ru Прямая. \en Line. - gt_LineSegment2d, ///< \ru Отрезок. \en Segment. - gt_Circle2d, ///< \ru Окружность. \en Circle. - gt_Arc2d, ///< \ru Дуга. \en Arc. - gt_Ellipse2d, ///< \ru Эллипс. \en Ellipse. - gt_EllipseArc2d, ///< \ru Дуга эллипса. \en Ellipse arc. - // gt_ViewPointerArrow, ///< \ru Отрезок. \en Segment. -}; - -//---------------------------------------------------------------------------------------- -// \ru Макросы \en Macros -// --- -#define CAST_PTR(T) IfGeom2dPtr // \ru Указатель с функцией приведения типов \en Pointer with function of type conversion -#define GEOM_PTR(T) IfGeom2dPtr // \ru Указатель с функцией приведения типов \en Pointer with function of type conversion -#define CAST2PTR(T,arg) (arg) != NULL ? (T*)((arg)->GetInterfacingGeom(iidr_ ## T)) : NULL // \ru Привести к другому типу \en Convert to another type - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Координата геометрического объекта или переменной \en Coordinate of a geometric object or a variable -////////////////////////////////////////////////////////////////////////////////////////// -struct ItGeomCoord : public ItCoord -{ - virtual refcount_t AddRef() const = 0; - virtual refcount_t Release() const = 0; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -/*\ru Надкласс примитивных геометрических объектов решателя - Внимание: Применяется только для САПР КОМПАС. Рекомендуется вместо него использовать вызовы API из gce_api.h - объектом IfSomething. Вместо макроса IFPTR применять GEOM_PTR.\n - После того, как MdViewObj будет наконец-то, освобождать память по правилам - IfSomething, нужно:\n - 1) Все слова IfSomethingGeom2d заменить на IfSomething;\n - 2) Все слова GetInterfacingGeom заменить на QueryInterface;\n - 3) Удалить этот класс;\n - 4) Компилятор сам подскажет, какие места нужно доправить;\n - - \en Used while there is no correct work with MdViewObj in 2D model - as with object IfSomething. GEOM_PTR is to be applied instead of macro IFPTR.\n - After MdViewObj has been implemented it is required to free memory by rules IfSomething, - it is necessary to:\n - 1) All words IfSomethingGeom2d replace by IfSomething;\n - 2) All words GetInterfacingGeom replace by QueryInterface;\n - 3) Delete this class;\n - 4) Compiler will prompt which places are to be corrected;\n \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// -struct IfSomethingGeom2d -{ - virtual IfSomethingGeom2d * GetInterfacingGeom( unsigned int iid ) = 0; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Геометрический объект параметризации \en Geometric object of parametrization -/*\ru Этот тип и его подтипы соответствуют словарю типов решателя, а не типам пользователя. - \en This type and its subtypes correspond to the dictionary of types of the solver but not to the user types. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// -struct IfGeom2d: public IfSomethingGeom2d -{ - virtual GcGeomType GetGeomType() const = 0; - /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual point_type IdentCtrlPoint( const IfGeomPoint2d & ) const = 0; - /// \ru Выдать обозначение координаты, принадлежащей объекту \en Get notation of coordinate belonging to the object - virtual coord_name IdentCoord( const ItGeomCoord & ) const = 0; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Точка на плоскости \en Point on the plane -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomPoint2d: public IfGeom2d -{ - virtual GcGeomType GetGeomType() const { return gt_Point2d; } - virtual ItGeomCoord * GetXCoord() const = 0; - virtual ItGeomCoord * GetYCoord() const = 0; - /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual coord_name IdentCoord( const ItGeomCoord & ) const; - -public: - inline MbCartPoint GetValue() const; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// Deprecated (2017). Use GCE_AddLine instead this. -/* - КОМПАС отвязан от этого интерфейса. -*/ -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomLine2d: public IfGeom2d -{ - virtual GcGeomType GetGeomType() const { return gt_Line2d; } - virtual ItGeomCoord * GetACoord() = 0; ///< \ru Выдать угол нормали прямой \en Get angle of line normal - virtual ItGeomCoord * GetDCoord() = 0; ///< \ru Выдать расстояние до начала СК в направлении нормали \en Get distance to the coordinate system origin in the normal direction - /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual coord_name IdentCoord( const ItGeomCoord & ) const; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Отрезок на плоскости \en Segment on the plane -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomLineSeg2d: public IfGeom2d -{ - virtual GcGeomType GetGeomType() const { return gt_LineSegment2d; } - virtual IfGeomPoint2d * GetEnd( int nb ) = 0; ///< \ru Выдать конец отрезка 1,2 \en Get end of segment 1,2 - virtual bool IsFixedLength() = 0; ///< \ru Признак отрезка постоянной длины (для стрелки взгляда) \en Flag of segment of constant length (for the view vector) - // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual coord_name IdentCoord( const ItGeomCoord & ) const { return GCE_NULL_CRD; } - inline GCE_point EndPoint( int nb ); ///< \ru Выдать конец отрезка 1,2 \en Get end of segment 1,2 -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// Deprecated (2017). Use GCE_AddCircle instead this. -/* - КОМПАС отвязан от этого интерфейса. -*/ -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomCircle2d: public IfGeom2d -{ - virtual GcGeomType GetGeomType() const { return gt_Circle2d; } - virtual IfGeomPoint2d * GetCentre() = 0; - virtual ItGeomCoord * GetRadius() = 0; - // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual coord_name IdentCoord( const ItGeomCoord & ) const; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Эллипс на плоскости \en Ellipse on the plane -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomEllipse2d: public IfGeom2d -{ - virtual GcGeomType GetGeomType() const { return gt_Ellipse2d; } - virtual IfGeomPoint2d * GetCentre() = 0; // \ru Выдать центр эллипса \en Get ellipse center - virtual ItGeomCoord * GetACoord() = 0; // \ru Выдать размер полуоси а \en Get size of semiaxis a - virtual ItGeomCoord * GetBCoord() = 0; // \ru Выдать размер полуоси b \en Get size of semiaxis b - virtual ItGeomCoord * GetPhiCoord() = 0; // \ru Выдать угол оси a \en Get angle of axis a - virtual coord_name IdentCoord( const ItGeomCoord & ) const; // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object - virtual bool IsClockwise() const = 0; // \ru Вернет true, усли параметризация эллипса по часовой стрелке. \en Returns true if the ellipse parametrization is directed clockwise. -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Дуга эллипса на плоскости \en Elliptical arc on the plane -////////////////////////////////////////////////////////////////////////////////////////// -struct GCE_CLASS IfGeomEllipseArc2d: public IfGeomEllipse2d -{ - virtual GcGeomType GetGeomType() const { return gt_EllipseArc2d; } - virtual IfGeomPoint2d * GetEnd( int nb ) = 0; - inline MbCartPoint GetEndValue( int nb ) - { - if ( const IfGeomPoint2d * bnd = GetEnd(nb) ) - { - return bnd->GetValue(); - } - return MbCartPoint(); - } -}; - -//---------------------------------------------------------------------------------------- -// \ru Выдать true, если оба указателя представляют одну и ту же точку параметрическую точку \en Return true if both pointers represent the same parametric point -/*\ru Поведение соответствует ParPoint::IsEqual - \en Behavior corresponds to ParPoint::IsEqual \~ -*/ -//--- -inline bool SamePoints( const IfGeomPoint2d * p1, const IfGeomPoint2d * p2 ) -{ - if ( p2 == p1 ) - { - return true; - } - if ( p1 && p2 ) - { - if ( p1->GetXCoord() == p2->GetXCoord() ) - { - return true; - } - } - - return false; -} - -//---------------------------------------------------------------------------------------- -// -//--- -inline MbCartPoint IfGeomPoint2d::GetValue() const -{ - MbCartPoint val; - if ( const ItGeomCoord * x = GetXCoord() ) - { - if ( const ItGeomCoord * y = GetYCoord() ) - { - val.Init( x->GetValue(), y->GetValue() ); - } - } - return val; -} - -//---------------------------------------------------------------------------------------- -// -//--- -inline GCE_point IfGeomLineSeg2d::EndPoint( int nb ) -{ - GCE_point val; - if ( IfGeomPoint2d * pnt = GetEnd(nb) ) - { - const MbCartPoint xy = pnt->GetValue(); - val.x = xy.x; - val.y = xy.y; - } - return val; -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// \ru Аналог IfPtr без работы со счетчиком ссылок \en Analog of IfPtr without working with reference counter -/*\ru Указатель с сервисом приведения типов - \en Pointer with type conversion service \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -template -class IfGeom2dPtr -{ - T * m_pI; - -public: - IfGeom2dPtr() : m_pI(0) {} - IfGeom2dPtr( T * pI ): m_pI(pI) {} - IfGeom2dPtr( IfSomethingGeom2d * pI ) : m_pI(0) { if ( pI != 0 ) m_pI = (T*)pI->GetInterfacingGeom(iid); } - IfGeom2dPtr( const IfGeom2dPtr & o ) : m_pI( o.m_pI ) {} - -public: - unsigned int GetIid() const { return iid; } - operator T*() const { return m_pI; } - T& operator *() { C3D_ASSERT(m_pI != 0); return *m_pI; } - T** operator &() { C3D_ASSERT(m_pI == 0); return &m_pI; } - T* operator->() { C3D_ASSERT(m_pI != 0); return m_pI; } - T* operator->() const { C3D_ASSERT(m_pI != 0); return m_pI; } - T* Get() const { return m_pI; } - T* operator= ( T* pI ) { m_pI = pI; } - T* operator= ( const IfGeom2dPtr & o ) { return operator=(o.m_pI); } - T* operator= ( IfSomethingGeom2d * pI ); -}; - -//---------------------------------------------------------------------------------------- -// \ru Присвоить другой интерфейс \en Assign another interface -// --- -template -inline T* IfGeom2dPtr::operator = ( IfSomethingGeom2d * pI ) { - T * pOld = m_pI; - m_pI = 0; - if ( pI != 0 ) - m_pI = (T*)pI->GetInterfacingGeom( iid ); - - return m_pI; -} - -//---------------------------------------------------------------------------------------- -// \ru Идентификаторы интерфейсов решателя сопряжений \en Identifiers of constraint solver interfaces -//--- -typedef enum -{ - // \ru Геометрические объекты \en Geometrical objects - iidr_IfSomethingGeom2d, - iidr_IfGeom2d, ///< \ru Плоский геометрический объект \en Planar geometric object - iidr_IfGeomPoint2d, - iidr_IfGeomLine2d, - iidr_IfGeomLineSeg2d, - iidr_IfGeomCircle2d, - iidr_IfGeomArc2d, - iidr_IfGeomEllipse2d, - iidr_IfGeomEllipseArc2d, - iidr_ParSolvingObj, ///< \ru Интерфейс неизвестного чертежного объекта, не обязательно примитивного, \en Interface of unknown drawing object, not necessary primitive -} EIfIDRolesMathGC; - -////////////////////////////////////////////////////////////////////////////////////////// -// Deprecated (2016). Use GCE_AddBoundedCurve with GCE_AddCircle instead this. -/* - КОМПАС отвязан от этого интерфейса. -*/ -////////////////////////////////////////////////////////////////////////////////////////// -struct IfGeomArc2d: public IfGeomCircle2d -{ -private: - virtual GcGeomType GetGeomType() const { return gt_Arc2d; } - virtual bool GetClockwise() const = 0; - virtual IfGeomPoint2d * GetEnd( int nb ) = 0; -}; - -#endif - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вспомогательный программный интерфейс решателя. + \en Auxiliary programming interface of the solver. \~ + \details + \ru Данный файл содержит устаревшие классы и вызовы. Данное API может оказаться + не удобным, а его методы могут быть удалены или изменены в будущих версиях. + Настоящее взаимодействие с 2D-решателем осуществляется через типы данных и вызовы, + опубликованные в заголовочных файлах gce_api.h, gce_types.h. + \en This file contains deprecrated classes and calls. This API can be inconvenient + and its methods can be deleted or modified in the future versions. + The actual interaction with the 2D-solver is througt the data types and calls + declared in gce_api.h, gce_types.h. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCE_GEOM_H +#define __GCE_GEOM_H +// +#include +#include +#include +// +#include "gce_types.h" + +struct IfGeomPoint2d; + +//---------------------------------------------------------------------------------------- +// \ru Перечисление параметрических объектов \en Enumeration of parametric objects. +//--- +enum GcGeomType +{ + vt_NULL, ///< \ru Неопределенный тип. \en Undefined type. + gt_Point2d, ///< \ru Точка. \en Point. + gt_Line2d, ///< \ru Прямая. \en Line. + gt_LineSegment2d, ///< \ru Отрезок. \en Segment. + gt_Circle2d, ///< \ru Окружность. \en Circle. + gt_Arc2d, ///< \ru Дуга. \en Arc. + gt_Ellipse2d, ///< \ru Эллипс. \en Ellipse. + gt_EllipseArc2d, ///< \ru Дуга эллипса. \en Ellipse arc. +}; + +//---------------------------------------------------------------------------------------- +// \ru Макросы \en Macros +// --- +#define CAST_PTR(T) IfGeom2dPtr // \ru Указатель с функцией приведения типов \en Pointer with function of type conversion +#define GEOM_PTR(T) IfGeom2dPtr // \ru Указатель с функцией приведения типов \en Pointer with function of type conversion +#define CAST2PTR(T,arg) (arg) != c3d_null ? (T*)((arg)->GetInterfacingGeom(iidr_ ## T)) : c3d_null // \ru Привести к другому типу \en Convert to another type + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Координата геометрического объекта или переменной \en Coordinate of a geometric object or a variable +////////////////////////////////////////////////////////////////////////////////////////// +struct ItGeomCoord : public ItCoord +{ + virtual refcount_t AddRef() const = 0; + virtual refcount_t Release() const = 0; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +/* + \ru Надкласс примитивных геометрических объектов решателя + Внимание: Применяется только для САПР КОМПАС. Рекомендуется вместо него использовать вызовы API из gce_api.h + объектом IfSomething. Вместо макроса IFPTR применять GEOM_PTR.\n + После того, как MdViewObj будет наконец-то, освобождать память по правилам + IfSomething, нужно:\n + 1) Все слова IfSomethingGeom2d заменить на IfSomething;\n + 2) Все слова GetInterfacingGeom заменить на QueryInterface;\n + 3) Удалить этот класс;\n + 4) Компилятор сам подскажет, какие места нужно доправить;\n + + \en Used while there is no correct work with MdViewObj in 2D model + as with object IfSomething. GEOM_PTR is to be applied instead of macro IFPTR.\n + After MdViewObj has been implemented it is required to free memory by rules IfSomething, + it is necessary to:\n + 1) All words IfSomethingGeom2d replace by IfSomething;\n + 2) All words GetInterfacingGeom replace by QueryInterface;\n + 3) Delete this class;\n + 4) Compiler will prompt which places are to be corrected;\n \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// +struct IfSomethingGeom2d +{ + virtual IfSomethingGeom2d * GetInterfacingGeom( unsigned int iid ) = 0; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Геометрический объект параметризации \en Geometric object of parametrization +/*\ru Этот тип и его подтипы соответствуют словарю типов решателя, а не типам пользователя. + \en This type and its subtypes correspond to the dictionary of types of the solver but not to the user types. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// +struct IfGeom2d: public IfSomethingGeom2d +{ + virtual GcGeomType GetGeomType() const = 0; + /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual point_type IdentCtrlPoint( const IfGeomPoint2d & ) const = 0; + /// \ru Выдать обозначение координаты, принадлежащей объекту \en Get notation of coordinate belonging to the object + virtual coord_name IdentCoord( const ItGeomCoord & ) const = 0; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Точка на плоскости \en Point on the plane +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomPoint2d: public IfGeom2d +{ + virtual GcGeomType GetGeomType() const { return gt_Point2d; } + virtual ItGeomCoord * GetXCoord() const = 0; + virtual ItGeomCoord * GetYCoord() const = 0; + /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual coord_name IdentCoord( const ItGeomCoord & ) const; + +public: + inline MbCartPoint GetValue() const; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// Deprecated (2017). Use GCE_AddLine instead this. +/* + КОМПАС отвязан от этого интерфейса. +*/ +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomLine2d: public IfGeom2d +{ + virtual GcGeomType GetGeomType() const { return gt_Line2d; } + virtual ItGeomCoord * GetACoord() = 0; ///< \ru Выдать угол нормали прямой \en Get angle of line normal + virtual ItGeomCoord * GetDCoord() = 0; ///< \ru Выдать расстояние до начала СК в направлении нормали \en Get distance to the coordinate system origin in the normal direction + /// \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual coord_name IdentCoord( const ItGeomCoord & ) const; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Отрезок на плоскости \en Segment on the plane +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomLineSeg2d: public IfGeom2d +{ + virtual GcGeomType GetGeomType() const { return gt_LineSegment2d; } + virtual IfGeomPoint2d * GetEnd( int nb ) = 0; ///< \ru Выдать конец отрезка 1,2 \en Get end of segment 1,2 + virtual bool IsFixedLength() = 0; ///< \ru Признак отрезка постоянной длины (для стрелки взгляда) \en Flag of segment of constant length (for the view vector) + // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual coord_name IdentCoord( const ItGeomCoord & ) const { return GCE_NULL_CRD; } + inline GCE_point EndPoint( int nb ); ///< \ru Выдать конец отрезка 1,2 \en Get end of segment 1,2 +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// Deprecated (2017). Use GCE_AddCircle instead this. +/* + КОМПАС отвязан от этого интерфейса. +*/ +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomCircle2d: public IfGeom2d +{ + virtual GcGeomType GetGeomType() const { return gt_Circle2d; } + virtual IfGeomPoint2d * GetCentre() = 0; + virtual ItGeomCoord * GetRadius() = 0; + // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual coord_name IdentCoord( const ItGeomCoord & ) const; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Эллипс на плоскости \en Ellipse on the plane +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomEllipse2d: public IfGeom2d +{ + virtual GcGeomType GetGeomType() const { return gt_Ellipse2d; } + virtual IfGeomPoint2d * GetCentre() = 0; // \ru Выдать центр эллипса \en Get ellipse center + virtual ItGeomCoord * GetACoord() = 0; // \ru Выдать размер полуоси а \en Get size of semiaxis a + virtual ItGeomCoord * GetBCoord() = 0; // \ru Выдать размер полуоси b \en Get size of semiaxis b + virtual ItGeomCoord * GetPhiCoord() = 0; // \ru Выдать угол оси a \en Get angle of axis a + virtual coord_name IdentCoord( const ItGeomCoord & ) const; // \ru Выдать обозначение контрольной точки, принадлежащей объекту \en Get notation of the control point belonging to the object + virtual bool IsClockwise() const = 0; // \ru Вернет true, усли параметризация эллипса по часовой стрелке. \en Returns true if the ellipse parametrization is directed clockwise. +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Дуга эллипса на плоскости \en Elliptical arc on the plane +////////////////////////////////////////////////////////////////////////////////////////// +struct GCE_CLASS IfGeomEllipseArc2d: public IfGeomEllipse2d +{ + virtual GcGeomType GetGeomType() const { return gt_EllipseArc2d; } + virtual IfGeomPoint2d * GetEnd( int nb ) = 0; + inline MbCartPoint GetEndValue( int nb ) + { + if ( const IfGeomPoint2d * bnd = GetEnd(nb) ) + { + return bnd->GetValue(); + } + return MbCartPoint(); + } +}; + +//---------------------------------------------------------------------------------------- +// \ru Выдать true, если оба указателя представляют одну и ту же точку параметрическую точку \en Return true if both pointers represent the same parametric point +/*\ru Поведение соответствует ParPoint::IsEqual + \en Behavior corresponds to ParPoint::IsEqual \~ +*/ +//--- +inline bool SamePoints( const IfGeomPoint2d * p1, const IfGeomPoint2d * p2 ) +{ + if ( p2 == p1 ) + { + return true; + } + if ( p1 && p2 ) + { + if ( p1->GetXCoord() == p2->GetXCoord() ) + { + return true; + } + } + + return false; +} + +//---------------------------------------------------------------------------------------- +// +//--- +inline MbCartPoint IfGeomPoint2d::GetValue() const +{ + MbCartPoint val; + if ( const ItGeomCoord * x = GetXCoord() ) + { + if ( const ItGeomCoord * y = GetYCoord() ) + { + val.Init( x->GetValue(), y->GetValue() ); + } + } + return val; +} + +//---------------------------------------------------------------------------------------- +// +//--- +inline GCE_point IfGeomLineSeg2d::EndPoint( int nb ) +{ + GCE_point val; + if ( IfGeomPoint2d * pnt = GetEnd(nb) ) + { + const MbCartPoint xy = pnt->GetValue(); + val.x = xy.x; + val.y = xy.y; + } + return val; +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// \ru Аналог IfPtr без работы со счетчиком ссылок \en Analog of IfPtr without working with reference counter +/*\ru Указатель с сервисом приведения типов + \en Pointer with type conversion service \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +template +class IfGeom2dPtr +{ + T * m_pI; + +public: + IfGeom2dPtr() : m_pI(c3d_null) {} + IfGeom2dPtr( T * pI ): m_pI(pI) {} + IfGeom2dPtr( IfSomethingGeom2d * pI ) : m_pI(c3d_null) { if ( pI != c3d_null ) m_pI = (T*)pI->GetInterfacingGeom(iid); } + IfGeom2dPtr( const IfGeom2dPtr & o ) : m_pI( o.m_pI ) {} + +public: + unsigned int GetIid() const { return iid; } + operator T*() const { return m_pI; } + T& operator *() { C3D_ASSERT(m_pI != c3d_null); return *m_pI; } + T** operator &() { C3D_ASSERT(m_pI == c3d_null); return &m_pI; } + T* operator->() { C3D_ASSERT(m_pI != c3d_null); return m_pI; } + T* operator->() const { C3D_ASSERT(m_pI != c3d_null); return m_pI; } + T* Get() const { return m_pI; } + T* operator= ( T* pI ) { m_pI = pI; } + T* operator= ( const IfGeom2dPtr & o ) { return operator=(o.m_pI); } + T* operator= ( IfSomethingGeom2d * pI ); +}; + +//---------------------------------------------------------------------------------------- +// \ru Присвоить другой интерфейс \en Assign another interface +// --- +template +inline T* IfGeom2dPtr::operator = ( IfSomethingGeom2d * pI ) { + T * pOld = m_pI; + m_pI = c3d_null; + if ( pI != c3d_null ) + m_pI = (T*)pI->GetInterfacingGeom( iid ); + + return m_pI; +} + +//---------------------------------------------------------------------------------------- +// \ru Идентификаторы интерфейсов решателя сопряжений \en Identifiers of constraint solver interfaces +//--- +typedef enum +{ + // \ru Геометрические объекты \en Geometrical objects + iidr_IfSomethingGeom2d, + iidr_IfGeom2d, ///< \ru Плоский геометрический объект \en Planar geometric object + iidr_IfGeomPoint2d, + iidr_IfGeomLine2d, + iidr_IfGeomLineSeg2d, + iidr_IfGeomCircle2d, + iidr_IfGeomEllipse2d, + iidr_IfGeomEllipseArc2d, + iidr_ParSolvingObj, ///< \ru Интерфейс неизвестного чертежного объекта, не обязательно примитивного, \en Interface of unknown drawing object, not necessary primitive +} EIfIDRolesMathGC; + +#endif + // eof \ No newline at end of file diff --git a/C3d/Include/gce_types.h b/C3d/Include/gce_types.h index 37ffdb4..5383d8e 100644 --- a/C3d/Include/gce_types.h +++ b/C3d/Include/gce_types.h @@ -1,685 +1,683 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Типы данных двумерного геометрического решателя. - \en Data types of the two-dimensional geometric solver. \~ - \details \ru Этот файл представляет собой набор типов данных, необходимых для - взаимодействия геометрического решателя с клиентским приложением. - \en This file contains set of data types necessary for interaction - of the geometrical solver with user application. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCE_TYPES_H -#define __GCE_TYPES_H - -#include -#include -#include -#include -#include -#include -#ifndef C3D_WINDOWS //_MSC_VER -#include -#endif //C3D_WINDOWS - -class MATH_CLASS MbNurbs; - -/** - \addtogroup Constraints2D_API - \{ -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Система геометрических ограничений. - \en Geometric constraints system. \~ - \details \ru GCE_system является типом данных, который обозначает систему ограничений, - которая создается с помощью вызова #GCE_CreateSystem. Реально, этот тип является - указателем на внутреннюю структуру данных, где содержится система ограничений и различные - рабочие данные, определяющие её внутреннее состояние. Время жизни системы ограничений - заканчивается только, когда к ней будет применен вызов API #GCE_RemoveSystem, после чего - значение GCE_system становится недействительным. - \en GCE_system is data type which denotes a system of constraints created by - call #GCE_CreateSystem. Actually this type is a pointer to an internal data structure with - a system of constraints and various working data determining its internal state. Lifetime - of the constraint system finishes only when a call of API #GCE_RemoveSystem - is applied to it, thereafter the value of GCE_system becomes invalid. \~ -*/ -typedef void * GCE_system; - -//---------------------------------------------------------------------------------------- -// \ru Типы данных. \en Data types. -//--- -/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. -typedef size_t geom_item; -/// \ru Дескриптор ограничения, зарегистрированного в решателе. \en Descriptor of a constraint registered in the solver. -typedef size_t constraint_item; -/// \ru Дескриптор переменной, зарегистрированной в решателе. \en Descriptor of a variable registered in the solver. -typedef size_t var_item; - -//---------------------------------------------------------------------------------------- -// \ru Константы. \en Constants. -//--- -/// \ru Неопределенное значение дескриптора или пустого объекта. \en Undefined value of descriptor or an empty object. -const size_t GCE_NULL = SYS_MAX_T; -/// \ru Неопределенное значение дескриптора типа #geom_item. \en Undefined value of #geom_item type. -const geom_item GCE_NULL_G = GCE_NULL; -/// \ru Неопределенное значение дескриптора типа #var_item. \en Undefined value of #var_item type. -const var_item GCE_NULL_V = GCE_NULL; -/// \ru Неопределенное значение дескриптора типа #constraint_item. \en Undefined value of #constraint_item type. -const constraint_item GCE_NULL_C = GCE_NULL; -/// \ru Не определенное значение числа double. \en An undefined value of double. -const double GCE_UNDEFINED_DBL = UNDEFINED_DBL; - -//---------------------------------------------------------------------------------------- -/// \ru Словарь типов геометрических примитивов. \en Dictionary of geometric primitives types. -//--- -typedef enum -{ - GCE_ANY_GEOM, ///< \ru Неизвестный тип. \en Unknown type. - - // \ru Основные типы. \en Basic types. - GCE_POINT, ///< \ru Точка на плоскости. \en Point on plane. - GCE_LINE, ///< \ru Прямая на плоскости. \en Line on plane. - GCE_CIRCLE, ///< \ru Окружность на плоскости. \en Circle on plane. - GCE_ELLIPSE, ///< \ru Эллипс на плоскости. \en Ellipse on plane. - GCE_SPLINE, ///< \ru Сплайн на плоскости. \en Spline on plane. - GCE_PARAMETRIC_CURVE, ///< \ru Параметрическая кривая на плоскости. \en Parametric curve on plane. - GCE_BOUNDED_CURVE, ///< \ru Ограниченная двумя точками, кривая. \en Curve bounded by two points. - - // \ru Дополнительные типы. \en Additional types. - GCE_LINE_SEGMENT, ///< \ru Отрезок прямой. \en Line segment. - GCE_SET, ///< \ru Подмножество геометрических объектов. \en Subset of geometric objects. -} geom_type; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Варианты контрольных точек, запрашиваемых у геометрического объекта. - \en Variants of control point requested from a geometric object. - \details \ru Это перечисление применяется для запроса дескриптора характерных точке объекта, - таких как центр окружности, концевая точка кривой и т.д... - \en This enum is used to request a descriptor of control point of an object, - such as center of circle, bounding point of a curve etc... - \see #GCE_PointOf -*/ -//--- -typedef enum -{ - /* - (!) Don't change the integer values of these names. It may be written to a file permanently. - */ - GCE_FIRST_PTYPE = 0 ///< \ru Значение начинающее последовательность вариантов. \en The value of beginning of the sequence. - , GCE_IMPROPER_POINT = 0 ///< \ru Точка, не принадлежащая объекту. \en Point not belonging to the object. - , GCE_FIRST_END ///< \ru Первый конец ограниченной кривой. \en The first end of bounded curve. - , GCE_SECOND_END ///< \ru Второй конец ограниченной кривой. \en The second end of bounded curve. - , GCE_CENTRE ///< \ru Центр окружности (дуги) или эллипса. \en Center of circle (arc) or ellipse. - , GCE_PROPER_POINT ///< \ru Собственно точка. \en Proper point. - , GCE_Q1 ///< \ru Квадрантная точка эллипса (3 часа). \en Quadrant point of ellipse (3 o'clock). - , GCE_Q2 ///< \ru Квадрантная точка эллипса (12 часов). \en Quadrant point of ellipse (12 o'clock). - , GCE_Q3 ///< \ru Квадрантная точка эллипса (6 часов). \en Quadrant point of ellipse (6 o'clock). - , GCE_Q4 ///< \ru Квадрантная точка эллипса (9 часов). \en Quadrant point of ellipse (9 o'clock). - , GCE_LOCATION_POINT ///< \ru Точка размещения геометрического объекта. \en Location point of geometric object. - , GCE_LAST_PTYPE ///< \ru Значение завершающее последовательность вариантов. \en The value of variants completes the sequence. - /* - The values below are used only within the solver. - */ - , GCE_DIRECTION ///< \ru Направляющий вектор эллипса (направление "большой" полуоси ). \en Vector of ellipse direction (direction of "major" semiaxis). - /** \brief \ru Единичный вектор ориентации: Нормаль прямой, направление "большой" полуоси эллипса. - \en Unit vector of orientation: Normal of a line, direction of "major" semiaxis of ellipse. \~ - */ - , GCE_ORIENTATION - -} query_geom_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Тип запрашиваемой точки (используется, как подмножество значений query_geom_type). - \en Type of the requested point (used as subset of values query_geom_type). -*/ -//--- -typedef query_geom_type point_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Перечисление координат геометрических объектов. - \en Enumeration of geom's coordinates. -*/ -//--- -typedef enum -{ - GCE_X, GCE_Y ///< \ru Координаты точки или вектора. \en Coordinates of a point or a vector. - , GCE_ACRD ///< \ru Угол нормали прямой, угол наклона эллипса. \en Angle of line normal, slope angle of ellipse. - , GCE_DCRD ///< \ru Координата смещения прямой, расстояние от начала координат до прямой. \en Coordinate of line shift, distance from CS origin to line. - , GCE_RADIUS ///< \ru Радиус окружности. \en Circle radius. - , GCE_MAJOR_RADIUS ///< \ru "Главная" полуось эллипса. \en "Major" semiaxis of ellipse. - , GCE_MINOR_RADIUS ///< \ru "Малая" полуось эллипса. \en "Minor" semiaxis of ellipse. - , GCE_NULL_CRD ///< \ru Пустая (несуществующая) координата. \en Empty (nonexistent) coordinate. -} coord_name; - -typedef coord_name coord_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Идентификатор типа 2D ограничения. - \en Identifier of 2D constraint type. \~ - \attention \ru На самом деле решатель поддерживает другие ограничения, кроме перечисленных. - См. вызовы API в 'gce_api.h' - \en Actually, the solver provides more constraint types than is given in the enum. - See the API calls in 'gce_api.h' \~ -*/ -typedef enum -{ - // \ru Унарные геометрические ограничения: \en Unary geometric constraints: - GCE_FIX_GEOM - , GCE_HORIZONTAL ///< \ru Горизонтальность прямой или отрезка. \en Horizontality of a linear object. - , GCE_VERTICAL ///< \ru Вертикальность прямой или отрезка. \en Verticality of a linear object. - , GCE_LENGTH ///< \ru Фиксация длины отрезка. \en Fixation of length of a line segment. - , GCE_ANGLE_OX - - // \ru Бинарные геометрические ограничения: "constr( geom1, geom2 )" \en Binary geometric constraints: "constr( geom1, geom2 )" - , GCE_COINCIDENT ///< \ru Совпадение пары геометрических объектов. \en Coincidence of a pair of geometric objects. - , GCE_EQUAL_LENGTH ///< \ru Равенство длин пары отрезков. \en Equality of two segments lengths. - , GCE_EQUAL_RADIUS ///< \ru Равенство радиусов пары окружностей. \en Equality of two circles lengths. - , GCE_PARALLEL ///< \ru Параллельность пары прямых или отрезков. \en Parallelism of two lines or segments. - , GCE_PERPENDICULAR ///< \ru Перпендикулярность пары прямых или отрезков. \en Perpendicularity of two lines or segments. - , GCE_TANGENT ///< \ru Касание пары кривых. \en Tangency of two curves. - , GCE_COLINEAR ///< \ru Коллинеарность пары прямых или отрезков. \en Collinearity of a pair of lines or segments. - , GCE_ALIGN_2P ///< \ru Выравнивание пары точек вдоль направления. \en Alignment of a pair of points along the direction. - , GCE_CURVATURE_EQUALITY ///< \ru Равенство кривизны кривых в точках. \en Equality of curves curvature in given points. - - // \ru Тернарные геометрические ограничения. \en Ternary geometric constraints. - , GCE_ANGLE_BISECTOR ///< \ru Биссектриса угла. \en Bisector of angle. - , GCE_MIDDLE_POINT ///< \ru Средняя точка. \en Middle point. - , GCE_COLINEAR_3P ///< \ru Коллинеарность тройки точек. \en Collinearity of a point triple. - , GCE_SYMMETRIC ///< \ru Симметричность. \en Symmetry. - - , GCE_PERCENT_POINT ///< \ru \en - , GCE_EQUATION ///< \ru Уравнение. \en Equation. - // \ru Размерные геометрические ограничения \en Dimensional geometric constraints - , GCE_DISTANCE - , GCE_RADIUS_DIM - , GCE_DIAMETER - , GCE_ANGLE - , GCE_CONSTRAINTS_COUNT ///< \ru Количество типов. \en Number of types. - , GCE_UNKNOWN = GCE_CONSTRAINTS_COUNT ///< \ru Неизвестный тип ограничения. \en Unknown constraint type. - , GCE_UNKNOWN_CON = GCE_UNKNOWN -} constraint_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Диагностические коды выполнения функций геометрического решателя. - \en Diagnostic codes of the geometric solver functions execution. \~ -*/ -//--- -typedef enum -{ - GCE_RESULT_None = 0, ///< \ru Нет результата (пустое сообщение). \en No result (empty message). - GCE_RESULT_Ok = 1, ///< \ru Успешный результат. \en Successful result. - GCE_RESULT_Satisfied = 1, ///< \ru Ограничение удовлетворено. \en The constraint is satisfied. - GCE_RESULT_Not_Satisfied = 2, ///< \ru Система ограничений не решена. \en The system of constraints is not solved. - GCE_RESULT_Overconstrained = 3, ///< \ru Переопределенная (несовместная) система ограничений. \en Overdetermined (inconsistent) system of constraints. - GCE_RESULT_InvalidGeometry = 4, ///< \ru Решение привело в нарушению геометрии. \en Solution leaded to violation of geometry. - GCE_RESULT_MovingOfFixedGeom = 5, ///< \ru Попытка перемещения фиксированного объекта. \en Attempt of a fixed object translation. - GCE_RESULT_Unregistered = 6, ///< \ru Обращение к недействительному объекту. \en Access to invalid object. - GCE_RESULT_SystemError = 7, ///< \ru Внутренняя системная ошибка. \en Internal system error. - GCE_RESULT_NullSystem = 8, ///< \ru Обращение к недействительной системе ограничений. \en Access to invalid system of constraints. - GCE_RESULT_CircleCantStretched = 9, ///< \ru Окружность не может быть масштабирована с разными коэффициентами по осям (растяжение). \en The circle can't be scaled with different scaling factors for each axis (stretching). - GCE_RESULT_SingularMatrix = 10, ///< \ru Прислали вырожденную матрицу трансформации. \en A singular transform matrix was received. - GCE_RESULT_DegenerateScalingFactor = 11, ///< \ru Вырожденный коэффициент масштабирования. \en Degenerate scaling factor. - GCE_RESULT_InvalidDimensionTransform = 12, ///< \ru Неудачное преобразование размера. \en Invalid dimension transformation. - GCE_RESULT_Aborted = 13, ///< \ru Процесс вычислений был прерван по запросу приложения. \en The evaluation process aborted by the application. \~ - GCE_RESULT_IsNotDrivingDimension = 14, ///< \ru Данное ограничение должно быть управляющим размером. \en Given constraint should be a driving dimension. - GCE_RESULT_UnsupportedConstraint = 15, ///< \ru На геометрические объекты было наложено невозможное ограничение. \en An impossible constraint was set on geometric objects. - GCE_RESULT_AnisotropicScaling = 16, ///< \ru Анизотропное масштабирование. \en Anisotropic scaling. -} GCE_result; - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Статус геометрического ограничения. - \en Status of a geometric constraint. - \details - \ru Статус ограничения подразумевает деление системы ограничения на подмножества, - которые маркируются следующим образом:\n - Ограничения, помеченые GCE_STATUS_WellTreated и GCE_STATUS_WellConditioned образуют - хорошо-обрабатываемую решателем часть системы ограничений, не содержащую переопределений - и обычно вычисляемую без противоречий.\n - Ограничения, помеченные статусами GCE_STATUS_WellConditioned и GCE_STATUS_IllConditioned - вместе образуют группу взаимосвязанных ограничений, которые обычно решаются без противоречий, - но потенциально могут противоречить друг другу при участии размеров. - Те из них, что помечены GCE_STATUS_IllConditioned создают условия для решаемости хуже, - чем GCE_STATUS_WellConditioned.\n - Статусом GCE_STATUS_Redundant решатель помечает лишние ограничения, которые можно удалить - из системы ограничений. Обычно такие ограничения исполняются за счет других ограничений - или создают ситуацию переопределенности (несовместная система ограничений).\n - Статусом GCE_STATUS_OverConstrained помечаются те из ограничений, которые остались не - решенными по причине несовместной переопределенности. Ограничения со статусами - GCE_STATUS_Redundant и GCE_STATUS_OverConstrained могут находится в противоречии с другими - ограничениями кроме тех, что помечены GCE_STATUS_WellTreated. - - The status of a constraint implies the division of the system into subsets, which are - labeled as follows: \n - Constraints marked by GCE_STATUS_WellTreated and GCE_STATUS_WellConditioned together form - well-resolved part that does not contain overdefining constraints and usually computed - without contradiction. \n - Constraints marked with GCE_STATUS_WellConditioned and GCE_STATUS_IllConditioned statuses - together form a group of interrelated constraints that are usually resolved without - contradiction, but potentially contradictory with dimensions. - Those that are labeled GCE_STATUS_IllConditioned make conditions for evaluating worse, - than GCE_STATUS_WellConditioned. \n - The status of GCE_STATUS_Redundant solver marks the extra constraints that can be removed. - from the constraint system. Usually such constraints are enforced by other constraints. - or create an overdefined situation (incompatible constraint system). \n - The status GCE_STATUS_OverConstrained marks those of constraints that was not solved - due to inconsistent overdefining. Constraints with GCE_STATUS_Redundant and - GCE_STATUS_OverConstrained statuses may conflict with other constraints except those - marked with GCE_STATUS_WellTreated. -*/ -//--- -typedef enum -{ - GCE_STATUS_Undefined = 0 - /* - Statuses indicating which of constraints belong to well-treated - or redundancy parts of the constraint system. - */ - , GCE_STATUS_WellTreated = 1 // Ограничение принадлежит рабочей части системы ограничений без переопределений. - , GCE_STATUS_WellConditioned = 2 // Ограничение принадлежит хорошо-обусловленной части уравнений. - , GCE_STATUS_IllConditioned = 3 ///< /ru Ограничения из плохо-обусловленной части. /en A constraint of ill-condition - , GCE_STATUS_Redundant = 4 ///< /ru Ограничение игнорируется решателем по причине избыточности. // en A constraint is ignored by the solving process beacause of the redundancy. - - /* - Statuses resulting the evaluation (call GCE_Evaluate). - */ - , GCE_STATUS_Solved // Ограничение решено - , GCE_STATUS_NotSolved // Не решено по каким-то причинам - , GCE_STATUS_NotConsistent // Не решено из-за противоречия с другими ограничениями. - , GCE_STATUS_OverConstrained // Не решено избыточное ограничение, противоречащее другим. - -} GCE_c_status; - -//---------------------------------------------------------------------------------------- -/// \ru Вернет 'true' в случае успешного результата. \en Return true, if the result code is successful. -// --- -inline bool OK( GCE_result resCode ) -{ - return resCode == GCE_RESULT_Ok; -} - -//---------------------------------------------------------------------------------------- -/// \ru Вариант решения биссектрисы для двух прямых. \en Variant of a bisector for two lines. -/* - \ru Идентификаторы не менять (возможна запись в файлы)! - \en Don't change identifiers (record to files is possible)! -*/ -//--- -typedef enum -{ - GCE_BISEC_CLOSEST = 0 ///< \ru Неопределенное направление (ближайшее решение). \en Undefined direction (nearest solution). - , GCE_BISEC_MINUS = 1 ///< \ru Биссектриса вдоль суммы направлений прямых/отрезков. \en Bisector along the difference of directions of lines/segments. - , GCE_BISEC_PLUS = 2 ///< \ru Биссектриса вдоль разности нормалей прямых/отрезков. \en Bisector along sum of directions of lines/segments. - -} GCE_bisec_variant; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты вектора. \en Vector coordinates. -//--- -struct GCE_vec2d -{ - double x, y; - GCE_vec2d() { x = y = 0; } -}; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты вектора n-й размерности. \en Coordinates of n-dimensional vector. -//--- -struct GCE_vecNd -{ - size_t size; - double * arg; - GCE_vecNd(): arg(0), size(0) {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты точки на плоскости. \en Coordinates of a point on plane. -//--- -struct GCE_point -{ - double x, y; ///< \ru Декартовы координаты на плоскости \en Cartesian coordinates on the plane - GCE_point() { x = y = 0; } -}; - -//---------------------------------------------------------------------------------------- -/// \ru Степень свободы точки. \en Degree of freedom of a point. -//--- -struct GCE_point_dof -{ - int dof; ///< Degree of freedom of the point. - GCE_vec2d dir; ///< Direction of point moving freedom. - GCE_point_dof(): dof(-1), dir() {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты прямой на плоскости. \en Coordinate of a line on the plane. -//--- -struct GCE_line -{ - GCE_point p; - GCE_vec2d norm; - GCE_line() : p(), norm() {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты окружности. \en Coordinates of a circle. -//--- -struct GCE_circle -{ - GCE_point centre; ///< \ru Центр окружности. \en Circle center. - double radius; ///< \ru Радиус окружности. \en Circle radius. - GCE_circle() : centre(), radius( 0.0 ) {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты эллипса. \en Coordinates of an ellipse. -//--- -struct GCE_ellipse -{ - GCE_point centre; ///< \ru Центр эллипса. \en Ellipse center. - GCE_vec2d direct; ///< \ru Направляющий вектор главной полуоси. \en Vector of the major semiaxis direction. - double majorR; ///< \ru Главная полуось. \en Major semiaxis. - double minorR; ///< \ru Вторая полуось. \en Second semiaxis. - - GCE_ellipse() - : centre() - , direct() - , majorR( 0.0 ) - , minorR( 0.0 ) - {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Координаты и характеристики сплайна. - \en Coordinates and characteristics of a spline.\~ - \details \ru - Сплайн можно задавать тремя способами: \n - 1) По уже существующему объекту MbNurbs. \n - 2) По уже существующему объекту MbNurbs и набору интерполяционных точек. \n - 3) По набору интерполяционных точек, соответствующих им параметров, порядку и признаку замкнутости. - \en - The spline can be specified in three ways: \n - 1) Using already existing object of MbNurbs. \n - 2) Using already existing object of MbNurbs and a set of interpolation points. \n - 3) Using a set of interpolation points, corresponding parameters, order and closedness attribute.\~ - \ingroup Constraints2D_API -*/ -// --- -struct GCE_CLASS GCE_spline -{ - size_t degree; ///< \ru Порядок В-сплайна. \en Order of B-spline. - bool isClosed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. - std::vector controlPoints; ///< \ru Множество контрольных точек. \en Set of control points. - std::vector controlWeights; ///< \ru Множество весов контрольных точек. \en Set of weights of the control points. - std::vector controlKnots; ///< \ru Узловой вектор. \en Knot vector. - std::vector interpPoints; ///< \ru Множество интерполяционных точек. \en Set of interpolation points. - std::vector interpParams; ///< \ru Множество значений параметров, соответствующих интерполяционным точкам. \en Set of the parameter values corresponding to interpolation points. - MbeNurbsCurveForm form; ///< \ru Форма кривой. \en Form of curve. - - GCE_spline() - : degree( Math::curveDegree ) - , isClosed( false ) - , controlPoints() - , controlWeights() - , controlKnots() - , interpPoints() - , interpParams() - , form( ncf_Unspecified ) - {} - explicit GCE_spline( const MbNurbs & nurbs ); - GCE_spline( const MbNurbs & nurbs, const std::vector & interp ); - GCE_spline( size_t deg, bool cls, const std::vector & interp, const std::vector & pars ); - -private: - GCE_spline( const GCE_spline & ); - GCE_spline & operator = ( const GCE_spline & ); -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Параметры размерного ограничения. - \en Parameters of dimensional constraint. \~ - \details - \ru Все размерные ограничения задаются над геометрическими объектами; кроме них - размер определяется дополнительными параметрами, которые передаются через - структуру #GCE_dim_pars. - \en All dimensional constraints are specified on geometrical objects; in addition - dimension is specified by additional parameters which are passed via - the structure #GCE_dim_pars. \~ - - \par - \ru Функции, в которые GCE_dim_pars передается в качестве аргумента: - #GCE_AddDistance, #GCE_AddDistance2P, #GCE_AddDistancePLs, #GCE_AddDistancePLs, - #GCE_AddDirectedDistance, #GCE_FormCirDimension. - \en Functions into which GCE_dim_pars is passed as argument: - #GCE_AddDistance, #GCE_AddDistance2P, #GCE_AddDistancePLs, #GCE_AddDistancePLs, - #GCE_AddDirectedDistance, #GCE_FormCirDimension. \~ - - \par \ru Размеры - - Размер - это числовая функция, аргументами которой являются геометрические объекты, - а возвращаемым значением является число. На основе размеров определяются - 'размерные ограничения'. Все 'размерные ограничения' связывают геометрические - объекты с числом, называемым значением размера. Если ограничение удовлетворено, - то его числовой параметр равен значению размера. Числовой параметр размера - задается либо фиксированным числом (константой), либо числовой переменной.\n - Решатель ограничений обрабатывает два типа размеров: Управляющие и вариационные.\n - - \en Dimensions - - Dimension is a numerical function which arguments are geometric - objects and return value is a number. 'Dimensional constraints' are defined - on the base of dimensions. All 'dimensional constraints' associate geometric - objects with a number called a value of dimension. If the constraint is satisfied, - then its numerical parameter is equal to the value of dimension. Numerical parameter of the dimension - is specified by a fixed number (a constant) or by a numerical variable.\n - The solver of constraints treats two types of dimensions: Driving and variational.\n \~ - - - \par \ru Виды размеров - - "Управляющий" размер - это размерное ограничение, задающее положение - геометрическим объектам согласно константного значения размера;\n - "Вариационный" размер - это ограничение, связывающее геометрические - объекты и переменную, равную значению размера. Под воздействием вариационного - размера может меняться и геометрия и переменная размера.\n - Размеры могу быть направленные, например, расстояние между - точками по горизонтали или по вертикали (функция #GCE_AddDirectedDistance). - - \en Kinds of dimension - - "Driving" dimension is a dimensional constraint specifying position of - geometric objects subject to a constant value of dimension;\n - "Variational" dimension is a constraint associating geometric - objects and a variable which is equal to the dimension value. Both geometry and variable of dimension - can vary under the influence of variational dimension.\n - Dimensions can be directed, for instance, horizontal or vertical distance between - points(function #GCE_AddDirectedDistance). \~ - - - \par \ru Параметры - var - дескриптор переменной, задающей значение размера (градусы, если размер угловой); \n - dimValue - параметр, задающий значение размера; \n - - Если var != GCE_NULL_V, это означает, что размер "вариационный". - Если var == GCE_NULL_V, то значение размера = dimValue, иначе значение размера - тождественно равно числовой переменной 'var', т.е. размер управляющий. - - \en Parameters - - var - descriptor of variable specifying the value of dimension (degrees if the dimension is angular); \n - dimValue - parameter specifying the value of dimension; \n - - If var != GCE_NULL_V, it means that the dimension is "variational" - If var == GCE_NULL_V, then the value of dimension equals dimValue, else the value of dimension - is identically equal to a numerical variable 'var', i.e. the dimension is driving; \~ -*/ -//--- -struct GCE_dim_pars -{ - var_item var; ///< \ru Значение размера, заданное переменной. \en Value of dimension specified by the variable. - double dimValue; ///< \ru Значение размера. \en Value of dimension. - - GCE_dim_pars() - : dimValue( 0.0 ) - , var( GCE_NULL_V ) - {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Параметры углового размерного ограничения. - \en Parameters of angular dimensional constraint. - - \details \ru Структура данных передает настройки для создания угловых размеров. Помимо - общих настроек, передаваемых через структуру #GCE_dim_pars, здесь добавлен флаг - типа угла и множитель пересчета угла в переменную. \n - - factor - множитель для пересчета из присланного угла в переменную. - Используется для создания кратных углов, например двойного.\n - adjacent - смежный угол. Соответствует углу (M_PI - a), где 'a' - угол - между векторами, задающими направление линейного объекта.\n - - Угловой размер можно задать для любых комбинаций линейных объектов. - - \en The data structure passes settings for creation of angular dimensions. - In addition to the general settings passed via structure #GCE_dim_pars there is a flag - of angle type and factor of conversion of angle to variable here. \n - - 'factor' is a factor for converting from a given angle to variable. - It is used for creation of multiple angles, for instance, double angle.\n - 'adjacent' - adjacent angle. It corresponds to angle (M_PI - a), where 'a' is an angle - between vectors specifying the direction of a linear object.\n - - Angular dimension can be specified for any combination of linear objects. \~ -*/ -//--- -struct GCE_adim_pars -{ - GCE_dim_pars dPars; ///< \ru Общие настройки размера. \en General settings of dimension. - double factor; ///< \ru Множитель для пересчета из угла в переменную. \en Factor for converting from angle to variable. - bool adjacent; ///< \ru Смежный угол. \en Adjacent angle. - - GCE_adim_pars() : dPars(), factor( 1.0 ), adjacent( false ) - {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Параметры линейного размерного ограничения. - \en Parameters of distance constraint. - - \details - \ru dirAngle - значение угла в радианах, задающее направление ориентируемых размеров. Пока - используется только для #GCE_AddDirectedDistance2P. \n - \en dirAngle - value of angle in radians specifying the direction of oriented dimensions. - Now it is used only for #GCE_AddDirectedDistance2P. \n \~ -*/ -//--- -struct GCE_ldim_pars -{ - GCE_dim_pars dPars; ///< \ru Числовое значение размера, заданное переменной или числом double. \en Numeric value of dimension specified as a variable or simple double. - double dirAngle; ///< \ru Направление измерения (Используется только для ориентируемых размеров) \en Direction of dimension (It is used for oriented dimensions only) - geom_item hp[2]; ///< \ru Пара дескрипторов вспомогательных точек размера. \en A pair of descriptors of help points of dimension. - - GCE_ldim_pars() : dPars(), dirAngle( 0.0 ) - { - hp[0] = hp[1] = GCE_NULL_G; - } -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Контрольная точка драггинга. - \en Control point of the dragging. - \details - \ru GCE_dragging_point::geom - Дескриптор геометрического объекта, выбранного для воздействия - с помощью функции драггинга ( #GCE_PrepareDraggingPoint).\n - GCE_dragging_point::point - Дескриптор контрольной точки геометрического объекта драггинга. - - \en GCE_dragging_point::geom - Descriptor of a geometric object chosen to interact through - a dragging function (#GCE_PrepareDraggingPoint).\n - GCE_dragging_point::point - Descriptor of control point of the dragging geometric object. - \~ - \see #GCE_PrepareDraggingPoint, #GCE_MovePoint. -*/ -//--- -struct GCE_dragging_point -{ - geom_item geom; ///< \ru Дескриптор геометрического объекта. \en Descriptor of the geometric object. - geom_item point; ///< \ru Дескриптор контрольной точки геометрического объекта. \en Descriptor of the geometric object control point. - GCE_dragging_point() : geom( GCE_NULL ), point( GCE_NULL ) {} - GCE_dragging_point( geom_item g, geom_item pnt ) : geom( g ), point( pnt ) {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Диагностические характеристики системы ограничений. - \en Diagnostic characteristics of constraint system. \~ - \note Used only for testing -*/ -//--- -struct GCE_diagnostic_pars -{ - size_t consCount; // A number of registered constraints. - size_t inConsCount; // A number of internal constraints. - double reductCoef; // Reduction ration of decomposition methods [percentage]. - GCE_diagnostic_pars() : consCount( 0 ), inConsCount( 0 ), reductCoef( 0. ) {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Диагностические характеристики системы ограничений. - \en Diagnostic characteristics of constraint system. \~ - \note Used only for testing -*/ -//--- -struct GCT_diagnostic_pars -{ - size_t consCount; // A number of registered constraints. - size_t inConsCount; // A number of internal constraints. - double reductCoef; // Reduction ratio of decomposition methods [percentage]. - size_t dof; // Degree of freedom of a constraint system. - GCT_diagnostic_pars() - : consCount(0) - , inConsCount(0) - , reductCoef(0) - , dof(0) - {} -}; - -/** - \} - Constraints2D_API -*/ - -//---------------------------------------------------------------------------------------- -// \ru Дескриптор контрольной точки объекта. \en Descriptor of the object control point. -/* - The data structure is deprecated. -*/ -//--- -struct geom_point -{ - geom_item geom; ///< \ru Дескриптор геометрического объекта \en Descriptor of the geometric object - point_type pntName; ///< \ru Имя контрольной точки геометрического объекта \en Name of the geometric object control point - geom_point() : geom( GCE_NULL ), pntName( GCE_IMPROPER_POINT ) {} - geom_point( geom_item g, point_type pnt ) : geom( g ), pntName( pnt ) {} -}; - -/* - The values below will be deleted (deprecated names). -*/ -const constraint_type GCE_INCIDENT = GCE_COINCIDENT; -const geom_type GCE_ARC = GCE_ANY_GEOM; -const geom_type GCE_ELLIPSE_ARC = GCE_ANY_GEOM; - -/* - The values below are deprecated. -*/ - -const query_geom_type GCE_EllipseQ1 = GCE_Q1; -const query_geom_type GCE_EllipseQ2 = GCE_Q2; -const query_geom_type GCE_EllipseQ3 = GCE_Q3; -const query_geom_type GCE_EllipseQ4 = GCE_Q4; - -#endif // __GCE_TYPES_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Типы данных двумерного геометрического решателя. + \en Data types of the two-dimensional geometric solver. \~ + \details \ru Этот файл представляет собой набор типов данных, необходимых для + взаимодействия геометрического решателя с клиентским приложением. + \en This file contains set of data types necessary for interaction + of the geometrical solver with user application. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCE_TYPES_H +#define __GCE_TYPES_H + +#include +#include +#include +#include +#include +#include +#ifndef C3D_WINDOWS //_MSC_VER +#include +#endif //C3D_WINDOWS + +class MATH_CLASS MbNurbs; + +/** + \addtogroup Constraints2D_API + \{ +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Система геометрических ограничений. + \en Geometric constraints system. \~ + \details \ru GCE_system является типом данных, который обозначает систему ограничений, + которая создается с помощью вызова #GCE_CreateSystem. Реально, этот тип является + указателем на внутреннюю структуру данных, где содержится система ограничений и различные + рабочие данные, определяющие её внутреннее состояние. Время жизни системы ограничений + заканчивается только, когда к ней будет применен вызов API #GCE_RemoveSystem, после чего + значение GCE_system становится недействительным. + \en GCE_system is data type which denotes a system of constraints created by + call #GCE_CreateSystem. Actually this type is a pointer to an internal data structure with + a system of constraints and various working data determining its internal state. Lifetime + of the constraint system finishes only when a call of API #GCE_RemoveSystem + is applied to it, thereafter the value of GCE_system becomes invalid. \~ +*/ +typedef void * GCE_system; + +//---------------------------------------------------------------------------------------- +// \ru Типы данных. \en Data types. +//--- +/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. +typedef size_t geom_item; +/// \ru Дескриптор ограничения, зарегистрированного в решателе. \en Descriptor of a constraint registered in the solver. +typedef size_t constraint_item; +/// \ru Дескриптор переменной, зарегистрированной в решателе. \en Descriptor of a variable registered in the solver. +typedef size_t var_item; + +//---------------------------------------------------------------------------------------- +// \ru Константы. \en Constants. +//--- +/// \ru Неопределенное значение дескриптора или пустого объекта. \en Undefined value of descriptor or an empty object. +const size_t GCE_NULL = SYS_MAX_T; +/// \ru Неопределенное значение дескриптора типа #geom_item. \en Undefined value of #geom_item type. +const geom_item GCE_NULL_G = GCE_NULL; +/// \ru Неопределенное значение дескриптора типа #var_item. \en Undefined value of #var_item type. +const var_item GCE_NULL_V = GCE_NULL; +/// \ru Неопределенное значение дескриптора типа #constraint_item. \en Undefined value of #constraint_item type. +const constraint_item GCE_NULL_C = GCE_NULL; +/// \ru Не определенное значение числа double. \en An undefined value of double. +const double GCE_UNDEFINED_DBL = UNDEFINED_DBL; + +//---------------------------------------------------------------------------------------- +/// \ru Словарь типов геометрических примитивов. \en Dictionary of geometric primitives types. +//--- +typedef enum +{ + GCE_ANY_GEOM, ///< \ru Неизвестный тип. \en Unknown type. + + // \ru Основные типы. \en Basic types. + GCE_POINT, ///< \ru Точка на плоскости. \en Point on plane. + GCE_LINE, ///< \ru Прямая на плоскости. \en Line on plane. + GCE_CIRCLE, ///< \ru Окружность на плоскости. \en Circle on plane. + GCE_ELLIPSE, ///< \ru Эллипс на плоскости. \en Ellipse on plane. + GCE_SPLINE, ///< \ru Сплайн на плоскости. \en Spline on plane. + GCE_PARAMETRIC_CURVE, ///< \ru Параметрическая кривая на плоскости. \en Parametric curve on plane. + GCE_BOUNDED_CURVE, ///< \ru Ограниченная двумя точками, кривая. \en Curve bounded by two points. + + // \ru Дополнительные типы. \en Additional types. + GCE_LINE_SEGMENT, ///< \ru Отрезок прямой. \en Line segment. + GCE_SET, ///< \ru Подмножество геометрических объектов. \en Subset of geometric objects. +} geom_type; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Варианты контрольных точек, запрашиваемых у геометрического объекта. + \en Variants of control point requested from a geometric object. + \details \ru Это перечисление применяется для запроса дескриптора характерных точке объекта, + таких как центр окружности, концевая точка кривой и т.д... + \en This enum is used to request a descriptor of control point of an object, + such as center of circle, bounding point of a curve etc... + \see #GCE_PointOf +*/ +//--- +typedef enum +{ + /* + (!) Don't change the integer values of these names. It may be written to a file permanently. + */ + GCE_FIRST_PTYPE = 0 ///< \ru Значение начинающее последовательность вариантов. \en The value of beginning of the sequence. + , GCE_IMPROPER_POINT = 0 ///< \ru Точка, не принадлежащая объекту. \en Point not belonging to the object. + , GCE_FIRST_END ///< \ru Первый конец ограниченной кривой. \en The first end of bounded curve. + , GCE_SECOND_END ///< \ru Второй конец ограниченной кривой. \en The second end of bounded curve. + , GCE_CENTRE ///< \ru Центр окружности (дуги) или эллипса. \en Center of circle (arc) or ellipse. + , GCE_PROPER_POINT ///< \ru Собственно точка. \en Proper point. + , GCE_Q1 ///< \ru Квадрантная точка эллипса (3 часа). \en Quadrant point of ellipse (3 o'clock). + , GCE_Q2 ///< \ru Квадрантная точка эллипса (12 часов). \en Quadrant point of ellipse (12 o'clock). + , GCE_Q3 ///< \ru Квадрантная точка эллипса (6 часов). \en Quadrant point of ellipse (6 o'clock). + , GCE_Q4 ///< \ru Квадрантная точка эллипса (9 часов). \en Quadrant point of ellipse (9 o'clock). + , GCE_LOCATION_POINT ///< \ru Точка размещения геометрического объекта. \en Location point of geometric object. + , GCE_LAST_PTYPE ///< \ru Значение завершающее последовательность вариантов. \en The value of variants completes the sequence. + /* + The values below are used only within the solver. + */ + , GCE_DIRECTION ///< \ru Направляющий вектор эллипса (направление "большой" полуоси ). \en Vector of ellipse direction (direction of "major" semiaxis). + /** \brief \ru Единичный вектор ориентации: Нормаль прямой, направление "большой" полуоси эллипса. + \en Unit vector of orientation: Normal of a line, direction of "major" semiaxis of ellipse. \~ + */ + , GCE_ORIENTATION + +} query_geom_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Тип запрашиваемой точки (используется, как подмножество значений query_geom_type). + \en Type of the requested point (used as subset of values query_geom_type). +*/ +//--- +typedef query_geom_type point_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Перечисление координат геометрических объектов. + \en Enumeration of geom's coordinates. +*/ +//--- +typedef enum +{ + GCE_X, GCE_Y ///< \ru Координаты точки или вектора. \en Coordinates of a point or a vector. + , GCE_ACRD ///< \ru Угол нормали прямой, угол наклона эллипса. \en Angle of line normal, slope angle of ellipse. + , GCE_DCRD ///< \ru Координата смещения прямой, расстояние от начала координат до прямой. \en Coordinate of line shift, distance from CS origin to line. + , GCE_RADIUS ///< \ru Радиус окружности. \en Circle radius. + , GCE_MAJOR_RADIUS ///< \ru "Главная" полуось эллипса. \en "Major" semiaxis of ellipse. + , GCE_MINOR_RADIUS ///< \ru "Малая" полуось эллипса. \en "Minor" semiaxis of ellipse. + , GCE_NULL_CRD ///< \ru Пустая (несуществующая) координата. \en Empty (nonexistent) coordinate. +} coord_name; + +typedef coord_name coord_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Идентификатор типа 2D ограничения. + \en Identifier of 2D constraint type. \~ + \attention \ru На самом деле решатель поддерживает другие ограничения, кроме перечисленных. + См. вызовы API в 'gce_api.h' + \en Actually, the solver provides more constraint types than is given in the enum. + See the API calls in 'gce_api.h' \~ +*/ +typedef enum +{ + // \ru Унарные геометрические ограничения: \en Unary geometric constraints: + GCE_FIX_GEOM + , GCE_HORIZONTAL ///< \ru Горизонтальность прямой или отрезка. \en Horizontality of a linear object. + , GCE_VERTICAL ///< \ru Вертикальность прямой или отрезка. \en Verticality of a linear object. + , GCE_LENGTH ///< \ru Фиксация длины отрезка. \en Fixation of length of a line segment. + , GCE_ANGLE_OX + + // \ru Бинарные геометрические ограничения: "constr( geom1, geom2 )" \en Binary geometric constraints: "constr( geom1, geom2 )" + , GCE_COINCIDENT ///< \ru Совпадение пары геометрических объектов. \en Coincidence of a pair of geometric objects. + , GCE_EQUAL_LENGTH ///< \ru Равенство длин пары отрезков. \en Equality of two segments lengths. + , GCE_EQUAL_RADIUS ///< \ru Равенство радиусов пары окружностей. \en Equality of two circles lengths. + , GCE_PARALLEL ///< \ru Параллельность пары прямых или отрезков. \en Parallelism of two lines or segments. + , GCE_PERPENDICULAR ///< \ru Перпендикулярность пары прямых или отрезков. \en Perpendicularity of two lines or segments. + , GCE_TANGENT ///< \ru Касание пары кривых. \en Tangency of two curves. + , GCE_COLINEAR ///< \ru Коллинеарность пары прямых или отрезков. \en Collinearity of a pair of lines or segments. + , GCE_ALIGN_2P ///< \ru Выравнивание пары точек вдоль направления. \en Alignment of a pair of points along the direction. + , GCE_CURVATURE_EQUALITY ///< \ru Равенство кривизны кривых в точках. \en Equality of curves curvature in given points. + + // \ru Тернарные геометрические ограничения. \en Ternary geometric constraints. + , GCE_ANGLE_BISECTOR ///< \ru Биссектриса угла. \en Bisector of angle. + , GCE_MIDDLE_POINT ///< \ru Средняя точка. \en Middle point. + , GCE_COLINEAR_3P ///< \ru Коллинеарность тройки точек. \en Collinearity of a point triple. + , GCE_SYMMETRIC ///< \ru Симметричность. \en Symmetry. + + , GCE_PERCENT_POINT ///< \ru \en + , GCE_EQUATION ///< \ru Уравнение. \en Equation. + // \ru Размерные геометрические ограничения \en Dimensional geometric constraints + , GCE_DISTANCE + , GCE_RADIUS_DIM + , GCE_DIAMETER + , GCE_ANGLE + , GCE_CONSTRAINTS_COUNT ///< \ru Количество типов. \en Number of types. + , GCE_UNKNOWN = GCE_CONSTRAINTS_COUNT ///< \ru Неизвестный тип ограничения. \en Unknown constraint type. + , GCE_UNKNOWN_CON = GCE_UNKNOWN +} constraint_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Диагностические коды выполнения функций геометрического решателя. + \en Diagnostic codes of the geometric solver functions execution. \~ +*/ +//--- +typedef enum +{ + GCE_RESULT_None = 0, ///< \ru Нет результата (пустое сообщение). \en No result (empty message). + GCE_RESULT_Ok = 1, ///< \ru Успешный результат. \en Successful result. + GCE_RESULT_Satisfied = 1, ///< \ru Ограничение удовлетворено. \en The constraint is satisfied. + GCE_RESULT_Not_Satisfied = 2, ///< \ru Система ограничений не решена. \en The system of constraints is not solved. + GCE_RESULT_Overconstrained = 3, ///< \ru Переопределенная (несовместная) система ограничений. \en Overdetermined (inconsistent) system of constraints. + GCE_RESULT_InvalidGeometry = 4, ///< \ru Решение привело в нарушению геометрии. \en Solution leaded to violation of geometry. + GCE_RESULT_MovingOfFixedGeom = 5, ///< \ru Попытка перемещения фиксированного объекта. \en Attempt of a fixed object translation. + GCE_RESULT_Unregistered = 6, ///< \ru Обращение к недействительному объекту. \en Access to invalid object. + GCE_RESULT_SystemError = 7, ///< \ru Внутренняя системная ошибка. \en Internal system error. + GCE_RESULT_NullSystem = 8, ///< \ru Обращение к недействительной системе ограничений. \en Access to invalid system of constraints. + GCE_RESULT_CircleCantStretched = 9, ///< \ru Окружность не может быть масштабирована с разными коэффициентами по осям (растяжение). \en The circle can't be scaled with different scaling factors for each axis (stretching). + GCE_RESULT_SingularMatrix = 10, ///< \ru Прислали вырожденную матрицу трансформации. \en A singular transform matrix was received. + GCE_RESULT_DegenerateScalingFactor = 11, ///< \ru Вырожденный коэффициент масштабирования. \en Degenerate scaling factor. + GCE_RESULT_InvalidDimensionTransform = 12, ///< \ru Неудачное преобразование размера. \en Invalid dimension transformation. + GCE_RESULT_Aborted = 13, ///< \ru Процесс вычислений был прерван по запросу приложения. \en The evaluation process aborted by the application. \~ + GCE_RESULT_IsNotDrivingDimension = 14, ///< \ru Данное ограничение должно быть управляющим размером. \en Given constraint should be a driving dimension. + GCE_RESULT_UnsupportedConstraint = 15, ///< \ru На геометрические объекты было наложено невозможное ограничение. \en An impossible constraint was set on geometric objects. + GCE_RESULT_AnisotropicScaling = 16, ///< \ru Анизотропное масштабирование. \en Anisotropic scaling. +} GCE_result; + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Статус геометрического ограничения. + \en Status of a geometric constraint. + \details + \ru Статус ограничения подразумевает деление системы ограничения на подмножества, + которые маркируются следующим образом:\n + Ограничения, помеченые GCE_STATUS_WellTreated и GCE_STATUS_WellConditioned образуют + хорошо-обрабатываемую решателем часть системы ограничений, не содержащую переопределений + и обычно вычисляемую без противоречий.\n + Ограничения, помеченные статусами GCE_STATUS_WellConditioned и GCE_STATUS_IllConditioned + вместе образуют группу взаимосвязанных ограничений, которые обычно решаются без противоречий, + но потенциально могут противоречить друг другу при участии размеров. + Те из них, что помечены GCE_STATUS_IllConditioned создают условия для решаемости хуже, + чем GCE_STATUS_WellConditioned.\n + Статусом GCE_STATUS_Redundant решатель помечает лишние ограничения, которые можно удалить + из системы ограничений. Обычно такие ограничения исполняются за счет других ограничений + или создают ситуацию переопределенности (несовместная система ограничений).\n + Статусом GCE_STATUS_OverConstrained помечаются те из ограничений, которые остались не + решенными по причине несовместной переопределенности. Ограничения со статусами + GCE_STATUS_Redundant и GCE_STATUS_OverConstrained могут находится в противоречии с другими + ограничениями кроме тех, что помечены GCE_STATUS_WellTreated. + + The status of a constraint implies the division of the system into subsets, which are + labeled as follows: \n + Constraints marked by GCE_STATUS_WellTreated and GCE_STATUS_WellConditioned together form + well-resolved part that does not contain overdefining constraints and usually computed + without contradiction. \n + Constraints marked with GCE_STATUS_WellConditioned and GCE_STATUS_IllConditioned statuses + together form a group of interrelated constraints that are usually resolved without + contradiction, but potentially contradictory with dimensions. + Those that are labeled GCE_STATUS_IllConditioned make conditions for evaluating worse, + than GCE_STATUS_WellConditioned. \n + The status of GCE_STATUS_Redundant solver marks the extra constraints that can be removed. + from the constraint system. Usually such constraints are enforced by other constraints. + or create an overdefined situation (incompatible constraint system). \n + The status GCE_STATUS_OverConstrained marks those of constraints that was not solved + due to inconsistent overdefining. Constraints with GCE_STATUS_Redundant and + GCE_STATUS_OverConstrained statuses may conflict with other constraints except those + marked with GCE_STATUS_WellTreated. +*/ +//--- +typedef enum +{ + GCE_STATUS_Undefined = 0 + /* + Statuses indicating which of constraints belong to well-treated + or redundancy parts of the constraint system. + */ + , GCE_STATUS_WellTreated = 1 // Ограничение принадлежит рабочей части системы ограничений без переопределений. + , GCE_STATUS_WellConditioned = 2 // Ограничение принадлежит хорошо-обусловленной части уравнений. + , GCE_STATUS_IllConditioned = 3 ///< /ru Ограничения из плохо-обусловленной части. /en A constraint of ill-condition + , GCE_STATUS_Redundant = 4 ///< /ru Ограничение игнорируется решателем по причине избыточности. // en A constraint is ignored by the solving process beacause of the redundancy. + + /* + Statuses resulting the evaluation (call GCE_Evaluate). + */ + , GCE_STATUS_Solved // Ограничение решено + , GCE_STATUS_NotSolved // Не решено по каким-то причинам + , GCE_STATUS_NotConsistent // Не решено из-за противоречия с другими ограничениями. + , GCE_STATUS_OverConstrained // Не решено избыточное ограничение, противоречащее другим. + +} GCE_c_status; + +//---------------------------------------------------------------------------------------- +/// \ru Вернет 'true' в случае успешного результата. \en Return true, if the result code is successful. +// --- +inline bool OK( GCE_result resCode ) +{ + return resCode == GCE_RESULT_Ok; +} + +//---------------------------------------------------------------------------------------- +/// \ru Вариант решения биссектрисы для двух прямых. \en Variant of a bisector for two lines. +/* + \ru Идентификаторы не менять (возможна запись в файлы)! + \en Don't change identifiers (record to files is possible)! +*/ +//--- +typedef enum +{ + GCE_BISEC_CLOSEST = 0 ///< \ru Неопределенное направление (ближайшее решение). \en Undefined direction (nearest solution). + , GCE_BISEC_MINUS = 1 ///< \ru Биссектриса вдоль суммы направлений прямых/отрезков. \en Bisector along the difference of directions of lines/segments. + , GCE_BISEC_PLUS = 2 ///< \ru Биссектриса вдоль разности нормалей прямых/отрезков. \en Bisector along sum of directions of lines/segments. + +} GCE_bisec_variant; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты вектора. \en Vector coordinates. +//--- +struct GCE_vec2d +{ + double x, y; + GCE_vec2d() { x = y = 0; } +}; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты вектора n-й размерности. \en Coordinates of n-dimensional vector. +//--- +struct GCE_vecNd +{ + size_t size; + double * arg; + GCE_vecNd(): arg(0), size(0) {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты точки на плоскости. \en Coordinates of a point on plane. +//--- +struct GCE_point +{ + double x, y; ///< \ru Декартовы координаты на плоскости \en Cartesian coordinates on the plane + GCE_point() { x = y = 0; } +}; + +//---------------------------------------------------------------------------------------- +/// \ru Степень свободы точки. \en Degree of freedom of a point. +//--- +struct GCE_point_dof +{ + int dof; ///< Degree of freedom of the point. + GCE_vec2d dir; ///< Direction of point moving freedom. + GCE_point_dof(): dof(-1), dir() {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты прямой на плоскости. \en Coordinate of a line on the plane. +//--- +struct GCE_line +{ + GCE_point p; + GCE_vec2d norm; + GCE_line() : p(), norm() {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты окружности. \en Coordinates of a circle. +//--- +struct GCE_circle +{ + GCE_point centre; ///< \ru Центр окружности. \en Circle center. + double radius; ///< \ru Радиус окружности. \en Circle radius. + GCE_circle() : centre(), radius( 0.0 ) {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты эллипса. \en Coordinates of an ellipse. +//--- +struct GCE_ellipse +{ + GCE_point centre; ///< \ru Центр эллипса. \en Ellipse center. + GCE_vec2d direct; ///< \ru Направляющий вектор главной полуоси. \en Vector of the major semiaxis direction. + double majorR; ///< \ru Главная полуось. \en Major semiaxis. + double minorR; ///< \ru Вторая полуось. \en Second semiaxis. + + GCE_ellipse() + : centre() + , direct() + , majorR( 0.0 ) + , minorR( 0.0 ) + {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Координаты и характеристики сплайна. + \en Coordinates and characteristics of a spline.\~ + \details \ru + Сплайн можно задавать тремя способами: \n + 1) По уже существующему объекту MbNurbs. \n + 2) По уже существующему объекту MbNurbs и набору интерполяционных точек. \n + 3) По набору интерполяционных точек, соответствующих им параметров, порядку и признаку замкнутости. + \en + The spline can be specified in three ways: \n + 1) Using already existing object of MbNurbs. \n + 2) Using already existing object of MbNurbs and a set of interpolation points. \n + 3) Using a set of interpolation points, corresponding parameters, order and closedness attribute.\~ + \ingroup Constraints2D_API +*/ +// --- +struct GCE_CLASS GCE_spline +{ + size_t degree; ///< \ru Порядок В-сплайна. \en Order of B-spline. + bool isClosed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. + std::vector controlPoints; ///< \ru Множество контрольных точек. \en Set of control points. + std::vector controlWeights; ///< \ru Множество весов контрольных точек. \en Set of weights of the control points. + std::vector controlKnots; ///< \ru Узловой вектор. \en Knot vector. + std::vector interpPoints; ///< \ru Множество интерполяционных точек. \en Set of interpolation points. + std::vector interpParams; ///< \ru Множество значений параметров, соответствующих интерполяционным точкам. \en Set of the parameter values corresponding to interpolation points. + MbeNurbsCurveForm form; ///< \ru Форма кривой. \en Form of curve. + + GCE_spline() + : degree( Math::curveDegree ) + , isClosed( false ) + , controlPoints() + , controlWeights() + , controlKnots() + , interpPoints() + , interpParams() + , form( ncf_Unspecified ) + {} + explicit GCE_spline( const MbNurbs & nurbs ); + GCE_spline( const MbNurbs & nurbs, const std::vector & interp ); + GCE_spline( size_t deg, bool cls, const std::vector & interp, const std::vector & pars ); + + OBVIOUS_PRIVATE_COPY( GCE_spline ); +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Параметры размерного ограничения. + \en Parameters of dimensional constraint. \~ + \details + \ru Все размерные ограничения задаются над геометрическими объектами; кроме них + размер определяется дополнительными параметрами, которые передаются через + структуру #GCE_dim_pars. + \en All dimensional constraints are specified on geometrical objects; in addition + dimension is specified by additional parameters which are passed via + the structure #GCE_dim_pars. \~ + + \par + \ru Функции, в которые GCE_dim_pars передается в качестве аргумента: + #GCE_AddDistance, #GCE_AddDistance2P, #GCE_AddDistancePLs, #GCE_AddDistancePLs, + #GCE_AddDirectedDistance, #GCE_FormCirDimension. + \en Functions into which GCE_dim_pars is passed as argument: + #GCE_AddDistance, #GCE_AddDistance2P, #GCE_AddDistancePLs, #GCE_AddDistancePLs, + #GCE_AddDirectedDistance, #GCE_FormCirDimension. \~ + + \par \ru Размеры + + Размер - это числовая функция, аргументами которой являются геометрические объекты, + а возвращаемым значением является число. На основе размеров определяются + 'размерные ограничения'. Все 'размерные ограничения' связывают геометрические + объекты с числом, называемым значением размера. Если ограничение удовлетворено, + то его числовой параметр равен значению размера. Числовой параметр размера + задается либо фиксированным числом (константой), либо числовой переменной.\n + Решатель ограничений обрабатывает два типа размеров: Управляющие и вариационные.\n + + \en Dimensions + + Dimension is a numerical function which arguments are geometric + objects and return value is a number. 'Dimensional constraints' are defined + on the base of dimensions. All 'dimensional constraints' associate geometric + objects with a number called a value of dimension. If the constraint is satisfied, + then its numerical parameter is equal to the value of dimension. Numerical parameter of the dimension + is specified by a fixed number (a constant) or by a numerical variable.\n + The solver of constraints treats two types of dimensions: Driving and variational.\n \~ + + + \par \ru Виды размеров + + "Управляющий" размер - это размерное ограничение, задающее положение + геометрическим объектам согласно константного значения размера;\n + "Вариационный" размер - это ограничение, связывающее геометрические + объекты и переменную, равную значению размера. Под воздействием вариационного + размера может меняться и геометрия и переменная размера.\n + Размеры могу быть направленные, например, расстояние между + точками по горизонтали или по вертикали (функция #GCE_AddDirectedDistance). + + \en Kinds of dimension + + "Driving" dimension is a dimensional constraint specifying position of + geometric objects subject to a constant value of dimension;\n + "Variational" dimension is a constraint associating geometric + objects and a variable which is equal to the dimension value. Both geometry and variable of dimension + can vary under the influence of variational dimension.\n + Dimensions can be directed, for instance, horizontal or vertical distance between + points(function #GCE_AddDirectedDistance). \~ + + + \par \ru Параметры + var - дескриптор переменной, задающей значение размера (градусы, если размер угловой); \n + dimValue - параметр, задающий значение размера; \n + + Если var != GCE_NULL_V, это означает, что размер "вариационный". + Если var == GCE_NULL_V, то значение размера = dimValue, иначе значение размера + тождественно равно числовой переменной 'var', т.е. размер управляющий. + + \en Parameters + + var - descriptor of variable specifying the value of dimension (degrees if the dimension is angular); \n + dimValue - parameter specifying the value of dimension; \n + + If var != GCE_NULL_V, it means that the dimension is "variational" + If var == GCE_NULL_V, then the value of dimension equals dimValue, else the value of dimension + is identically equal to a numerical variable 'var', i.e. the dimension is driving; \~ +*/ +//--- +struct GCE_dim_pars +{ + var_item var; ///< \ru Значение размера, заданное переменной. \en Value of dimension specified by the variable. + double dimValue; ///< \ru Значение размера. \en Value of dimension. + + GCE_dim_pars() + : dimValue( 0.0 ) + , var( GCE_NULL_V ) + {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Параметры углового размерного ограничения. + \en Parameters of angular dimensional constraint. + + \details \ru Структура данных передает настройки для создания угловых размеров. Помимо + общих настроек, передаваемых через структуру #GCE_dim_pars, здесь добавлен флаг + типа угла и множитель пересчета угла в переменную. \n + + factor - множитель для пересчета из присланного угла в переменную. + Используется для создания кратных углов, например двойного.\n + adjacent - смежный угол. Соответствует углу (M_PI - a), где 'a' - угол + между векторами, задающими направление линейного объекта.\n + + Угловой размер можно задать для любых комбинаций линейных объектов. + + \en The data structure passes settings for creation of angular dimensions. + In addition to the general settings passed via structure #GCE_dim_pars there is a flag + of angle type and factor of conversion of angle to variable here. \n + + 'factor' is a factor for converting from a given angle to variable. + It is used for creation of multiple angles, for instance, double angle.\n + 'adjacent' - adjacent angle. It corresponds to angle (M_PI - a), where 'a' is an angle + between vectors specifying the direction of a linear object.\n + + Angular dimension can be specified for any combination of linear objects. \~ +*/ +//--- +struct GCE_adim_pars +{ + GCE_dim_pars dPars; ///< \ru Общие настройки размера. \en General settings of dimension. + double factor; ///< \ru Множитель для пересчета из угла в переменную. \en Factor for converting from angle to variable. + bool adjacent; ///< \ru Смежный угол. \en Adjacent angle. + + GCE_adim_pars() : dPars(), factor( 1.0 ), adjacent( false ) + {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Параметры линейного размерного ограничения. + \en Parameters of distance constraint. + + \details + \ru dirAngle - значение угла в радианах, задающее направление ориентируемых размеров. Пока + используется только для #GCE_AddDirectedDistance2P. \n + \en dirAngle - value of angle in radians specifying the direction of oriented dimensions. + Now it is used only for #GCE_AddDirectedDistance2P. \n \~ +*/ +//--- +struct GCE_ldim_pars +{ + GCE_dim_pars dPars; ///< \ru Числовое значение размера, заданное переменной или числом double. \en Numeric value of dimension specified as a variable or simple double. + double dirAngle; ///< \ru Направление измерения (Используется только для ориентируемых размеров) \en Direction of dimension (It is used for oriented dimensions only) + geom_item hp[2]; ///< \ru Пара дескрипторов вспомогательных точек размера. \en A pair of descriptors of help points of dimension. + + GCE_ldim_pars() : dPars(), dirAngle( 0.0 ) + { + hp[0] = hp[1] = GCE_NULL_G; + } +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Контрольная точка драггинга. + \en Control point of the dragging. + \details + \ru GCE_dragging_point::geom - Дескриптор геометрического объекта, выбранного для воздействия + с помощью функции драггинга ( #GCE_PrepareDraggingPoint).\n + GCE_dragging_point::point - Дескриптор контрольной точки геометрического объекта драггинга. + + \en GCE_dragging_point::geom - Descriptor of a geometric object chosen to interact through + a dragging function (#GCE_PrepareDraggingPoint).\n + GCE_dragging_point::point - Descriptor of control point of the dragging geometric object. + \~ + \see #GCE_PrepareDraggingPoint, #GCE_MovePoint. +*/ +//--- +struct GCE_dragging_point +{ + geom_item geom; ///< \ru Дескриптор геометрического объекта. \en Descriptor of the geometric object. + geom_item point; ///< \ru Дескриптор контрольной точки геометрического объекта. \en Descriptor of the geometric object control point. + GCE_dragging_point() : geom( GCE_NULL ), point( GCE_NULL ) {} + GCE_dragging_point( geom_item g, geom_item pnt ) : geom( g ), point( pnt ) {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Диагностические характеристики системы ограничений. + \en Diagnostic characteristics of constraint system. \~ + \note Used only for testing +*/ +//--- +struct GCE_diagnostic_pars +{ + size_t consCount; // A number of registered constraints. + size_t inConsCount; // A number of internal constraints. + double reductCoef; // Reduction ration of decomposition methods [percentage]. + GCE_diagnostic_pars() : consCount( 0 ), inConsCount( 0 ), reductCoef( 0. ) {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Диагностические характеристики системы ограничений. + \en Diagnostic characteristics of constraint system. \~ + \note Used only for testing +*/ +//--- +struct GCT_diagnostic_pars +{ + size_t consCount; // A number of registered constraints. + size_t inConsCount; // A number of internal constraints. + double reductCoef; // Reduction ratio of decomposition methods [percentage]. + size_t dof; // Degree of freedom of a constraint system. + GCT_diagnostic_pars() + : consCount(0) + , inConsCount(0) + , reductCoef(0) + , dof(0) + {} +}; + +/** + \} + Constraints2D_API +*/ + +//---------------------------------------------------------------------------------------- +// \ru Дескриптор контрольной точки объекта. \en Descriptor of the object control point. +/* + The data structure is deprecated. +*/ +//--- +struct geom_point +{ + geom_item geom; ///< \ru Дескриптор геометрического объекта \en Descriptor of the geometric object + point_type pntName; ///< \ru Имя контрольной точки геометрического объекта \en Name of the geometric object control point + geom_point() : geom( GCE_NULL ), pntName( GCE_IMPROPER_POINT ) {} + geom_point( geom_item g, point_type pnt ) : geom( g ), pntName( pnt ) {} +}; + +/* + The values below will be deleted (deprecated names). +*/ +const constraint_type GCE_INCIDENT = GCE_COINCIDENT; +const geom_type GCE_ARC = GCE_ANY_GEOM; +const geom_type GCE_ELLIPSE_ARC = GCE_ANY_GEOM; + +/* + The values below are deprecated. +*/ + +const query_geom_type GCE_EllipseQ1 = GCE_Q1; +const query_geom_type GCE_EllipseQ2 = GCE_Q2; +const query_geom_type GCE_EllipseQ3 = GCE_Q3; +const query_geom_type GCE_EllipseQ4 = GCE_Q4; + +#endif // __GCE_TYPES_H + +// eof diff --git a/C3d/Include/gcm_api.h b/C3d/Include/gcm_api.h index 0d4fd5a..26e1cd0 100644 --- a/C3d/Include/gcm_api.h +++ b/C3d/Include/gcm_api.h @@ -1,1085 +1,1085 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Программный интерфейс 3D решателя геометрических ограничений. - \en Program interface of three-dimensional geometric constraints solver. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCM_API_H -#define __GCM_API_H - -#include -// -#include -#include -#include - -class reader; -class writer; - -/** - \addtogroup GCM_3D_API - \{ -*/ - -/* - Constructing and deleting a constraint system -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Создать пустую систему ограничений. - \en Create a simple constraint system. \~ - \details \ru Вызов создает пустую систему ограничений. Кроме того, в памяти создаются - внутренние структуры данных геометрического решателя, обслуживающего систему ограничений. - Функция возвращает специальный дескриптор, по которому система ограничений доступна для - различных манипуляций: добавление или удаление геометрических объектов, ограничений, - варьирование размеров, драггинг недоопределенных объектов и т.д. - \en The call creates a simple constraint system. Besides, there are created - internal data structures of geometric solver maintaining the system of constraints. - The function returns a special descriptor by which the constraint system is available - for various manipulations: addition and deletion of geometric objects, constraints, - variation of sizes, dragging underconstrained objects etc. \~ - - \return \ru Дескриптор системы ограничений. - \en Descriptor of constraint system. \~ -*/ -//--- -GCM_FUNC(GCM_system) GCM_CreateSystem(); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Сделать систему ограничений пустой. - \en Make the constraint system empty. \~ - \details \ru Данный метод делает систему ограничений пустой при этом дескриптор gSys - остается действительным, т.е. можно осуществлять дальнейшую работу с системой ограничений. - \en This method makes the constraint system empty while the descriptor gSys - remains valid, i.e. it is possible to perform the further work with the constraint system. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \sa #GCM_RemoveSystem -*/ -//--- -GCM_FUNC(void) GCM_ClearSystem( GCM_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить систему ограничений. - \en Delete system of constraints. \~ - \details \ru Данный метод делает систему ограничений недействительной. Осуществляется - освобождение ОЗУ от внутренних структур данных, обслуживающих систему ограничений. - \en This method makes the constraint system invalid. Deallocation of RAM - from the internal data structures maintaining the system of constraints is performed. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \sa #GCM_ClearSystem -*/ -//--- -GCM_FUNC(void) GCM_RemoveSystem( GCM_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Читать систему ограничений из потока - \en Read constraint system from stream. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] in - \ru Поток для чтения. - \en Stream for reading. \~ -*/ -//--- -GCM_FUNC(bool) GCM_ReadSystem( GCM_system gSys, reader & in ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Запись системы ограничений в поток - \en Write constraint system to stream. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] out - \ru Поток для записи. - \en Stream for writing. \~ -*/ -//--- -GCM_FUNC(bool) GCM_WriteSystem( GCM_system gSys, writer & out ); - -//---------------------------------------------------------------------------------------- -/// Query to interrupt calculations -//--- -typedef bool ( *GCM_abort )(); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Назначить функцию прерывания вычислений - \en Set a callback to interrupt the calculations. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cbFunc - \ru Функция обратного вызова для прерывания операций. - \en A callback to interrupt the calculation. \~ -*/ -//--- -GCM_FUNC(void) GCM_SetCallback( GCM_system gSys, GCM_abort cbFunc ); - - -/* - Specifying geometry data structures (GCM_g_record) -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать запись пустого геометрического объекта. - \en Give the record of empty geometric object. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_NullGeom(); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать запись точки из типа MbCartPoint3D в типе GCM_g_record. - \en Get a record of point from the type MbCartPoint3D to the type GCM_g_record. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Point( const MbCartPoint3D & ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Запись прямой, заданной её точкой и направляющим вектором. - \en Record of line specified by the point and direction vector. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Line( const MbCartPoint3D & org - , const MbVector3D & axisZ ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Запись плоскости, заданной точкой и нормалью. - \en Record of plane specified by the point and normal vector. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Plane( const MbCartPoint3D & org, const MbVector3D & axisZ ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись конуса по заданному набору параметров. - \en Get data record of cone for the given set of parameters. \~ - \param[in] centre - \ru Центр окружности-основания конуса. - \en Center of base circle of the cone. \~ - \param[in] axis - \ru Направляющий вектор оси конуса. - \en Direction vector of the cone axis. \~ - \param[in] radiusA - \ru Радиус основания конуса. - \en Radius of the base circle. \~ - \param[in] radiusB - \ru Радиус сечения конуса ("малый" радиус). - \en Radius of section of circle ("minor" radius). \~ - \return \ru Запись конуса. - \en Record of cone. \~ - - \details \ru Предполагается, что параметры конуса описывают воображаемый усеченный конус, - высота которого всегда равна единице длины. При этом radiusA - это радиус - основания конуса, а radiusB - радиус его сечения. - \en It is assumed that the parameters describe the imaginary cone frustum, - whose height is always unit of length. In this radiusA - is the radius of - the base of the cone, and radiusB - the radius of its cross-section. -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Cone( const MbCartPoint3D & centre, const MbVector3D & axis - , double radiusA, double radiusB ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись цилиндра по заданному набору параметров. - \en Get data record of cylinder for the given set of parameters. \~ - \param[in] centre - \ru Центр окружности-основания цилиндра. - \en Center of base circle of the cylinder. \~ - \param[in] axis - \ru Направляющий вектор оси цилиндра. - \en Direction vector of the cylinder axis. \~ - \param[in] radius - \ru Радиус основания цилиндра. - \en Radius of the base circle. \~ - \return \ru Запись цилиндра. - \en Record of cylinder. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Cylinder( const MbCartPoint3D & centre, const MbVector3D & axis - , double radius ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись окружности, заданной набором параметров. - \en Get record of circle specified by the set of parameters. \~ - \param[in] centre - \ru Центр окружности. - \en Center of the circle. \~ - \param[in] axis - \ru Направляющий вектор оси окружности. - \en Direction vector of the circle axis. \~ - \param[in] radius - \ru Радиус окружности. - \en Radius of the circle. \~ - \return \ru Запись данных об окружности. - \en Data record of the circle. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Circle( const MbCartPoint3D & centre, const MbVector3D & axis, double radius ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись тороида по заданному набору параметров. - \en Get data record of torus for the given set of parameters. \~ - \param[in] centre - \ru Центр тора. - \en Center of torus. \~ - \param[in] axis - \ru Направляющий вектор оси вращения. - \en Direction vector of the rotation axis. \~ - \param[in] majorR - \ru "Большой" радиус тора - радиус окружности, описывающей вращение центра сечения. - \en "Major" radius is the radius of circle sweeping center of the rotating section. - \~ - \param[in] minorR - \ru Радиус окружности вращения ("малый" радиус). - \en Radius of section of circle ("minor" radius). \~ - - \details \ru Таким образом предполагается, что тор это воображаемая поверхность вращения, образованная - вращением окружности с радиусом minorR, лежащей в одной плоскости с осью вращения и центром, - расположенном на расстоянии majorR от оси тора. - \en Thus, it is assumed that the torus is an imaginary surface formed by - rotation of a circle of "minor radius" lying in the same plane as the axis - of rotation and the center located at a distance of majorR from the axis. -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Torus( const MbCartPoint3D & centre, const MbVector3D & axis - , double majorR, double minorR ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись данных о сфере, заданной центром и радиусом. - \en Get data record of sphere specified by center and radius. \~ - \param[in] centre - \ru Центр сферы. - \en Center of the sphere. \~ - \param[in] radius - \ru Радиус сферы. - \en Radius of the sphere. \~ - \return \ru Запись данных о сфере. - \en Data record of the sphere. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_Sphere( const MbCartPoint3D & centre, double radius ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись данных твердого тела, заданной началом координат и осями Z, X. - \en Get a data record of solid specified by its origin of coordinates, Z-axis and X-axis. \~ - \details - \ru Результат, который возвращает данная функция, используется для задания - в системе ограничений твердого тела (кластера) с помощью вызовов - GCM_AddGeom или #GCM_SubGeom. - \en The result, which returns this function, is used to specify a rigid body - (cluster) in the system by calling #GCM_AddGeom or #GCM_SubGeom. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_SolidLCS( const MbCartPoint3D & org - , const MbVector3D & axisZ = MbVector3D::zAxis - , const MbVector3D & axisX = MbVector3D::xAxis ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить запись данных системы координат твердого тела. - \en Get a data record of the solid coordinate system by its placement. \~ - \details - \ru Результат, который возвращает данная функция, используется для задания - в системе ограничений твердого тела (кластера) с помощью вызовов - GCM_AddGeom или GCM_SubGeom. - \en The result, which returns this function, is used to specify a rigid body - (cluster) in the system by calling #GCM_AddGeom or #GCM_SubGeom. \~ -*/ -//--- -GCM_FUNC(GCM_g_record) GCM_SolidLCS( const MbPlacement3D & ); - -/* - Defining geometry of constraint system -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений точку. - \en Add point to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] pVal - \ru Координаты точки. - \en Coordinates of a point. \~ - \return \ru Дескриптор зарегистрированной точки. - \en Descriptor of registered point. \~ -*/ -//--- -GCM_FUNC(GCM_geom) GCM_AddPoint( GCM_system gSys, const MbCartPoint3D & pVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений геометрический объект. - \en Add geometric object to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] gRec - \ru Запись геометрического объекта. - \en Record of geometric record. \~ - \return \ru Дескриптор зарегистрированного объекта. - \en Descriptor of registered object. \~ -*/ -//--- -GCM_FUNC(GCM_geom) GCM_AddGeom( GCM_system gSys, const GCM_g_record & gRec ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в систему ограничений геометрический объект. - \en Add geometric object to the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] gType - \ru Тип геометрического объекта. - \en Type of geometric object. \~ - \param[in] gMat - \ru Прямая матрица ЛСК объекта. - \en Direct matrix of geometric object. \~ - \param[in] radiusA - \ru Радиус окружности, цилиндра, сферы, а также "мажорный" радиус конуса и тора. - \en Radius of circle, cylinder, sphere, also "major" radius of cone and torus. \~ - \param[in] radiusB - \ru "Минорный" радиус конуса или тора. - \en "Minor" radius of cone and torus. \~ - \return \ru Дескриптор зарегистрированного объекта. - \en Descriptor of registered object. \~ -*/ -//-- -GCM_FUNC(GCM_geom) GCM_AddGeom( GCM_system gSys, GCM_g_type gType - , const MbMatrix3D & gMat - , double radiusA, double radiusB ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить в подсистему твердого тела (кластера) подчиненный геометрический объект. - \en Include a geometric sub-object to the subsystem of a solid (rigid cluster). \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] sol - \ru Твердое тело или кластер. - \en Solid or rigid cluster. \~ - \param[in] gRec - \ru Запись геометрического подчиненного объекта, заданного в ЛСК тела. - \en Record of geometric sub-object, which is given in LCS of the solid. \~ - \return \ru Дескриптор подчиненного объекта из подмножества тела. - \en Descriptor of sub-object in subset of the solid. \~ -*/ -//--- -GCM_FUNC(GCM_geom) GCM_SubGeom( GCM_system gSys, GCM_geom sol, const GCM_g_record & gRec ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать кластер (тело), в который включен данный геометрический объект. - \en Give a cluster (solid) in which a geometric object is included. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] subGeom -\ru Геометрический объект, принадлежащий кластеру. - \en A geometric object belonging to the cluster.. \~ - \return \ru Дескриптор кластера, которому принадлежит данный геометрический объект. - \en Descriptor of the cluster that owns this geometric object. \~ -*/ -//--- -GCM_FUNC(GCM_geom) GCM_Parent( GCM_system gSys, GCM_geom subGeom ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Тип геометрического объекта. - \en A type of geometric object. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \return \ru Геометрический тип объекта. - \en Geometric type of an object. \~ -*/ -//--- -GCM_FUNC(GCM_g_type) GCM_GeomType( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить геометрический объект из системы ограничений. - \en Delete a geometric object from the constraint system. \~ - \param gSys - \ru Система ограничений. - \en System of constraints. \~ - \param g - \ru Дескриптор геометрического объекта. - \en Descriptor of geometric object \~ - \details \ru После применения этой функции дескриптор объекта становится недействительным. - Надо заметить, что удаляемый геометрический объект может все еще участвовать в других - объектах и ограничениях. В этом случае удаляемый объект, хотя и считается удаленным, - фактически продолжает действовать до тех пор, пока другие объекты, связанные с ним, - не будут удалены. - \en After using this function the object descriptor 'g' will be invalidated. - It should be noted that the removed geometric object can still involved in other - objects and constraints. In this case, the object to be deleted, although it is considered - removed actually remains in effect until other objects connected with will be deleted. -*/ -//--- -GCE_FUNC(void) GCM_RemoveGeom( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вернет true, если объект все еще действительный. - \en Returns true if the object is still valid. \~ -*/ -//--- -//GCE_FUNC(bool) GCM_IsValid( GCM_system gSys, GCM_geom g ); - -/* - Defining a system of constraints -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать бинарное ограничение для пары геометрических объектов. - \en Set a binary constraint for two geometric objects. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g1 - \ru Дескриптор первого объекта. - \en Descriptors of first object. \~ - \param[in] g2 - \ru Дескриптор второго объекта. - \en Descriptors of second object. \~ - \param[in] aVal - \ru Опция выравнивания. - \en Alignment option. \~ - \param[in] tVar - \ru Вариант касания для ограничения c типом 'GCM_TANGENT'. - \en Variant of tangency for constraint of type 'GCM_TANGENT'. \~ - - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details - \ru Эта функция применяется для задания в системе бинарного ограничения любого - типа кроме размерных, а именно ограничения следующих типов: GCM_COINCIDENT, GCM_PARALLEL, - GCM_PERPENDICULAR, GCM_TANGENT, GCM_CONCENTRIC, GCM_IN_PLACE. В случае неудавшегося вызова, - функция вернет дескриптор пустого объекта GCM_NULL. - - \en The function is used to set a binary constraint of any type except - dimensional constraints, namely one of the following types: GCM_COINCIDENT, GCM_PARALLEL, - GCM_PERPENDICULAR, GCM_TANGENT, GCM_CONCENTRIC, GCM_IN_PLACE. In a case of failure, - the function returns a handle to an empty object GCM_NULL. \~ -*/ -//--- -GCM_FUNC(GCM_constraint) GCM_AddBinConstraint( GCM_system gSys, GCM_c_type cType - , GCM_geom g1, GCM_geom g2, GCM_alignment aVal = GCM_CLOSEST - , GCM_tan_choice tVar = GCM_TAN_POINT ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение, устанавливающее расстояние между парой геометрических объектов. - \en Set a constraint which specifies distance between a pair of geometric objects. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g1 - \ru Дескриптор первого объекта. - \en Descriptors of first object. \~ - \param[in] g2 - \ru Дескриптор второго объекта. - \en Descriptors of second object. \~ - \param[in] dVal - \ru Значение размера. - \en The value of dimension. \~ - \param[in] aVal - \ru Опция выравнивания. - \en Alignment option. \~ - \return \ru Дескриптор нового ограничения c типом GCM_DISTANCE. - \en Descriptor of the created constraint of type GCM_DISTANCE. \~ - - \details \ru Эта функция создает в системе размерное ограничение с типом GCM_DISTANCE, - которое задает линейный размер между двумя геометрическими объектами. - В случае неудачного вызова, функция вернет дескриптор пустого объекта GCM_NULL. - \en The function creates a dimensional constraint of type GCM_DISTANCE, which - specifies linear dimension between two geometric objects. - In a failed call, the function returns a handle to an empty object GCM_NULL.\~ - - \note \ru Значение dVal может быть знакопеременным для ориентируемых объектов. - \en Value of dVal can be positive as well as negative for oriented objects. \~ -*/ -//--- -GCM_FUNC(GCM_constraint) GCM_AddDistance( GCM_system gSys, GCM_geom g1, GCM_geom g2 - , double dVal, GCM_alignment aVal = GCM_CLOSEST ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение, устанавливающее угол между двумя геометрическими объектами. - \en Set a constraint which specifies angle between a pair of geometric objects. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g1 - \ru Дескриптор первого объекта. - \en Descriptors of first object. \~ - \param[in] g2 - \ru Дескриптор второго объекта. - \en Descriptors of second object. \~ - \param[in] axis - \ru Дескриптор объекта, задающего ось вращения угла. Может быть = GCM_NULL. - \en Descriptor of an object that specifying the rotation axis of angle. It can be GCM_NULL. \~ - \param[in] dVal - \ru Значение размера (радианы). - \en The value of dimension (radians). \~ - \return \ru Дескриптор нового ограничения c типом GCM_ANGLE. - \en Descriptor of the created constraint of type GCM_ANGLE. \~ - - \details \ru Эта функция создает в системе размерное ограничение с типом GCM_ANGLE, - которое задает угол между направлениями двух геометрических объектов. - Если ось вращения axis задана (т.е. != GCM_NULL), то угол имеет планарный - способ измерения (0 ... 2пи). В этом случае направления 'g1' и 'g2' обязаны - лежать в плоскости с нормалью заданной осью axis (оба направления перпендикулярны оси). - В случае неудавшегося вызова, функция вернет дескриптор пустого объекта GCM_NULL. - \en The function creates a dimensional constraint of type GCM_ANGLE, which - specifies angle between the directions of two geometric objects. - If the rotational axis is specified (i.e. != GCM_NULL), the angle has an - planar method of measurement (0 ... 2пи). In this case directions of - 'g1' and 'g2' must lie on a plane which has a normal specified by - the 'axis' parameter (both directions perpendicular to the axis ). - In a failed call, the function returns a handle to an empty object GCM_NULL. \~ -*/ -//--- -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 To create a constraint which specifies a radius of geometric objects. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g1 - \ru Дескриптор геометрического объекта, обладающего ненулевым радиусом. - \en Descriptor of the first object which has nonzero radius. \~ - \return \ru Дескриптор нового ограничения c типом GCM_RADIUS. - \en Descriptor of the created constraint which has a type GCM_RADIUS. \~ - - \details \ru Эта функция позволяет задать радиус геометрического объекта. Изменить величину - радиуса можно с помощью функции #GCM_ChangeDrivingDimension. Удаляется - радиальный размер вызовом функции #GCM_RemoveConstraint. - В случае неудачного вызова, функция вернет дескриптор пустого объекта GCM_NULL. - \en This function allows to specify a radius of the geometric object. To change - radius value use the function #GCM_ChangeDrivingDimension. To remove limitation - on radius of the geometric object use the function #GCM_RemoveConstraint. - In a case of failure, the function returns a handle to an empty object GCM_NULL. \~ -*/ -//--- -GCM_FUNC(GCM_constraint) GCM_FixRadius( GCM_system gSys, GCM_geom g1 ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать управляющий планарный угол между двумя геометрическими объектами. - \en Set a driving planar angle between a pair of geometric objects. \~ - \details \ru Функция аналогична вызову GCM_AddAngle, однако требует ось 'axis', - задающую плоскость откладывания угла. - \en This is the same call GCM_AddAngle, but requires an axis, which defines - a plane in which the angle is measured. \~ -*/ -//--- -GCM_FUNC(GCM_constraint) GCM_AddPlanarAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2 - , GCM_geom axis, double dVal ); - -//---------------------------------------------------------------------------------------- -// Not yet documented -//--- -GCM_FUNC(GCM_constraint) GCM_AddSymmeric( GCM_system gSys, GCM_geom g1, GCM_geom g2 - , GCM_geom plane, GCM_alignment aVal = GCM_NO_ALIGNMENT ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать линейный паттерн. - \en Create a linear pattern constraint. \~ - \details \ru Ограничение "Линейный Паттерн" задаёт закон, согласно которому группа - геометрических объектов, добавленных в этот паттерн с помощью функции - #GCM_AddGeomToPattern, располагается на заданной прямой. Кроме направляющей - прямой, для создания Линейного Паттерна требуется задать геометрический объект, - называемый образцом. Этот объект определяет начало координат (нулевую точку) - направляющей прямой. Таким образом в системе координат направляющей прямой - Линейного Паттерна образец всегда остаётся неподвижным относительно любых - трансляций, поворотов и деформаций. Положение любого добавляемого в паттерн - объекта (копии) определяется его положением на прямой, направленной вдоль - заданной оси, началом координат которой является начало координат ЛСК образца. - \en The Linear Pattern constraint defines the law under which geometric objects - added to this pattern using #GCM_AddGeomToPattern function are located on the - given line (guide line). In addition to the guide line to create a Linear - Pattern constraint it's necessary to specify a geometric object called a - Sample. This object defines the starting point of the guide line of the Linear - Pattern. Thus, Sample always remains stationary relative to any translations, - rotations and deformations in the coordinate system of the Linear Pattern guide - line. The position of any object (called a Copy) to be added to the pattern is - determined by its position on the guide line with the origin coinciding with the - origin of the LCS of the Sample.\~ - \par \ru Порядок удаления - Чтобы удалить Линейный Паттерн целиком нужно воспользоваться функцией - #GCM_RemoveConstraint. При этом не требуется удалять ограничения, созданные при - добавлении новых элементов в паттерн с помощью функции #GCM_AddGeomToPattern: - они будут удалены автоматически. - \en Removal procedure - To remove the Linear Pattern completely It's necessary to use the - #GCM_RemoveConstraint function. There is no need to remove constraints that were - created by the addition of new Copies to the pattern using the function - #GCM_AddGeomToPattern. They will be deleted automatically. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g1 - \ru Дескриптор образца. - \en Descriptor of the sample. \~ - \param[in] g2 - \ru Дескриптор направляющей оси линейного паттерна. - \en Descriptor of the direction axis of the Linear Pattern. \~ - \param[in] align - \ru Опция выравнивания образца относительно направляющей оси. Если задана - опция GCM_ALIGN_WITH_AXIAL_GEOM, то образец g1 будет лежать на направлеющей - прямой(оси) линейного паттерна. - \en Option of alignment of a sample g1 relative to the direction axis. If the - option #GCM_ALIGN_WITH_AXIAL_GEOM is given the sample g1 will be coincident - with the direction line(axis). \~ - \return \ru Дескриптор нового ограничения c типом GCM_LINEAR_PATTERN. - \en Descriptor of the created constraint which has a type GCM_LINEAR_PATTERN. \~ -*/ -// --- -GCM_FUNC(GCM_pattern) GCM_AddLinearPattern( GCM_system gSys, GCM_geom g1, GCM_geom g2, GCM_alignment align=GCM_NO_ALIGNMENT ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать угловой паттерн. - \en Create an angular pattern constraint. \~ - \details \ru Ограничение "Угловой Паттерн" задаёт закон, согласно которому группа - геометрических объектов, добавленных в этот паттерн с помощью функции - #GCM_AddGeomToPattern, располагается на некоторой окружности. Окружность эта - лежит в плоскости перпендикулярной заданной оси, а центр окружности лежит на - этой оси. Кроме оси вращения для создания Углового Паттерна требуется задать - геометрический объект, называемый образцом. Этот объект определяет нулевой угол - и начальный радиус окружности. Таким образом положение любого добавляемого в - паттерн объекта (копии) определяется вращением вокруг заданной оси, начиная от - образца. При этом радиус окружности (расстояние от копии или образца до оси) не - не является константой и может варьироваться (изменяться) в ходе решения. - \en The Angular Pattern constraint defines the law under which geometric objects - added to this pattern using #GCM_AddGeomToPattern function are located on the - given circle. This circle lies in a plane that is perpendicular to the given - axis, and the center of this circle lies on this axis. In addition to the axis - to create an Angular Pattern constraint it's necessary to specify a geometric - object called a Sample. This object defines the zero angle and the initial - radius of the circle for the Angular Pattern. The position of any object (called - a Copy) to be added to the pattern is determined by the rotation around the - given axis, starting from the Sample. The radius of the circle (the distance - from the Copy or the Sample to the axis) is not constant and can vary in the - process of solving the system of equations. \~ - - \par \ru Порядок удаления - Чтобы удалить Угловой Паттерн целиком нужно воспользоваться функцией - #GCM_RemoveConstraint. При этом не требуется удалять ограничения, созданные при - добавлении новых элементов в паттерн с помощью #GCM_AddGeomToPattern: они будут - удалены автоматически. - \en Removal procedure - To remove the Angular Pattern completely It's necessary to use the - #GCM_RemoveConstraint function. There is no need to remove constraints that were - created by the addition of new Copies to the pattern using the function - #GCM_AddGeomToPattern. They will be deleted automatically. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] smp - \ru Дескриптор образца. - \en Descriptor of the sample. \~ - \param[in] axial - \ru Дескриптор оси вращения углового паттерна. - \en Descriptor of the rotation axis of the Angular Pattern. \~ - \param[in] align - \ru Опция выравнивания образца относительно направляющей оси. Если задана - опция GCM_ALIGN_WITH_AXIAL_GEOM, то образец 'smp' будет лежать в плоскости - XY направляющего обекта (оси вращения), и если направляющий объект имеет - радиус (например, это окружность), то расстояние от объектов Углового - Паттерна до оси вращения будет равно радиусу направляющего объекта - (например, радиусу окружности). - \en Option of alignment of a sample relative to the direction axis. - If the GCM_ALIGN_WITH_AXIAL_GEOM option is specified sample g1 will lie in - the XY plane of the direction axis object (rotation axis) and if the - direction axis object has a radius (for example, this is a circle) the - distance from the Angle Pattern objects to the rotation axis will be equal - to the radius of the direction axis object (for example, radius of a circle). \~ - \return \ru Дескриптор нового ограничения c типом GCM_ANGULAR_PATTERN. - \en Descriptor of the created constraint which has a type GCM_ANGULAR_PATTERN. \~ -*/ -// --- -GCM_FUNC(GCM_pattern) GCM_AddAngularPattern( GCM_system gSys, GCM_geom smp, GCM_geom axial, GCM_alignment align=GCM_NO_ALIGNMENT ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Добавить геометрический объект в паттерн. - \en Add geometric object to the pattern. \~ - \details \ru Объект, добавляемый в паттерн, назовём копией. - Если копия добавляется в Линейный Паттерн, то требуется указать расстояние от - копии до образца. Оно может быть положительным или отрицательным и определяется - требуемым положением копии относительно образца с учётом направляющей оси. Так - же можно опционально задать выравнивание ЛСК копии относительно ЛСК образца. - Если копия добавляется в Угловой Паттерн, то требуется указать угол поворота - копии относительно образца, вокруг оси вращения паттерна. Так же можно - опционально задать выравнивание копии относительно образца. Возможны 2 типа - выравнивания: GCM_ALIGNED - выравнивание ЛСК копии и образца и GCM_ROTATED - - выравнивание ЛСК копии с ЛСК образца, повёрнутого вокруг оси вращения на тот же - угол, что и копия. - Расстояние (или угол поворота) от образца до копии по умолчанию фиксировано, - но может быть варьируемым при задании соответствующей опции #GCM_scale. - \en Let's call a Copy the object that is added to the pattern. - If the Copy is added to the Linear Pattern it's necessary to specify the - distance from the Copy to the Sample. It can be positive or negative and is - determined by the required position of the Copy relative to the Sample taking - into account the guide axis. It's optionally possible to specify alignment of - the Copy LCS relative to the Sample LCS. - If the Copy is added to the Angular Pattern it's necessary to specify the - angle of rotation of the Copy relative to the Sample around the pattern rotation - axis. It's optionally possible to specify alignment of the Copy relative to the - Sample. There are 2 types of alignment: GCM_ALIGNED - alignment of the local - coordinate systems of the Copy and the Sample, GCM_ROTATED - the alignment of - the local coordinate system of the Copy with the local coordinate system of the - Sample that is rotated around the axis of rotation at the same angle as the Copy. - The distance (or angle of rotation) from the sample to the copy is fixed by default, -                 but can be varied by specifying the appropriate #GCM_scale option.\~ - - \par \ru Порядок удаления. - Чтобы удалить копию из паттерна используйте функцию #GCM_RemoveConstraint. Если - же вам надо удалить паттерн целиком, то вам не требуется удалять каждую копию из - паттерна, просто удалите паттерн. - \en Removal procedure - To remove a Copy from the pattern use the function #GCM_RemoveConstraint. If - it's necessary to remove the pattern completely there is no need to remove each - copy from the pattern. Just remove the pattern constraint. \~ - - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] ptrn - \ru Дескриптор паттерна, в который добавляем копию. - \en Descriptor of the pattern. \~ - \param[in] geom - \ru Дескриптор добавляемого геометрического объекта (копии). - \en Descriptor of the copy. \~ - \param[in] position - \ru Переменная, задающая положение добавляемой копии в паттерне (расстояние или угол). - \en Variable that specifies the position of the copy in the pattern (distance or angle). \~ - \param[in] align - \ru Опция, задающая выравнивание копии по отношению к образцу. - \en Option that specifies the alignment of copy relative to the sample. \~ - \param[in] scale - \ru Тип масштабирования элемента паттерна. - \en Scaling type of pattern element. \~ - \return \ru Дескриптор нового ограничения c типом GCM_PATTERNED. - \en Descriptor of the created constraint which has a type GCM_PATTERNED. \~ -*/ -// --- -GCM_FUNC(GCM_constraint) GCM_AddGeomToPattern( GCM_system gSys, GCM_pattern ptrn, GCM_geom geom, double position, - GCM_alignment align = GCM_NO_ALIGNMENT, GCM_scale scale = GCM_RIGID ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать ограничение. - \en Set a constraint. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cRec - \ru Унифицированная запись ограничения. - \en Uniform record of a constraint. \~ - \return \ru Дескриптор нового ограничения. - \en Descriptor of a new constraint. \~ - \details - \ru Эта функция применяется только для автоматического тестирования решателя, - поэтому подробно не документировалась. - \en This function is used only for the automated testing of the solver therefore not documented. -*/ -//--- -GCM_FUNC(GCM_constraint) GCM_AddConstraint( GCM_system gSys, const GCM_c_record & cRec ); - -//---------------------------------------------------------------------------------------- -// Not yet documented -//--- -GCM_FUNC(GCM_geom) GCM_SetDependent( GCM_system gSys, GCM_constraint con, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Удалить ограничение из системы. - \en Delete a constraint from the system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] con - \ru Дескриптор ограничения. - \en Descriptor of constraint. \~ -*/ -//--- -GCE_FUNC(void) GCM_RemoveConstraint( GCM_system gSys, GCM_constraint con ); - - -/* - Fixation and freeing of a geometry -*/ - -//---------------------------------------------------------------------------------------- -// Create fixing constraint of the geom -//--- -GCM_FUNC(GCM_constraint) GCM_FixGeom_( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Сделать геометрический объект неподвижным. - \en Set a geometric object fixed. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Дескриптор геометрического объекта. - \en Descriptors of geometric object. \~ - - \details - \ru Эта функция делает объект неподвижным лишая его всех степеней свобод. Если геометрический - объект является суб-объектом тела (кластера), то объект замораживается только в рамках кластера, - однако в глобальной системе координат объект имеет такую же свободу как и кластер, - которому он принадлежит. - \en Thе function makes the object fixed depriving it of all degrees of freedom. If the geometric object - is a sub geom of a solid (cluster), the object is frozen only in the framework of the cluster, - but in the global coordinate system the object has the same freedom as the cluster - to which it belongs. - \~ - \note \ru На будущее планируется, что данная функция будет возвращать дескриптор ограничения. - \en In the future this function will be returning a descriptor of constraint, i.e. will create a fixing constraint. \~ - \sa GCM_FreeGeom -*/ -//--- -GCM_FUNC(bool) GCM_FreezeGeom( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Освободить объект, зафиксированный методом GCM_FreezeGeom. - \en Set free geometric object fixed by GCM_FreezeGeom call. \~ - \sa GCM_FreezeGeom -*/ -//--- -GCM_FUNC(void) GCM_FreeGeom( GCM_system gSys, GCM_geom g ); - -/* - Evaluating methods -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вычислить систему ограничений. - \en Calculate the constraint system. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \return \ru Код результата вычислений. - \en Calculation result code. \~ - \details \ru Функция решает задачу ограничений. Задача ограничений формулируется - функциями API геометрического решателя; функции вида GCM_Add_XXXXXXX добавляют новые - объекты, функции вида GCM_Change_XXXXXXX, GCM_Set_XXXXXXX изменяют состояние объектов. - Таким образом, что бы все такие изменения вступили в силу, нужно вызвать - метод #GCM_Evaluate.\n - Алгоритмы GCM_Evaluate учитывают удовлетворенность систем ограничений; если - все ограничения уже решены, то функция не тратит время на вычисления, а - состояние геометрических объектов остается неизменным. - \en The function solves problem of constraints. The problem of constraint is - formulated by API functions of geometric solver; the functions of a kind GCM_Add_XXXXXXX - add a new object, the functions of kinds GCM_Change_XXXXXXX and GCM_Set_XXXXXXX change - a state of objects. Thus, for all changes to take effect it is necessary to call the - method #GCM_Evaluate.\n - The algorithms GCM_Evaluate take into account whether constraint systems are satisfied, - if all constraints have been already solved, then the function does not spend time - for calculations, and the state of geometric objects remains unchanged. \~ -*/ -//--- -GCM_FUNC(GCM_result) GCM_Evaluate( GCM_system gSys ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Получить код результата вычисления ограничения. - \en Get result code of the evaluation of constraint. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cItem - \ru Дескриптор ограничения, принадлежащего системе gSys. - \en Descriptor of constraint belonging to the system gSys. \~ - \note \ru Если система еще не вычислялась, то функция вернет код GCM_RESULT_None. - \en If the system has not yet been evaluated then the function will return - the code GCM_RESULT_None. \~ - \return \ru Диагностический код хранящийся в системе после последней вызова GCM_Evaluate. - \en Diagnostic code stored in the system after the last call GCM_Evaluate. \~ -*/ -//--- -GCM_FUNC(GCM_result) GCM_EvaluationResult( GCM_system gSys, GCM_constraint cItem ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выполнить проверку удовлетворенности ограничения. - \en Perform a check that a constraint is satisfied. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] cItem - \ru Дескриптор ограничения. - \en Descriptor of constraint. \~ - \return \ru true, если ограничение удовлетворено. - \en true if a constraint is satisfied. \~ -*/ -//--- -GCM_FUNC(bool) GCM_IsSatisfied( GCM_system gSys, GCM_constraint cItem ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать текущее положение (решение) геометрического объекта. - \en Get current placement (solution) of the geometric object. -*/ -//--- -GCM_FUNC(MbPlacement3D) GCM_Placement( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выдать начало СК геометрического объекта. - \en Get an LCS origin of the geometric object. - \details \ru Функция вернет координаты начала ЛСК объекта. Данный вызов может быть - использован для любых типов геометрии. Например, для окружности данный вызов вернет ее - центр, для плоскости - точку, лежащую на плоскости, для цилиндра - центр основания - цилиндра и т.д. - \en The function returns coordinates of the origin of the LCS. The call can be applied - to any type of geometry. For example, for a circle the call will return its center, - for a plane - it is a point laying on the plane, - for a cylinder - it is a center of its foundation circle and so on. - -*/ -//--- -GCM_FUNC(MbCartPoint3D) GCM_Origin( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Текущее значение радиуса геометрического объекта. - \en Current radius value of the geometric object. -*/ -//--- -GCM_FUNC(double) GCM_Radius( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Текущее значение "большого" радиуса тора или конуса. - \en Current "major" radius value of torus or cone. -*/ -//--- -GCM_FUNC(double) GCM_RadiusA( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Текущее значение "малого" радиуса тора или конуса. - \en Current "minor" radius value of torus or cone. -*/ -//--- -GCM_FUNC(double) GCM_RadiusB( GCM_system gSys, GCM_geom g ); - -/* - Changing methods -*/ - -//---------------------------------------------------------------------------------------- -/** \brief \ru Изменить значение управляющего размера. - \en Change the value of driving dimension. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] dItem - \ru Дескриптор размерного ограничения. - \en Descriptor of dimensional constraint. \~ - \param[in] dVal - \ru Требуемое значение размера. - \en Required value of constraint. \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \details \ru Функция применяется только для управляющих размеров. Если управляющий размер - является угловым, то параметр dVal задается в радианах.\n - Следует учитывать, что настоящая функция не осуществляет вычислений, а только подготавливает - изменение размера. Что бы изменения вступили в силу, необходимо вызвать функцию #GCE_Evaluate. - \en The function is used only for driving dimensions. If the driving dimension - is angular, then the parameter dVal is specified in radians. \n - It should be noted that the function doesn't perform computations but only prepares - the changing of dimension. For the changes to take effect it is required to call - the function #GCM_Evaluate. \~ -*/ -//--- -GCM_FUNC(GCM_result) GCM_ChangeDrivingDimension( GCM_system gSys, GCM_constraint dItem, double dVal ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Задать текущее положение геометрического объекта. - \en Set current placement of the geometric object. - \note \ru Эта функция только придает объекту новое состояние без переоценки системы - ограничений. Вызов GCM_Evaluate может поменять заданное состояние, если - имеются не удовлетворенные ограничения. - \en The function only impart new state of the object without the revaluation - of constraints. Call GCM_Evaluate can change the given state to satisfy - constraints of this object. \~ -*/ -//--- -GCM_FUNC(void) GCM_SetPlacement( GCM_system gSys, GCM_geom g, const MbPlacement3D & place ); - - -/* - Dragging functions -*/ - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Инициализировать режим перетаскивания объектов в плоскости экрана. - \en Initialize mode of object moving in the screen plane. - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] movGeom - \ru Компонент, деталь, которой манипулируют. - \en Component, part which is manipulated. \~ - \param[in] projPlane - \ru Плоскость экрана, заданная в ГСК сборки. - \en Plane of the screen given in the WCS of assembly. \~ - \param[in] curPnt - \ru Точка, принадлежащая компоненту, которая проецируется на плоскость - экрана в положение курсора, и за которую осуществляется 'перетаскивание'. - curPnt задана в ЛСК геом.объекта movGeom. - \en Point of the component which is projected onto plane of the screen to - cursor position and is 'dragging'. curPnt given in the LCS of - the geometric object movGeom; \~ - \return \ru Код результата. \en Result code. \~ - - \details - \ru Функция запускается однократно перед входом в режим перетаскивания компонент, который управляется - (по движению мыши) через команду #GCM_SolveReposition(GCM_system, const MbCartPoint3D &). Режим - прекращается вызовом любой иной команды, кроме #GCM_PrepareReposition. Также есть специальная - функция для выхода из режима "перетаскивания" - #GCM_FinishReposition, для явного сбрасывания - режима перемещения. - \en The function runs once to start the dragging mode of components, which is controlled - (by movement of the mouse) by the command #GCM_SolveReposition(GCM_system, const MbCartPoint3D &). - Mode is stopped by the calling any other command except #GCM_PrepareReposition. There is also - the special function to exit from the dragging mode explicitly - #GCM_FinishReposition. \~ -*/ -//--- -GCM_FUNC(GCM_result) GCM_PrepareReposition( GCM_system gSys, GCM_geom movGeom, - const MbPlacement3D & projPlane, const MbCartPoint3D & curPnt ); - -/** \brief \ru Инициализировать режим вращения компонента вокруг фиксированной оси. - \en To initialize the rotation mode of the component around a fixed axis. -*/ -GCM_FUNC(GCM_result) GCM_PrepareReposition( GCM_system gSys, GCM_geom rotGeom, const MbCartPoint3D & org, const MbVector3D & axis ); - -/// \ru Завершить режим "перетаскивания". \en Finish the dragging mode. -GCM_FUNC(void) GCM_FinishReposition( GCM_system gSys ); - -/** \brief \ru Выдать объект манипуляции, с которым работает решатель, находясь в режиме вращения/перемещения объектом (драггинг). - \en Get manipulation object with which the Solver works when being in the dragging mode (rotating or moving). -*/ -GCM_FUNC(GCM_geom) GCM_GetMovingGeom( GCM_system gSys ); - -/** - \brief \ru Решить систему для произвольного изменения положения одного тела. - \en Solve the system for an arbitrary change of position of one solid. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] g - \ru Тело, положение которого меняется. - \en Solid, the position of which is changed. \~ - \param[in] newPos - \ru Новое пололожение тела. - \en New position of a solid. \~ - \param[in] movType - \ru Код желаемого поведения - \en Code of the desired behavior \~ - \return \ru Код результата. \en Result code. \~ - - \note \ru Эта функция не позволяет вывести систему сопряжений из состояния решаемости, - кроме случаев, когда до вызова функции система уже находилась в нерешенном - состоянии. Если новое положение 'newPos' не позволяет удовлетворять системе сопряжений, - то новое положение тела окажется наиболее близким к newPos (при сохранении решаемости). - \en This function doesn't allow to take out constraint system from decided state, - except when before call of function the system was already unsolved. If new position - 'newPos' doesn't allow to satisfy the system of constraints, then new position of solid - will be the most nearest to newPos (while preserving solvability). \~ -*/ -GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, GCM_geom g, - const MbPlacement3D & newPos, GCM_reposition movType ); - -/** - \brief \ru Решить систему сопряжений для новой позиции курсора в режиме драггинга. - \en Solve the system of constraints for new position of cursor in the dragging mode. - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] curPos - \ru Текущее положение курсора в ГСК. - \en Current position of a cursor in the WCS. \~ - \return \ru Код результата. \en Result code. \~ - - \details \ru Процедура, управляющая режимом перетаскивания, который прекращается вызовом любой иной команды. - \en Procedure that controls dragging mode which are stopped after calling any other command. \~ -*/ -GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, const MbCartPoint3D & curPos ); - -/** - \brief \ru Решить систему в режиме драггинга с одно-параметрическим управлением. - \en Solve the system under one-parametric driving in the dragging mode. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] alpha - \ru Управляющий параметр (зачастую задается в радианах). - \en Driving parameter (this is ussualy an angle given in radians). \~ - \return \ru Код результата. \en Result code. \~ - - \details \ru Это функция, управляющая режимом динамического перепозиционирования - (см. #GCM_PrepareReposition), в котором положение тела управляется изменением одной - координаты, например, угла вращения вокруг оси. Режим прекращается вызовом - #GCM_FinishReposition или любой иной командой, меняющей состояние решетеля, например, - #GCM_AddConstraint. - \en This function controls dynamic reposition mode (see #GCM_PrepareReposition), - in which the position of the solid is driven by changing one coordinate. For example - the angle of rotation around an axis. Mode is stopped by calling #GCM_FinishReposition - or any other command, which is changes state of the Solver, for example #GCM_AddConstraint. - \~ -*/ -GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, double alpha ); - -/* - Journaling functions -*/ - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Включить журналирование и назначить файл для записи журнала вызовов API. - \en Switch on the journaling and specify the file for recording a journal of GCE API calls. \~ - \param[in] gSys - \ru Система ограничений. - \en System of constraints. \~ - \param[in] fName - \ru Имя файла назначения с полным путем. - \en Name of destination file with a full path. \~ - \return true, if journaling has been successfully switched on. - - \attention - \ru Файл журнала будет записан только после завершения сеанса работы с системой - ограничений, а именно сразу после вызова GCM_RemoveSystem. - \en The journal file will be written only when a session of work with the - constraint system is finished, i.e. immediately after calling the - GCM_RemoveSystem method. - \ru Добавление записей в журнал из параллельного кода не происходит. - \en Adding records to the journal from parallel code does not occur. -*/ -//--- -GCE_FUNC(bool) GCM_SetJournal( GCM_system gSys, const char * fName ); - - -/** \} */ // GCM_3D_API - -struct GCT_diagnostic_pars; -//---------------------------------------------------------------------------------------- -/* - It's used for testing purposes only. -*/ -//--- -GCM_FUNC(const GCT_diagnostic_pars &) GCM_DiagnosticPars( GCM_system gSys ); - -//---------------------------------------------------------------------------------------- -// Use GCM_FreezeGeom instead this (2019). -//--- -GCM_FUNC(void) GCM_FixGeom( GCM_system gSys, GCM_geom g ); - -//---------------------------------------------------------------------------------------- -// Deprecated -//--- -GCM_FUNC(bool) GCM_IsFixed( GCM_system gSys, GCM_geom g ); - - -#endif // __GCM_API_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Программный интерфейс 3D решателя геометрических ограничений. + \en Program interface of three-dimensional geometric constraints solver. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCM_API_H +#define __GCM_API_H + +#include +// +#include +#include +#include + +class reader; +class writer; + +/** + \addtogroup GCM_3D_API + \{ +*/ + +/* + Constructing and deleting a constraint system +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Создать пустую систему ограничений. + \en Create a simple constraint system. \~ + \details \ru Вызов создает пустую систему ограничений. Кроме того, в памяти создаются + внутренние структуры данных геометрического решателя, обслуживающего систему ограничений. + Функция возвращает специальный дескриптор, по которому система ограничений доступна для + различных манипуляций: добавление или удаление геометрических объектов, ограничений, + варьирование размеров, драггинг недоопределенных объектов и т.д. + \en The call creates a simple constraint system. Besides, there are created + internal data structures of geometric solver maintaining the system of constraints. + The function returns a special descriptor by which the constraint system is available + for various manipulations: addition and deletion of geometric objects, constraints, + variation of sizes, dragging underconstrained objects etc. \~ + + \return \ru Дескриптор системы ограничений. + \en Descriptor of constraint system. \~ +*/ +//--- +GCM_FUNC(GCM_system) GCM_CreateSystem(); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Сделать систему ограничений пустой. + \en Make the constraint system empty. \~ + \details \ru Данный метод делает систему ограничений пустой при этом дескриптор gSys + остается действительным, т.е. можно осуществлять дальнейшую работу с системой ограничений. + \en This method makes the constraint system empty while the descriptor gSys + remains valid, i.e. it is possible to perform the further work with the constraint system. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \sa #GCM_RemoveSystem +*/ +//--- +GCM_FUNC(void) GCM_ClearSystem( GCM_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить систему ограничений. + \en Delete system of constraints. \~ + \details \ru Данный метод делает систему ограничений недействительной. Осуществляется + освобождение ОЗУ от внутренних структур данных, обслуживающих систему ограничений. + \en This method makes the constraint system invalid. Deallocation of RAM + from the internal data structures maintaining the system of constraints is performed. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \sa #GCM_ClearSystem +*/ +//--- +GCM_FUNC(void) GCM_RemoveSystem( GCM_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Читать систему ограничений из потока + \en Read constraint system from stream. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] in - \ru Поток для чтения. + \en Stream for reading. \~ +*/ +//--- +GCM_FUNC(bool) GCM_ReadSystem( GCM_system gSys, reader & in ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Запись системы ограничений в поток + \en Write constraint system to stream. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] out - \ru Поток для записи. + \en Stream for writing. \~ +*/ +//--- +GCM_FUNC(bool) GCM_WriteSystem( GCM_system gSys, writer & out ); + +//---------------------------------------------------------------------------------------- +/// Query to interrupt calculations +//--- +typedef bool ( *GCM_abort )(); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Назначить функцию прерывания вычислений + \en Set a callback to interrupt the calculations. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cbFunc - \ru Функция обратного вызова для прерывания операций. + \en A callback to interrupt the calculation. \~ +*/ +//--- +GCM_FUNC(void) GCM_SetCallback( GCM_system gSys, GCM_abort cbFunc ); + + +/* + Specifying geometry data structures (GCM_g_record) +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать запись пустого геометрического объекта. + \en Give the record of empty geometric object. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_NullGeom(); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать запись точки из типа MbCartPoint3D в типе GCM_g_record. + \en Get a record of point from the type MbCartPoint3D to the type GCM_g_record. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Point( const MbCartPoint3D & ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Запись прямой, заданной её точкой и направляющим вектором. + \en Record of line specified by the point and direction vector. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Line( const MbCartPoint3D & org + , const MbVector3D & axisZ ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Запись плоскости, заданной точкой и нормалью. + \en Record of plane specified by the point and normal vector. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Plane( const MbCartPoint3D & org, const MbVector3D & axisZ ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись конуса по заданному набору параметров. + \en Get data record of cone for the given set of parameters. \~ + \param[in] centre - \ru Центр окружности-основания конуса. + \en Center of base circle of the cone. \~ + \param[in] axis - \ru Направляющий вектор оси конуса. + \en Direction vector of the cone axis. \~ + \param[in] radiusA - \ru Радиус основания конуса. + \en Radius of the base circle. \~ + \param[in] radiusB - \ru Радиус сечения конуса ("малый" радиус). + \en Radius of section of circle ("minor" radius). \~ + \return \ru Запись конуса. + \en Record of cone. \~ + + \details \ru Предполагается, что параметры конуса описывают воображаемый усеченный конус, + высота которого всегда равна единице длины. При этом radiusA - это радиус + основания конуса, а radiusB - радиус его сечения. + \en It is assumed that the parameters describe the imaginary cone frustum, + whose height is always unit of length. In this radiusA - is the radius of + the base of the cone, and radiusB - the radius of its cross-section. +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Cone( const MbCartPoint3D & centre, const MbVector3D & axis + , double radiusA, double radiusB ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись цилиндра по заданному набору параметров. + \en Get data record of cylinder for the given set of parameters. \~ + \param[in] centre - \ru Центр окружности-основания цилиндра. + \en Center of base circle of the cylinder. \~ + \param[in] axis - \ru Направляющий вектор оси цилиндра. + \en Direction vector of the cylinder axis. \~ + \param[in] radius - \ru Радиус основания цилиндра. + \en Radius of the base circle. \~ + \return \ru Запись цилиндра. + \en Record of cylinder. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Cylinder( const MbCartPoint3D & centre, const MbVector3D & axis + , double radius ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись окружности, заданной набором параметров. + \en Get record of circle specified by the set of parameters. \~ + \param[in] centre - \ru Центр окружности. + \en Center of the circle. \~ + \param[in] axis - \ru Направляющий вектор оси окружности. + \en Direction vector of the circle axis. \~ + \param[in] radius - \ru Радиус окружности. + \en Radius of the circle. \~ + \return \ru Запись данных об окружности. + \en Data record of the circle. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Circle( const MbCartPoint3D & centre, const MbVector3D & axis, double radius ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись тороида по заданному набору параметров. + \en Get data record of torus for the given set of parameters. \~ + \param[in] centre - \ru Центр тора. + \en Center of torus. \~ + \param[in] axis - \ru Направляющий вектор оси вращения. + \en Direction vector of the rotation axis. \~ + \param[in] majorR - \ru "Большой" радиус тора - радиус окружности, описывающей вращение центра сечения. + \en "Major" radius is the radius of circle sweeping center of the rotating section. + \~ + \param[in] minorR - \ru Радиус окружности вращения ("малый" радиус). + \en Radius of section of circle ("minor" radius). \~ + + \details \ru Таким образом предполагается, что тор это воображаемая поверхность вращения, образованная + вращением окружности с радиусом minorR, лежащей в одной плоскости с осью вращения и центром, + расположенном на расстоянии majorR от оси тора. + \en Thus, it is assumed that the torus is an imaginary surface formed by + rotation of a circle of "minor radius" lying in the same plane as the axis + of rotation and the center located at a distance of majorR from the axis. +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Torus( const MbCartPoint3D & centre, const MbVector3D & axis + , double majorR, double minorR ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись данных о сфере, заданной центром и радиусом. + \en Get data record of sphere specified by center and radius. \~ + \param[in] centre - \ru Центр сферы. + \en Center of the sphere. \~ + \param[in] radius - \ru Радиус сферы. + \en Radius of the sphere. \~ + \return \ru Запись данных о сфере. + \en Data record of the sphere. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_Sphere( const MbCartPoint3D & centre, double radius ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись данных твердого тела, заданной началом координат и осями Z, X. + \en Get a data record of solid specified by its origin of coordinates, Z-axis and X-axis. \~ + \details + \ru Результат, который возвращает данная функция, используется для задания + в системе ограничений твердого тела (кластера) с помощью вызовов + GCM_AddGeom или #GCM_SubGeom. + \en The result, which returns this function, is used to specify a rigid body + (cluster) in the system by calling #GCM_AddGeom or #GCM_SubGeom. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_SolidLCS( const MbCartPoint3D & org + , const MbVector3D & axisZ = MbVector3D::zAxis + , const MbVector3D & axisX = MbVector3D::xAxis ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить запись данных системы координат твердого тела. + \en Get a data record of the solid coordinate system by its placement. \~ + \details + \ru Результат, который возвращает данная функция, используется для задания + в системе ограничений твердого тела (кластера) с помощью вызовов + GCM_AddGeom или GCM_SubGeom. + \en The result, which returns this function, is used to specify a rigid body + (cluster) in the system by calling #GCM_AddGeom or #GCM_SubGeom. \~ +*/ +//--- +GCM_FUNC(GCM_g_record) GCM_SolidLCS( const MbPlacement3D & ); + +/* + Defining geometry of constraint system +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений точку. + \en Add point to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] pVal - \ru Координаты точки. + \en Coordinates of a point. \~ + \return \ru Дескриптор зарегистрированной точки. + \en Descriptor of registered point. \~ +*/ +//--- +GCM_FUNC(GCM_geom) GCM_AddPoint( GCM_system gSys, const MbCartPoint3D & pVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений геометрический объект. + \en Add geometric object to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] gRec - \ru Запись геометрического объекта. + \en Record of geometric record. \~ + \return \ru Дескриптор зарегистрированного объекта. + \en Descriptor of registered object. \~ +*/ +//--- +GCM_FUNC(GCM_geom) GCM_AddGeom( GCM_system gSys, const GCM_g_record & gRec ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в систему ограничений геометрический объект. + \en Add geometric object to the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] gType - \ru Тип геометрического объекта. + \en Type of geometric object. \~ + \param[in] gMat - \ru Прямая матрица ЛСК объекта. + \en Direct matrix of geometric object. \~ + \param[in] radiusA - \ru Радиус окружности, цилиндра, сферы, а также "мажорный" радиус конуса и тора. + \en Radius of circle, cylinder, sphere, also "major" radius of cone and torus. \~ + \param[in] radiusB - \ru "Минорный" радиус конуса или тора. + \en "Minor" radius of cone and torus. \~ + \return \ru Дескриптор зарегистрированного объекта. + \en Descriptor of registered object. \~ +*/ +//-- +GCM_FUNC(GCM_geom) GCM_AddGeom( GCM_system gSys, GCM_g_type gType + , const MbMatrix3D & gMat + , double radiusA, double radiusB ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить в подсистему твердого тела (кластера) подчиненный геометрический объект. + \en Include a geometric sub-object to the subsystem of a solid (rigid cluster). \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] sol - \ru Твердое тело или кластер. + \en Solid or rigid cluster. \~ + \param[in] gRec - \ru Запись геометрического подчиненного объекта, заданного в ЛСК тела. + \en Record of geometric sub-object, which is given in LCS of the solid. \~ + \return \ru Дескриптор подчиненного объекта из подмножества тела. + \en Descriptor of sub-object in subset of the solid. \~ +*/ +//--- +GCM_FUNC(GCM_geom) GCM_SubGeom( GCM_system gSys, GCM_geom sol, const GCM_g_record & gRec ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать кластер (тело), в который включен данный геометрический объект. + \en Give a cluster (solid) in which a geometric object is included. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] subGeom -\ru Геометрический объект, принадлежащий кластеру. + \en A geometric object belonging to the cluster.. \~ + \return \ru Дескриптор кластера, которому принадлежит данный геометрический объект. + \en Descriptor of the cluster that owns this geometric object. \~ +*/ +//--- +GCM_FUNC(GCM_geom) GCM_Parent( GCM_system gSys, GCM_geom subGeom ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Тип геометрического объекта. + \en A type of geometric object. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \return \ru Геометрический тип объекта. + \en Geometric type of an object. \~ +*/ +//--- +GCM_FUNC(GCM_g_type) GCM_GeomType( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить геометрический объект из системы ограничений. + \en Delete a geometric object from the constraint system. \~ + \param gSys - \ru Система ограничений. + \en System of constraints. \~ + \param g - \ru Дескриптор геометрического объекта. + \en Descriptor of geometric object \~ + \details \ru После применения этой функции дескриптор объекта становится недействительным. + Надо заметить, что удаляемый геометрический объект может все еще участвовать в других + объектах и ограничениях. В этом случае удаляемый объект, хотя и считается удаленным, + фактически продолжает действовать до тех пор, пока другие объекты, связанные с ним, + не будут удалены. + \en After using this function the object descriptor 'g' will be invalidated. + It should be noted that the removed geometric object can still involved in other + objects and constraints. In this case, the object to be deleted, although it is considered + removed actually remains in effect until other objects connected with will be deleted. +*/ +//--- +GCE_FUNC(void) GCM_RemoveGeom( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вернет true, если объект все еще действительный. + \en Returns true if the object is still valid. \~ +*/ +//--- +//GCE_FUNC(bool) GCM_IsValid( GCM_system gSys, GCM_geom g ); + +/* + Defining a system of constraints +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать бинарное ограничение для пары геометрических объектов. + \en Set a binary constraint for two geometric objects. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g1 - \ru Дескриптор первого объекта. + \en Descriptors of first object. \~ + \param[in] g2 - \ru Дескриптор второго объекта. + \en Descriptors of second object. \~ + \param[in] aVal - \ru Опция выравнивания. + \en Alignment option. \~ + \param[in] tVar - \ru Вариант касания для ограничения c типом 'GCM_TANGENT'. + \en Variant of tangency for constraint of type 'GCM_TANGENT'. \~ + + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details + \ru Эта функция применяется для задания в системе бинарного ограничения любого + типа кроме размерных, а именно ограничения следующих типов: GCM_COINCIDENT, GCM_PARALLEL, + GCM_PERPENDICULAR, GCM_TANGENT, GCM_CONCENTRIC, GCM_IN_PLACE. В случае неудавшегося вызова, + функция вернет дескриптор пустого объекта GCM_NULL. + + \en The function is used to set a binary constraint of any type except + dimensional constraints, namely one of the following types: GCM_COINCIDENT, GCM_PARALLEL, + GCM_PERPENDICULAR, GCM_TANGENT, GCM_CONCENTRIC, GCM_IN_PLACE. In a case of failure, + the function returns a handle to an empty object GCM_NULL. \~ +*/ +//--- +GCM_FUNC(GCM_constraint) GCM_AddBinConstraint( GCM_system gSys, GCM_c_type cType + , GCM_geom g1, GCM_geom g2, GCM_alignment aVal = GCM_CLOSEST + , GCM_tan_choice tVar = GCM_TAN_POINT ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение, устанавливающее расстояние между парой геометрических объектов. + \en Set a constraint which specifies distance between a pair of geometric objects. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g1 - \ru Дескриптор первого объекта. + \en Descriptors of first object. \~ + \param[in] g2 - \ru Дескриптор второго объекта. + \en Descriptors of second object. \~ + \param[in] dVal - \ru Значение размера. + \en The value of dimension. \~ + \param[in] aVal - \ru Опция выравнивания. + \en Alignment option. \~ + \return \ru Дескриптор нового ограничения c типом GCM_DISTANCE. + \en Descriptor of the created constraint of type GCM_DISTANCE. \~ + + \details \ru Эта функция создает в системе размерное ограничение с типом GCM_DISTANCE, + которое задает линейный размер между двумя геометрическими объектами. + В случае неудачного вызова, функция вернет дескриптор пустого объекта GCM_NULL. + \en The function creates a dimensional constraint of type GCM_DISTANCE, which + specifies linear dimension between two geometric objects. + In a failed call, the function returns a handle to an empty object GCM_NULL.\~ + + \note \ru Значение dVal может быть знакопеременным для ориентируемых объектов. + \en Value of dVal can be positive as well as negative for oriented objects. \~ +*/ +//--- +GCM_FUNC(GCM_constraint) GCM_AddDistance( GCM_system gSys, GCM_geom g1, GCM_geom g2 + , double dVal, GCM_alignment aVal = GCM_CLOSEST ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение, устанавливающее угол между двумя геометрическими объектами. + \en Set a constraint which specifies angle between a pair of geometric objects. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g1 - \ru Дескриптор первого объекта. + \en Descriptors of first object. \~ + \param[in] g2 - \ru Дескриптор второго объекта. + \en Descriptors of second object. \~ + \param[in] axis - \ru Дескриптор объекта, задающего ось вращения угла. Может быть = GCM_NULL. + \en Descriptor of an object that specifying the rotation axis of angle. It can be GCM_NULL. \~ + \param[in] dVal - \ru Значение размера (радианы). + \en The value of dimension (radians). \~ + \return \ru Дескриптор нового ограничения c типом GCM_ANGLE. + \en Descriptor of the created constraint of type GCM_ANGLE. \~ + + \details \ru Эта функция создает в системе размерное ограничение с типом GCM_ANGLE, + которое задает угол между направлениями двух геометрических объектов. + Если ось вращения axis задана (т.е. != GCM_NULL), то угол имеет планарный + способ измерения (0 ... 2пи). В этом случае направления 'g1' и 'g2' обязаны + лежать в плоскости с нормалью заданной осью axis (оба направления перпендикулярны оси). + В случае неудавшегося вызова, функция вернет дескриптор пустого объекта GCM_NULL. + \en The function creates a dimensional constraint of type GCM_ANGLE, which + specifies angle between the directions of two geometric objects. + If the rotational axis is specified (i.e. != GCM_NULL), the angle has an + planar method of measurement (0 ... 2пи). In this case directions of + 'g1' and 'g2' must lie on a plane which has a normal specified by + the 'axis' parameter (both directions perpendicular to the axis ). + In a failed call, the function returns a handle to an empty object GCM_NULL. \~ +*/ +//--- +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 To create a constraint which specifies a radius of geometric objects. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g1 - \ru Дескриптор геометрического объекта, обладающего ненулевым радиусом. + \en Descriptor of the first object which has nonzero radius. \~ + \return \ru Дескриптор нового ограничения c типом GCM_RADIUS. + \en Descriptor of the created constraint which has a type GCM_RADIUS. \~ + + \details \ru Эта функция позволяет задать радиус геометрического объекта. Изменить величину + радиуса можно с помощью функции #GCM_ChangeDrivingDimension. Удаляется + радиальный размер вызовом функции #GCM_RemoveConstraint. + В случае неудачного вызова, функция вернет дескриптор пустого объекта GCM_NULL. + \en This function allows to specify a radius of the geometric object. To change + radius value use the function #GCM_ChangeDrivingDimension. To remove limitation + on radius of the geometric object use the function #GCM_RemoveConstraint. + In a case of failure, the function returns a handle to an empty object GCM_NULL. \~ +*/ +//--- +GCM_FUNC(GCM_constraint) GCM_FixRadius( GCM_system gSys, GCM_geom g1 ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать управляющий планарный угол между двумя геометрическими объектами. + \en Set a driving planar angle between a pair of geometric objects. \~ + \details \ru Функция аналогична вызову GCM_AddAngle, однако требует ось 'axis', + задающую плоскость откладывания угла. + \en This is the same call GCM_AddAngle, but requires an axis, which defines + a plane in which the angle is measured. \~ +*/ +//--- +GCM_FUNC(GCM_constraint) GCM_AddPlanarAngle( GCM_system gSys, GCM_geom g1, GCM_geom g2 + , GCM_geom axis, double dVal ); + +//---------------------------------------------------------------------------------------- +// Not yet documented +//--- +GCM_FUNC(GCM_constraint) GCM_AddSymmeric( GCM_system gSys, GCM_geom g1, GCM_geom g2 + , GCM_geom plane, GCM_alignment aVal = GCM_NO_ALIGNMENT ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать линейный паттерн. + \en Create a linear pattern constraint. \~ + \details \ru Ограничение "Линейный Паттерн" задаёт закон, согласно которому группа + геометрических объектов, добавленных в этот паттерн с помощью функции + #GCM_AddGeomToPattern, располагается на заданной прямой. Кроме направляющей + прямой, для создания Линейного Паттерна требуется задать геометрический объект, + называемый образцом. Этот объект определяет начало координат (нулевую точку) + направляющей прямой. Таким образом в системе координат направляющей прямой + Линейного Паттерна образец всегда остаётся неподвижным относительно любых + трансляций, поворотов и деформаций. Положение любого добавляемого в паттерн + объекта (копии) определяется его положением на прямой, направленной вдоль + заданной оси, началом координат которой является начало координат ЛСК образца. + \en The Linear Pattern constraint defines the law under which geometric objects + added to this pattern using #GCM_AddGeomToPattern function are located on the + given line (guide line). In addition to the guide line to create a Linear + Pattern constraint it's necessary to specify a geometric object called a + Sample. This object defines the starting point of the guide line of the Linear + Pattern. Thus, Sample always remains stationary relative to any translations, + rotations and deformations in the coordinate system of the Linear Pattern guide + line. The position of any object (called a Copy) to be added to the pattern is + determined by its position on the guide line with the origin coinciding with the + origin of the LCS of the Sample.\~ + \par \ru Порядок удаления + Чтобы удалить Линейный Паттерн целиком нужно воспользоваться функцией + #GCM_RemoveConstraint. При этом не требуется удалять ограничения, созданные при + добавлении новых элементов в паттерн с помощью функции #GCM_AddGeomToPattern: + они будут удалены автоматически. + \en Removal procedure + To remove the Linear Pattern completely It's necessary to use the + #GCM_RemoveConstraint function. There is no need to remove constraints that were + created by the addition of new Copies to the pattern using the function + #GCM_AddGeomToPattern. They will be deleted automatically. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g1 - \ru Дескриптор образца. + \en Descriptor of the sample. \~ + \param[in] g2 - \ru Дескриптор направляющей оси линейного паттерна. + \en Descriptor of the direction axis of the Linear Pattern. \~ + \param[in] align - \ru Опция выравнивания образца относительно направляющей оси. Если задана + опция GCM_ALIGN_WITH_AXIAL_GEOM, то образец g1 будет лежать на направлеющей + прямой(оси) линейного паттерна. + \en Option of alignment of a sample g1 relative to the direction axis. If the + option #GCM_ALIGN_WITH_AXIAL_GEOM is given the sample g1 will be coincident + with the direction line(axis). \~ + \return \ru Дескриптор нового ограничения c типом GCM_LINEAR_PATTERN. + \en Descriptor of the created constraint which has a type GCM_LINEAR_PATTERN. \~ +*/ +// --- +GCM_FUNC(GCM_pattern) GCM_AddLinearPattern( GCM_system gSys, GCM_geom g1, GCM_geom g2, GCM_alignment align=GCM_NO_ALIGNMENT ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать угловой паттерн. + \en Create an angular pattern constraint. \~ + \details \ru Ограничение "Угловой Паттерн" задаёт закон, согласно которому группа + геометрических объектов, добавленных в этот паттерн с помощью функции + #GCM_AddGeomToPattern, располагается на некоторой окружности. Окружность эта + лежит в плоскости перпендикулярной заданной оси, а центр окружности лежит на + этой оси. Кроме оси вращения для создания Углового Паттерна требуется задать + геометрический объект, называемый образцом. Этот объект определяет нулевой угол + и начальный радиус окружности. Таким образом положение любого добавляемого в + паттерн объекта (копии) определяется вращением вокруг заданной оси, начиная от + образца. При этом радиус окружности (расстояние от копии или образца до оси) не + не является константой и может варьироваться (изменяться) в ходе решения. + \en The Angular Pattern constraint defines the law under which geometric objects + added to this pattern using #GCM_AddGeomToPattern function are located on the + given circle. This circle lies in a plane that is perpendicular to the given + axis, and the center of this circle lies on this axis. In addition to the axis + to create an Angular Pattern constraint it's necessary to specify a geometric + object called a Sample. This object defines the zero angle and the initial + radius of the circle for the Angular Pattern. The position of any object (called + a Copy) to be added to the pattern is determined by the rotation around the + given axis, starting from the Sample. The radius of the circle (the distance + from the Copy or the Sample to the axis) is not constant and can vary in the + process of solving the system of equations. \~ + + \par \ru Порядок удаления + Чтобы удалить Угловой Паттерн целиком нужно воспользоваться функцией + #GCM_RemoveConstraint. При этом не требуется удалять ограничения, созданные при + добавлении новых элементов в паттерн с помощью #GCM_AddGeomToPattern: они будут + удалены автоматически. + \en Removal procedure + To remove the Angular Pattern completely It's necessary to use the + #GCM_RemoveConstraint function. There is no need to remove constraints that were + created by the addition of new Copies to the pattern using the function + #GCM_AddGeomToPattern. They will be deleted automatically. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] smp - \ru Дескриптор образца. + \en Descriptor of the sample. \~ + \param[in] axial - \ru Дескриптор оси вращения углового паттерна. + \en Descriptor of the rotation axis of the Angular Pattern. \~ + \param[in] align - \ru Опция выравнивания образца относительно направляющей оси. Если задана + опция GCM_ALIGN_WITH_AXIAL_GEOM, то образец 'smp' будет лежать в плоскости + XY направляющего обекта (оси вращения), и если направляющий объект имеет + радиус (например, это окружность), то расстояние от объектов Углового + Паттерна до оси вращения будет равно радиусу направляющего объекта + (например, радиусу окружности). + \en Option of alignment of a sample relative to the direction axis. + If the GCM_ALIGN_WITH_AXIAL_GEOM option is specified sample g1 will lie in + the XY plane of the direction axis object (rotation axis) and if the + direction axis object has a radius (for example, this is a circle) the + distance from the Angle Pattern objects to the rotation axis will be equal + to the radius of the direction axis object (for example, radius of a circle). \~ + \return \ru Дескриптор нового ограничения c типом GCM_ANGULAR_PATTERN. + \en Descriptor of the created constraint which has a type GCM_ANGULAR_PATTERN. \~ +*/ +// --- +GCM_FUNC(GCM_pattern) GCM_AddAngularPattern( GCM_system gSys, GCM_geom smp, GCM_geom axial, GCM_alignment align=GCM_NO_ALIGNMENT ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Добавить геометрический объект в паттерн. + \en Add geometric object to the pattern. \~ + \details \ru Объект, добавляемый в паттерн, назовём копией. + Если копия добавляется в Линейный Паттерн, то требуется указать расстояние от + копии до образца. Оно может быть положительным или отрицательным и определяется + требуемым положением копии относительно образца с учётом направляющей оси. Так + же можно опционально задать выравнивание ЛСК копии относительно ЛСК образца. + Если копия добавляется в Угловой Паттерн, то требуется указать угол поворота + копии относительно образца, вокруг оси вращения паттерна. Так же можно + опционально задать выравнивание копии относительно образца. Возможны 2 типа + выравнивания: GCM_ALIGNED - выравнивание ЛСК копии и образца и GCM_ROTATED - + выравнивание ЛСК копии с ЛСК образца, повёрнутого вокруг оси вращения на тот же + угол, что и копия. + Расстояние (или угол поворота) от образца до копии по умолчанию фиксировано, + но может быть варьируемым при задании соответствующей опции #GCM_scale. + \en Let's call a Copy the object that is added to the pattern. + If the Copy is added to the Linear Pattern it's necessary to specify the + distance from the Copy to the Sample. It can be positive or negative and is + determined by the required position of the Copy relative to the Sample taking + into account the guide axis. It's optionally possible to specify alignment of + the Copy LCS relative to the Sample LCS. + If the Copy is added to the Angular Pattern it's necessary to specify the + angle of rotation of the Copy relative to the Sample around the pattern rotation + axis. It's optionally possible to specify alignment of the Copy relative to the + Sample. There are 2 types of alignment: GCM_ALIGNED - alignment of the local + coordinate systems of the Copy and the Sample, GCM_ROTATED - the alignment of + the local coordinate system of the Copy with the local coordinate system of the + Sample that is rotated around the axis of rotation at the same angle as the Copy. + The distance (or angle of rotation) from the sample to the copy is fixed by default, + but can be varied by specifying the appropriate #GCM_scale option.\~ + + \par \ru Порядок удаления. + Чтобы удалить копию из паттерна используйте функцию #GCM_RemoveConstraint. Если + же вам надо удалить паттерн целиком, то вам не требуется удалять каждую копию из + паттерна, просто удалите паттерн. + \en Removal procedure + To remove a Copy from the pattern use the function #GCM_RemoveConstraint. If + it's necessary to remove the pattern completely there is no need to remove each + copy from the pattern. Just remove the pattern constraint. \~ + + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] ptrn - \ru Дескриптор паттерна, в который добавляем копию. + \en Descriptor of the pattern. \~ + \param[in] geom - \ru Дескриптор добавляемого геометрического объекта (копии). + \en Descriptor of the copy. \~ + \param[in] position - \ru Переменная, задающая положение добавляемой копии в паттерне (расстояние или угол). + \en Variable that specifies the position of the copy in the pattern (distance or angle). \~ + \param[in] align - \ru Опция, задающая выравнивание копии по отношению к образцу. + \en Option that specifies the alignment of copy relative to the sample. \~ + \param[in] scale - \ru Тип масштабирования элемента паттерна. + \en Scaling type of pattern element. \~ + \return \ru Дескриптор нового ограничения c типом GCM_PATTERNED. + \en Descriptor of the created constraint which has a type GCM_PATTERNED. \~ +*/ +// --- +GCM_FUNC(GCM_constraint) GCM_AddGeomToPattern( GCM_system gSys, GCM_pattern ptrn, GCM_geom geom, double position, + GCM_alignment align = GCM_NO_ALIGNMENT, GCM_scale scale = GCM_RIGID ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать ограничение. + \en Set a constraint. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cRec - \ru Унифицированная запись ограничения. + \en Uniform record of a constraint. \~ + \return \ru Дескриптор нового ограничения. + \en Descriptor of a new constraint. \~ + \details + \ru Эта функция применяется только для автоматического тестирования решателя, + поэтому подробно не документировалась. + \en This function is used only for the automated testing of the solver therefore not documented. +*/ +//--- +GCM_FUNC(GCM_constraint) GCM_AddConstraint( GCM_system gSys, const GCM_c_record & cRec ); + +//---------------------------------------------------------------------------------------- +// Not yet documented +//--- +GCM_FUNC(GCM_geom) GCM_SetDependent( GCM_system gSys, GCM_constraint con, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Удалить ограничение из системы. + \en Delete a constraint from the system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] con - \ru Дескриптор ограничения. + \en Descriptor of constraint. \~ +*/ +//--- +GCE_FUNC(void) GCM_RemoveConstraint( GCM_system gSys, GCM_constraint con ); + + +/* + Fixation and freeing of a geometry +*/ + +//---------------------------------------------------------------------------------------- +// Create fixing constraint of the geom +//--- +GCM_FUNC(GCM_constraint) GCM_FixGeom_( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Сделать геометрический объект неподвижным. + \en Set a geometric object fixed. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Дескриптор геометрического объекта. + \en Descriptors of geometric object. \~ + + \details + \ru Эта функция делает объект неподвижным лишая его всех степеней свобод. Если геометрический + объект является суб-объектом тела (кластера), то объект замораживается только в рамках кластера, + однако в глобальной системе координат объект имеет такую же свободу как и кластер, + которому он принадлежит. + \en Thе function makes the object fixed depriving it of all degrees of freedom. If the geometric object + is a sub geom of a solid (cluster), the object is frozen only in the framework of the cluster, + but in the global coordinate system the object has the same freedom as the cluster + to which it belongs. + \~ + \note \ru На будущее планируется, что данная функция будет возвращать дескриптор ограничения. + \en In the future this function will be returning a descriptor of constraint, i.e. will create a fixing constraint. \~ + \sa GCM_FreeGeom +*/ +//--- +GCM_FUNC(bool) GCM_FreezeGeom( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Освободить объект, зафиксированный методом GCM_FreezeGeom. + \en Set free geometric object fixed by GCM_FreezeGeom call. \~ + \sa GCM_FreezeGeom +*/ +//--- +GCM_FUNC(void) GCM_FreeGeom( GCM_system gSys, GCM_geom g ); + +/* + Evaluating methods +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вычислить систему ограничений. + \en Calculate the constraint system. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \return \ru Код результата вычислений. + \en Calculation result code. \~ + \details \ru Функция решает задачу ограничений. Задача ограничений формулируется + функциями API геометрического решателя; функции вида GCM_Add_XXXXXXX добавляют новые + объекты, функции вида GCM_Change_XXXXXXX, GCM_Set_XXXXXXX изменяют состояние объектов. + Таким образом, что бы все такие изменения вступили в силу, нужно вызвать + метод #GCM_Evaluate.\n + Алгоритмы GCM_Evaluate учитывают удовлетворенность систем ограничений; если + все ограничения уже решены, то функция не тратит время на вычисления, а + состояние геометрических объектов остается неизменным. + \en The function solves problem of constraints. The problem of constraint is + formulated by API functions of geometric solver; the functions of a kind GCM_Add_XXXXXXX + add a new object, the functions of kinds GCM_Change_XXXXXXX and GCM_Set_XXXXXXX change + a state of objects. Thus, for all changes to take effect it is necessary to call the + method #GCM_Evaluate.\n + The algorithms GCM_Evaluate take into account whether constraint systems are satisfied, + if all constraints have been already solved, then the function does not spend time + for calculations, and the state of geometric objects remains unchanged. \~ +*/ +//--- +GCM_FUNC(GCM_result) GCM_Evaluate( GCM_system gSys ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Получить код результата вычисления ограничения. + \en Get result code of the evaluation of constraint. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cItem - \ru Дескриптор ограничения, принадлежащего системе gSys. + \en Descriptor of constraint belonging to the system gSys. \~ + \note \ru Если система еще не вычислялась, то функция вернет код GCM_RESULT_None. + \en If the system has not yet been evaluated then the function will return + the code GCM_RESULT_None. \~ + \return \ru Диагностический код хранящийся в системе после последней вызова GCM_Evaluate. + \en Diagnostic code stored in the system after the last call GCM_Evaluate. \~ +*/ +//--- +GCM_FUNC(GCM_result) GCM_EvaluationResult( GCM_system gSys, GCM_constraint cItem ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выполнить проверку удовлетворенности ограничения. + \en Perform a check that a constraint is satisfied. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] cItem - \ru Дескриптор ограничения. + \en Descriptor of constraint. \~ + \return \ru true, если ограничение удовлетворено. + \en true if a constraint is satisfied. \~ +*/ +//--- +GCM_FUNC(bool) GCM_IsSatisfied( GCM_system gSys, GCM_constraint cItem ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать текущее положение (решение) геометрического объекта. + \en Get current placement (solution) of the geometric object. +*/ +//--- +GCM_FUNC(MbPlacement3D) GCM_Placement( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выдать начало СК геометрического объекта. + \en Get an LCS origin of the geometric object. + \details \ru Функция вернет координаты начала ЛСК объекта. Данный вызов может быть + использован для любых типов геометрии. Например, для окружности данный вызов вернет ее + центр, для плоскости - точку, лежащую на плоскости, для цилиндра - центр основания + цилиндра и т.д. + \en The function returns coordinates of the origin of the LCS. The call can be applied + to any type of geometry. For example, for a circle the call will return its center, + for a plane - it is a point laying on the plane, + for a cylinder - it is a center of its foundation circle and so on. + +*/ +//--- +GCM_FUNC(MbCartPoint3D) GCM_Origin( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Текущее значение радиуса геометрического объекта. + \en Current radius value of the geometric object. +*/ +//--- +GCM_FUNC(double) GCM_Radius( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Текущее значение "большого" радиуса тора или конуса. + \en Current "major" radius value of torus or cone. +*/ +//--- +GCM_FUNC(double) GCM_RadiusA( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Текущее значение "малого" радиуса тора или конуса. + \en Current "minor" radius value of torus or cone. +*/ +//--- +GCM_FUNC(double) GCM_RadiusB( GCM_system gSys, GCM_geom g ); + +/* + Changing methods +*/ + +//---------------------------------------------------------------------------------------- +/** \brief \ru Изменить значение управляющего размера. + \en Change the value of driving dimension. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] dItem - \ru Дескриптор размерного ограничения. + \en Descriptor of dimensional constraint. \~ + \param[in] dVal - \ru Требуемое значение размера. + \en Required value of constraint. \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \details \ru Функция применяется только для управляющих размеров. Если управляющий размер + является угловым, то параметр dVal задается в радианах.\n + Следует учитывать, что настоящая функция не осуществляет вычислений, а только подготавливает + изменение размера. Что бы изменения вступили в силу, необходимо вызвать функцию #GCE_Evaluate. + \en The function is used only for driving dimensions. If the driving dimension + is angular, then the parameter dVal is specified in radians. \n + It should be noted that the function doesn't perform computations but only prepares + the changing of dimension. For the changes to take effect it is required to call + the function #GCM_Evaluate. \~ +*/ +//--- +GCM_FUNC(GCM_result) GCM_ChangeDrivingDimension( GCM_system gSys, GCM_constraint dItem, double dVal ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Задать текущее положение геометрического объекта. + \en Set current placement of the geometric object. + \note \ru Эта функция только придает объекту новое состояние без переоценки системы + ограничений. Вызов GCM_Evaluate может поменять заданное состояние, если + имеются не удовлетворенные ограничения. + \en The function only impart new state of the object without the revaluation + of constraints. Call GCM_Evaluate can change the given state to satisfy + constraints of this object. \~ +*/ +//--- +GCM_FUNC(void) GCM_SetPlacement( GCM_system gSys, GCM_geom g, const MbPlacement3D & place ); + + +/* + Dragging functions +*/ + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Инициализировать режим перетаскивания объектов в плоскости экрана. + \en Initialize mode of object moving in the screen plane. + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] movGeom - \ru Компонент, деталь, которой манипулируют. + \en Component, part which is manipulated. \~ + \param[in] projPlane - \ru Плоскость экрана, заданная в ГСК сборки. + \en Plane of the screen given in the WCS of assembly. \~ + \param[in] curPnt - \ru Точка, принадлежащая компоненту, которая проецируется на плоскость + экрана в положение курсора, и за которую осуществляется 'перетаскивание'. + curPnt задана в ЛСК геом.объекта movGeom. + \en Point of the component which is projected onto plane of the screen to + cursor position and is 'dragging'. curPnt given in the LCS of + the geometric object movGeom; \~ + \return \ru Код результата. \en Result code. \~ + + \details + \ru Функция запускается однократно перед входом в режим перетаскивания компонент, который управляется + (по движению мыши) через команду #GCM_SolveReposition(GCM_system, const MbCartPoint3D &). Режим + прекращается вызовом любой иной команды, кроме #GCM_PrepareReposition. Также есть специальная + функция для выхода из режима "перетаскивания" - #GCM_FinishReposition, для явного сбрасывания + режима перемещения. + \en The function runs once to start the dragging mode of components, which is controlled + (by movement of the mouse) by the command #GCM_SolveReposition(GCM_system, const MbCartPoint3D &). + Mode is stopped by the calling any other command except #GCM_PrepareReposition. There is also + the special function to exit from the dragging mode explicitly - #GCM_FinishReposition. \~ +*/ +//--- +GCM_FUNC(GCM_result) GCM_PrepareReposition( GCM_system gSys, GCM_geom movGeom, + const MbPlacement3D & projPlane, const MbCartPoint3D & curPnt ); + +/** \brief \ru Инициализировать режим вращения компонента вокруг фиксированной оси. + \en To initialize the rotation mode of the component around a fixed axis. +*/ +GCM_FUNC(GCM_result) GCM_PrepareReposition( GCM_system gSys, GCM_geom rotGeom, const MbCartPoint3D & org, const MbVector3D & axis ); + +/// \ru Завершить режим "перетаскивания". \en Finish the dragging mode. +GCM_FUNC(void) GCM_FinishReposition( GCM_system gSys ); + +/** \brief \ru Выдать объект манипуляции, с которым работает решатель, находясь в режиме вращения/перемещения объектом (драггинг). + \en Get manipulation object with which the Solver works when being in the dragging mode (rotating or moving). +*/ +GCM_FUNC(GCM_geom) GCM_GetMovingGeom( GCM_system gSys ); + +/** + \brief \ru Решить систему для произвольного изменения положения одного тела. + \en Solve the system for an arbitrary change of position of one solid. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] g - \ru Тело, положение которого меняется. + \en Solid, the position of which is changed. \~ + \param[in] newPos - \ru Новое пололожение тела. + \en New position of a solid. \~ + \param[in] movType - \ru Код желаемого поведения + \en Code of the desired behavior \~ + \return \ru Код результата. \en Result code. \~ + + \note \ru Эта функция не позволяет вывести систему сопряжений из состояния решаемости, + кроме случаев, когда до вызова функции система уже находилась в нерешенном + состоянии. Если новое положение 'newPos' не позволяет удовлетворять системе сопряжений, + то новое положение тела окажется наиболее близким к newPos (при сохранении решаемости). + \en This function doesn't allow to take out constraint system from decided state, + except when before call of function the system was already unsolved. If new position + 'newPos' doesn't allow to satisfy the system of constraints, then new position of solid + will be the most nearest to newPos (while preserving solvability). \~ +*/ +GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, GCM_geom g, + const MbPlacement3D & newPos, GCM_reposition movType ); + +/** + \brief \ru Решить систему сопряжений для новой позиции курсора в режиме драггинга. + \en Solve the system of constraints for new position of cursor in the dragging mode. + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] curPos - \ru Текущее положение курсора в ГСК. + \en Current position of a cursor in the WCS. \~ + \return \ru Код результата. \en Result code. \~ + + \details \ru Процедура, управляющая режимом перетаскивания, который прекращается вызовом любой иной команды. + \en Procedure that controls dragging mode which are stopped after calling any other command. \~ +*/ +GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, const MbCartPoint3D & curPos ); + +/** + \brief \ru Решить систему в режиме драггинга с одно-параметрическим управлением. + \en Solve the system under one-parametric driving in the dragging mode. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] alpha - \ru Управляющий параметр (зачастую задается в радианах). + \en Driving parameter (this is ussualy an angle given in radians). \~ + \return \ru Код результата. \en Result code. \~ + + \details \ru Это функция, управляющая режимом динамического перепозиционирования + (см. #GCM_PrepareReposition), в котором положение тела управляется изменением одной + координаты, например, угла вращения вокруг оси. Режим прекращается вызовом + #GCM_FinishReposition или любой иной командой, меняющей состояние решетеля, например, + #GCM_AddConstraint. + \en This function controls dynamic reposition mode (see #GCM_PrepareReposition), + in which the position of the solid is driven by changing one coordinate. For example + the angle of rotation around an axis. Mode is stopped by calling #GCM_FinishReposition + or any other command, which is changes state of the Solver, for example #GCM_AddConstraint. + \~ +*/ +GCM_FUNC(GCM_result) GCM_SolveReposition( GCM_system gSys, double alpha ); + +/* + Journaling functions +*/ + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Включить журналирование и назначить файл для записи журнала вызовов API. + \en Switch on the journaling and specify the file for recording a journal of GCE API calls. \~ + \param[in] gSys - \ru Система ограничений. + \en System of constraints. \~ + \param[in] fName - \ru Имя файла назначения с полным путем. + \en Name of destination file with a full path. \~ + \return true, if journaling has been successfully switched on. + + \attention + \ru Файл журнала будет записан только после завершения сеанса работы с системой + ограничений, а именно сразу после вызова GCM_RemoveSystem. + \en The journal file will be written only when a session of work with the + constraint system is finished, i.e. immediately after calling the + GCM_RemoveSystem method. + \ru Добавление записей в журнал из параллельного кода не происходит. + \en Adding records to the journal from parallel code does not occur. +*/ +//--- +GCE_FUNC(bool) GCM_SetJournal( GCM_system gSys, const char * fName ); + + +/** \} */ // GCM_3D_API + +struct GCT_diagnostic_pars; +//---------------------------------------------------------------------------------------- +/* + It's used for testing purposes only. +*/ +//--- +GCM_FUNC(const GCT_diagnostic_pars &) GCM_DiagnosticPars( GCM_system gSys ); + +//---------------------------------------------------------------------------------------- +// Use GCM_FreezeGeom instead this (2019). +//--- +GCM_FUNC(void) GCM_FixGeom( GCM_system gSys, GCM_geom g ); + +//---------------------------------------------------------------------------------------- +// Deprecated +//--- +GCM_FUNC(bool) GCM_IsFixed( GCM_system gSys, GCM_geom g ); + + +#endif // __GCM_API_H + +// eof diff --git a/C3d/Include/gcm_constraint.h b/C3d/Include/gcm_constraint.h index 703cdd7..e679e97 100644 --- a/C3d/Include/gcm_constraint.h +++ b/C3d/Include/gcm_constraint.h @@ -30,7 +30,7 @@ struct GCM_geom_axis ItGeomPtr geomPtr; ///< \ru Тело, которому принадлежит ось планарного угла. \en solid the axis of a planar angle belongs to. GCM_geom_axis() : axis( MbVector3D::zero ) - , geomPtr( NULL ) {} + , geomPtr( c3d_null ) {} }; //---------------------------------------------------------------------------------------- @@ -131,7 +131,7 @@ public: /* \en Callback function which defines a law of positioning of the first geometric object which is dependent on positions of other objects. */ - virtual GCM_dependent_func Function() const { return NULL; } + virtual GCM_dependent_func Function() const { return c3d_null; } virtual GCM_extra_param ExtraParam() const { return GCM_extra_param(); } public: /* @@ -309,7 +309,7 @@ inline void ItConstraintItem::GetParams( GCM_c_params & pars ) const //--- inline ItGeomPtr ItConstraintItem::DependentGeom() const { - return (ConstraintType() == GCM_DEPENDENT) ? GeomItem(1) : NULL; + return (ConstraintType() == GCM_DEPENDENT) ? GeomItem(1) : c3d_null; } //---------------------------------------------------------------------------------------- @@ -320,18 +320,18 @@ inline ItGeomPtr ItConstraintItem::DependentGeom() const //--- struct ItMateTransmission { - enum Motion ///< \ru Тип движения \en Type of motion + enum Motion ///< \ru Тип движения. \en Type of motion. { - NoDefined, ///< \ru Не задано \en Not specified - Translation, ///< \ru Линейное перемещение \en Linear increment - Rotation, ///< \ru Вращение \en Rotation + NoDefined, ///< \ru Не задано. \en Not specified. + Translation, ///< \ru Линейное перемещение. \en Linear increment. + Rotation, ///< \ru Вращение. \en Rotation. }; /// \ru Выдать первое или второе тело (nb -номер тела 1,2); \en Get the first or the second solid (ng is the number of solid 1,2); virtual ItGeomPtr GetGeom( short nb ) const = 0; /// \ru Выдать первое или второе тело, задающее направление вращения/перемещения (nb - номер тела 1,2); \en Get the first or the second solid specifying the direction of rotation/translation (nb is the number of solid 1,2); virtual ItGeomPtr GetDirectionGeom( short nb ) const = 0; - /// \ru Выдать направление и тип движения для первого или второго тела, axis задается в ЛСК тела GetDirectionGeom(); \en Get direction and type of motion for the first or the second solid, axis is specified in LCS of solid GetDirectionGeom(); + /// \ru Выдать направление и тип движения для первого или второго тела, axis задается в ЛСК тела GetDirectionGeom(). \en Get direction and type of motion for the first or the second solid, axis is specified in LCS of solid GetDirectionGeom(). virtual Motion GetAxis( short nb, MbAxis3D & axis ) const = 0; /// \ru Выдать соотношение N1:N2; \en Get ratio N1:N2; virtual double GetRatio() const = 0; @@ -474,7 +474,7 @@ GCM_FUNC(void) PrevSolution( GCM_alignment & ); //--- inline ItGeomPtr ItConstraintItem::_GArg( int geomN ) const { - return size_t(geomN-1) < m_args.size() ? m_args[geomN-1] : ItGeomPtr( NULL ); + return size_t(geomN-1) < m_args.size() ? m_args[geomN-1] : ItGeomPtr( c3d_null ); } //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/gcm_geom.h b/C3d/Include/gcm_geom.h index 646c62b..7c70d77 100644 --- a/C3d/Include/gcm_geom.h +++ b/C3d/Include/gcm_geom.h @@ -130,12 +130,12 @@ class MtParGeom; class GCM_CLASS MtGeomVariant { public: - MtGeomVariant() : m_value( NULL ) {} + MtGeomVariant() : m_value( c3d_null ) {} MtGeomVariant( const MbCartPoint3D & ); MtGeomVariant( const MtGeomVariant & ); - MtGeomVariant( const MtParGeom & g ) : m_value( NULL ) { Assign(g); } + MtGeomVariant( const MtParGeom & g ) : m_value( c3d_null ) { Assign(g); } MtGeomVariant( const GCM_g_type ); - MtGeomVariant( MtParGeom & g ) : m_value( NULL ) { Share(g); } + MtGeomVariant( MtParGeom & g ) : m_value( c3d_null ) { Share(g); } MtGeomVariant & operator = ( const MtGeomVariant & gVar ) { return Assign( gVar ); } ~MtGeomVariant(); @@ -230,9 +230,9 @@ private: public: MtMatingGeometry() - : myGeom( NULL ) + : myGeom( c3d_null ) , myOrientation( Unoriented ) - , myLCSMatrix( NULL ) + , myLCSMatrix( c3d_null ) {} ~MtMatingGeometry() { @@ -244,7 +244,7 @@ public: MtGeomType GetGeomType() const { return myGeomType; } /// \ru Выдать ориентацию; \en Get orientation; Orient GetOrientation() const { return myOrientation; } - /// \ru Выдать геометрический объект сопряжения. Если =NULL, то это точка, заданная MtMatingGeometry::myMatingPoint; \en Get geometric object of the mating. If =NULL, then this is a point specified by MtMatingGeometry::myMatingPoint; + /// \ru Выдать геометрический объект сопряжения. Если =c3d_null, то это точка, заданная MtMatingGeometry::myMatingPoint; \en Get geometric object of the mating. If =c3d_null, then this is a point specified by MtMatingGeometry::myMatingPoint; const MbSpaceItem * GetMatingGeom() const { return myGeom; } /// \ru Выдать матрицу ЛСК, в которой задан геометрический объект сопряжения \en Get matrix of LCS in which the geometric object of the mating is specified const MbMatrix3D & LCSMatrix() const; @@ -314,7 +314,7 @@ private: // \ru Реализовать при необходимости \en Imp //--- inline const MbMatrix3D & MtMatingGeometry::LCSMatrix() const { - if ( myLCSMatrix != NULL ) + if ( myLCSMatrix != c3d_null ) return *myLCSMatrix; return MbMatrix3D::identity; } @@ -371,7 +371,7 @@ inline void MtMatingGeometry::SetAsMarker( const MbCartPoint3D & org, const MbVe inline void MtMatingGeometry::SetAsLCS( const MbPlacement3D & lcs ) { myGeomType = GCM_LCS; - myGeom = NULL; // new MbMarker( MbCartPoint::origin, MbVector3D::zAxis, MbVector3D::xAxis ); + myGeom = c3d_null; // new MbMarker( MbCartPoint::origin, MbVector3D::zAxis, MbVector3D::xAxis ); myOrientation = Unoriented; _SetLCSMatrix( lcs.GetMatrixFrom() ); } @@ -397,11 +397,11 @@ inline void MtMatingGeometry::SetAsMatingGeomItem( SPtr gIte //--- inline void MtMatingGeometry::_ClearMatrix() { - if ( myLCSMatrix != NULL ) + if ( myLCSMatrix != c3d_null ) { delete myLCSMatrix; } - myLCSMatrix = NULL; + myLCSMatrix = c3d_null; } //---------------------------------------------------------------------------------------- @@ -415,7 +415,7 @@ inline void MtMatingGeometry::_SetLCSMatrix( const MbMatrix3D & gSpan ) } else { - if ( myLCSMatrix == NULL ) + if ( myLCSMatrix == c3d_null ) myLCSMatrix = new MbMatrix3D( gSpan ); else *myLCSMatrix = gSpan; @@ -428,7 +428,7 @@ inline void MtMatingGeometry::_SetLCSMatrix( const MbMatrix3D & gSpan ) inline void MtMatingGeometry::SetNull() { myGeomType = GCM_NULL_GTYPE; - myGeom = NULL; + myGeom = c3d_null; myOrientation = Unoriented; _ClearMatrix(); } diff --git a/C3d/Include/gcm_mates_generator.h b/C3d/Include/gcm_mates_generator.h index 5a0edee..654e690 100644 --- a/C3d/Include/gcm_mates_generator.h +++ b/C3d/Include/gcm_mates_generator.h @@ -1,310 +1,310 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Тестовый генератор 3D-сопряжений - \en Test generator of 3D-mates \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCM_MATES_GENERATOR_H -#define __GCM_MATES_GENERATOR_H - -#include -#include -#include -#include -#include -#include - -#include - -class MtGeomSolver; - -//---------------------------------------------------------------------------------------- -// Параметры сопряжений. -// --- -struct TMParameters -{ - typedef GCM_alignment AlignCondition; - - GCM_c_type matetype; // Constraint type. - GCM_alignment align; // Alignment condition. - double realpar; // Dimension value. - - TMParameters( AlignCondition al, MtMateType mtype, double par = 0. ) - : align ( al ) - , matetype( mtype ) - , realpar ( par ) - {} - TMParameters( GCM_c_type mtype, double par = 0.0, GCM_alignment al = GCM_NO_ALIGNMENT ) - : align ( al ) - , matetype( mtype ) - , realpar ( par ) - {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Размеры кирпича. \en Box sizes. -// --- -struct TMBoxSize -{ -public: - double length; ///< \ru Длина (вдоль OX). \en Length (along OX). - double width; ///< \ru Ширина (вдоль OY). \en Width (along OY). - double height; ///< \ru Высота (вдоль OZ). \en Height (along OZ). - double radius; ///< \ru Радиус отверстия посередине. Если < MIN_RADIUS, значит сплошной кирпич без отверстий. \en Radius of hole in the middle. If < MIN_RADIUS therefore a solid box without holes. - -public: - TMBoxSize() - : length( 30. ) - , width ( 60. ) - , height( 90. ) - , radius( 20. ) - {} - - TMBoxSize( double l, double w, double h, double r ) - : length( l ) - , width ( w ) - , height( h ) - , radius( r ) - {} -}; - -//---------------------------------------------------------------------------------------- -// \ru Элементарный кирпич для наложения сопряжений. \en Elementary box for the overlay of mates. -// --- -class MATH_CLASS TMBox : public ItGeom - , public MtRefItem -{ -public: - enum MateMarker ///< \ru маркер для наложения сопряжения. \en marker for overlay of mate. - { - front, - back, - left, - right, - up, - down, - axis, - distance - }; - -private: - MbPlacement3D place; // \ru ЛСК кирпича. \en LCS of box. - TMBoxSize size; // \ru Размер кирпича. \en Box size. - c3d::mt_string name; // \ru Имя. \en Name. - -public: - TMBox( const MbPlacement3D & p, const TMBoxSize & sz, const c3d::mt_char * n = _T("B") ); // \ru Конструктор. \en Constructor. - -public: - /// \ru Задать новую ЛСК. \en Set the new LCS. - void SetPlacement( const MbPlacement3D & p ) { place.Init( p ); } - void SetName( const c3d::mt_char * n ) { name = n; } // \ru Задать имя. \en Set the name. - double Length() const { return size.length; } // \ru Выдать длину. \en Get the length. - double Width() const { return size.width; } // \ru Выдать ширину. \en Get the width. - double Height() const { return size.height; } // \ru Выдать высоту. \en Get the height. - double Radius() const { return size.radius; } // \ru Выдать радиус. \en Get the radius. - bool IsHoled() const { return size.radius > c3d::MIN_RADIUS - GcPrecision::lengthRegion; } // \ru С цилиндром ли кирпич. \en Whether there is a hole. - MbVector3D CylinderAxis() const { return place.GetAxisX(); } // \ru выдать ось цилиндра. \en Get the cylinder axis. - -public: // Реализация ItGeom - - /// \ru Выдать положение объекта ItGeom; \en Get position of ItGeom object; - virtual void GetPlacement( MbPlacement3D & p ) const { p.Init(place); } - /// \ru Выдать null-terminated строку имени геометрического объекта \en Get null-terminated name string of geometric object - virtual const c3d::mt_char * GetName() const { return name.c_str(); } - virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } - virtual refcount_t Release() const { return MtRefItem::Release(); } - -private: - TMBox(); - TMBox( const TMBox & ); - TMBox & operator = ( const TMBox & ); -}; - - -//---------------------------------------------------------------------------------------- -// \ru Наложение сопряжения на 2 кирпича. \en Overlaying mate onto two boxes. -// --- -class MATH_CLASS MtBoxConstraint : public MtRefItem - , public ItConstraintItem -{ - SPtr box1; // \ru Кирпич 1. \en Box 1. - SPtr box2; // \ru Кирпич 2. \en Box 2. - TMBox::MateMarker side1; // \ru Маркер сопряжения 1. \en Marker of mate 1. - TMBox::MateMarker side2; // \ru Маркер сопряжения 2. \en Marker of mate 2. - GCM_alignment aligncond; // \ru Условие выравнивания. \en Condition of alignment. - MtMateType matetype; // \ru Тип сопряжения. \en The mate type. - double realpar; // \ru Расстояние. \en Distance. - MtResultCode3D rescode; // \ru Коды ошибки сопряжения. \en Error code of mate. - -public: - MtBoxConstraint( TMBox & b1, TMBox::MateMarker s1, TMBox & b2, TMBox::MateMarker s2, TMParameters ); - -public: // \ru Запросы (const-методы) \en Requests (const-methods) - virtual GCM_alignment AlignType() const { return aligncond; } // \ru Выдать параметр условия выравнивания \en Get the parameter of alignment condition - virtual GCM_angle_type AngleType() const { return GCM_NONE_ANGLE; } // \ru Выдать тип угла (3D или планарный) \en Get the angle type (3D or planar) - virtual GCM_geom_axis AxisOfPlanarAngle() const { return GCM_geom_axis(); } // \ru Выдать ось для планарного углового сопряжения, заданную в ЛСК некоторого тела \en Get the axis for planar angular mate. Axis is given in the LCS of some solid - virtual MbVector3D AxisOf3DAngleType() const { return MbVector3D::zero; } // \ru Взять ось для планарного углового сопряжения \en Get the axis for planar angular mate - virtual MtMateType ConstraintType() const { return matetype; } // \ru Выдать тип сопряжения \en Get the mate type - virtual ItGeomPtr GeomItem( int nb ) const { return (nb==1)? box1.get(): box2.get(); } // \ru Выдать первый сопрягаемый объект \en Get the first mating object - virtual double DimParameter() const { return realpar; } // \ru Выдать вещественный параметр \en Get the real parameter - virtual GCM_tan_choice TangencyChoice() const { return GCM_TAN_NONE; } // \ru Выдать вариант касания \en Get the tangency choice - /// \ru Диагностический код ошибки, прикрепленный к данному ограничению. \en Diagnostic error code attached to this constraint. - virtual MtResultCode3D ErrorCode() const { return rescode; } - virtual VERSION Version() const { return GetCurrentMathFileVersion(); } // \ru Выдать версию сопряжения, которая совпадает с версией потока \en Get the mate version which same as the stream version - -public: - void SetDistance( double dist ) { realpar = dist; } - -public: // \ru Методы для обратной связи (задающие) \en Callback methods - /// \ru Задать код ошибки для неудовлетворенного сопряжения \en Set the error code for unsatisfied mate - virtual void SetErrorCode( MtResultCode3D res ) { rescode = res; } - /// \ru Задать ось для углового сопряжения с трехмерным типом измерения; \en Set axis for angular mate with three-dimensional type of dimension; - virtual void SetAxisOf3DAngleType( const MbVector3D & /*axis*/ ) { /*planarang.axis = axis;*/ } - -public: // \ru Методы для Smart-указателей \en The methods for Smart-pointers - virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } - virtual refcount_t Release() const { return MtRefItem::Release(); } - -private: - virtual MtGeomVariant _LinkageItem( int geomNb ) const; - -private: - MtBoxConstraint(); - MtBoxConstraint( const MtBoxConstraint & ); - MtBoxConstraint & operator = ( const MtBoxConstraint & ); -}; - -//---------------------------------------------------------------------------------------- -// \ru Земля. \en Ground. -// --- -class MATH_CLASS TMGround : public ItGeom - , public MtRefItem -{ -private: - MbPlacement3D place; - -public: - explicit TMGround( const MbPlacement3D & p ); - -public: - /// \ru Выдать null-terminated строку имени геометрического объекта \en Get null-terminated name string of geometric object - virtual const TCHAR * GetName() const; - virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } - virtual refcount_t Release() const { return MtRefItem::Release(); } - -private: - /// \ru Выдать положение объекта ItGeom; \en Get position of ItGeom object; - virtual void GetPlacement( MbPlacement3D & p ) const { p.Init(place); } - -private: - TMGround(); - TMGround( const TMGround & ); - TMGround & operator = ( const TMGround & ); -}; - -//---------------------------------------------------------------------------------------- -// \ru Управление положением в сборке. \en Position control in the assembly. -// --- -struct MATH_CLASS TMBoxPositioner : public MtRefItem - , public ItPositionManager -{ -private: - TMGround & ground; - -public: - explicit TMBoxPositioner( TMGround & ); - TMBoxPositioner( const TMBoxPositioner & ); - -public: - /// \ru Установить новое положение объекта \en Set new position of the object - virtual void Reposition( ItGeom & geom, const MbPlacement3D & pos ); - /// \ru Выдать геометрический объект-земля, со степенью свободы = 0 (жёстко привязанный к ГСК); \en Get geometric object- ground with the degree of freedom = 0 (hard bound to GCS); - virtual ItGeom & GetGround() const { return ground; } - /// \ru Выдать характер связи для пары сопрягаемых тел (направленность соединения) \en Get the link character for pair of mating solids (direct connection) - virtual GCM_dependency GetJointStatus( const ItGeom &, const ItGeom & ) const { return GCM_NO_DEPENDENCY; } - virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } - virtual refcount_t Release() const { return MtRefItem::Release(); } - -private: - TMBoxPositioner(); - TMBoxPositioner & operator = ( const TMBoxPositioner & ); -}; - -typedef std::vector > MtBoxVector; -typedef std::vector MtBlocksVector; - -//---------------------------------------------------------------------------------------- -/// \ru Генератор сборок. \en Assembly generator. -// --- -class MATH_CLASS AssemblyGenerator -{ -public: - enum TMMateType ///< \ru Тип связи между блоками в сборке. \en Type of connection between the bricks in the assembly. - { - tmt_Rigid1Brick = 1, - tmt_Rigid3Bricks, - tmt_Rigid2Axis, - tmt_NonRigid2Axis, - tmt_NonRigidAxisDist, - tmt_NonRigidAxis - }; - - enum TMBrickMateType ///< \ru Тип связи между кирпичами. \en Type of connection between the boxes. - { - tbmt_1Mate = 1, ///< \ru Совпадение протипоположных плоскостей. \en Coincidence of opposite planes. - tbmt_2Mate = 2, ///< \ru Совпадение протипоположных плоскостей + 1-ой пары сонаправленных. \en Coincidence of opposite planes + 1-pair of codirected. - tbmt_3Mate = 3, ///< \ru Совпадение протипоположных плоскостей + 2-ух пар сонаправленных (жесткая связь). \en Coincidence of opposite planes + 2-pairs of codirected (hard link). - tbmt_Rigid = tbmt_3Mate ///< \ru Жесткая связь. \en Rigid link. - }; - -public: - std::list > dimConstrs; - -private: - MtGeomSolver & manager; ///< \ru Решатель сборки. \en Solver of the assembly. - -public: - AssemblyGenerator( MtGeomSolver & m ) : manager( m ), dimConstrs() {} - -private: - AssemblyGenerator(); - AssemblyGenerator( const AssemblyGenerator & ); - AssemblyGenerator & operator = ( const AssemblyGenerator & ); - -public: - /// \ru Сгенерировать линию из кирпичей. \en Generate a line from boxes. - size_t GenerateLine( MtBoxVector & line, size_t n, TMBrickMateType mttype = tbmt_Rigid ); - /// \ru Сгенерировать стенку из кирпичей. \en Generate a wall from boxes. - size_t GenerateWall( MtBoxVector & wall, size_t n, TMBrickMateType mttype = tbmt_Rigid ); - /// \ru Сгенерировать куб из кирпичей. \en Generate a cube from boxes. - size_t GenerateCube( MtBoxVector & cube, size_t n, TMBrickMateType mttype = tbmt_Rigid ); - /// \ru Сгенерировать фрактал. \en Generate fractal. - size_t GenerateFractal( MtBlocksVector & fractal, size_t n, TMMateType mttype = tmt_Rigid3Bricks, TMBrickMateType bmttype = tbmt_3Mate ); - /// \ru Сгенерировать нежестко сопряженную сборку с распределенными степенями свободы. \en Generate a non-rigid mating assembly with distributed degrees of freedom. - size_t NonRigidDistributedDoF( MtBlocksVector & assembly, size_t nBlocks - , TMMateType mttype = tmt_NonRigidAxis, TMBrickMateType bmttype = tbmt_3Mate ); - /// \ru Сгенерировать жестко сопряженную сборку с распределенными степенями свободы. \en Generate a rigid mating assembly with distributed degrees of freedom. - size_t RigidDistributedDoF( MtBlocksVector & assembly, size_t nRings, size_t nBlocksInRing - , TMMateType matetype = tmt_Rigid2Axis, TMBrickMateType bmttype = tbmt_3Mate, double dist = 0. ); - - /// \ru Передвинуть кирпичи. \en Shift boxes. - void ShiftBoxes( MtBoxVector & boxes, const MbVector3D & shift, bool comulative, bool shiftfirst = false ); - /// \ru Передвинуть блоки. \en Shift blocks. - void ShiftBoxes( MtBlocksVector & boxes, const MbVector3D & shift, bool comulative, bool shiftfirst = false ); - /// \ru Повернуть кирпичи. \en Rotate boxes. - void RotateBoxes( MtBoxVector & boxes, const MbVector3D & angles, bool comulative ); - /// \ru Повернуть блоки. \en Rotate blocks. - void RotateBoxes( MtBlocksVector & boxes, const MbVector3D & angles, bool comulative ); - -private: - /// \ru Сгенерировать N кирпичей. \en Generate N boxes. - void GenerateNBoxes( MtBoxVector & boxes, size_t n, const TMBoxSize & size ) const; - void SetBoxesNames( const MtBoxVector & boxes ); // \ru Задать имена кирпичей. \en Set names for boxes. - size_t CreateBlock( MtBoxVector & block, TMBrickMateType bmttype, bool solve = true ); // \ru Создать блок. \en Create a block. - void GetFractal( size_t & mtCnt, MtBlocksVector & boxes, size_t nBlocks, TMMateType mttype, TMBrickMateType bmttype, size_t ind = 0 ); // \ru Создать фрактал. \en Create a fractal. -}; - -#endif // __GCM_MATES_GENERATOR_H +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Тестовый генератор 3D-сопряжений + \en Test generator of 3D-mates \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCM_MATES_GENERATOR_H +#define __GCM_MATES_GENERATOR_H + +#include +#include +#include +#include +#include +#include + +#include + +class MtGeomSolver; + +//---------------------------------------------------------------------------------------- +// Параметры сопряжений. +// --- +struct TMParameters +{ + typedef GCM_alignment AlignCondition; + + GCM_c_type matetype; // Constraint type. + GCM_alignment align; // Alignment condition. + double realpar; // Dimension value. + + TMParameters( AlignCondition al, MtMateType mtype, double par = 0. ) + : align ( al ) + , matetype( mtype ) + , realpar ( par ) + {} + TMParameters( GCM_c_type mtype, double par = 0.0, GCM_alignment al = GCM_NO_ALIGNMENT ) + : align ( al ) + , matetype( mtype ) + , realpar ( par ) + {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Размеры кирпича. \en Box sizes. +// --- +struct TMBoxSize +{ +public: + double length; ///< \ru Длина (вдоль OX). \en Length (along OX). + double width; ///< \ru Ширина (вдоль OY). \en Width (along OY). + double height; ///< \ru Высота (вдоль OZ). \en Height (along OZ). + double radius; ///< \ru Радиус отверстия посередине. Если < MIN_RADIUS, значит сплошной кирпич без отверстий. \en Radius of hole in the middle. If < MIN_RADIUS therefore a solid box without holes. + +public: + TMBoxSize() + : length( 30. ) + , width ( 60. ) + , height( 90. ) + , radius( 20. ) + {} + + TMBoxSize( double l, double w, double h, double r ) + : length( l ) + , width ( w ) + , height( h ) + , radius( r ) + {} +}; + +//---------------------------------------------------------------------------------------- +// \ru Элементарный кирпич для наложения сопряжений. \en Elementary box for the overlay of mates. +// --- +class MATH_CLASS TMBox : public ItGeom + , public MtRefItem +{ +public: + enum MateMarker ///< \ru маркер для наложения сопряжения. \en marker for overlay of mate. + { + front, + back, + left, + right, + up, + down, + axis, + distance + }; + +private: + MbPlacement3D place; // \ru ЛСК кирпича. \en LCS of box. + TMBoxSize size; // \ru Размер кирпича. \en Box size. + c3d::mt_string name; // \ru Имя. \en Name. + +public: + TMBox( const MbPlacement3D & p, const TMBoxSize & sz, const c3d::mt_char * n = _T("B") ); // \ru Конструктор. \en Constructor. + +public: + /// \ru Задать новую ЛСК. \en Set the new LCS. + void SetPlacement( const MbPlacement3D & p ) { place.Init( p ); } + void SetName( const c3d::mt_char * n ) { name = n; } // \ru Задать имя. \en Set the name. + double Length() const { return size.length; } // \ru Выдать длину. \en Get the length. + double Width() const { return size.width; } // \ru Выдать ширину. \en Get the width. + double Height() const { return size.height; } // \ru Выдать высоту. \en Get the height. + double Radius() const { return size.radius; } // \ru Выдать радиус. \en Get the radius. + bool IsHoled() const { return size.radius > c3d::MIN_RADIUS - GcPrecision::lengthRegion; } // \ru С цилиндром ли кирпич. \en Whether there is a hole. + MbVector3D CylinderAxis() const { return place.GetAxisX(); } // \ru выдать ось цилиндра. \en Get the cylinder axis. + +public: // Реализация ItGeom + + /// \ru Выдать положение объекта ItGeom; \en Get position of ItGeom object; + virtual void GetPlacement( MbPlacement3D & p ) const { p.Init(place); } + /// \ru Выдать null-terminated строку имени геометрического объекта \en Get null-terminated name string of geometric object + virtual const c3d::mt_char * GetName() const { return name.c_str(); } + virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } + virtual refcount_t Release() const { return MtRefItem::Release(); } + +private: + TMBox(); + TMBox( const TMBox & ); + TMBox & operator = ( const TMBox & ); +}; + + +//---------------------------------------------------------------------------------------- +// \ru Наложение сопряжения на 2 кирпича. \en Overlaying mate onto two boxes. +// --- +class MATH_CLASS MtBoxConstraint : public MtRefItem + , public ItConstraintItem +{ + SPtr box1; // \ru Кирпич 1. \en Box 1. + SPtr box2; // \ru Кирпич 2. \en Box 2. + TMBox::MateMarker side1; // \ru Маркер сопряжения 1. \en Marker of mate 1. + TMBox::MateMarker side2; // \ru Маркер сопряжения 2. \en Marker of mate 2. + GCM_alignment aligncond; // \ru Условие выравнивания. \en Condition of alignment. + MtMateType matetype; // \ru Тип сопряжения. \en The mate type. + double realpar; // \ru Расстояние. \en Distance. + MtResultCode3D rescode; // \ru Коды ошибки сопряжения. \en Error code of mate. + +public: + MtBoxConstraint( TMBox & b1, TMBox::MateMarker s1, TMBox & b2, TMBox::MateMarker s2, TMParameters ); + +public: // \ru Запросы (const-методы) \en Requests (const-methods) + virtual GCM_alignment AlignType() const { return aligncond; } // \ru Выдать параметр условия выравнивания \en Get the parameter of alignment condition + virtual GCM_angle_type AngleType() const { return GCM_NONE_ANGLE; } // \ru Выдать тип угла (3D или планарный) \en Get the angle type (3D or planar) + virtual GCM_geom_axis AxisOfPlanarAngle() const { return GCM_geom_axis(); } // \ru Выдать ось для планарного углового сопряжения, заданную в ЛСК некоторого тела \en Get the axis for planar angular mate. Axis is given in the LCS of some solid + virtual MbVector3D AxisOf3DAngleType() const { return MbVector3D::zero; } // \ru Взять ось для планарного углового сопряжения \en Get the axis for planar angular mate + virtual MtMateType ConstraintType() const { return matetype; } // \ru Выдать тип сопряжения \en Get the mate type + virtual ItGeomPtr GeomItem( int nb ) const { return (nb==1)? box1.get(): box2.get(); } // \ru Выдать первый сопрягаемый объект \en Get the first mating object + virtual double DimParameter() const { return realpar; } // \ru Выдать вещественный параметр \en Get the real parameter + virtual GCM_tan_choice TangencyChoice() const { return GCM_TAN_NONE; } // \ru Выдать вариант касания \en Get the tangency choice + /// \ru Диагностический код ошибки, прикрепленный к данному ограничению. \en Diagnostic error code attached to this constraint. + virtual MtResultCode3D ErrorCode() const { return rescode; } + virtual VERSION Version() const { return GetCurrentMathFileVersion(); } // \ru Выдать версию сопряжения, которая совпадает с версией потока \en Get the mate version which same as the stream version + +public: + void SetDistance( double dist ) { realpar = dist; } + +public: // \ru Методы для обратной связи (задающие) \en Callback methods + /// \ru Задать код ошибки для неудовлетворенного сопряжения \en Set the error code for unsatisfied mate + virtual void SetErrorCode( MtResultCode3D res ) { rescode = res; } + /// \ru Задать ось для углового сопряжения с трехмерным типом измерения; \en Set axis for angular mate with three-dimensional type of dimension; + virtual void SetAxisOf3DAngleType( const MbVector3D & /*axis*/ ) { /*planarang.axis = axis;*/ } + +public: // \ru Методы для Smart-указателей \en The methods for Smart-pointers + virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } + virtual refcount_t Release() const { return MtRefItem::Release(); } + +private: + virtual MtGeomVariant _LinkageItem( int geomNb ) const; + +private: + MtBoxConstraint(); + MtBoxConstraint( const MtBoxConstraint & ); + MtBoxConstraint & operator = ( const MtBoxConstraint & ); +}; + +//---------------------------------------------------------------------------------------- +// \ru Земля. \en Ground. +// --- +class MATH_CLASS TMGround : public ItGeom + , public MtRefItem +{ +private: + MbPlacement3D place; + +public: + explicit TMGround( const MbPlacement3D & p ); + +public: + /// \ru Выдать null-terminated строку имени геометрического объекта \en Get null-terminated name string of geometric object + virtual const TCHAR * GetName() const; + virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } + virtual refcount_t Release() const { return MtRefItem::Release(); } + +private: + /// \ru Выдать положение объекта ItGeom; \en Get position of ItGeom object; + virtual void GetPlacement( MbPlacement3D & p ) const { p.Init(place); } + +private: + TMGround(); + TMGround( const TMGround & ); + TMGround & operator = ( const TMGround & ); +}; + +//---------------------------------------------------------------------------------------- +// \ru Управление положением в сборке. \en Position control in the assembly. +// --- +struct MATH_CLASS TMBoxPositioner : public MtRefItem + , public ItPositionManager +{ +private: + TMGround & ground; + +public: + explicit TMBoxPositioner( TMGround & ); + TMBoxPositioner( const TMBoxPositioner & ); + +public: + /// \ru Установить новое положение объекта \en Set new position of the object + virtual void Reposition( ItGeom & geom, const MbPlacement3D & pos ); + /// \ru Выдать геометрический объект-земля, со степенью свободы = 0 (жёстко привязанный к ГСК); \en Get geometric object- ground with the degree of freedom = 0 (hard bound to GCS); + virtual ItGeom & GetGround() const { return ground; } + /// \ru Выдать характер связи для пары сопрягаемых тел (направленность соединения) \en Get the link character for pair of mating solids (direct connection) + virtual GCM_dependency GetJointStatus( const ItGeom &, const ItGeom & ) const { return GCM_NO_DEPENDENCY; } + virtual refcount_t AddRef() const { return MtRefItem::AddRef(); } + virtual refcount_t Release() const { return MtRefItem::Release(); } + +private: + TMBoxPositioner(); + TMBoxPositioner & operator = ( const TMBoxPositioner & ); +}; + +typedef std::vector > MtBoxVector; +typedef std::vector MtBlocksVector; + +//---------------------------------------------------------------------------------------- +/// \ru Генератор сборок. \en Assembly generator. +// --- +class MATH_CLASS AssemblyGenerator +{ +public: + enum TMMateType ///< \ru Тип связи между блоками в сборке. \en Type of connection between the bricks in the assembly. + { + tmt_Rigid1Brick = 1, + tmt_Rigid3Bricks, + tmt_Rigid2Axis, + tmt_NonRigid2Axis, + tmt_NonRigidAxisDist, + tmt_NonRigidAxis + }; + + enum TMBrickMateType ///< \ru Тип связи между кирпичами. \en Type of connection between the boxes. + { + tbmt_1Mate = 1, ///< \ru Совпадение протипоположных плоскостей. \en Coincidence of opposite planes. + tbmt_2Mate = 2, ///< \ru Совпадение протипоположных плоскостей + 1-ой пары сонаправленных. \en Coincidence of opposite planes + 1-pair of codirected. + tbmt_3Mate = 3, ///< \ru Совпадение протипоположных плоскостей + 2-ух пар сонаправленных (жесткая связь). \en Coincidence of opposite planes + 2-pairs of codirected (hard link). + tbmt_Rigid = tbmt_3Mate ///< \ru Жесткая связь. \en Rigid link. + }; + +public: + std::list > dimConstrs; + +private: + MtGeomSolver & manager; ///< \ru Решатель сборки. \en Solver of the assembly. + +public: + AssemblyGenerator( MtGeomSolver & m ) : manager( m ), dimConstrs() {} + +private: + AssemblyGenerator(); + AssemblyGenerator( const AssemblyGenerator & ); + AssemblyGenerator & operator = ( const AssemblyGenerator & ); + +public: + /// \ru Сгенерировать линию из кирпичей. \en Generate a line from boxes. + size_t GenerateLine( MtBoxVector & line, size_t n, TMBrickMateType mttype = tbmt_Rigid ); + /// \ru Сгенерировать стенку из кирпичей. \en Generate a wall from boxes. + size_t GenerateWall( MtBoxVector & wall, size_t n, TMBrickMateType mttype = tbmt_Rigid ); + /// \ru Сгенерировать куб из кирпичей. \en Generate a cube from boxes. + size_t GenerateCube( MtBoxVector & cube, size_t n, TMBrickMateType mttype = tbmt_Rigid ); + /// \ru Сгенерировать фрактал. \en Generate fractal. + size_t GenerateFractal( MtBlocksVector & fractal, size_t n, TMMateType mttype = tmt_Rigid3Bricks, TMBrickMateType bmttype = tbmt_3Mate ); + /// \ru Сгенерировать нежестко сопряженную сборку с распределенными степенями свободы. \en Generate a non-rigid mating assembly with distributed degrees of freedom. + size_t NonRigidDistributedDoF( MtBlocksVector & assembly, size_t nBlocks + , TMMateType mttype = tmt_NonRigidAxis, TMBrickMateType bmttype = tbmt_3Mate ); + /// \ru Сгенерировать жестко сопряженную сборку с распределенными степенями свободы. \en Generate a rigid mating assembly with distributed degrees of freedom. + size_t RigidDistributedDoF( MtBlocksVector & assembly, size_t nRings, size_t nBlocksInRing + , TMMateType matetype = tmt_Rigid2Axis, TMBrickMateType bmttype = tbmt_3Mate, double dist = 0. ); + + /// \ru Передвинуть кирпичи. \en Shift boxes. + void ShiftBoxes( MtBoxVector & boxes, const MbVector3D & shift, bool comulative, bool shiftfirst = false ); + /// \ru Передвинуть блоки. \en Shift blocks. + void ShiftBoxes( MtBlocksVector & boxes, const MbVector3D & shift, bool comulative, bool shiftfirst = false ); + /// \ru Повернуть кирпичи. \en Rotate boxes. + void RotateBoxes( MtBoxVector & boxes, const MbVector3D & angles, bool comulative ); + /// \ru Повернуть блоки. \en Rotate blocks. + void RotateBoxes( MtBlocksVector & boxes, const MbVector3D & angles, bool comulative ); + +private: + /// \ru Сгенерировать N кирпичей. \en Generate N boxes. + void GenerateNBoxes( MtBoxVector & boxes, size_t n, const TMBoxSize & size ) const; + void SetBoxesNames( const MtBoxVector & boxes ); // \ru Задать имена кирпичей. \en Set names for boxes. + size_t CreateBlock( MtBoxVector & block, TMBrickMateType bmttype, bool solve = true ); // \ru Создать блок. \en Create a block. + void GetFractal( size_t & mtCnt, MtBlocksVector & boxes, size_t nBlocks, TMMateType mttype, TMBrickMateType bmttype, size_t ind = 0 ); // \ru Создать фрактал. \en Create a fractal. +}; + +#endif // __GCM_MATES_GENERATOR_H diff --git a/C3d/Include/gcm_res_code.h b/C3d/Include/gcm_res_code.h index 71eb7e4..7942185 100644 --- a/C3d/Include/gcm_res_code.h +++ b/C3d/Include/gcm_res_code.h @@ -1,156 +1,157 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Коды ошибок геометрического решателя для 3D - \en Error codes of geometric solver for 3D \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCM_RES_CODE_H -#define __GCM_RES_CODE_H - -#include - -//---------------------------------------------------------------------------------------- -// \ru Приоритетность кода ошибки \en Priority of the error code. -/* - \ru Функция выдает критерий, т.е. целое число, которое позволяет выбрать какую из - двух ошибок, обнаруженных решателем в отношении одного и того же сопряжения, - лучше показать пользователю. Ошибка с более высоким приоритетом поглощает ошибку - с более низким приоритетом. - \en Function gives a criterion, i.e. an integer which allows to choose which of - the two errors detected by solver with respect to the same mate - better to show to the user. Error with the highest priority error absorbs error - with lower priority. \~ - \param \ru resCode Код ошибки - \en resCode Error code \~ - \return \ru Целочисленная величина приоритетности кода ошибки для пользователя - \en The integer value of the priority of the error code to the user \~ -*/ -//--- -inline int PriorityLevel( GCM_result resCode ) -{ - switch ( resCode ) - { - case GCM_RESULT_Ok: return 0; // \ru Хороший результат - самый низкий приоритет потому, что всегда поглащается любым плохим результатом \en Good result - the lowest priority because it always is absorbed by any bad result - case GCM_RESULT_None: return 1; // \ru Нет результат - тоже низкий приоритет, поскольку мало информативен; \en None result - too low a priority as not enough informative; - case GCM_RESULT_Error: return 2; // \ru Неустановленная ошибка, малоинформативная ошибка. Unknown error, uninformative error. - - case GCM_RESULT_Duplicated: return 3; // \ru Эта ошибка не делает систему не решаемой, поэтому покажем её только если нет других проблем, связанных с нерешаемостью; \en This error does not make the unsolved system therefore it will be shown only if there are no other problems with unsolvable; - case GCM_RESULT_Not_Satisfied: return 4; // \ru Приоритет меньше, чем GCM_RESULT_Unsolvable, поскольку меньше информативность; //-V112 \en Priority is less than GCM_RESULT_Unsolvable because less informativeness; //-V112 - case GCM_RESULT_Unsolvable: return 5; // \ru Приоритет должен быть выше, чем у mtResCode_Not_Satisfied - дает больше информации пользователю; \en Priority must be higher than mtResCode_Not_Satisfied - gives more information to the user; - case GCM_RESULT_InconsistentAlignment: return 6; // \ru Приоритет должен быть меньше, чем у GCM_RESULT_Overconstrained, потому, что правильность диагностики гарантируется только при осутствии сообщения mtResCode_OverConstraint; \en Priority must be less than mtResCode_OverConstraint because the correct diagnosis can be guaranteed if there is not message GCM_RESULT_Overconstrained; - case GCM_RESULT_Overconstrained: return 7; // \ru Приоритет выше, чем у GCM_RESULT_Unsolvable, поскольку точнее выявлена причина не решаемости; \en Priority higher than that of GCM_RESULT_Unsolvable because unsolvable reason have been found; - - /* - \ru Более высокий приоритет у группы ошибок, связанных с некорректными - зависимостями для черных ящиков - такие ошибки нужно устранять в - первую очередь. - \en Higher priority for the group errors associated with incorrect - dependencies for black boxes - first of all such errors must - be eliminated. - */ - - case GCM_RESULT_MultiDependedGeom: // \ru Задана входящая зависимость для выходного объекта черного ящика; \en Given an incoming dependence of the output object of a black box; - case GCM_RESULT_OverconstrainingDependedGeoms: // \ru Задана зависимость между экземплярами массива (выходными); \en Given dependence between copies of the pattern (output); - case GCM_RESULT_DependedGeomCantBeFixed: // The depended geom can't be fixed. - return 8; - - case GCM_RESULT_CyclicDependence: // \ru Задана циклическая зависимость \en Given a cyclic dependence - return 9; - - /* - Группа ошибок, связанная с некорректно заданным сопряжением. - Group of errors related to incorrectly specified constraint. - */ - case GCM_RESULT_InappropriateArgument: - case GCM_RESULT_InappropriateAlignment: // - case GCM_RESULT_InvalidArguments: // \ru В ограничении не заданы аргументы (пустые аргументы). \en Constraint has invalid or undefined (void) arguments. - case GCM_RESULT_IncompatibleArguments: - case mtResCode_UnsupportedTangencyChoice: // \ru Для сопряжения касание - опция выбора по окружности или по образующей не поддреживается \en For mate the option of tangency choice by circle or generating curve is unsupported - case mtResCode_IsNoPossibleForCircTanChoice: // \ru Для данной пары поверхностей касание по окружности геометрически не возможно \en For a given pair of surfaces the touching along the circle is geometrically impossible - case GCM_RESULT_InconsistentPlanarAngle: // \ru Не соблюдаются условия планарного угла (векторы от пары тел должны быть перпендикулярны оси) \en Planar angle conditions are not met (vectors from a pair of solids should be perpendicular to the axis) - case mtResCode_InconsistentFollowerAxis: - case mtResCode_CoaxialMtGearTransmissionIsNotAvalable: - return 10; - - /* - The group of system error codes. Priority overlapping all other errors. - */ - case GCM_RESULT_InternalError: - case GCM_RESULT_Aborted: - case GCM_RESULT_ItsNotDrivingDimension: - case GCM_RESULT_Unregistered: - return 99; - - /* - \ru Все остальные геометрические ошибки (Самый информативный для пользователя вариант); - \en All other geometric errors (the most informative variant for the user); - */ - - default: return 90; - } -} - -/** - \addtogroup GCM_3D_Routines - \{ -*/ - -//---------------------------------------------------------------------------------------- -// -// --- -inline bool OK( GCM_result res ) -{ - return res == mtResCode_Ok; -} - -//---------------------------------------------------------------------------------------- -// -// --- -inline GCM_result ResCode( bool ok ) -{ - return ok ? mtResCode_Ok : mtResCode_None; -} - -//---------------------------------------------------------------------------------------- -/** \brief \ru Выбрать "худший" результат. - \en Select "the worst" result code. \~ - \details \ru Функция выбирает из двух сообщений об ошибке, то которое нуждается во - внимании пользователя прежде другого. - \en The function selects from two error messages, something that needs - attention before another error. -*/ -//--- -inline GCM_result WorseResult( GCM_result res1, GCM_result res2 ) -{ - return PriorityLevel( res1 ) > PriorityLevel( res2 ) ? res1 : res2; -} - -//---------------------------------------------------------------------------------------- -/** \brief \ru Суммировать результирующий код. \en Summarize the resulting code. - \details \ru Оператор выбирает из потока ошибок, то которое нуждается во - внимании пользователя прежде других. - \en The operator selects from stream of error messages, something that needs - attention before anything else. - -*/ -//--- -inline GCM_result & operator << ( GCM_result & sumRes, const GCM_result r ) -{ - if ( r == GCM_RESULT_None ) - { - return sumRes; - } - if ( PriorityLevel(r) > PriorityLevel(sumRes) || (sumRes==GCM_RESULT_None) ) - { - sumRes = r; - } - return sumRes; -} - -/** \} */ // GCM_3D_Routines - -#endif // __GCM_RES_CODE_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Коды ошибок геометрического решателя для 3D + \en Error codes of geometric solver for 3D \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCM_RES_CODE_H +#define __GCM_RES_CODE_H + +#include + +//---------------------------------------------------------------------------------------- +// \ru Приоритетность кода ошибки \en Priority of the error code. +/* + \ru Функция выдает критерий, т.е. целое число, которое позволяет выбрать какую из + двух ошибок, обнаруженных решателем в отношении одного и того же сопряжения, + лучше показать пользователю. Ошибка с более высоким приоритетом поглощает ошибку + с более низким приоритетом. + \en Function gives a criterion, i.e. an integer which allows to choose which of + the two errors detected by solver with respect to the same mate + better to show to the user. Error with the highest priority error absorbs error + with lower priority. \~ + \param \ru resCode Код ошибки + \en resCode Error code \~ + \return \ru Целочисленная величина приоритетности кода ошибки для пользователя + \en The integer value of the priority of the error code to the user \~ +*/ +//--- +inline int PriorityLevel( GCM_result resCode ) +{ + switch ( resCode ) + { + case GCM_RESULT_Ok: return 0; // \ru Хороший результат - самый низкий приоритет потому, что всегда поглащается любым плохим результатом \en Good result - the lowest priority because it always is absorbed by any bad result + case GCM_RESULT_None: return 1; // \ru Нет результат - тоже низкий приоритет, поскольку мало информативен; \en None result - too low a priority as not enough informative; + case GCM_RESULT_Error: return 2; // \ru Неустановленная ошибка, малоинформативная ошибка. Unknown error, uninformative error. + + case GCM_RESULT_Duplicated: return 3; // \ru Эта ошибка не делает систему не решаемой, поэтому покажем её только если нет других проблем, связанных с нерешаемостью; \en This error does not make the unsolved system therefore it will be shown only if there are no other problems with unsolvable; + case GCM_RESULT_Not_Satisfied: return 4; // \ru Приоритет меньше, чем GCM_RESULT_Unsolvable, поскольку меньше информативность; //-V112 \en Priority is less than GCM_RESULT_Unsolvable because less informativeness; + case GCM_RESULT_Unsolvable: return 5; // \ru Приоритет должен быть выше, чем у GCM_RESULT_Not_Satisfied - дает больше информации пользователю; \en Priority must be higher than GCM_RESULT_Not_Satisfied - gives more information to the user; + case GCM_RESULT_InconsistentAlignment: return 6; // \ru Приоритет должен быть меньше, чем у GCM_RESULT_Overconstrained, потому, что правильность диагностики гарантируется только при осутствии сообщения mtResCode_OverConstraint; \en Priority must be less than mtResCode_OverConstraint because the correct diagnosis can be guaranteed if there is not message GCM_RESULT_Overconstrained; + case GCM_RESULT_Overconstrained: return 7; // \ru Приоритет выше, чем у GCM_RESULT_Unsolvable, поскольку точнее выявлена причина не решаемости; \en Priority higher than that of GCM_RESULT_Unsolvable because unsolvable reason have been found; + + /* + \ru Более высокий приоритет у группы ошибок, связанных с некорректными + зависимостями для черных ящиков - такие ошибки нужно устранять в + первую очередь. + \en Higher priority for the group errors associated with incorrect + dependencies for black boxes - first of all such errors must + be eliminated. + */ + + case GCM_RESULT_MultiDependedGeom: // \ru Задана входящая зависимость для выходного объекта черного ящика; \en Given an incoming dependence of the output object of a black box; + case GCM_RESULT_OverconstrainingDependedGeoms: // \ru Задана зависимость между экземплярами массива (выходными); \en Given dependence between copies of the pattern (output); + case GCM_RESULT_DependedGeomCantBeFixed: // The depended geom can't be fixed. + return 8; + + case GCM_RESULT_CyclicDependence: // \ru Задана циклическая зависимость \en Given a cyclic dependence + return 9; + + /* + Группа ошибок, связанная с некорректно заданным сопряжением. + Group of errors related to incorrectly specified constraint. + */ + case GCM_RESULT_InappropriateArgument: + case GCM_RESULT_InappropriateAlignment: // + case GCM_RESULT_InvalidArguments: // \ru В ограничении не заданы аргументы (пустые аргументы). \en Constraint has invalid or undefined (void) arguments. + case GCM_RESULT_IncompatibleArguments: + case mtResCode_UnsupportedTangencyChoice: // \ru Для сопряжения касание - опция выбора по окружности или по образующей не поддреживается \en For mate the option of tangency choice by circle or generating curve is unsupported + case GCM_RESULT_UnsupportedFollowerSurface: + case mtResCode_IsNoPossibleForCircTanChoice: // \ru Для данной пары поверхностей касание по окружности геометрически не возможно \en For a given pair of surfaces the touching along the circle is geometrically impossible + case GCM_RESULT_InconsistentPlanarAngle: // \ru Не соблюдаются условия планарного угла (векторы от пары тел должны быть перпендикулярны оси) \en Planar angle conditions are not met (vectors from a pair of solids should be perpendicular to the axis) + case GCM_RESULT_InconsistentFollowerAxis: + case mtResCode_CoaxialMtGearTransmissionIsNotAvalable: + return 10; + + /* + The group of system error codes. Priority overlapping all other errors. + */ + case GCM_RESULT_InternalError: + case GCM_RESULT_Aborted: + case GCM_RESULT_ItsNotDrivingDimension: + case GCM_RESULT_Unregistered: + return 99; + + /* + \ru Все остальные геометрические ошибки (Самый информативный для пользователя вариант); + \en All other geometric errors (the most informative variant for the user); + */ + + default: return 90; + } +} + +/** + \addtogroup GCM_3D_Routines + \{ +*/ + +//---------------------------------------------------------------------------------------- +// +// --- +inline bool OK( GCM_result res ) +{ + return res == mtResCode_Ok; +} + +//---------------------------------------------------------------------------------------- +// +// --- +inline GCM_result ResCode( bool ok ) +{ + return ok ? GCM_RESULT_Ok : GCM_RESULT_None; +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Выбрать "худший" результат. + \en Select "the worst" result code. \~ + \details \ru Функция выбирает из двух сообщений об ошибке, то которое нуждается во + внимании пользователя прежде другого. + \en The function selects from two error messages, something that needs + attention before another error. +*/ +//--- +inline GCM_result WorseResult( GCM_result res1, GCM_result res2 ) +{ + return PriorityLevel( res1 ) > PriorityLevel( res2 ) ? res1 : res2; +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Суммировать результирующий код. \en Summarize the resulting code. + \details \ru Оператор выбирает из потока ошибок, то которое нуждается во + внимании пользователя прежде других. + \en The operator selects from stream of error messages, something that needs + attention before anything else. + +*/ +//--- +inline GCM_result & operator << ( GCM_result & sumRes, const GCM_result r ) +{ + if ( r == GCM_RESULT_None ) + { + return sumRes; + } + if ( PriorityLevel(r) > PriorityLevel(sumRes) || (sumRes==GCM_RESULT_None) ) + { + sumRes = r; + } + return sumRes; +} + +/** \} */ // GCM_3D_Routines + +#endif // __GCM_RES_CODE_H + +// eof diff --git a/C3d/Include/gcm_types.h b/C3d/Include/gcm_types.h index 23a3080..f0ff680 100644 --- a/C3d/Include/gcm_types.h +++ b/C3d/Include/gcm_types.h @@ -1,535 +1,540 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Типы данных геометрического решателя - \en Data types of geometric solver \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GCM_TYPES_H -#define __GCM_TYPES_H - -#include - -class MtGeomSolver; -class MbPlacement3D; - -#define GCM_ID_TYPE 1 // 1 - MtObjectId is a struct, 0 - MtObjectId is simple integer. - -#if ( GCM_ID_TYPE == 1 ) - -typedef struct { uint32 id; } MtObjectId; -const MtObjectId _GCM_NULL = { SYS_MAX_UINT32 }; -const MtObjectId _GCM_GROUND = { 0 }; - -#else // GCM_ID_TYPE - -typedef uint32 MtObjectId; -const MtObjectId _GCM_NULL = SYS_MAX_UINT32; -const MtObjectId _GCM_GROUND = 0; - -#endif // GCM_ID_TYPE - -/** \addtogroup GCM_3D_API - \{ -*/ - -/// \ru Система геометрических ограничений. \en System of geometric constraints. \~ -typedef MtGeomSolver* GCM_system; -/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. -typedef MtObjectId GCM_object; -/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. -typedef GCM_object GCM_geom; -/// \ru Дескриптор ограничения, зарегистрированного в решателе. \en Descriptor of a constraint registered in the solver. -typedef GCM_object GCM_constraint; -/// \ru Дескриптор паттерна, зарегистрированного в решателе. \en Descriptor of a pattern registered in the solver. -typedef GCM_object GCM_pattern; -/// \ru Дескриптор пустого объекта или ограничения. \en Descriptor of empty object or constraint. \~ -const GCM_object GCM_NULL = _GCM_NULL; -/** \brief \ru Дескриптор неподвижного подмножества объектов, заданных в глобальной системой координат. - \en Descriptor of rigid subset of objects which are given in global coordinate system. \~ -*/ -const GCM_geom GCM_GROUND = _GCM_GROUND; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Словарь типов геометрических примитивов. - \en Dictionary of geometric primitives types. \~ -*/ -// --- -typedef enum -{ - /* - (!) Do not change the integral constants (they are written to file permanently). - */ - - GCM_NULL_GTYPE = 0 ///< \ru Пустой геометрический объект. \en Empty geometric object. - , GCM_POINT ///< \ru Точка. \en Point. - , GCM_LINE ///< \ru Прямая. \en Line. - , GCM_PLANE ///< \ru Плоскость. \en Plane. - , GCM_CYLINDER ///< \ru Цилиндр. \en Cylinder. - , GCM_CONE ///< \ru Конус. \en Cone. - , GCM_SPHERE ///< \ru Сферическая поверхность. \en Spherical surface. - , GCM_TORUS ///< \ru Тороидальная поверхность. \en Toroidal surface. - , GCM_CIRCLE ///< \ru Окружность. \en Circle. - , GCM_LCS ///< \ru Система координат. \en Coordinate system. - , GCM_MARKER ///< \ru Точка и пара ортонормированных векторов. \en Point and pair of orthonormalized vectors. - , GCM_SPLINE ///< \ru Сплайновая кривая. \en Spline curve. - , GCM_VECTOR // Unit vector (internal use only) - , GCM_AXIS // Point with unit vector (internal use only) - , GCM_UNKNOWN_GTYPE // \ru Геометрический тип, не поддерживаемый решателем. \en Some geometric type, which is not supported by the solver. \~ - , GCM_LAST_GTYPE // \ru Количество типов. \en The count of types. -} GCM_g_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Словарь типов ограничения. - \en Dictionary of constraint types. \~ - - \note \ru Значения этого перечисления могут быть использованы для постоянного - хранения и останутся неизменными в следующих версиях. - \en Values of this enum can be used for permanent storage - and will be kept in the future versions. \~ -*/ -//--- -typedef enum -{ - /* - (!) Do not change the integral constants (they are written to file permanently). - */ - GCM_UNKNOWN = -1 ///< \ru Не определенный тип. \en Unknown type. - , GCM_COINCIDENT = 0 ///< \ru Геометрическое совпадение. \en Coincidence of loci. - , GCM_PARALLEL = 1 ///< \ru Параллельность двух объектов, имеющих направление. \en Parallelism of two objects which have a direction vector. - , GCM_PERPENDICULAR = 2 ///< \ru Перпендикулярность двух объектов, имеющих направление. \en Perpendicularity of two objects which have a direction vector. - , GCM_TANGENT = 3 ///< \ru Касание двух поверхностей или кривых. \en Tangency of two objects, surfaces and curves. - , GCM_CONCENTRIC = 4 ///< \ru Концентричность двух объектов, имеющих ось или центр. \en Concentricity of two objects having a center or an axis. - , GCM_DISTANCE = 5 ///< \ru Линейное размер между объектами. \en Linear dimension between objects. - , GCM_ANGLE = 6 ///< \ru Угловой размер между векторными объектами. \en Angular dimension between directed objects (vectors). - , GCM_TRANSMITTION = 9 ///< \ru Механическая передача. \en Mechanical transmission. - , GCM_CAM_MECHANISM = 10 ///< \ru Кулачковый механизм. \en Cam mechanism. - , GCM_SYMMETRIC = 11 ///< \ru Симметричность. \en Symmetry. - , GCM_DEPENDENT = 14 ///< \ru Зависимый объект. \en Dependent object. - , GCM_PATTERNED = 15 ///< \ru Элемент паттерна. \en Patterned object. - , GCM_LINEAR_PATTERN = 16 ///< \ru Линейный паттерн. \en Linear pattern. - , GCM_ANGULAR_PATTERN = 17 ///< \ru Угловой паттерн. \en Angular pattern. - , GCM_RADIUS = 18 ///< \ru Радиальный размер. \en Radial dimension. - , GCM_LAST_CTYPE - , GCM_IN_PLACE = 7 // Deprecated -} GCM_c_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Варианты выравнивания направлений. - \en Variants of alignment. \~ - \note \ru Значения этого перечисления могут быть использованы для постоянного - хранения и останутся неизменными в следующих версиях. - \en Values of this enum can be used for permanent storage - and will be kept in the future versions. \~ -*/ -//--- -typedef enum -{ - /* - (!) Do not change the constants (they are written to file permanently). - */ - GCM_MIN_ALIGNMENT= -1, // Minimum value of this enum - GCM_OPPOSITE = -1, ///< \ru Противонаправленные. \en Anti-align the directions. \~ - GCM_CLOSEST = 0, ///< \ru Ориентация согласно ближайшего решения. \en Orientation according to the nearest solution. \~ - GCM_COORIENTED = 1, ///< \ru Сонаправленные. \en Cooriented directions. \~ - GCM_NO_ALIGNMENT = 2, ///< \ru Нет определенной ориентации. \en No defined orientation. \~ - /* - Additional variants of alignment (they are used for tangency variants) - */ - GCM_ALIGNED_0 = GCM_COORIENTED, - GCM_ALIGNED_1 = 3, - GCM_ALIGNED_2 = 4, - GCM_ALIGNED_3 = 5, - GCM_REVERSE_0 = GCM_OPPOSITE, - GCM_REVERSE_1 = 6, - GCM_REVERSE_2 = 7, - GCM_REVERSE_3 = 8, - /* - Additional variants of alignment (they are used for patterns and symmetry) - */ - 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_alignment; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вариант углового размера. - \en Variant of angular dimension. \~ - \note \ru Значения этого перечисления могут быть использованы для постоянного - хранения данных приложения и останутся неизменными в следующих версиях. - \en Values of this enum can be used for permanent storing of app data - and will be kept in the future versions. \~ -*/ -//--- -typedef enum -{ - GCM_NONE_ANGLE = 0, ///< \ru Неопределен \en Undefined - GCM_2D_ANGLE = 1, ///< \ru Угол для планарных соединений (0 .. 360 градусов) \en Angle of planar joints (0 .. 360 degrees) - GCM_3D_ANGLE = 2, ///< \ru Угол в пространстве (0 .. 180 градусов) \en Angle in space (0 .. 180 degrees) - GCM_PLANAR_ANGLE = GCM_2D_ANGLE -} GCM_angle_type; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Варианты касания поверхностей или кривых. - \en Variants of tangency of surfaces or curves. \~ - \note \ru Значения этого перечисления могут быть использованы для постоянного - хранения данных приложения и останутся неизменными в следующих версиях. - \en Values of this enum can be used for permanent storage of app data and will - be kept in the future versions. \~ -*/ -//--- -typedef enum -{ - /* - (!) Do not change the constants - */ - GCM_TAN_NONE = 0x00 ///< \ru Не выбрано. \en Not chosen. - , GCM_TAN_POINT = 0x01 ///< \ru Касание в общем случае (контакт точкой). \en Tangency in general case (contact at a point). - , GCM_TAN_LINE = 0x02 ///< \ru Касание по образующей прямой (например два цилиндра с параллельными осями). \en Tangency by a generating line (for instance, two cylinders with parallel axes). - , GCM_TAN_CIRCLE = 0x04 ///< \ru Касание по окружности (например сфера в конусе). \en Tangency by a circle (for instance, a sphere inside a cone). -} GCM_tan_choice; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Диагностические коды 3d-решателя. \en Diagnostic codes of 3D-solver. \~ - \details \ru GCM_result перечисляет значения, возвращаемые вызовами API компонента GCM, - включая диагностические коды решения геометрических ограничений. Значения данного типа - возвращаются такими функциями, как GCM_Evaluate и GCM_EvaluationResult. - \en GCM_result enumerates the values returned by the GCM API calls including - the diagnostic codes of solving geometric constraints. Values of this type are returned - by functions such as GCM_Evaluate and GCM_EvaluationResult. - \note \ru Значения этого перечисления могут быть использованы для постоянного - хранения данных приложения и останутся неизменными в следующих версиях. - \en Values of this enum can be used for permanent storage of app data and will - be kept in the future versions. \~ -*/ -//--- -typedef enum -{ - GCM_RESULT_None = 0 ///< \ru Код неопределенного результата или состояния. \en Code of undefined result or status. \~ - , GCM_RESULT_Ok = 1 ///< \ru Успешный результат вызова API компонента GCM. \en The successful result of GCM API call. \~ - , GCM_RESULT_Satisfied = GCM_RESULT_Ok ///< \ru Ограничение или система ограничения решены. \en Constraint or system of constraints are fulfilled. \~ - , GCM_RESULT_Overconstrained = 2 ///< \ru Ограничение переопределяет систему и противоречит другим условиям. \en Constraint is redundant and contradicts the other conditions. \~ - , GCM_RESULT_MatedFixation = 3 ///< \ru Заданы ограничения для пары фиксированных объектов. \en Constraints are specified for pair of fixed objects. \~ - , GCM_RESULT_DraggingFailed = 4 ///< \ru Неудачная попытка перемещения фиксированного объекта (равно, как объекта жестко-связанного с фиксированным). \en Failed attempt to move a fixed object (as the object rigidly connected with fixed). \~ - , GCM_RESULT_Not_Satisfied = 5 ///< \ru Ограничение(я) не решено (по неизвестным причинам). \en Constraint(s) has not been solved (for unknown reasons). \~ - , GCM_RESULT_Unsolvable = 6 ///< \ru Ограничение(я) не разрешимо. \en Constraint(s) is not solvable. \~ - - /** - \brief \ru Ограничение GCM_DEPENDENT не вычислено или ее независимые аргументы находятся вне области решений. - \en The GCM_DEPENDENT constraint is not solved or its independent arguments are out of the solution domain. - \note \ru Ситуация возникает, когда функция GCM_dependent_func возвращает false. - \en The situation occurs when the GCM_dependent_func function returns false. - */ - , GCM_RESULT_DependentConstraintUnsolved = 7 - , GCM_RESULT_Error = 8 ///< \ru Неизвестная ошибка, как правило, не связанная с процессом решения. \en Unknown error is usually not related to the solving. \~ - , GCM_RESULT_InappropriateAlignment = 9 ///< \ru Опция выравнивания не подходит для данного типа ограничения. \en The alignment option is inappropriate to a given constraint type. \~ - , GCM_RESULT_InappropriateArgument = 10 ///< \ru Геометрический тип аргумента не подходит для данного ограничения. \en Geometric type of an argument is inappropriate to the constraint. \~ - - /* - Additional message codes. - */ - - , GCM_RESULT_IncompatibleArguments = 3001 ///< \ru Несовместные типы аргументов ограничения. \en Inconsistent types of constraint arguments. \~ - , GCM_RESULT_InconsistentAngleType ///< \ru Угловая опция несовместима со степенью свободы соединения (планарный тип угла применим только для соединения, оставляющего единственную степень свободы вращения). \en Angular option is inconsistent with the degree of freedom of the joint (planar type of angle is only applicable for the joint leaving only one degree of freedom of rotation); \~ - , GCM_RESULT_InconsistentAlignment ///< \ru Величина ориентации несовместна с другими сопряжениями. \en The orientation value is inconsistent with other mates. \~ - , GCM_RESULT_Duplicated ///< \ru Ограничение дублирует другое. \en Constraint duplicates another. - , GCM_RESULT_CyclicDependence ///< \ru Неразрешимая циклическая зависимость. \en Unsolvable cyclic dependence. - , GCM_RESULT_MultiDependedGeom ///< \ru Объект является зависимым от двух и более ограничений 'GCM_DEPENDED'. \en A geometric object is dependent on two or more constraints of 'GCM_DEPENDED' type. - , GCM_RESULT_OverconstrainingDependedGeoms ///< \ru Избыточное ограничение между зависимыми объектами. \en A redundancy constraint between depended geoms. \~ - , GCM_RESULT_DependedGeomCantBeFixed ///< \ru Зависимый аргумент ограничения 'GCM_DEPENDED' не может быть зафиксирован. \en The depended argument of 'GCM_DEPENDED' can't be fixed. - , GCM_RESULT_InvalidArguments ///< \ru В ограничении не заданы аргументы (пустые аргументы). \en Constraint has invalid or undefined (void) arguments. - , mtResCode_UnsupportedTangencyChoice ///< \ru Для сопряжения касание - опция выбора по окружности или по образующей не поддреживается \en For mate the option of tangency choice by circle or generating curve is unsupported. - , mtResCode_IsNoPossibleForCircTanChoice ///< \ru Для данной пары поверхностей касание по окружности геометрически не возможно \en For a given pair of surfaces the touching along the circle is geometrically impossible. - , mtResCode_CoaxialMtGearTransmissionIsNotAvalable ///< \ru Механическая передача вращения компонентов с совпадающими осями не поддерживается \en Mechanical transmission of components rotation with the same axis is not supported - , mtResCode_NoSeparatedSolutionForCamGear ///< \ru В сборке присутствуют сопряжения (геометрические условия), создающие зависимость движения толкателя от движения кулачка, помимо самого кулачкового механизма \en The assembly contains mates (geometric conditions) creating dependence of the motion of the pusher from the motion of cam in addition to the cam gear - , mtResCode_CyclicDependenceForTwoOrMoreCamGears ///< \ru Задана циклическая зависимость для двух или более кулачковых механизмов \en Given the cyclic dependence for two or more cam gears - , mtResCode_InconsistentFollowerAxis ///< \ru Заданные сопряжения для толкателя не соответствую его оси движения \en Given mates for pusher doesn't correspond to its motion axis - , GCM_RESULT_InconsistentPlanarAngle ///< \ru Не соблюдаются условия планарного угла (векторы сторон угла должны быть перпендикулярны оси). \en Planar angle conditions are not met (vectors from the sides of angle should be perpendicular to the axis). - /* - ATTENTION: New error messages should be added only before this line. - */ - - /* - \ru Сообщения о некорректных результатах вызовов API решателя (не вычислительные). - \en Messages about incorrect results of the solver API calls (not computational). \~ - */ - , GCM_RESULT_ItsNotDrivingDimension ///< \ru Данное ограничение должно быть управляющим размером. \en Given constraint should be a driving dimension. - , GCM_RESULT_Unregistered ///< \ru Обращение к недействительному объекту. \en Access to invalid object. - , GCM_RESULT_InternalError - , GCM_RESULT_Aborted ///< \ru Процесс вычислений был прерван по запросу приложения. \en The evaluation process aborted by the application. \~ - , GCM_RESULT_Last_ // The last error code of user for mates (adding before this line) -} GCM_result; - -//---------------------------------------------------------------------------------------- -/// \ru Характер зависимости пары тел (geoms) \en Dependency character of solid pair (geoms) -// --- -typedef enum -{ - GCM_NO_DEPENDENCY = 0 ///< \ru Нет односторонней зависимости. \en It means no one-directed dependency. - , GCM_1ST_DEPENDENT = 2 ///< \ru Первый объект зависит от другого(других). \en The first object is dependent on the other(s). - , GCM_2ND_DEPENDENT = 1 ///< \ru Второй объект зависит от другого(других). \en The second object is dependent on the other(s). -} GCM_dependency; - -//---------------------------------------------------------------------------------------- -/// \ru Тип связи между элементами в паттерне. \en The type of relationship between elements in the pattern. -// --- -typedef enum -{ - GCM_NO_SCALE = 0, - GCM_RIGID = 1, ///< \ru Шаг между элементами константен. Паттерн не масштабируется (не растягивается). \en Distance between elements is constant. The pattern is not scaled. - GCM_LINEAR_SCALE = 2 ///< \ru Шаг между элементами линейно масштабируется при растяжениях. \en Distance between elements is linearly scaled when stretching. -} GCM_scale; - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Режим поведения при манипулировании недоопределенной системой. - \en Mode of the behavior when manipulating the undeconstrained system. \~ -*/ -// --- -typedef enum -{ - /* - Произвольное поведение (arbitrary behavior). - */ - GCM_REPOSITION_FreeRotation ///< \ru Произвольная репозиция с преимуществом вращения. \en Arbitrary reposition with predominant rotation. - , GCM_REPOSITION_FreeMoving ///< \ru Произвольная репозиция с преимуществом перемещения. \en Arbitrary reposition with predominant moving. - - /* - Строгое поведение (strict behavior). - */ - , GCM_REPOSITION_Dragging ///< \ru Перетаскивание в плоскости "экрана". \en Dragging in the plane of the screen. - , GCM_REPOSITION_Rotation ///< \ru Вращение вокруг неподвижной оси. \en Rotation around fixed axis. - - /** \brief \ru Перенос только для одного твердого тела. \en Shift only one solid. - \note \ru Этот режим был задуман для процессов вставки нового тела в сборку САПР. - \en This mode have been intended for insertion processes of a new solid in the CAD assembly. - */ - , GCM_REPOSITION_Transfer - -} GCM_reposition; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты 3D-вектора. \en Coordinates of 3D-vector. -//--- -struct GCM_vec3d { double x, y, z; }; - -//---------------------------------------------------------------------------------------- -/// \ru Координаты точки 3D пространства. \en Coordinates of point in three-dimensional space. -//--- -struct GCM_point { double x, y, z; }; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Структура полей данных, представляющих геометрический объект. - \en Structure of data fields representing a geometric object. \~ - \details \ru Эта простая структура данных представляет варианты геометрических типов, - с которыми работает решатель.\n - \en This plain data structure represents variants of geometric data types that - the solver works with.\n - \~ - \par - \ru Кортежи, соответствующие типам геометрии:\n - \en Corresponding tuples of geometric types:\n - - \~ { GCM_POINT origin } - simple point;\n - { GCM_SPHERE origin radiusA } - center and radius of a sphere;\n - { GCM_LINE origin axisZ } - point and direction of a line;\n - { GCM_PLANE origin axisZ } - point and normal of a plane;\n - { GCM_CIRCLE origin axisZ radiusA } - center, rotation axis and radius;\n - { GCM_CYLINDER origin axisZ radiusA } - center, rotation axis and radius;\n - { GCM_CONE origin axisZ radiusA radiusB } - center, rotation axis and two radiuses;\n - { GCM_TORUS origin axisZ radiusA radiusB };\n - { GCM_LCS origin axisZ axisX axisY } - local coordinate system that specify a solid position.\n -*/ -//--- -struct GCM_g_record -{ - GCM_g_type type; ///< \ru Тип геометрии. \en Type of geometric object. - GCM_point origin; ///< \ru Точка позиционирования геометрического объекта. \en Location of a geometric object. - GCM_vec3d axisZ; ///< \ru Направляющий вектор прямой или вектор нормали плоскости. \en Direction of line, normal of plane, Z-axis of a local coordinate frame. - GCM_vec3d axisX; ///< \ru Ось X локальной системы координат. \en X-axis of local coordinate frame . - GCM_vec3d axisY; ///< \ru Ось Y локальной системы координат. \en Y-axis of local coordinate frame. - double radiusA; ///< \ru Радиус окружности, сферы или цилиндра либо радиус основания конуса, "большой" радиус тора. \en Radius of circle, sphere and cylinder or major radius of cone and torus. - double radiusB; ///< \ru "Малый" радиус тора или конуса. \en Minor radius of cone and torus. -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Дополнительный параметр для функций типа #GCM_dependent_func. - \en Additional parameter for functions of type #GCM_dependent_func. \~ - \sa #GCM_dependent_geom_func, #GCM_dependent_func -*/ -//--- -struct GCM_extra_param -{ - size_t funcId; // integral identifier of a user-defined callback - void * funcData; // pointer to an application data structure - GCM_extra_param() { funcId = 0, funcData = 0; } -}; - -//---------------------------------------------------------------------------------------- -// The function calculates position of a dependent geom regarding to other independent geoms. -/* - Note: The dependent geom is first element of argument list inGeoms, and others are independent. - argNb Number of arguments of dependency constraint, equals to size of inGeoms. - g1 = f( g2 g3 ... gn ); -*/ -//--- -typedef bool (*GCM_dependent_func) ( MbPlacement3D gPlaces[] - , size_t gPlacesSize - , GCM_extra_param exPar ); - -//---------------------------------------------------------------------------------------- -/// \~ Alternative typename of #GCM_dependent_func -//--- -typedef GCM_dependent_func GCM_dependent_geom_func; - -/** \} */ // GCM_3D_API - -//---------------------------------------------------------------------------------------- -// Argument of constraint to record in type 'GCM_c_record' -//-- -struct GCM_c_arg -{ - union - { - GCM_object geom; // Geometric object. - GCM_alignment alignVal; // Variant of alignment. - GCM_tan_choice tanChoice; // Option for tangency constraint only. - GCM_angle_type angType; // Option for angular constraint only. - GCM_scale scale; // Option for pattern constraint only. - double dimValue; // Numeric value of a dimension. - int enumVal; - }; - GCM_c_arg & operator = ( double val ) - { - dimValue = val; - return *this; - } - template - GCM_c_arg & operator = ( const _Enum & val ) - { - enumVal = static_cast( val ); - return *this; - } - GCM_c_arg & operator = ( const GCM_geom & gId ) - { - geom = gId; - return *this; - } - GCM_c_arg() { dimValue = 0.0; } -}; - -//---------------------------------------------------------------------------------------- -/** \brief \en Structure of geometric constraint record. - \ru Структура записи геометрического ограничения. \~ -*/ -/* - The argument tuples of each constraint type: - { GCM_c_type GCM_c_arg ... GCM_c_arg } - -------------------|------------------------------- - { GCM_COINCIDENT GCM_geom GCM_geom GCM_alignment } - { GCM_CONCENTRIC GCM_geom GCM_geom GCM_alignment } - { GCM_PARALLEL GCM_geom GCM_geom GCM_alignment } - { GCM_PERPENDICULAR GCM_geom GCM_geom GCM_alignment } - { GCM_IN_PLACE GCM_geom GCM_geom GCM_NO_ALIGNMENT } - { GCM_DISTANCE GCM_geom GCM_geom double GCM_alignment } - { GCM_TANGENT GCM_geom GCM_geom GCM_alignment GCM_tan_choice } - { GCM_ANGLE GCM_geom GCM_geom GCM_geom double GCM_alignment } - planar kind of angle - { GCM_ANGLE GCM_geom GCM_geom GCM_NULL double GCM_alignment } - 3d kind of angle - { GCM_SYMMETRIC GCM_geom GCM_geom GCM_geom GCM_alignment } - { 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_TRANSMITTION not specified } - { GCM_CAM_MECHANISM not specified } - { GCM_RADIUS GCM_geom double } - { GCM_UNKNOWN } - Sample of the journal line: (GCM_AddConstraint (GCM_COINCIDENT #1 #2 GCM_CLOSEST) #3) -*/ -struct GCM_c_record -{ - static const size_t argsN = 5; - GCM_c_type type; // \ru Тип ограничения. \en Type of constraint. - GCM_c_arg args[argsN]; // \ru Аргументы ограничения. \en Arguments of constraint. -}; - -#if ( GCM_ID_TYPE == 1 ) - -inline bool operator == ( const MtObjectId & f, const MtObjectId & s ) { return f.id == s.id; } -inline bool operator != ( const MtObjectId & f, const MtObjectId & s ) { return f.id != s.id; } -inline bool operator < ( const MtObjectId & f, const MtObjectId & s ) { return f.id < s.id; } -inline uint32 & _id( MtObjectId & obj ) { return obj.id; } -inline const uint32 & _id( const MtObjectId & obj ) { return obj.id; } - -#else // GCM_ID_TYPE - -inline uint32 & _id( MtObjectId & obj ) { return obj; } -inline const uint32 & _id( const MtObjectId & obj ) { return obj; } - -#endif // GCM_ID_TYPE - -typedef GCM_alignment MtAlignType; -typedef GCM_g_type MtGeometryType; -typedef GCM_result MtResultCode3D; - -/* - The constants below are deprecated (2015) -*/ - -static const GCM_alignment GCM_NOT_ORIENTED = GCM_NO_ALIGNMENT; -static const GCM_alignment GCM_Opposite = GCM_OPPOSITE; -static const GCM_alignment GCM_Closest = GCM_CLOSEST; -static const GCM_alignment GCM_Cooriented = GCM_COORIENTED; -static const GCM_alignment GCM_None = GCM_NO_ALIGNMENT; -static const GCM_alignment GCM_Min = GCM_OPPOSITE; -static const GCM_alignment GCM_Max = GCM_MAX_ALIGNMENT; - -static const GCM_g_type GCM_FIRST_GTYPE = GCM_NULL_GTYPE; -static const GCM_g_type mgt_Cylinder = GCM_CYLINDER; -static const GCM_c_type mct_Coincidence = GCM_COINCIDENT; -static const GCM_c_type mct_Parallel = GCM_PARALLEL; -static const GCM_c_type mct_Perpendicular = GCM_PERPENDICULAR; -static const GCM_c_type mct_Tangency = GCM_TANGENT; -static const GCM_c_type mct_Concentric = GCM_CONCENTRIC; -static const GCM_c_type mct_Distance = GCM_DISTANCE; -static const GCM_c_type mct_Angle = GCM_ANGLE; -static const GCM_c_type mct_InPlace = GCM_IN_PLACE; -static const GCM_c_type mct_Unknown = GCM_UNKNOWN; -static const GCM_c_type mct_CamMechanism = GCM_CAM_MECHANISM; -static const GCM_c_type mct_Symmetry = GCM_SYMMETRIC; -static const GCM_c_type mct_Symmetric = GCM_SYMMETRIC; -static const GCM_c_type mct_Parallelism = GCM_PARALLEL; - -static const GCM_result mtResCode_None = GCM_RESULT_None; -static const GCM_result mtResCode_Ok = GCM_RESULT_Ok; -static const GCM_result mtResCode_Satisfied = GCM_RESULT_Ok; -static const GCM_result mtResCode_SystemError = GCM_RESULT_Error; -static const GCM_result mtResCode_Error = GCM_RESULT_Error; -static const GCM_result mtResCode_Overconstrained = GCM_RESULT_Overconstrained; -static const GCM_result mtResCode_Not_Satisfied = GCM_RESULT_Not_Satisfied; -static const GCM_result mtResCode_MovingOfFixedGeom = GCM_RESULT_DraggingFailed; -static const GCM_result mtResCode_InvalidAxisOfPlanarAngle = GCM_RESULT_InconsistentPlanarAngle; -static const GCM_result mtResCode_CyclicDependence = GCM_RESULT_CyclicDependence; -static const GCM_result mtResCode_InvalidDependenceForOutGeom = GCM_RESULT_MultiDependedGeom; -static const GCM_result mtResCode_InvalidDependenceForOutGeoms = GCM_RESULT_OverconstrainingDependedGeoms; // (2018) -static const GCM_result mtResCode_InvalidDependenceForFixGeom = GCM_RESULT_DependedGeomCantBeFixed; - -const GCM_dependency GCM_2ST_DEPENDENT = GCM_2ND_DEPENDENT; - -/* - Deprecated names of a dynamic reposition modes (2019) -*/ -const GCM_reposition rep_FreeRotation = GCM_REPOSITION_FreeRotation; -const GCM_reposition rep_FreeMoving = GCM_REPOSITION_FreeMoving; -const GCM_reposition rep_MovingToPoint = GCM_REPOSITION_Dragging; -const GCM_reposition rep_RotationAboutAxis = GCM_REPOSITION_Rotation; -const GCM_reposition rep_TransferOneGeomOnly = GCM_REPOSITION_Transfer; - - -#endif - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Типы данных геометрического решателя + \en Data types of geometric solver \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GCM_TYPES_H +#define __GCM_TYPES_H + +#include + +class MtGeomSolver; +class MbPlacement3D; + +#define GCM_ID_TYPE 1 // 1 - MtObjectId is a struct, 0 - MtObjectId is simple integer. + +#if ( GCM_ID_TYPE == 1 ) + +typedef struct { uint32 id; } MtObjectId; +const MtObjectId _GCM_NULL = { SYS_MAX_UINT32 }; +const MtObjectId _GCM_GROUND = { 0 }; + +#else // GCM_ID_TYPE + +typedef uint32 MtObjectId; +const MtObjectId _GCM_NULL = SYS_MAX_UINT32; +const MtObjectId _GCM_GROUND = 0; + +#endif // GCM_ID_TYPE + +/** \addtogroup GCM_3D_API + \{ +*/ + +/// \ru Система геометрических ограничений. \en System of geometric constraints. \~ +typedef MtGeomSolver* GCM_system; +/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. +typedef MtObjectId GCM_object; +/// \ru Дескриптор геометрического объекта, зарегистрированного в контексте решателя. \en Descriptor of geometrical object registered in the solver context. +typedef GCM_object GCM_geom; +/// \ru Дескриптор ограничения, зарегистрированного в решателе. \en Descriptor of a constraint registered in the solver. +typedef GCM_object GCM_constraint; +/// \ru Дескриптор паттерна, зарегистрированного в решателе. \en Descriptor of a pattern registered in the solver. +typedef GCM_object GCM_pattern; +/// \ru Дескриптор пустого объекта или ограничения. \en Descriptor of empty object or constraint. \~ +const GCM_object GCM_NULL = _GCM_NULL; +/** \brief \ru Дескриптор неподвижного подмножества объектов, заданных в глобальной системой координат. + \en Descriptor of rigid subset of objects which are given in global coordinate system. \~ +*/ +const GCM_geom GCM_GROUND = _GCM_GROUND; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Словарь типов геометрических примитивов. + \en Dictionary of geometric primitives types. \~ +*/ +// --- +typedef enum +{ + /* + (!) Do not change the integral constants (they are written to file permanently). + */ + + GCM_NULL_GTYPE = 0 ///< \ru Пустой геометрический объект. \en Empty geometric object. + , GCM_POINT ///< \ru Точка. \en Point. + , GCM_LINE ///< \ru Прямая. \en Line. + , GCM_PLANE ///< \ru Плоскость. \en Plane. + , GCM_CYLINDER ///< \ru Цилиндр. \en Cylinder. + , GCM_CONE ///< \ru Конус. \en Cone. + , GCM_SPHERE ///< \ru Сферическая поверхность. \en Spherical surface. + , GCM_TORUS ///< \ru Тороидальная поверхность. \en Toroidal surface. + , GCM_CIRCLE ///< \ru Окружность. \en Circle. + , GCM_LCS ///< \ru Система координат. \en Coordinate system. + , GCM_MARKER ///< \ru Точка и пара ортонормированных векторов. \en Point and pair of orthonormalized vectors. + , GCM_SPLINE ///< \ru Сплайновая кривая. \en Spline curve. + , GCM_VECTOR // Unit vector (internal use only) + , GCM_AXIS // Point with unit vector (internal use only) + , GCM_UNKNOWN_GTYPE // \ru Геометрический тип, не поддерживаемый решателем. \en Some geometric type, which is not supported by the solver. \~ + , GCM_LAST_GTYPE // \ru Количество типов. \en The count of types. +} GCM_g_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Словарь типов ограничения. + \en Dictionary of constraint types. \~ + + \note \ru Значения этого перечисления могут быть использованы для постоянного + хранения и останутся неизменными в следующих версиях. + \en Values of this enum can be used for permanent storage + and will be kept in the future versions. \~ +*/ +//--- +typedef enum +{ + /* + (!) Do not change the integral constants (they are written to file permanently). + */ + GCM_UNKNOWN = -1 ///< \ru Не определенный тип. \en Unknown type. + , GCM_COINCIDENT = 0 ///< \ru Геометрическое совпадение. \en Coincidence of loci. + , GCM_PARALLEL = 1 ///< \ru Параллельность двух объектов, имеющих направление. \en Parallelism of two objects which have a direction vector. + , GCM_PERPENDICULAR = 2 ///< \ru Перпендикулярность двух объектов, имеющих направление. \en Perpendicularity of two objects which have a direction vector. + , GCM_TANGENT = 3 ///< \ru Касание двух поверхностей или кривых. \en Tangency of two objects, surfaces and curves. + , GCM_CONCENTRIC = 4 ///< \ru Концентричность двух объектов, имеющих ось или центр. \en Concentricity of two objects having a center or an axis. + , GCM_DISTANCE = 5 ///< \ru Линейное размер между объектами. \en Linear dimension between objects. + , GCM_ANGLE = 6 ///< \ru Угловой размер между векторными объектами. \en Angular dimension between directed objects (vectors). + , GCM_TRANSMITTION = 9 ///< \ru Механическая передача. \en Mechanical transmission. + , GCM_CAM_MECHANISM = 10 ///< \ru Кулачковый механизм. \en Cam mechanism. + , GCM_SYMMETRIC = 11 ///< \ru Симметричность. \en Symmetry. + , GCM_DEPENDENT = 14 ///< \ru Зависимый объект. \en Dependent object. + , GCM_PATTERNED = 15 ///< \ru Элемент паттерна. \en Patterned object. + , GCM_LINEAR_PATTERN = 16 ///< \ru Линейный паттерн. \en Linear pattern. + , GCM_ANGULAR_PATTERN = 17 ///< \ru Угловой паттерн. \en Angular pattern. + , GCM_RADIUS = 18 ///< \ru Радиальный размер. \en Radial dimension. + , GCM_LAST_CTYPE + , GCM_IN_PLACE = 7 // Deprecated +} GCM_c_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Варианты выравнивания направлений. + \en Variants of alignment. \~ + \note \ru Значения этого перечисления могут быть использованы для постоянного + хранения и останутся неизменными в следующих версиях. + \en Values of this enum can be used for permanent storage + and will be kept in the future versions. \~ +*/ +//--- +typedef enum +{ + /* + (!) Do not change the constants (they are written to file permanently). + */ + GCM_MIN_ALIGNMENT= -1, // Minimum value of this enum + GCM_OPPOSITE = -1, ///< \ru Противонаправленные. \en Anti-align the directions. \~ + GCM_CLOSEST = 0, ///< \ru Ориентация согласно ближайшего решения. \en Orientation according to the nearest solution. \~ + GCM_COORIENTED = 1, ///< \ru Сонаправленные. \en Cooriented directions. \~ + GCM_NO_ALIGNMENT = 2, ///< \ru Нет определенной ориентации. \en No defined orientation. \~ + /* + Additional variants of alignment (they are used for tangency variants) + */ + GCM_ALIGNED_0 = GCM_COORIENTED, + GCM_ALIGNED_1 = 3, + GCM_ALIGNED_2 = 4, + GCM_ALIGNED_3 = 5, + GCM_REVERSE_0 = GCM_OPPOSITE, + GCM_REVERSE_1 = 6, + GCM_REVERSE_2 = 7, + GCM_REVERSE_3 = 8, + /* + Additional variants of alignment (they are used for patterns and symmetry) + */ + 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_alignment; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вариант углового размера. + \en Variant of angular dimension. \~ + \note \ru Значения этого перечисления могут быть использованы для постоянного + хранения данных приложения и останутся неизменными в следующих версиях. + \en Values of this enum can be used for permanent storing of app data + and will be kept in the future versions. \~ +*/ +//--- +typedef enum +{ + GCM_NONE_ANGLE = 0, ///< \ru Неопределен \en Undefined + GCM_2D_ANGLE = 1, ///< \ru Угол для планарных соединений (0 .. 360 градусов) \en Angle of planar joints (0 .. 360 degrees) + GCM_3D_ANGLE = 2, ///< \ru Угол в пространстве (0 .. 180 градусов) \en Angle in space (0 .. 180 degrees) + GCM_PLANAR_ANGLE = GCM_2D_ANGLE +} GCM_angle_type; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Варианты касания поверхностей или кривых. + \en Variants of tangency of surfaces or curves. \~ + \note \ru Значения этого перечисления могут быть использованы для постоянного + хранения данных приложения и останутся неизменными в следующих версиях. + \en Values of this enum can be used for permanent storage of app data and will + be kept in the future versions. \~ +*/ +//--- +typedef enum +{ + /* + (!) Do not change the constants + */ + GCM_TAN_NONE = 0x00 ///< \ru Не выбрано. \en Not chosen. + , GCM_TAN_POINT = 0x01 ///< \ru Касание в общем случае (контакт точкой). \en Tangency in general case (contact at a point). + , GCM_TAN_LINE = 0x02 ///< \ru Касание по образующей прямой (например два цилиндра с параллельными осями). \en Tangency by a generating line (for instance, two cylinders with parallel axes). + , GCM_TAN_CIRCLE = 0x04 ///< \ru Касание по окружности (например сфера в конусе). \en Tangency by a circle (for instance, a sphere inside a cone). +} GCM_tan_choice; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Диагностические коды 3d-решателя. \en Diagnostic codes of 3D-solver. \~ + \details \ru GCM_result перечисляет значения, возвращаемые вызовами API компонента GCM, + включая диагностические коды решения геометрических ограничений. Значения данного типа + возвращаются такими функциями, как GCM_Evaluate и GCM_EvaluationResult. + \en GCM_result enumerates the values returned by the GCM API calls including + the diagnostic codes of solving geometric constraints. Values of this type are returned + by functions such as GCM_Evaluate and GCM_EvaluationResult. + \note \ru Значения этого перечисления могут быть использованы для постоянного + хранения данных приложения и останутся неизменными в следующих версиях. + \en Values of this enum can be used for permanent storage of app data and will + be kept in the future versions. \~ +*/ +//--- +typedef enum +{ + GCM_RESULT_None = 0 ///< \ru Код неопределенного результата или состояния. \en Code of undefined result or status. \~ + , GCM_RESULT_Ok = 1 ///< \ru Успешный результат вызова API компонента GCM. \en The successful result of GCM API call. \~ + , GCM_RESULT_Satisfied = GCM_RESULT_Ok ///< \ru Ограничение или система ограничения решены. \en Constraint or system of constraints are fulfilled. \~ + , GCM_RESULT_Overconstrained = 2 ///< \ru Ограничение переопределяет систему и противоречит другим условиям. \en Constraint is redundant and contradicts the other conditions. \~ + , GCM_RESULT_MatedFixation = 3 ///< \ru Заданы ограничения для пары фиксированных объектов. \en Constraints are specified for pair of fixed objects. \~ + , GCM_RESULT_DraggingFailed = 4 ///< \ru Неудачная попытка перемещения фиксированного объекта (равно, как объекта жестко-связанного с фиксированным). \en Failed attempt to move a fixed object (as the object rigidly connected with fixed). \~ + , GCM_RESULT_Not_Satisfied = 5 ///< \ru Ограничение(я) не решено (по неизвестным причинам). \en Constraint(s) has not been solved (for unknown reasons). \~ + , GCM_RESULT_Unsolvable = 6 ///< \ru Ограничение(я) не разрешимо. \en Constraint(s) is not solvable. \~ + + /** + \brief \ru Ограничение GCM_DEPENDENT не вычислено или ее независимые аргументы находятся вне области решений. + \en The GCM_DEPENDENT constraint is not solved or its independent arguments are out of the solution domain. + \note \ru Ситуация возникает, когда функция GCM_dependent_func возвращает false. + \en The situation occurs when the GCM_dependent_func function returns false. + */ + , GCM_RESULT_DependentConstraintUnsolved = 7 + , GCM_RESULT_Error = 8 ///< \ru Неизвестная ошибка, как правило, не связанная с процессом решения. \en Unknown error is usually not related to the solving. \~ + , GCM_RESULT_InappropriateAlignment = 9 ///< \ru Опция выравнивания не подходит для данного типа ограничения. \en The alignment option is inappropriate to a given constraint type. \~ + , GCM_RESULT_InappropriateArgument = 10 ///< \ru Геометрический тип аргумента не подходит для данного ограничения. \en Geometric type of an argument is inappropriate to the constraint. \~ + + /* + Additional message codes. + */ + + , GCM_RESULT_IncompatibleArguments = 3001 ///< \ru Несовместные типы аргументов ограничения. \en Inconsistent types of constraint arguments. \~ + , GCM_RESULT_InconsistentAngleType ///< \ru Угловая опция несовместима со степенью свободы соединения (планарный тип угла применим только для соединения, оставляющего единственную степень свободы вращения). \en Angular option is inconsistent with the degree of freedom of the joint (planar type of angle is only applicable for the joint leaving only one degree of freedom of rotation); \~ + , GCM_RESULT_InconsistentAlignment ///< \ru Величина ориентации несовместна с другими сопряжениями. \en The orientation value is inconsistent with other mates. \~ + , GCM_RESULT_Duplicated ///< \ru Ограничение дублирует другое. \en Constraint duplicates another. + , GCM_RESULT_CyclicDependence ///< \ru Неразрешимая циклическая зависимость. \en Unsolvable cyclic dependence. + , GCM_RESULT_MultiDependedGeom ///< \ru Объект является зависимым от двух и более ограничений 'GCM_DEPENDED'. \en A geometric object is dependent on two or more constraints of 'GCM_DEPENDED' type. + , GCM_RESULT_OverconstrainingDependedGeoms ///< \ru Избыточное ограничение между зависимыми объектами. \en A redundancy constraint between depended geoms. \~ + , GCM_RESULT_DependedGeomCantBeFixed ///< \ru Зависимый аргумент ограничения 'GCM_DEPENDED' не может быть зафиксирован. \en The depended argument of 'GCM_DEPENDED' can't be fixed. + , GCM_RESULT_InvalidArguments ///< \ru В ограничении не заданы аргументы (пустые аргументы). \en Constraint has invalid or undefined (void) arguments. + , mtResCode_UnsupportedTangencyChoice ///< \ru Для сопряжения касание - опция выбора по окружности или по образующей не поддреживается \en For mate the option of tangency choice by circle or generating curve is unsupported. + , mtResCode_IsNoPossibleForCircTanChoice ///< \ru Для данной пары поверхностей касание по окружности геометрически не возможно \en For a given pair of surfaces the touching along the circle is geometrically impossible. + , mtResCode_CoaxialMtGearTransmissionIsNotAvalable ///< \ru Механическая передача вращения компонентов с совпадающими осями не поддерживается \en Mechanical transmission of components rotation with the same axis is not supported + , GCM_RESULT_OverconstrainedCamMechanism ///< \ru Имеются ограничения, создающие зависимость движения толкателя от движения кулачка, помимо самого кулачкового механизма. \en There are constraints creating dependence of the follower displacement from the cam in addition to the cam mechanism. + , mtResCode_CyclicDependenceForTwoOrMoreCamGears ///< \ru Задана циклическая зависимость для двух или более кулачковых механизмов \en Given the cyclic dependence for two or more cam gears + , GCM_RESULT_InconsistentFollowerAxis ///< \ru Заданные ограничения для толкателя не соответствую его оси движения. \en Given constraints for the follwer doesn't correspond to its motion axis. + , GCM_RESULT_InconsistentPlanarAngle ///< \ru Не соблюдаются условия планарного угла (векторы сторон угла должны быть перпендикулярны оси). \en Planar angle conditions are not met (vectors from the sides of angle should be perpendicular to the axis). + , GCM_RESULT_UnsupportedFollowerSurface ///< \ru Контактная поверхность толкателя, выбранная для кинематической пары "кулачек-толкатель", пока не поддерживается решателем. \en The follower contact surface selected for the cam-follower kinematic pair is not yet supported by the solver. + + + /* + ATTENTION: New error messages should be added only before this line. + */ + + /* + \ru Сообщения о некорректных результатах вызовов API решателя (не вычислительные). + \en Messages about incorrect results of the solver API calls (not computational). \~ + */ + , GCM_RESULT_ItsNotDrivingDimension ///< \ru Данное ограничение должно быть управляющим размером. \en Given constraint should be a driving dimension. + , GCM_RESULT_Unregistered ///< \ru Обращение к недействительному объекту. \en Access to invalid object. + , GCM_RESULT_InternalError + , GCM_RESULT_Aborted ///< \ru Процесс вычислений был прерван по запросу приложения. \en The evaluation process aborted by the application. \~ + , GCM_RESULT_Last_ // The last error code of user for mates (adding before this line) +} GCM_result; + +//---------------------------------------------------------------------------------------- +/// \ru Характер зависимости пары тел (geoms) \en Dependency character of solid pair (geoms) +// --- +typedef enum +{ + GCM_NO_DEPENDENCY = 0 ///< \ru Нет односторонней зависимости. \en It means no one-directed dependency. + , GCM_1ST_DEPENDENT = 2 ///< \ru Первый объект зависит от другого(других). \en The first object is dependent on the other(s). + , GCM_2ND_DEPENDENT = 1 ///< \ru Второй объект зависит от другого(других). \en The second object is dependent on the other(s). +} GCM_dependency; + +//---------------------------------------------------------------------------------------- +/// \ru Тип связи между элементами в паттерне. \en The type of relationship between elements in the pattern. +// --- +typedef enum +{ + GCM_NO_SCALE = 0, + GCM_RIGID = 1, ///< \ru Шаг между элементами константен. Паттерн не масштабируется (не растягивается). \en Distance between elements is constant. The pattern is not scaled. + GCM_LINEAR_SCALE = 2 ///< \ru Шаг между элементами линейно масштабируется при растяжениях. \en Distance between elements is linearly scaled when stretching. +} GCM_scale; + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Режим поведения при манипулировании недоопределенной системой. + \en Mode of the behavior when manipulating the undeconstrained system. \~ +*/ +// --- +typedef enum +{ + /* + Произвольное поведение (arbitrary behavior). + */ + GCM_REPOSITION_FreeRotation ///< \ru Произвольная репозиция с преимуществом вращения. \en Arbitrary reposition with predominant rotation. + , GCM_REPOSITION_FreeMoving ///< \ru Произвольная репозиция с преимуществом перемещения. \en Arbitrary reposition with predominant moving. + + /* + Строгое поведение (strict behavior). + */ + , GCM_REPOSITION_Dragging ///< \ru Перетаскивание в плоскости "экрана". \en Dragging in the plane of the screen. + , GCM_REPOSITION_Rotation ///< \ru Вращение вокруг неподвижной оси. \en Rotation around fixed axis. + + /** \brief \ru Перенос только для одного твердого тела. \en Shift only one solid. + \note \ru Этот режим был задуман для процессов вставки нового тела в сборку САПР. + \en This mode have been intended for insertion processes of a new solid in the CAD assembly. + */ + , GCM_REPOSITION_Transfer + +} GCM_reposition; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты 3D-вектора. \en Coordinates of 3D-vector. +//--- +struct GCM_vec3d { double x, y, z; }; + +//---------------------------------------------------------------------------------------- +/// \ru Координаты точки 3D пространства. \en Coordinates of point in three-dimensional space. +//--- +struct GCM_point { double x, y, z; }; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Структура полей данных, представляющих геометрический объект. + \en Structure of data fields representing a geometric object. \~ + \details \ru Эта простая структура данных представляет варианты геометрических типов, + с которыми работает решатель.\n + \en This plain data structure represents variants of geometric data types that + the solver works with.\n + \~ + \par + \ru Кортежи, соответствующие типам геометрии:\n + \en Corresponding tuples of geometric types:\n + + \~ { GCM_POINT origin } - simple point;\n + { GCM_SPHERE origin radiusA } - center and radius of a sphere;\n + { GCM_LINE origin axisZ } - point and direction of a line;\n + { GCM_PLANE origin axisZ } - point and normal of a plane;\n + { GCM_CIRCLE origin axisZ radiusA } - center, rotation axis and radius;\n + { GCM_CYLINDER origin axisZ radiusA } - center, rotation axis and radius;\n + { GCM_CONE origin axisZ radiusA radiusB } - center, rotation axis and two radiuses;\n + { GCM_TORUS origin axisZ radiusA radiusB };\n + { GCM_LCS origin axisZ axisX axisY } - local coordinate system that specify a solid position.\n +*/ +//--- +struct GCM_g_record +{ + GCM_g_type type; ///< \ru Тип геометрии. \en Type of geometric object. + GCM_point origin; ///< \ru Точка позиционирования геометрического объекта. \en Location of a geometric object. + GCM_vec3d axisZ; ///< \ru Направляющий вектор прямой или вектор нормали плоскости. \en Direction of line, normal of plane, Z-axis of a local coordinate frame. + GCM_vec3d axisX; ///< \ru Ось X локальной системы координат. \en X-axis of local coordinate frame . + GCM_vec3d axisY; ///< \ru Ось Y локальной системы координат. \en Y-axis of local coordinate frame. + double radiusA; ///< \ru Радиус окружности, сферы или цилиндра либо радиус основания конуса, "большой" радиус тора. \en Radius of circle, sphere and cylinder or major radius of cone and torus. + double radiusB; ///< \ru "Малый" радиус тора или конуса. \en Minor radius of cone and torus. +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Дополнительный параметр для функций типа #GCM_dependent_func. + \en Additional parameter for functions of type #GCM_dependent_func. \~ + \sa #GCM_dependent_geom_func, #GCM_dependent_func +*/ +//--- +struct GCM_extra_param +{ + size_t funcId; // integral identifier of a user-defined callback + void * funcData; // pointer to an application data structure + GCM_extra_param() { funcId = 0, funcData = 0; } +}; + +//---------------------------------------------------------------------------------------- +// The function calculates position of a dependent geom regarding to other independent geoms. +/* + Note: The dependent geom is first element of argument list inGeoms, and others are independent. + argNb Number of arguments of dependency constraint, equals to size of inGeoms. + g1 = f( g2 g3 ... gn ); +*/ +//--- +typedef bool (*GCM_dependent_func) ( MbPlacement3D gPlaces[] + , size_t gPlacesSize + , GCM_extra_param exPar ); + +//---------------------------------------------------------------------------------------- +/// \~ Alternative typename of #GCM_dependent_func +//--- +typedef GCM_dependent_func GCM_dependent_geom_func; + +/** \} */ // GCM_3D_API + +//---------------------------------------------------------------------------------------- +// Argument of constraint to record in type 'GCM_c_record' +//-- +struct GCM_c_arg +{ + union + { + GCM_object geom; // Geometric object. + GCM_alignment alignVal; // Variant of alignment. + GCM_tan_choice tanChoice; // Option for tangency constraint only. + GCM_angle_type angType; // Option for angular constraint only. + GCM_scale scale; // Option for pattern constraint only. + double dimValue; // Numeric value of a dimension. + int enumVal; + }; + GCM_c_arg & operator = ( double val ) + { + dimValue = val; + return *this; + } + template + GCM_c_arg & operator = ( const _Enum & val ) + { + enumVal = static_cast( val ); + return *this; + } + GCM_c_arg & operator = ( const GCM_geom & gId ) + { + geom = gId; + return *this; + } + GCM_c_arg() { dimValue = 0.0; } +}; + +//---------------------------------------------------------------------------------------- +/** \brief \en Structure of geometric constraint record. + \ru Структура записи геометрического ограничения. \~ +*/ +/* + The argument tuples of each constraint type: + { GCM_c_type GCM_c_arg ... GCM_c_arg } + -------------------|------------------------------- + { GCM_COINCIDENT GCM_geom GCM_geom GCM_alignment } + { GCM_CONCENTRIC GCM_geom GCM_geom GCM_alignment } + { GCM_PARALLEL GCM_geom GCM_geom GCM_alignment } + { GCM_PERPENDICULAR GCM_geom GCM_geom GCM_alignment } + { GCM_IN_PLACE GCM_geom GCM_geom GCM_NO_ALIGNMENT } + { GCM_DISTANCE GCM_geom GCM_geom double GCM_alignment } + { GCM_TANGENT GCM_geom GCM_geom GCM_alignment GCM_tan_choice } + { GCM_ANGLE GCM_geom GCM_geom GCM_geom double GCM_alignment } - planar kind of angle + { GCM_ANGLE GCM_geom GCM_geom GCM_NULL double GCM_alignment } - 3d kind of angle + { GCM_SYMMETRIC GCM_geom GCM_geom GCM_geom GCM_alignment } + { 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_TRANSMITTION not specified } + { GCM_CAM_MECHANISM not specified } + { GCM_RADIUS GCM_geom double } + { GCM_UNKNOWN } + Sample of the journal line: (GCM_AddConstraint (GCM_COINCIDENT #1 #2 GCM_CLOSEST) #3) +*/ +struct GCM_c_record +{ + static const size_t argsN = 5; + GCM_c_type type; // \ru Тип ограничения. \en Type of constraint. + GCM_c_arg args[argsN]; // \ru Аргументы ограничения. \en Arguments of constraint. +}; + +#if ( GCM_ID_TYPE == 1 ) + +inline bool operator == ( const MtObjectId & f, const MtObjectId & s ) { return f.id == s.id; } +inline bool operator != ( const MtObjectId & f, const MtObjectId & s ) { return f.id != s.id; } +inline bool operator < ( const MtObjectId & f, const MtObjectId & s ) { return f.id < s.id; } +inline uint32 & _id( MtObjectId & obj ) { return obj.id; } +inline const uint32 & _id( const MtObjectId & obj ) { return obj.id; } + +#else // GCM_ID_TYPE + +inline uint32 & _id( MtObjectId & obj ) { return obj; } +inline const uint32 & _id( const MtObjectId & obj ) { return obj; } + +#endif // GCM_ID_TYPE + +typedef GCM_alignment MtAlignType; +typedef GCM_g_type MtGeometryType; +typedef GCM_result MtResultCode3D; + +/* + The constants below are deprecated (2015, Kompas does not use them, 02.12.2020) +*/ + +static const GCM_alignment GCM_NOT_ORIENTED = GCM_NO_ALIGNMENT; +static const GCM_alignment GCM_Opposite = GCM_OPPOSITE; +static const GCM_alignment GCM_Closest = GCM_CLOSEST; +static const GCM_alignment GCM_Cooriented = GCM_COORIENTED; +static const GCM_alignment GCM_None = GCM_NO_ALIGNMENT; +static const GCM_alignment GCM_Min = GCM_MIN_ALIGNMENT; +static const GCM_alignment GCM_Max = GCM_MAX_ALIGNMENT; + +/* + The constants below are deprecated (2015) +*/ + +static const GCM_g_type GCM_FIRST_GTYPE = GCM_NULL_GTYPE; +static const GCM_g_type mgt_Cylinder = GCM_CYLINDER; +static const GCM_c_type mct_Coincidence = GCM_COINCIDENT; +static const GCM_c_type mct_Parallel = GCM_PARALLEL; +static const GCM_c_type mct_Perpendicular = GCM_PERPENDICULAR; +static const GCM_c_type mct_Tangency = GCM_TANGENT; +static const GCM_c_type mct_Concentric = GCM_CONCENTRIC; +static const GCM_c_type mct_Distance = GCM_DISTANCE; +static const GCM_c_type mct_Angle = GCM_ANGLE; +static const GCM_c_type mct_InPlace = GCM_IN_PLACE; +static const GCM_c_type mct_Unknown = GCM_UNKNOWN; +static const GCM_c_type mct_CamMechanism = GCM_CAM_MECHANISM; +static const GCM_c_type mct_Symmetry = GCM_SYMMETRIC; +static const GCM_c_type mct_Symmetric = GCM_SYMMETRIC; +static const GCM_c_type mct_Parallelism = GCM_PARALLEL; + +static const GCM_result mtResCode_None = GCM_RESULT_None; +static const GCM_result mtResCode_Ok = GCM_RESULT_Ok; +static const GCM_result mtResCode_SystemError = GCM_RESULT_Error; +static const GCM_result mtResCode_Error = GCM_RESULT_Error; +static const GCM_result mtResCode_MovingOfFixedGeom = GCM_RESULT_DraggingFailed; +static const GCM_result mtResCode_InvalidAxisOfPlanarAngle = GCM_RESULT_InconsistentPlanarAngle; +static const GCM_result mtResCode_CyclicDependence = GCM_RESULT_CyclicDependence; +static const GCM_result mtResCode_InvalidDependenceForOutGeom = GCM_RESULT_MultiDependedGeom; +static const GCM_result mtResCode_InvalidDependenceForOutGeoms = GCM_RESULT_OverconstrainingDependedGeoms; // (2018) +static const GCM_result mtResCode_InvalidDependenceForFixGeom = GCM_RESULT_DependedGeomCantBeFixed; +static const GCM_result mtResCode_InconsistentFollowerAxis = GCM_RESULT_InconsistentFollowerAxis; /* 2020 */ +static const GCM_result mtResCode_NoSeparatedSolutionForCamGear = GCM_RESULT_OverconstrainedCamMechanism; /* 2020 */ +const GCM_dependency GCM_2ST_DEPENDENT = GCM_2ND_DEPENDENT; + +/* + Deprecated names of a dynamic reposition modes (2019) +*/ +const GCM_reposition rep_FreeRotation = GCM_REPOSITION_FreeRotation; +const GCM_reposition rep_FreeMoving = GCM_REPOSITION_FreeMoving; +const GCM_reposition rep_MovingToPoint = GCM_REPOSITION_Dragging; +const GCM_reposition rep_RotationAboutAxis = GCM_REPOSITION_Rotation; +const GCM_reposition rep_TransferOneGeomOnly = GCM_REPOSITION_Transfer; + + +#endif + +// eof diff --git a/C3d/Include/generic_utility.h b/C3d/Include/generic_utility.h index 1f5712b..14b83d0 100644 --- a/C3d/Include/generic_utility.h +++ b/C3d/Include/generic_utility.h @@ -1,1193 +1,1193 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Шаблонные утилиты. - \en Template utilities. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __GENERIC_UTILITY_H -#define __GENERIC_UTILITY_H - -#include -// -#include -// -#include -#include - -#include -#include -#include -#include - -//---------------------------------------------------------------------------------------- -/// \ru Пустой тип данных. \en Empty data type. -//--- -struct null_type -{ - static const null_type value() { return null_type(); } -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Шаблон для получения индексного типа (для статического сопоставления типов на этапе компиляции) - \en Template to generate an indexed type (for static type-matching in compile-time) -*/ -//--- -template -struct index_tag -{ - index_tag() {} // Constructor under GCC compiler -}; - -//---------------------------------------------------------------------------------------- -/// \ru Цветовая маркировка (применяется для графов) \en Color marking (used for graphs) -//--- -enum color_code -{ - white_color=0 - , black_color=1 - , red_color=2 - , gray_color - , green_color - , orange_color - , visited_color -}; - -//---------------------------------------------------------------------------------------- -// Constant valued function -//--- -template -bool boolFunc() { return boolVal; } - -/* -//---------------------------------------------------------------------------------------- -/// \ru Цветовая маркировка, например, для графовых объектов \en Color marking, for example: for graph objects -//--- -template -struct color_traits -{ - static color_code white() { return white_color; } - static color_code gray() { return gray_color; } - static color_code green() { return green_color; } - static color_code red() { return red_color; } - static color_code black() { return black_color; } -}; - -template<> -struct color_traits -{ - static char white() { return 0; } - static char gray() { return 1; } - static char green() { return 2; } - static char red() { return 3; } - static char black() { return 4; } -}; -*/ - -//---------------------------------------------------------------------------------------- -/// \ru Графовые характеристики типов. \en Graph datatype traits. -//--- -template< class Graph > -struct graph_traits -{ - /* - Ассоциативные типы данных концепции графа. - Associative datatypes of the graph concept. - */ - typedef typename Graph::vertex vertex; // Тип, интерпретируемый, как вершина графа. - typedef typename Graph::edge edge; // Тип, интерпретируемый, как ребро графа - typedef typename Graph::vertex_iterator vertex_iterator; // Обход всех вершин графа - typedef typename Graph::adjacency_iterator adjacency_iterator; // Обход смежных вершин некоторой вершины - typedef typename Graph::vertices_size_t vertices_size_t; // Целочисленный тип размера графа - typedef typename Graph::degree_size_t degree_size_t; // Целочисленный тип вершинной степени - typedef typename Graph::edge_iterator edge_iterator; // Итератор обхода исходящих ребер [или неориентированных ребер] -}; - -//---------------------------------------------------------------------------------------- -/// \ru Пара ссылок. \en A pair of references. -//--- -template -struct ref_pair -{ - _Ty1 & first; - _Ty2 & second; - - ref_pair( _Ty1 & val1, _Ty2 & val2 ) - : first(val1), second(val2) - {} - ref_pair( const ref_pair & other ) - : first(other.first), second(other.second) - {} - - template - ref_pair( const std::pair<_Other1, _Other2> & right ) - : first(right.first), second(right.second) - {} - - template - ref_pair & operator = ( const std::pair<_Other1, _Other2> & right ) - { - first = right.first; - second = right.second; - return *this; - } - -private: - ref_pair & operator = ( const ref_pair & ); // \ru не реализуемо \en not implemented -}; - -//---------------------------------------------------------------------------------------- -/// \ru Выдать ссылки одной связкой. \en Get references as one bunch. -//--- -template -inline ref_pair -tie( Type & iter1, Type & iter2 ) -{ - return ref_pair ( iter1, iter2 ); -} - -//---------------------------------------------------------------------------------------- -/// \ru Наибольшее из двух. \en Maximum of two. -// --- -template -inline const T & max_of( const T & elem1, const T & elem2 ) -{ - if ( elem2 < elem1 ) - return elem1; - return elem2; -} - -//---------------------------------------------------------------------------------------- -/// \ru Наибольшее из двух. \en Maximum of two. -// --- -template -inline const T & min_of( const T & elem1, const T & elem2 ) -{ - if ( elem1 < elem2 ) - return elem1; - return elem2; -} - -//---------------------------------------------------------------------------------------- -/// \ru Поменять местами значения. \en Swap the values. -// --- -template -inline void swap_vals( T & elem1, T & elem2 ) -{ - T tmp = elem1; - elem1 = elem2; - elem2 = tmp; -} - -//---------------------------------------------------------------------------------------- -/// \ru Поменять местами значения указателей. \en Swap the values of pointers. -// --- -template -inline void swap_ptrs( T* & elem1, T* & elem2 ) -{ - T * tmp = elem1; - elem1 = elem2; - elem2 = tmp; -} - -//---------------------------------------------------------------------------------------- -/// \ru Поменять местами значения указателей. \en Swap the values of pointers. -//--- -template -inline void swap_ptrs( SPtr & p1, SPtr & p2 ) -{ - SPtr t = p1; - p1 = p2; - p2 = t; -} - -//---------------------------------------------------------------------------------------- -// \ru Равенство пары указателей \en Equality of pointer pair -//--- -template< class Type1, class Type2 > -bool equal_ptrs( const Type1 * ptr1, const Type2 * ptr2 ) -{ - return static_cast(ptr1) == ptr2; -} - -//---------------------------------------------------------------------------------------- -// \ru Равенство пары указателей \en Equality of pointer pair -//--- -template< class Type1, class Type2 > -bool equal_ptrs( SPtr ptr1, const Type2 * ptr2 ) -{ - return static_cast(ptr1.get()) == ptr2; -} - -//---------------------------------------------------------------------------------------- -// \ru Равенство пары двухмерных векторов или точек \en Equality of 2D points or vectors -//--- -template< class XY1, class XY2 > -bool equal_xy( const XY1 & v1, const XY2 & v2, double eps ) -{ - if ( fabs(v1.x-v2.x) > eps ) - return false; - if ( fabs(v1.y-v2.y) > eps ) - return false; - return true; -} - -//---------------------------------------------------------------------------------------- -// \ru Наименьший общий делитель \en The lowest common denominator -// --- -template < typename Integer > -Integer euclid_algo ( Integer a, Integer b ) -{ - Integer const zero = static_cast( 0 ); - - bool goOn = true; - while ( goOn ) - { - if ( a == zero ) { - goOn = false; - return b; - } - - b %= a; - - if ( b == zero ) { - goOn = false; - return a; - } - - a %= b; - } - return zero; -} - -//---------------------------------------------------------------------------------------- -/// \ru Получить НОД для пары целых чисел \en Get GCD for a pair of integers -// --- -template < typename IntegerType > -inline IntegerType gcd( IntegerType a, IntegerType b ) -{ - IntegerType const zero = static_cast( 0 ); - IntegerType const result = ::euclid_algo( a, b ); - return ( result < zero ) ? -result : result; -} - - -//---------------------------------------------------------------------------------------- -// \ru Функциональный объект - коллектор \en The functional object - collector -/*\ru Играет роль посетителя foreach-алгоритмов, осуществляющий накачку STL-совместимых контейнеров - \en Serves as a visitor of foreach-algorithms exercising pumping of STL-compatible containers \~ -*/ -//--- -template -struct collector -{ - typedef typename _Cont::value_type value_type; - _Cont & container; // \ru STL-совместимый контейнер \en STL-compatible container - - collector( _Cont & arr ) - : container( arr ) {} - collector( const collector & c ) : container( c.container ) {} - void operator () ( const value_type & elem ) const - { - container.push_back( elem ); - } - -private: // \ru не реализовано \en not implemented - collector & operator = ( const collector & ); -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Статический вектор. - \en Static vector. - \note \ru Требуется, что бы элементы вектора имели конструктор по умолчанию, - конструктор копирования и оператор присвоения. - \en Required that the vector elements have a default constructor, - copy constructor and assignment operator. \~ -*/ -//--- -template -class static_array -{ -public: - typedef Elem value_type; // \ru ассоциативный тип элемента массива \en associative type of array element - -private: - value_type arr[arrSize]; // \ru статическое выделение памяти под массив \en static allocation for the array - -public: - /// \ru Инициализация одним элементом. \en Initialization of one element. - explicit static_array( const Elem & val ) - { - fill( val ); - } - /// \ru Инициализация парой элементов. \en Initialization of a pair of elements. - static_array( const Elem & e1, const Elem & e2 ) - { - PRECONDITION( arrSize == 2 ); - arr[0] = e1; - arr[1] = e2; - } - /// \ru Конструктор по тройке. \en Constructs as a triplet. - static_array( const Elem & e1, const Elem & e2, const Elem & e3 ) - { - PRECONDITION( arrSize == 3 ); - arr[0] = e1; - arr[1] = e2; - arr[2] = e3; - } - explicit static_array( const static_array & vec ) - { - _Assign( vec ); - } - - template - static_array( const _Vector & vec ) - { - _Assign( vec ); - } - - /// \ru Инициализация одним элементом. \en Initialization of one element. - static_array & fill( const Elem & val ) - { - for( size_t idx = 0; idx - static_array & assign( _Iter iter, _Iter last ) - { - for ( value_type * myIter = arr ; iter!=last; ++iter, ++myIter ) - { - PRECONDITION( myIter < arr+arrSize ); - *myIter = *iter; - } - return *this; - } - - inline value_type & operator[] ( size_t idx ) - { - PRECONDITION( idx < arrSize ); - return arr[idx]; - } - inline const value_type & operator[] ( size_t idx ) const - { - PRECONDITION( idx < arrSize ); - return arr[idx]; - } - template - static_array & operator = ( const _Vector & vec ) - { - _Assign( vec ); - return *this; - } - - inline const Elem * c_arr() const { return arr; } - inline Elem * c_arr() { return arr; } - inline size_t size() const { return arrSize; } - inline value_type & front() { return *arr; } - inline value_type & back() { PRECONDITION(arrSize>0); return arr[arrSize-1]; } - inline const value_type & front() const { return *arr; } - inline const value_type & back() const { PRECONDITION(arrSize>0); return arr[arrSize-1]; } - -private: - template< class _Vector > - void _Assign( const _Vector & vec ) - { - PRECONDITION( vec.size() == size() ); - for ( size_t idx = ::min_of( arrSize, vec.size() ); idx > 0; ) - { - idx--; - arr[idx] = vec[idx]; - } - } -}; - -// \ru (!) Запретить пустые статические массивы \en (!) Prevent empty static arrays -template class static_array {}; - -//---------------------------------------------------------------------------------------- -/// \ru Статический вектор двух элементов (пара). \en Static vector of two elements (pair). -//--- -template -struct static_pair: public static_array -{ - typedef static_array parent_type; - // static_pair(): parent_type() {} - explicit static_pair( const Elem & el ): parent_type( el ) {} - static_pair( const Elem & el1, const Elem & el2 ): parent_type( el1, el2 ) {} - explicit static_pair( const static_pair & pair ) : parent_type( pair ) {} - - static_pair & operator = ( const static_pair & vec ) - { - parent_type::operator=( vec ); - return *this; - } -}; - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Динамический контейнер для хранения элементов упорядоченного множества. - \en Dynamic container for storing elements of an ordered set. - - \details - \ru Тип элемента контейнера должен иметь операторы порядка. Не стоит путать этот - тип контейнера с set или map. Он вовсе не обязан всегда поддерживаться в отсортированном - состоянии, а только тогда, когда это закажут (с кэшированием алгоритма сортировки). - Гарантируется, что вектор отсортирован сразу после вызова функций get_sorted или sort. - Константные методы, а также метод erase не нарушают сортировки.\n - \en Type of container element must have order operators. Do not confuse this - type of container with a set or map. It is not obliged always be supported in a sorted - state, and only when it is needed (with caching of sorting algorithm). It is guaranteed - that the vector is sorted immediately after the function call get_sorted or sort. - Const methods and the erase method does not break sorting. \n \~ - - \par \ru Про эффективность - - Часто сортированный вектор оказывается более эффективным, чем std::map или std::set, - особенно если добавление/удаление элементов массива осуществляется серийно и достаточно - редко перемежаются, с запросами быстрого (бинарного) поиска элемента или его места по - порядку. В отличие от map или set минимально дефрагментируется память и не требуется - избыточной информации для хранения указателей (может занимать в 4 раза меньше памяти). - Для быстрых запросов можно применять стандартные алгоритмы, такие - как std::binary_search, std::lower_bound и т.п. - - \en About efficiency - - Often sorted vector is more effective than - std::map or std::set especially when adding/removing elements - of the array is standard and is rarely interspersed - with queries quickly (binary) search of element or its place by - the order. In contrast to the map or set minimal defragmented - memory and does not require excess information for storage of pointers - (can occupy memory in less than 4 times). - For fast queries, can use standard algorithms such - as std::binary_search, std::lower_bound etc. \~ -*/ -//--- -template > // \ru KeyType - тип элемента с операторами порядка "<" \en KeyType - the element type with the operators of order "<" -class sorting_array -{ -public: - typedef std::vector container_type; - typedef typename container_type::value_type value_type; - typedef typename container_type::size_type size_type; - typedef typename container_type::const_iterator iterator; - typedef typename container_type::iterator _iterator; - typedef std::pair iter_range; - typedef _Pr key_compare; // \ru отношение порядка (предикат) \en order relation (predicate) - -public: - sorting_array() : m_vector(), m_sorted( true ) {} - -public: - iter_range get_sorted() { sort(); return iter_range(m_vector.begin(), m_vector.end()); } - iter_range range() const { return iter_range(m_vector.begin(), m_vector.end()); } - const KeyType & sorted_back() { sort(); return m_vector.back(); } - bool empty() const { return m_vector.empty(); } - iterator begin() const { return m_vector.begin(); } - iterator end() const { return m_vector.end(); } - _iterator _begin() { return m_vector.begin(); } - _iterator _end() { return m_vector.end(); } - const KeyType & front() const { return m_vector.front(); } - const KeyType & back() const { return m_vector.back(); } - void erase( iterator ); - void erase( iterator f, iterator l ); - bool is_sorted() const { return m_sorted; } - iterator insert( iterator _whereItr, const KeyType & val ); // \ru вставить элемент перед позицией whereItr \en insert element before position whereItr - template - void insert( iterator position, InputIterator first, InputIterator last ) - { - m_vector.insert( position, first, last ); - m_sorted = false; - } - template - void assign ( InputIterator first, InputIterator last ) - { - m_vector.assign( first, last ); - m_sorted = false; - } - void resize( size_t n, const KeyType & val ); - void reserve ( size_t n ) { m_vector.reserve( n ); } - void push_back( const KeyType & val ); - void sort() - { - if ( !m_sorted ) - { - std::sort( m_vector.begin(), m_vector.end(), _Pr() ); - m_sorted = true; - } - } - void clear() { m_vector.clear(); } - size_t size() const { return m_vector.size(); } - KeyType & operator[] ( size_t n ) { PRECONDITION( n < m_vector.size() ); return m_vector[n]; } - const KeyType & operator[] ( size_t n ) const { PRECONDITION( n < m_vector.size() ); return m_vector[n]; } - -private: - container_type m_vector; - bool m_sorted; - -private: - sorting_array( const sorting_array & ); // \ru реализовать по необходимости \en implement if necessary - sorting_array & operator = ( const sorting_array & ); // \ru реализовать по необходимости \en implement if necessary -}; - -//---------------------------------------------------------------------------------------- -// -// --- -template -void sorting_array::push_back( const KeyType & val ) -{ - m_sorted = m_vector.empty() ? true : m_sorted && _Pr()( m_vector.back(), val ); - m_vector.push_back( val ); -} - -//---------------------------------------------------------------------------------------- -// -//--- -template -void sorting_array::erase( iterator ersItr ) -{ - m_vector.erase( m_vector.begin() + (ersItr - begin()) ); -} - -//---------------------------------------------------------------------------------------- -// -//--- -template -void sorting_array::erase( iterator f, iterator l ) -{ - typename container_type::iterator first, last; - first = last = m_vector.begin(); - std::advance( first, std::distance(begin(),f) ); // convert from const-iterator to non-const - std::advance( last, std::distance(begin(),l) ); - m_vector.erase( first, last ); -} - -//---------------------------------------------------------------------------------------- -// \ru Вставить элемент перед позицией whereItr \en Insert element before position whereItr -//--- -template -typename sorting_array::iterator -sorting_array::insert( iterator _whereItr, const KeyType & val ) -{ - typename container_type::iterator whereItr = m_vector.begin(); - std::advance( whereItr, std::distance(begin(),_whereItr) ); // \ru перевод из конст-итератора в неконст \en convert from const-iterator to non-const - // \ru Далее проверяем не нарушает ли новая вставка упорядоченности массива \en Next, whether new insert does not break ordering of the array - if ( m_sorted && (_whereItr != m_vector.end()) ) - { - m_sorted = ! key_compare()( *_whereItr, val ); - if ( m_sorted ) // val <= _where - { - m_sorted = ( _whereItr == m_vector.begin() ) || !key_compare()( val, *(--_whereItr) ); - } - } - - // \ru Вставка \en Insert - return m_vector.insert( whereItr, val ); -} - -//---------------------------------------------------------------------------------------- -// -//--- -template -void sorting_array::resize( size_t n, const KeyType & val ) -{ - if ( m_sorted && (m_vector.size() < n) && !m_vector.empty() ) - { - m_sorted = !key_compare()( val, m_vector.back() ); // m_vector.back() <= val - } - - m_vector.resize( n, val ); -} - -//---------------------------------------------------------------------------------------- -/// \ru Проверка упорядоченности массива \en Check for ordering array -//--- -template -bool check_ordering( const SortedArray & arr ) -{ - if ( arr.is_sorted() && !arr.empty() ) - { - typename SortedArray::value_type prev( *arr.begin() ); - typename SortedArray::iterator first = arr.begin()+1; - typename SortedArray::iterator last = arr.end(); - for( ; first!=last; ++first ) - { - if ( (*first) < prev ) - { - return false; // \ru нарушен порядок следования \en order has been broken - } - prev = *first; - } - } - - return true; -} - -//---------------------------------------------------------------------------------------- -/// \ru Обнулить структуру данных (использовать осторожно!). \en Reset the data structure (use with caution!). -//--- -template< class DataSt > -inline DataSt null_struct() -{ - DataSt data; - ::memset( &data, 0, sizeof(DataSt) ); - return data; -} - -//---------------------------------------------------------------------------------------- -/// \ru Отладочный инспектор union-контейнера (НЕдоделан!). \en Debug Inspector of union-container (NOT completed yet!). -//--- -template -struct dbg_inspector -{ - union data_t - { - typename _PairUnion::value_type * first; - }; - data_t data; - dbg_inspector() { data.first = 0; } - void init( const _PairUnion & ) {} -}; - -//---------------------------------------------------------------------------------------- -/// \ru Хвостовой элемент для рекурсивного определения типа recursive_union. \en Tail element for recursive determination of type recursive_union. -//--- -struct empty_variant -{ - static const size_t dataSize = 0; - static const size_t power = 0; - struct value_type {}; - bool empty() { return true; } -}; - -//---------------------------------------------------------------------------------------- -/// \ru Получить номер типа из списка union-контейнера. \en Get type index from the list of union-container. -//--- -template -struct which_type -{ - static const int value = 1 + which_type::value; -}; - -// \ru Специализация 1 \en Specialization 1 -template -struct which_type<_PairUnion,typename _PairUnion::value_type> -{ - static const int value = 0; -}; - -// \ru Специализация 2 \en Specialization 2 -template -struct which_type -{ - static const int value = -1; -}; - -//---------------------------------------------------------------------------------------- -/// \ru Получить тип варианта с заданным номером. \en Get variant type with a given index. -//--- -template -struct type_which -{ - typedef typename T::tail_type tail_t; - typedef typename type_which::value_t value_t; -}; - -template -struct type_which -{ - typedef typename T::value_type value_t; -}; - -template -struct type_which -{ -private: - typedef null_type value_t; -}; - -//---------------------------------------------------------------------------------------- -/// \ru Проводник посетителя для рекурсивно-заданного контейнера. \en Conductor of visitor for recursively given container. -//--- -template -struct union_conductor -{ - typedef typename type_which<_PairUnion,typeNb>::value_t _Type; - - /// \ru Статическое приведение типа. \en Static cast of type. - template - static T * unsafe_cast( U & u ) { return u.template unsafe_cast(); } - - /// \ru Статическое приведение типа. \en Static cast of type. - template - static const T * unsafe_cast( const U & u ) { return u.template unsafe_cast(); } - - /// \ru Применить функтор. \en Apply the functor. - template - static inline void apply( const _Visitor & vis, _PairUnion & oper ) - { - if ( oper.which() == typeNb ) - { - vis( *unsafe_cast<_PairUnion,_Type>(oper) ); - } - else - { - union_conductor<_PairUnion,typeNb+1,power>::apply( vis, oper ); - } - } -}; - -//---------------------------------------------------------------------------------------- -// \ru Вызвать деструктор для указателя, если его тип попадает в диапазон от t до power. \en Call the destructor for the pointer if its type is within the range from t to power. -//--- -template -struct union_conductor<_PairUnion,power,power> -{ - template - static inline void apply( const _Visitor & , _PairUnion & ) {} -}; - -//---------------------------------------------------------------------------------------- -/** - \brief \ru Рекурсивное определение класса "union-контейнер". - \en Recursive definition of class "union-container". - \details \ru Контейнер, который может хранить элемент типа "value_type" или один из типов - хвостового контейнера. - \en Container which can store the element of type "value_type" or one of types - of tail container. \~ -*/ -//--- -template -class recursive_union -{ - typedef recursive_union _Myt; - -public: // \ru доступные ассоциативные типы и константы \en available associative types and constants - static const size_t dataSize = sizeof(Type) > Tail::dataSize ? sizeof(Type) : Tail::dataSize; - static const size_t power = 1 + Tail::power; // \ru Количество типов, которое может обеспечить вариант \en The count of types which can provide a variant - - typedef Type value_type; - typedef Tail tail_type; - -public: - recursive_union() : m_typeNb(-1) { ::memset(m_data, 0, dataSize); } - recursive_union( const Type & ); - -#ifndef __DEBUG_MEMORY_ALLOCATE_FREE_ - template - recursive_union( const _Type & elem ) - : m_typeNb( which_type<_Myt,_Type>::value ) - , dbg_data() - { - if ( m_typeNb >= 0 ) - { - new ( (void*)m_data ) _Type( elem ); - } - } -#else // __DEBUG_MEMORY_ALLOCATE_FREE_ - template - recursive_union( const _Type & ) - : m_typeNb( which_type<_Myt,_Type>::value ) - , dbg_data() - { - // (!) The placement form of operator new is required. - C3D_ASSERT_UNCONDITIONAL( false ); - } -#endif //__DEBUG_MEMORY_ALLOCATE_FREE_ - - ~recursive_union(); - -private: // \ru вспомогательные объекты \en assisting objects - // \ru Посетитель для вызова конструктора типа, которым занят union-контейнер \en The visitor to call the type constructor which is occupied by union-container - struct assigner - { - assigner( _Myt & d ) : lOper(&d) {} - - template - void operator() ( const _Type & elem ) const - { - C3D_ASSERT( lOper ); - *lOper = elem; - } - private: - mutable _Myt * lOper; // \ru Левый операнд присвоения \en The left operand of assignment - - private: - assigner & operator = ( const assigner & ); - }; - - // \ru Посетитель для вызова деcтруктора типа, которым занят union-контейнер \en The visitor to call the type destructor which is occupied by union-container - struct destroyer - { - template - static void ignore(const _Type & ) {} // \ru для подавления сообщений \en for suppression of messages - - template - void operator() (const _Type & elem ) const - { - ignore( elem ); - elem.~_Type(); - } - }; - - // \ru Проверка на равенство \en The check for equality - struct comparer - { - const _Myt & data; - mutable bool result; - comparer( const _Myt & d ) : data( d ), result(false) {} - template - void operator() ( const _Type & elem ) const - { - result = (data == elem); - } - private: - comparer & operator = ( const comparer & ); - }; - - struct conductor: public union_conductor<_Myt,0,power> {}; - struct const_conductor: public union_conductor {}; - -public: - int which() const { return m_typeNb; } - // \ru Проверить пустой ли контейнер \en Check whether the container is empty - bool empty() const { return m_typeNb < 0; } - - // \ru Безопасное динамическое приведение типа \en Secure dynamic cast of type - template - _Type * safe_cast() - { - if ( which_type<_Myt,_Type>::value == m_typeNb ) - { - return (_Type*)m_data; - } - return 0; - } - // \ru Безопасное динамическое приведение типа \en Secure dynamic cast of type - template - const _Type * safe_cast() const - { - if ( which_type<_Myt,_Type>::value == m_typeNb ) - { - return (const _Type*)m_data; - } - return 0; - } - - // \ru Статическое приведение типа \en Static cast of type - template - _Type * unsafe_cast() - { - assert( (which_type<_Myt,_Type>::value == m_typeNb) ); - return (_Type*)m_data; - } - - // \ru Статическое приведение типа \en Static cast of type - /* - template typename type_which<_Myt,_typeNb>::value_t & - unsafe_get(); - */ - /* - { - assert( (which_type<_Myt,_Type>::value == m_typeNb) ); - return (type_which<_Myt,_typeNb>::value_t*)m_data; - } - */ - - // \ru Статическое приведение типа \en Static cast of type - template - const _Type * unsafe_cast() const - { - assert( (which_type<_Myt,_Type>::value == m_typeNb) ); - return reinterpret_cast( m_data ); - } - - void release() - { - accept( destroyer() ); - m_typeNb = -1; - } - /* - template - void release() - { - if ( which_type<_Myt,_Type>::value == m_typeNb ) - { - ((_Type*)m_data)->~_Type(); - m_typeNb = -1; - } - } - */ - - // \ru Присвоение другого union-контейнера \en Assignment of another union-container - _Myt & operator = ( const _Myt & v ) - { - release(); - v.accept( assigner(*this) ); - C3D_ASSERT( m_typeNb == v.m_typeNb ); - return *this; - } - - // \ru Присвоение произвольного типа \en Assignment of arbitrary type - /* - template - _Myt & operator = ( const _Type & elem ) - { - m_typeNb = which_type<_Myt,_Type>::value; - if ( m_typeNb >= 0 ) - { - new ( (void*)m_data ) _Type( elem ); - } - return *this; - } - */ - - // \ru Равенство \en Equality - bool operator == ( const _Myt & v ) const - { - if ( m_typeNb == v.m_typeNb ) - { - comparer cmp( *this ); - v.accept( cmp ); - return cmp.result; - } - return false; - } - - // \ru Равенство \en Equality - template - bool operator == ( const _Type & elem ) const - { - if ( m_typeNb == which_type<_Myt,_Type>::value ) - { - return elem == *unsafe_cast<_Type>(); - } - return false; - } - - // \ru Доступ посетителя \en Visitor access - template - void accept( const _Visitor & vis ) const - { - const_conductor::apply( vis, *this ); - } - // \ru Доступ посетителя \en Visitor access - template - void accept( const _Visitor & vis ) - { - conductor::apply( vis, *this ); - } - -private: // \ru данные \en data - char m_data[dataSize]; - int m_typeNb; - dbg_inspector<_Myt> dbg_data; -}; - -//---------------------------------------------------------------------------------------- -// -//--- -template -recursive_union::recursive_union( const Type & elem ) - : m_typeNb( 0 ) - , dbg_data() -{ - dbg_data.init( *this ); - new ( (void*)m_data ) Type( elem ); -} - -//---------------------------------------------------------------------------------------- -// -//--- -template -recursive_union::~recursive_union() -{ - release(); -} - -template -struct def_pair_union // \ru определитель рекурсивного контейнера для пары типов \en determinant of a recursive container for a pair of types -{ - typedef recursive_union value_t; -}; -template -struct def_pair_union -{ - typedef recursive_union value_t; -}; -template<> -struct def_pair_union -{ - typedef empty_variant value_t; -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru union-контейнер для экземпляра типа из определенного набора типов. - \en union-container for instance of type from a specific set of types. - \details \ru Позволяет создать тип, принимающий значения из некоторого набора разнородных - типов. - \en Allows to create a type which takes values ??from a set of heterogeneous - types. \~ -*/ -//--- -template< - class T0 - , class T1 - , class T2 = null_type - , class T3 = null_type - , class T4 = null_type - , class T5 = null_type> -class aligned_union -{ - typedef empty_variant _Tail6; - typedef typename def_pair_union::value_t _Tail5; - typedef typename def_pair_union::value_t _Tail4; - typedef typename def_pair_union::value_t _Tail3; - typedef typename def_pair_union::value_t _Tail2; - typedef typename def_pair_union::value_t _Tail1; - typedef typename def_pair_union::value_t _Variant; - - typedef aligned_union _Myt; - -public: - aligned_union(): m_data() {} - template - aligned_union( const T & elem ) : m_data( elem ) {} - -public: - /// \ru Выдать номер текущего типа, которым занят контейнер \en Get a index of the current type which is occupied container - int which() const { return m_data.which(); } - /// \ru Проверить пустой ли контейнер \en Check whether the container is empty - bool empty() const { return m_data.empty(); } - /// \ru Применить функтор (посетитель) \en Apply the functor (visitor) - template - void accept( const _Vis & vis ) const { m_data.accept( vis ); } - /// \ru Применить функтор (посетитель) \en Apply the functor (visitor) - template - void accept( const _Vis & vis ) { m_data.accept( vis ); } - /// \ru Сделать контейнер пустым \en Make an empty container - void clear() { m_data.release(); } - /// \ru Операция присвоения \en Assignment operation - _Myt & operator = ( const _Myt & elem ) { m_data = elem.m_data; return *this; } - template - _Myt & operator = ( const T & elem ) { m_data = elem; return *this; } - // \ru Операция сравнения \en Compare operation - bool operator == ( const _Myt & elem ) const { return m_data == elem.m_data; } - template - bool operator == ( const T & elem ) const { return m_data == elem; } - /// \ru Безопасно преобразовать тип контейнера к указателю \en Safely convert type of container to a pointer - template - T * safe_cast() { return m_data.template safe_cast(); } - template - const T * safe_cast() const { return m_data.template safe_cast(); } - template - bool get( T & val ) const - { - if ( const T * ptr = m_data.template safe_cast() ) - { - val = *ptr; - return true; - } - return false; - } - -private: - _Variant m_data; -}; - -//---------------------------------------------------------------------------------------- -// -// --- -template -bool is_exist( _Iterator begIt, _Iterator endIt, const _Element & elem ) -{ - return std::find( begIt, endIt, elem ) != endIt; -} - -//---------------------------------------------------------------------------------------- -// -// --- -template -bool is_exist_if( _Iterator begIt, _Iterator endIt, _UnaryPredicate _Pred ) -{ - return std::find_if( begIt, endIt, _Pred ) != endIt; -} - -namespace c3d -{ - struct color_label - { - color_code val; - color_label() : val( white_color ) {} - bool operator == ( color_code col ) const { return col == val; } - color_label & operator = ( color_code col ) { val = col; return *this; } - }; - -//---------------------------------------------------------------------------------------- -// -//--- -template -struct _IterTraits { - typedef typename Iterator::value_type value_type; -}; - -template -struct _IterTraits { - typedef T value_type; -}; - -//---------------------------------------------------------------------------------------- -// Диапазон итераторов -//--- -template -struct range : public std::pair -{ - typedef std::pair _Pair; - typedef typename _IterTraits::value_type value_type; - - range( const Iterator & iter, const Iterator & last ) :_Pair( iter, last ) {} - range( const _Pair & other ) :_Pair( other ) {} - range() :_Pair() {} - Iterator begin() const { return _Pair::first; } - Iterator end() const { return _Pair::second; } - bool empty() const { return _Pair::first == _Pair::second; } - size_t size() const { return (size_t)std::distance( _Pair::first, _Pair::second ); } - void clear() { _Pair::first = _Pair::second; } - range & move_front() { ++_Pair::first; return *this; } - - const value_type & front() const { return (*begin()); } - const value_type & back() const { return (*(end() - 1)); } -}; - -//---------------------------------------------------------------------------------------- -// Get a range of the STL-container -//--- -template -range range_of( const _Cont & list ) -{ - range rng( list.begin(), list.end() ); - return rng; -} - -//---------------------------------------------------------------------------------------- -// Get a range of iterators -//--- -template -range<_Iterator> make_range( _Iterator first, _Iterator last ) -{ - c3d::range<_Iterator> rng( first, last ); - return rng; -} - -}; - -#endif // __GENERIC_UTILITY_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Шаблонные утилиты. + \en Template utilities. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __GENERIC_UTILITY_H +#define __GENERIC_UTILITY_H + +#include +// +#include +// +#include +#include + +#include +#include +#include +#include + +//---------------------------------------------------------------------------------------- +/// \ru Пустой тип данных. \en Empty data type. +//--- +struct null_type +{ + static const null_type value() { return null_type(); } +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Шаблон для получения индексного типа (для статического сопоставления типов на этапе компиляции) + \en Template to generate an indexed type (for static type-matching in compile-time) +*/ +//--- +template +struct index_tag +{ + index_tag() {} // Constructor under GCC compiler +}; + +//---------------------------------------------------------------------------------------- +/// \ru Цветовая маркировка (применяется для графов) \en Color marking (used for graphs) +//--- +enum color_code +{ + white_color=0 + , black_color=1 + , red_color=2 + , gray_color + , green_color + , orange_color + , visited_color +}; + +//---------------------------------------------------------------------------------------- +// Constant valued function +//--- +template +bool boolFunc() { return boolVal; } + +/* +//---------------------------------------------------------------------------------------- +/// \ru Цветовая маркировка, например, для графовых объектов \en Color marking, for example: for graph objects +//--- +template +struct color_traits +{ + static color_code white() { return white_color; } + static color_code gray() { return gray_color; } + static color_code green() { return green_color; } + static color_code red() { return red_color; } + static color_code black() { return black_color; } +}; + +template<> +struct color_traits +{ + static char white() { return 0; } + static char gray() { return 1; } + static char green() { return 2; } + static char red() { return 3; } + static char black() { return 4; } +}; +*/ + +//---------------------------------------------------------------------------------------- +/// \ru Графовые характеристики типов. \en Graph datatype traits. +//--- +template< class Graph > +struct graph_traits +{ + /* + Ассоциативные типы данных концепции графа. + Associative datatypes of the graph concept. + */ + typedef typename Graph::vertex vertex; // Тип, интерпретируемый, как вершина графа. + typedef typename Graph::edge edge; // Тип, интерпретируемый, как ребро графа + typedef typename Graph::vertex_iterator vertex_iterator; // Обход всех вершин графа + typedef typename Graph::adjacency_iterator adjacency_iterator; // Обход смежных вершин некоторой вершины + typedef typename Graph::vertices_size_t vertices_size_t; // Целочисленный тип размера графа + typedef typename Graph::degree_size_t degree_size_t; // Целочисленный тип вершинной степени + typedef typename Graph::edge_iterator edge_iterator; // Итератор обхода исходящих ребер [или неориентированных ребер] +}; + +//---------------------------------------------------------------------------------------- +/// \ru Пара ссылок. \en A pair of references. +//--- +template +struct ref_pair +{ + _Ty1 & first; + _Ty2 & second; + + ref_pair( _Ty1 & val1, _Ty2 & val2 ) + : first(val1), second(val2) + {} + ref_pair( const ref_pair & other ) + : first(other.first), second(other.second) + {} + + template + ref_pair( const std::pair<_Other1, _Other2> & right ) + : first(right.first), second(right.second) + {} + + template + ref_pair & operator = ( const std::pair<_Other1, _Other2> & right ) + { + first = right.first; + second = right.second; + return *this; + } + +private: + ref_pair & operator = ( const ref_pair & ); // \ru не реализуемо \en not implemented +}; + +//---------------------------------------------------------------------------------------- +/// \ru Выдать ссылки одной связкой. \en Get references as one bunch. +//--- +template +inline ref_pair +tie( Type & iter1, Type & iter2 ) +{ + return ref_pair ( iter1, iter2 ); +} + +//---------------------------------------------------------------------------------------- +/// \ru Наибольшее из двух. \en Maximum of two. +// --- +template +inline const T & max_of( const T & elem1, const T & elem2 ) +{ + if ( elem2 < elem1 ) + return elem1; + return elem2; +} + +//---------------------------------------------------------------------------------------- +/// \ru Наибольшее из двух. \en Maximum of two. +// --- +template +inline const T & min_of( const T & elem1, const T & elem2 ) +{ + if ( elem1 < elem2 ) + return elem1; + return elem2; +} + +//---------------------------------------------------------------------------------------- +/// \ru Поменять местами значения. \en Swap the values. +// --- +template +inline void swap_vals( T & elem1, T & elem2 ) +{ + T tmp = elem1; + elem1 = elem2; + elem2 = tmp; +} + +//---------------------------------------------------------------------------------------- +/// \ru Поменять местами значения указателей. \en Swap the values of pointers. +// --- +template +inline void swap_ptrs( T* & elem1, T* & elem2 ) +{ + T * tmp = elem1; + elem1 = elem2; + elem2 = tmp; +} + +//---------------------------------------------------------------------------------------- +/// \ru Поменять местами значения указателей. \en Swap the values of pointers. +//--- +template +inline void swap_ptrs( SPtr & p1, SPtr & p2 ) +{ + SPtr t = p1; + p1 = p2; + p2 = t; +} + +//---------------------------------------------------------------------------------------- +// \ru Равенство пары указателей \en Equality of pointer pair +//--- +template< class Type1, class Type2 > +bool equal_ptrs( const Type1 * ptr1, const Type2 * ptr2 ) +{ + return static_cast(ptr1) == ptr2; +} + +//---------------------------------------------------------------------------------------- +// \ru Равенство пары указателей \en Equality of pointer pair +//--- +template< class Type1, class Type2 > +bool equal_ptrs( SPtr ptr1, const Type2 * ptr2 ) +{ + return static_cast(ptr1.get()) == ptr2; +} + +//---------------------------------------------------------------------------------------- +// \ru Равенство пары двухмерных векторов или точек \en Equality of 2D points or vectors +//--- +template< class XY1, class XY2 > +bool equal_xy( const XY1 & v1, const XY2 & v2, double eps ) +{ + if ( fabs(v1.x-v2.x) > eps ) + return false; + if ( fabs(v1.y-v2.y) > eps ) + return false; + return true; +} + +//---------------------------------------------------------------------------------------- +// \ru Наименьший общий делитель \en The lowest common denominator +// --- +template < typename Integer > +Integer euclid_algo ( Integer a, Integer b ) +{ + Integer const zero = static_cast( 0 ); + + bool goOn = true; + while ( goOn ) + { + if ( a == zero ) { + goOn = false; + return b; + } + + b %= a; + + if ( b == zero ) { + goOn = false; + return a; + } + + a %= b; + } + return zero; +} + +//---------------------------------------------------------------------------------------- +/// \ru Получить НОД для пары целых чисел \en Get GCD for a pair of integers +// --- +template < typename IntegerType > +inline IntegerType gcd( IntegerType a, IntegerType b ) +{ + IntegerType const zero = static_cast( 0 ); + IntegerType const result = ::euclid_algo( a, b ); + return ( result < zero ) ? -result : result; +} + + +//---------------------------------------------------------------------------------------- +// \ru Функциональный объект - коллектор \en The functional object - collector +/*\ru Играет роль посетителя foreach-алгоритмов, осуществляющий накачку STL-совместимых контейнеров + \en Serves as a visitor of foreach-algorithms exercising pumping of STL-compatible containers \~ +*/ +//--- +template +struct collector +{ + typedef typename _Cont::value_type value_type; + _Cont & container; // \ru STL-совместимый контейнер \en STL-compatible container + + collector( _Cont & arr ) + : container( arr ) {} + collector( const collector & c ) : container( c.container ) {} + void operator () ( const value_type & elem ) const + { + container.push_back( elem ); + } + +private: // \ru не реализовано \en not implemented + collector & operator = ( const collector & ); +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Статический вектор. + \en Static vector. + \note \ru Требуется, что бы элементы вектора имели конструктор по умолчанию, + конструктор копирования и оператор присвоения. + \en Required that the vector elements have a default constructor, + copy constructor and assignment operator. \~ +*/ +//--- +template +class static_array +{ +public: + typedef Elem value_type; // \ru ассоциативный тип элемента массива \en associative type of array element + +private: + value_type arr[arrSize]; // \ru статическое выделение памяти под массив \en static allocation for the array + +public: + /// \ru Инициализация одним элементом. \en Initialization of one element. + explicit static_array( const Elem & val ) + { + fill( val ); + } + /// \ru Инициализация парой элементов. \en Initialization of a pair of elements. + static_array( const Elem & e1, const Elem & e2 ) + { + PRECONDITION( arrSize == 2 ); + arr[0] = e1; + arr[1] = e2; + } + /// \ru Конструктор по тройке. \en Constructs as a triplet. + static_array( const Elem & e1, const Elem & e2, const Elem & e3 ) + { + PRECONDITION( arrSize == 3 ); + arr[0] = e1; + arr[1] = e2; + arr[2] = e3; + } + explicit static_array( const static_array & vec ) + { + _Assign( vec ); + } + + template + static_array( const _Vector & vec ) + { + _Assign( vec ); + } + + /// \ru Инициализация одним элементом. \en Initialization of one element. + static_array & fill( const Elem & val ) + { + for( size_t idx = 0; idx + static_array & assign( _Iter iter, _Iter last ) + { + for ( value_type * myIter = arr ; iter!=last; ++iter, ++myIter ) + { + PRECONDITION( myIter < arr+arrSize ); + *myIter = *iter; + } + return *this; + } + + inline value_type & operator[] ( size_t idx ) + { + PRECONDITION( idx < arrSize ); + return arr[idx]; + } + inline const value_type & operator[] ( size_t idx ) const + { + PRECONDITION( idx < arrSize ); + return arr[idx]; + } + template + static_array & operator = ( const _Vector & vec ) + { + _Assign( vec ); + return *this; + } + + inline const Elem * c_arr() const { return arr; } + inline Elem * c_arr() { return arr; } + inline size_t size() const { return arrSize; } + inline value_type & front() { return *arr; } + inline value_type & back() { PRECONDITION(arrSize>0); return arr[arrSize-1]; } + inline const value_type & front() const { return *arr; } + inline const value_type & back() const { PRECONDITION(arrSize>0); return arr[arrSize-1]; } + +private: + template< class _Vector > + void _Assign( const _Vector & vec ) + { + PRECONDITION( vec.size() == size() ); + for ( size_t idx = ::min_of( arrSize, vec.size() ); idx > 0; ) + { + idx--; + arr[idx] = vec[idx]; + } + } +}; + +// \ru (!) Запретить пустые статические массивы \en (!) Prevent empty static arrays +template class static_array {}; + +//---------------------------------------------------------------------------------------- +/// \ru Статический вектор двух элементов (пара). \en Static vector of two elements (pair). +//--- +template +struct static_pair: public static_array +{ + typedef static_array parent_type; + // static_pair(): parent_type() {} + explicit static_pair( const Elem & el ): parent_type( el ) {} + static_pair( const Elem & el1, const Elem & el2 ): parent_type( el1, el2 ) {} + explicit static_pair( const static_pair & pair ) : parent_type( pair ) {} + + static_pair & operator = ( const static_pair & vec ) + { + parent_type::operator=( vec ); + return *this; + } +}; + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Динамический контейнер для хранения элементов упорядоченного множества. + \en Dynamic container for storing elements of an ordered set. + + \details + \ru Тип элемента контейнера должен иметь операторы порядка. Не стоит путать этот + тип контейнера с set или map. Он вовсе не обязан всегда поддерживаться в отсортированном + состоянии, а только тогда, когда это закажут (с кэшированием алгоритма сортировки). + Гарантируется, что вектор отсортирован сразу после вызова функций get_sorted или sort. + Константные методы, а также метод erase не нарушают сортировки.\n + \en Type of container element must have order operators. Do not confuse this + type of container with a set or map. It is not obliged always be supported in a sorted + state, and only when it is needed (with caching of sorting algorithm). It is guaranteed + that the vector is sorted immediately after the function call get_sorted or sort. + Const methods and the erase method does not break sorting. \n \~ + + \par \ru Про эффективность + + Часто сортированный вектор оказывается более эффективным, чем std::map или std::set, + особенно если добавление/удаление элементов массива осуществляется серийно и достаточно + редко перемежаются, с запросами быстрого (бинарного) поиска элемента или его места по + порядку. В отличие от map или set минимально дефрагментируется память и не требуется + избыточной информации для хранения указателей (может занимать в 4 раза меньше памяти). + Для быстрых запросов можно применять стандартные алгоритмы, такие + как std::binary_search, std::lower_bound и т.п. + + \en About efficiency + + Often sorted vector is more effective than + std::map or std::set especially when adding/removing elements + of the array is standard and is rarely interspersed + with queries quickly (binary) search of element or its place by + the order. In contrast to the map or set minimal defragmented + memory and does not require excess information for storage of pointers + (can occupy memory in less than 4 times). + For fast queries, can use standard algorithms such + as std::binary_search, std::lower_bound etc. \~ +*/ +//--- +template > // \ru KeyType - тип элемента с операторами порядка "<" \en KeyType - the element type with the operators of order "<" +class sorting_array +{ +public: + typedef std::vector container_type; + typedef typename container_type::value_type value_type; + typedef typename container_type::size_type size_type; + typedef typename container_type::const_iterator iterator; + typedef typename container_type::iterator _iterator; + typedef std::pair iter_range; + typedef _Pr key_compare; // \ru отношение порядка (предикат) \en order relation (predicate) + +public: + sorting_array() : m_vector(), m_sorted( true ) {} + +public: + iter_range get_sorted() { sort(); return iter_range(m_vector.begin(), m_vector.end()); } + iter_range range() const { return iter_range(m_vector.begin(), m_vector.end()); } + const KeyType & sorted_back() { sort(); return m_vector.back(); } + bool empty() const { return m_vector.empty(); } + iterator begin() const { return m_vector.begin(); } + iterator end() const { return m_vector.end(); } + _iterator _begin() { return m_vector.begin(); } + _iterator _end() { return m_vector.end(); } + const KeyType & front() const { return m_vector.front(); } + const KeyType & back() const { return m_vector.back(); } + void erase( iterator ); + void erase( iterator f, iterator l ); + bool is_sorted() const { return m_sorted; } + iterator insert( iterator _whereItr, const KeyType & val ); // \ru вставить элемент перед позицией whereItr \en insert element before position whereItr + template + void insert( iterator position, InputIterator first, InputIterator last ) + { + m_vector.insert( position, first, last ); + m_sorted = false; + } + template + void assign ( InputIterator first, InputIterator last ) + { + m_vector.assign( first, last ); + m_sorted = false; + } + void resize( size_t n, const KeyType & val ); + void reserve ( size_t n ) { m_vector.reserve( n ); } + void push_back( const KeyType & val ); + void sort() + { + if ( !m_sorted ) + { + std::sort( m_vector.begin(), m_vector.end(), _Pr() ); + m_sorted = true; + } + } + void clear() { m_vector.clear(); } + size_t size() const { return m_vector.size(); } + KeyType & operator[] ( size_t n ) { PRECONDITION( n < m_vector.size() ); return m_vector[n]; } + const KeyType & operator[] ( size_t n ) const { PRECONDITION( n < m_vector.size() ); return m_vector[n]; } + +private: + container_type m_vector; + bool m_sorted; + +private: + sorting_array( const sorting_array & ); // \ru реализовать по необходимости \en implement if necessary + sorting_array & operator = ( const sorting_array & ); // \ru реализовать по необходимости \en implement if necessary +}; + +//---------------------------------------------------------------------------------------- +// +// --- +template +void sorting_array::push_back( const KeyType & val ) +{ + m_sorted = m_vector.empty() ? true : m_sorted && _Pr()( m_vector.back(), val ); + m_vector.push_back( val ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template +void sorting_array::erase( iterator ersItr ) +{ + m_vector.erase( m_vector.begin() + (ersItr - begin()) ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template +void sorting_array::erase( iterator f, iterator l ) +{ + typename container_type::iterator first, last; + first = last = m_vector.begin(); + std::advance( first, std::distance(begin(),f) ); // convert from const-iterator to non-const + std::advance( last, std::distance(begin(),l) ); + m_vector.erase( first, last ); +} + +//---------------------------------------------------------------------------------------- +// \ru Вставить элемент перед позицией whereItr \en Insert element before position whereItr +//--- +template +typename sorting_array::iterator +sorting_array::insert( iterator _whereItr, const KeyType & val ) +{ + typename container_type::iterator whereItr = m_vector.begin(); + std::advance( whereItr, std::distance(begin(),_whereItr) ); // \ru перевод из конст-итератора в неконст \en convert from const-iterator to non-const + // \ru Далее проверяем не нарушает ли новая вставка упорядоченности массива \en Next, whether new insert does not break ordering of the array + if ( m_sorted && (_whereItr != m_vector.end()) ) + { + m_sorted = ! key_compare()( *_whereItr, val ); + if ( m_sorted ) // val <= _where + { + m_sorted = ( _whereItr == m_vector.begin() ) || !key_compare()( val, *(--_whereItr) ); + } + } + + // \ru Вставка \en Insert + return m_vector.insert( whereItr, val ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template +void sorting_array::resize( size_t n, const KeyType & val ) +{ + if ( m_sorted && (m_vector.size() < n) && !m_vector.empty() ) + { + m_sorted = !key_compare()( val, m_vector.back() ); // m_vector.back() <= val + } + + m_vector.resize( n, val ); +} + +//---------------------------------------------------------------------------------------- +/// \ru Проверка упорядоченности массива \en Check for ordering array +//--- +template +bool check_ordering( const SortedArray & arr ) +{ + if ( arr.is_sorted() && !arr.empty() ) + { + typename SortedArray::value_type prev( *arr.begin() ); + typename SortedArray::iterator first = arr.begin()+1; + typename SortedArray::iterator last = arr.end(); + for( ; first!=last; ++first ) + { + if ( (*first) < prev ) + { + return false; // \ru нарушен порядок следования \en order has been broken + } + prev = *first; + } + } + + return true; +} + +//---------------------------------------------------------------------------------------- +/// \ru Обнулить структуру данных (использовать осторожно!). \en Reset the data structure (use with caution!). +//--- +template< class DataSt > +inline DataSt null_struct() +{ + DataSt data; + ::memset( &data, 0, sizeof(DataSt) ); + return data; +} + +//---------------------------------------------------------------------------------------- +/// \ru Отладочный инспектор union-контейнера (НЕдоделан!). \en Debug Inspector of union-container (NOT completed yet!). +//--- +template +struct dbg_inspector +{ + union data_t + { + typename _PairUnion::value_type * first; + }; + data_t data; + dbg_inspector() { data.first = 0; } + void init( const _PairUnion & ) {} +}; + +//---------------------------------------------------------------------------------------- +/// \ru Хвостовой элемент для рекурсивного определения типа recursive_union. \en Tail element for recursive determination of type recursive_union. +//--- +struct empty_variant +{ + static const size_t dataSize = 0; + static const size_t power = 0; + struct value_type {}; + bool empty() { return true; } +}; + +//---------------------------------------------------------------------------------------- +/// \ru Получить номер типа из списка union-контейнера. \en Get type index from the list of union-container. +//--- +template +struct which_type +{ + static const int value = 1 + which_type::value; +}; + +// \ru Специализация 1 \en Specialization 1 +template +struct which_type<_PairUnion,typename _PairUnion::value_type> +{ + static const int value = 0; +}; + +// \ru Специализация 2 \en Specialization 2 +template +struct which_type +{ + static const int value = -1; +}; + +//---------------------------------------------------------------------------------------- +/// \ru Получить тип варианта с заданным номером. \en Get variant type with a given index. +//--- +template +struct type_which +{ + typedef typename T::tail_type tail_t; + typedef typename type_which::value_t value_t; +}; + +template +struct type_which +{ + typedef typename T::value_type value_t; +}; + +template +struct type_which +{ +private: + typedef null_type value_t; +}; + +//---------------------------------------------------------------------------------------- +/// \ru Проводник посетителя для рекурсивно-заданного контейнера. \en Conductor of visitor for recursively given container. +//--- +template +struct union_conductor +{ + typedef typename type_which<_PairUnion,typeNb>::value_t _Type; + + /// \ru Статическое приведение типа. \en Static cast of type. + template + static T * unsafe_cast( U & u ) { return u.template unsafe_cast(); } + + /// \ru Статическое приведение типа. \en Static cast of type. + template + static const T * unsafe_cast( const U & u ) { return u.template unsafe_cast(); } + + /// \ru Применить функтор. \en Apply the functor. + template + static inline void apply( const _Visitor & vis, _PairUnion & oper ) + { + if ( oper.which() == typeNb ) + { + vis( *unsafe_cast<_PairUnion,_Type>(oper) ); + } + else + { + union_conductor<_PairUnion,typeNb+1,power>::apply( vis, oper ); + } + } +}; + +//---------------------------------------------------------------------------------------- +// \ru Вызвать деструктор для указателя, если его тип попадает в диапазон от t до power. \en Call the destructor for the pointer if its type is within the range from t to power. +//--- +template +struct union_conductor<_PairUnion,power,power> +{ + template + static inline void apply( const _Visitor & , _PairUnion & ) {} +}; + +//---------------------------------------------------------------------------------------- +/** + \brief \ru Рекурсивное определение класса "union-контейнер". + \en Recursive definition of class "union-container". + \details \ru Контейнер, который может хранить элемент типа "value_type" или один из типов + хвостового контейнера. + \en Container which can store the element of type "value_type" or one of types + of tail container. \~ +*/ +//--- +template +class recursive_union +{ + typedef recursive_union _Myt; + +public: // \ru доступные ассоциативные типы и константы \en available associative types and constants + static const size_t dataSize = sizeof(Type) > Tail::dataSize ? sizeof(Type) : Tail::dataSize; + static const size_t power = 1 + Tail::power; // \ru Количество типов, которое может обеспечить вариант \en The count of types which can provide a variant + + typedef Type value_type; + typedef Tail tail_type; + +public: + recursive_union() : m_typeNb(-1) { ::memset(m_data, 0, dataSize); } + recursive_union( const Type & ); + +#ifndef __DEBUG_MEMORY_ALLOCATE_FREE_ + template + recursive_union( const _Type & elem ) + : m_typeNb( which_type<_Myt,_Type>::value ) + , dbg_data() + { + if ( m_typeNb >= 0 ) + { + new ( (void*)m_data ) _Type( elem ); + } + } +#else // __DEBUG_MEMORY_ALLOCATE_FREE_ + template + recursive_union( const _Type & ) + : m_typeNb( which_type<_Myt,_Type>::value ) + , dbg_data() + { + // (!) The placement form of operator new is required. + C3D_ASSERT_UNCONDITIONAL( false ); + } +#endif //__DEBUG_MEMORY_ALLOCATE_FREE_ + + ~recursive_union(); + +private: // \ru вспомогательные объекты \en assisting objects + // \ru Посетитель для вызова конструктора типа, которым занят union-контейнер \en The visitor to call the type constructor which is occupied by union-container + struct assigner + { + assigner( _Myt & d ) : lOper(&d) {} + + template + void operator() ( const _Type & elem ) const + { + C3D_ASSERT( lOper ); + *lOper = elem; + } + private: + mutable _Myt * lOper; // \ru Левый операнд присвоения \en The left operand of assignment + + private: + assigner & operator = ( const assigner & ); + }; + + // \ru Посетитель для вызова деcтруктора типа, которым занят union-контейнер \en The visitor to call the type destructor which is occupied by union-container + struct destroyer + { + template + static void ignore(const _Type & ) {} // \ru для подавления сообщений \en for suppression of messages + + template + void operator() (const _Type & elem ) const + { + ignore( elem ); + elem.~_Type(); + } + }; + + // \ru Проверка на равенство \en The check for equality + struct comparer + { + const _Myt & data; + mutable bool result; + comparer( const _Myt & d ) : data( d ), result(false) {} + template + void operator() ( const _Type & elem ) const + { + result = (data == elem); + } + private: + comparer & operator = ( const comparer & ); + }; + + struct conductor: public union_conductor<_Myt,0,power> {}; + struct const_conductor: public union_conductor {}; + +public: + int which() const { return m_typeNb; } + // \ru Проверить пустой ли контейнер \en Check whether the container is empty + bool empty() const { return m_typeNb < 0; } + + // \ru Безопасное динамическое приведение типа \en Secure dynamic cast of type + template + _Type * safe_cast() + { + if ( which_type<_Myt,_Type>::value == m_typeNb ) + { + return (_Type*)m_data; + } + return 0; + } + // \ru Безопасное динамическое приведение типа \en Secure dynamic cast of type + template + const _Type * safe_cast() const + { + if ( which_type<_Myt,_Type>::value == m_typeNb ) + { + return (const _Type*)m_data; + } + return 0; + } + + // \ru Статическое приведение типа \en Static cast of type + template + _Type * unsafe_cast() + { + assert( (which_type<_Myt,_Type>::value == m_typeNb) ); + return (_Type*)m_data; + } + + // \ru Статическое приведение типа \en Static cast of type + /* + template typename type_which<_Myt,_typeNb>::value_t & + unsafe_get(); + */ + /* + { + assert( (which_type<_Myt,_Type>::value == m_typeNb) ); + return (type_which<_Myt,_typeNb>::value_t*)m_data; + } + */ + + // \ru Статическое приведение типа \en Static cast of type + template + const _Type * unsafe_cast() const + { + assert( (which_type<_Myt,_Type>::value == m_typeNb) ); + return reinterpret_cast( m_data ); + } + + void release() + { + accept( destroyer() ); + m_typeNb = -1; + } + /* + template + void release() + { + if ( which_type<_Myt,_Type>::value == m_typeNb ) + { + ((_Type*)m_data)->~_Type(); + m_typeNb = -1; + } + } + */ + + // \ru Присвоение другого union-контейнера \en Assignment of another union-container + _Myt & operator = ( const _Myt & v ) + { + release(); + v.accept( assigner(*this) ); + C3D_ASSERT( m_typeNb == v.m_typeNb ); + return *this; + } + + // \ru Присвоение произвольного типа \en Assignment of arbitrary type + /* + template + _Myt & operator = ( const _Type & elem ) + { + m_typeNb = which_type<_Myt,_Type>::value; + if ( m_typeNb >= 0 ) + { + new ( (void*)m_data ) _Type( elem ); + } + return *this; + } + */ + + // \ru Равенство \en Equality + bool operator == ( const _Myt & v ) const + { + if ( m_typeNb == v.m_typeNb ) + { + comparer cmp( *this ); + v.accept( cmp ); + return cmp.result; + } + return false; + } + + // \ru Равенство \en Equality + template + bool operator == ( const _Type & elem ) const + { + if ( m_typeNb == which_type<_Myt,_Type>::value ) + { + return elem == *unsafe_cast<_Type>(); + } + return false; + } + + // \ru Доступ посетителя \en Visitor access + template + void accept( const _Visitor & vis ) const + { + const_conductor::apply( vis, *this ); + } + // \ru Доступ посетителя \en Visitor access + template + void accept( const _Visitor & vis ) + { + conductor::apply( vis, *this ); + } + +private: // \ru данные \en data + char m_data[dataSize]; + int m_typeNb; + dbg_inspector<_Myt> dbg_data; +}; + +//---------------------------------------------------------------------------------------- +// +//--- +template +recursive_union::recursive_union( const Type & elem ) + : m_typeNb( 0 ) + , dbg_data() +{ + dbg_data.init( *this ); + new ( (void*)m_data ) Type( elem ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template +recursive_union::~recursive_union() +{ + release(); +} + +template +struct def_pair_union // \ru определитель рекурсивного контейнера для пары типов \en determinant of a recursive container for a pair of types +{ + typedef recursive_union value_t; +}; +template +struct def_pair_union +{ + typedef recursive_union value_t; +}; +template<> +struct def_pair_union +{ + typedef empty_variant value_t; +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru union-контейнер для экземпляра типа из определенного набора типов. + \en union-container for instance of type from a specific set of types. + \details \ru Позволяет создать тип, принимающий значения из некоторого набора разнородных + типов. + \en Allows to create a type which takes values ??from a set of heterogeneous + types. \~ +*/ +//--- +template< + class T0 + , class T1 + , class T2 = null_type + , class T3 = null_type + , class T4 = null_type + , class T5 = null_type> +class aligned_union +{ + typedef empty_variant _Tail6; + typedef typename def_pair_union::value_t _Tail5; + typedef typename def_pair_union::value_t _Tail4; + typedef typename def_pair_union::value_t _Tail3; + typedef typename def_pair_union::value_t _Tail2; + typedef typename def_pair_union::value_t _Tail1; + typedef typename def_pair_union::value_t _Variant; + + typedef aligned_union _Myt; + +public: + aligned_union(): m_data() {} + template + aligned_union( const T & elem ) : m_data( elem ) {} + +public: + /// \ru Выдать номер текущего типа, которым занят контейнер \en Get a index of the current type which is occupied container + int which() const { return m_data.which(); } + /// \ru Проверить пустой ли контейнер \en Check whether the container is empty + bool empty() const { return m_data.empty(); } + /// \ru Применить функтор (посетитель) \en Apply the functor (visitor) + template + void accept( const _Vis & vis ) const { m_data.accept( vis ); } + /// \ru Применить функтор (посетитель) \en Apply the functor (visitor) + template + void accept( const _Vis & vis ) { m_data.accept( vis ); } + /// \ru Сделать контейнер пустым \en Make an empty container + void clear() { m_data.release(); } + /// \ru Операция присвоения \en Assignment operation + _Myt & operator = ( const _Myt & elem ) { m_data = elem.m_data; return *this; } + template + _Myt & operator = ( const T & elem ) { m_data = elem; return *this; } + // \ru Операция сравнения \en Compare operation + bool operator == ( const _Myt & elem ) const { return m_data == elem.m_data; } + template + bool operator == ( const T & elem ) const { return m_data == elem; } + /// \ru Безопасно преобразовать тип контейнера к указателю \en Safely convert type of container to a pointer + template + T * safe_cast() { return m_data.template safe_cast(); } + template + const T * safe_cast() const { return m_data.template safe_cast(); } + template + bool get( T & val ) const + { + if ( const T * ptr = m_data.template safe_cast() ) + { + val = *ptr; + return true; + } + return false; + } + +private: + _Variant m_data; +}; + +//---------------------------------------------------------------------------------------- +// +// --- +template +bool is_exist( _Iterator begIt, _Iterator endIt, const _Element & elem ) +{ + return std::find( begIt, endIt, elem ) != endIt; +} + +//---------------------------------------------------------------------------------------- +// +// --- +template +bool is_exist_if( _Iterator begIt, _Iterator endIt, _UnaryPredicate _Pred ) +{ + return std::find_if( begIt, endIt, _Pred ) != endIt; +} + +namespace c3d +{ + struct color_label + { + color_code val; + color_label() : val( white_color ) {} + bool operator == ( color_code col ) const { return col == val; } + color_label & operator = ( color_code col ) { val = col; return *this; } + }; + +//---------------------------------------------------------------------------------------- +// +//--- +template +struct _IterTraits { + typedef typename Iterator::value_type value_type; +}; + +template +struct _IterTraits { + typedef T value_type; +}; + +//---------------------------------------------------------------------------------------- +// Диапазон итераторов +//--- +template +struct range : public std::pair +{ + typedef std::pair _Pair; + typedef typename _IterTraits::value_type value_type; + + range( const Iterator & iter, const Iterator & last ) :_Pair( iter, last ) {} + range( const _Pair & other ) :_Pair( other ) {} + range() :_Pair() {} + Iterator begin() const { return _Pair::first; } + Iterator end() const { return _Pair::second; } + bool empty() const { return _Pair::first == _Pair::second; } + size_t size() const { return (size_t)std::distance( _Pair::first, _Pair::second ); } + void clear() { _Pair::first = _Pair::second; } + range & move_front() { ++_Pair::first; return *this; } + + const value_type & front() const { return (*begin()); } + const value_type & back() const { return (*(end() - 1)); } +}; + +//---------------------------------------------------------------------------------------- +// Get a range of the STL-container +//--- +template +range range_of( const _Cont & list ) +{ + range rng( list.begin(), list.end() ); + return rng; +} + +//---------------------------------------------------------------------------------------- +// Get a range of iterators +//--- +template +range<_Iterator> make_range( _Iterator first, _Iterator last ) +{ + c3d::range<_Iterator> rng( first, last ); + return rng; +} + +}; + +#endif // __GENERIC_UTILITY_H + +// eof diff --git a/C3d/Include/graph_algorithms.h b/C3d/Include/graph_algorithms.h index 58dcccb..df80c0c 100644 --- a/C3d/Include/graph_algorithms.h +++ b/C3d/Include/graph_algorithms.h @@ -1,1030 +1,1030 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Обобщенные алгоритмы на графах. - \en Generic graph algorithms. \~ - -*/ -/////////////////////////////////////////////////////////////////////// MA 25.10.2010 //// - -#ifndef __GRAPH_ALGORITHMS_H -#define __GRAPH_ALGORITHMS_H -// -#include -#include - -//---------------------------------------------------------------------------------------- -// -/// Пустой посетитель алгоритма обхода графа в глубину -/** - \ingroup MathGC_Algo - \attention Класс не предназначен для того, что бы применять статический - или динамический полиморфизм, т.е. не обязывает своих наследников - перегружать методы. -*/ -//--- -template -struct DefaultDFSVisitor -{ - typedef typename Graph::vertex_index vertex_index; - - /// Встретили "обратное" ребро (дуга, если орграф) dfs-дерева. - /** - Вызывается когда при посещении вершины v найдено исх.ребро, направленное к - ранее посещенной вершине. Другими словами, вершина u является предком - вершине v в dfs-дереве. - */ - void BackEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} - /// Вызывается, когда впервые проходим через исходящую дугу v->u, вершину u еще не посещали - void ExamineEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} - /// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться - void DiscoverNode( vertex_index /*v*/, const Graph & /*g*/ ) {} - /// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены - void FinishNode( vertex_index /*v*/, const Graph & /*g*/ ) {} - /// Встретили "поперечное" или "прямое" ребро - /** - Вызывается, когда находим дугу, идущую к другому dfs-дереву, либо прямую дугу, - идущую к потомку того же дерева, имеющему два и более отцов. - Для поперечного ребра вызывается только для ориентированных графов. - */ - void ForwardOrCrossEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} - /// Отвечает, что вершина исключена из рассмотрения - bool Ignored( vertex_index /*v*/, const Graph & /*g*/ ) const { return false; } - /// Означает, что начато рассмотрение корневой вершины будущего дерева обхода - void StartNode( vertex_index /*v*/, const Graph & /*g*/ ) {} - /// Ребро стало "древесным" (принадлежит dfs-дереву). Вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u - void TreeEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// Посетитель алгоритма поиска блоков и точек сочленения в неориентированном графе -/** - Позволяет настроить алгоритм поиска блоков и точек сочленения под конкретные реализации. -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -template< class Graph > -struct DefaultBicompVisitor -{ - /// Найден блок, как последовательность ребер - template - void BlockFounded( EdgeIterator, EdgeIterator, const Graph & ) {} - - /// Обнаружена точка сочленения (articulation vertex) - template - void CutNode( Vertex, const Graph & ) {} - - /// Функция обратного вызова: Фильтрация для точек сочленения - /** - С момощью этой функции пользователь настраивает поведение алгорита поиска блоков. - Если визитер отвечает true, то алгоритм не учитывает данную вершину, - как вершину разреза, отделяющую блоки. Таким образом в результате - отфильтрованная точка сочленения всегда будет принадлежать одному блоку. - */ - template - bool IsFilteredCut( Vertex, const Graph & ) const { return false; } -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// Посетитель обхода в глубину для поиска блоков и точек сочленения -/** - Класс является автономным и не нуждается в уточнении наследованием от него. - Graph - предполагается, что это неориентированный граф. - BicompVisitor - надстроенный визитер, посетитель этого визитера, который - реализует события обнаружения блока, точки сочленения и - фильтрацию вершин, которые принудительно запрещается быть - точками сочленения. -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -template< class Graph, class BicompVisitor = DefaultBicompVisitor > -class BicompDFSVisitor: public DefaultDFSVisitor -{ -public: - typedef typename Graph::adj_iterator adj_iterator; - typedef typename Graph::edge edge; - -public: - static const typename Graph::vertex_index NO_VERTEX = (size_t)-1; - - BicompDFSVisitor( BicompVisitor & vis ) - : m_graph( NULL ) - , m_bicompVis( vis ) - , m_dfsCounter( 1 ) - , num() - , father() - , lval() - , m_stackEdges() - {} - - /// Встретили поперечное или прямое ребро - void ForwardOrCrossEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & ) - { - DEBUG_UNUSED_PARAMETER( u ); - DEBUG_UNUSED_PARAMETER( v ); - PRECONDITION( num[v] < num[u] ); - } - - /// Найдено обратное ребро dfs-дерева, вызывается когда при посещении вершины v найдено исх.ребро к ранее посещенной вершине - /** - Вершина u является предком вершине v в dfs-дереве. - */ - void BackEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g ) - { - DEBUG_UNUSED_PARAMETER( g ); - PRECONDITION( m_graph == &g ); - PRECONDITION( num[u] < num[v] ); - PRECONDITION( father[v] != NO_VERTEX ); - if ( u != father[v] ) - { - // Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве; - m_stackEdges.push_back( edge(v,u) ); // вставить ребро vu; - lval[v] = min_of( lval[v], num[u] ); // см.лемму 6; - } - } - - /// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться - void DiscoverNode( typename Graph::vertex_index v, const Graph & g ) - { - DEBUG_UNUSED_PARAMETER( g ); - C3D_ASSERT( m_graph == &g ); - PRECONDITION( num[v] == 0 ); - PRECONDITION( lval[v] == 0 ); - num[v] = lval[v] = m_dfsCounter++; - } - - /// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены - void FinishNode( typename Graph::vertex_index u, const Graph & g ) - { - PRECONDITION( m_graph == &g ); - typename Graph::vertex_index v = father[u]; - if ( v == NO_VERTEX ) // СЛУЧАЙ 1: Вершина u - корневая, завершен обход fds-дерева - { - // Оценить является ли u - точкой сочленения - // Сколько раз стартовая вершина стала папой (столько же в ней стыкуется блоков) - if ( _ChildrenNb(u, g) > 1) - { - // В корневой вершине стыкуются 2 или более блоков - значит она же является и точкой сочленения - m_bicompVis.CutNode( u, g ); - } - // Извещение о найденном блоке - if ( !m_stackEdges.empty() ) // Все что есть в m_stackEdges - следует считать последним найденным блоком. - { - m_bicompVis.BlockFounded( m_stackEdges.begin(), m_stackEdges.end(), g ); - // После извещения визитера - вычищаем стек - m_stackEdges.clear(); - } - } - else // СЛУЧАЙ 2: u - не корневая вершина - { - lval[v] = min_of( lval[v], lval[u] ); // см. лемму 6; - if ( lval[u] >= num[v] ) - { - // Здесь можно получить новый блок, для чего достаточно вытолкнуть из - // стека все ребра, включая ребро vu. - - // (!) Если вершина v не корень d-дерева, то можно утверждать, что она - есть точка сочленения; - // См. теорему 8.2. - if ( father[v] != NO_VERTEX ) // если v корневая вершина, то оценки для неё делаются в конце обхода дерева - { - m_bicompVis.CutNode( v, *m_graph ); - } - - // Извещение о найденном блоке - if ( !m_bicompVis.IsFilteredCut(v,*m_graph) ) // Запрет на отфильтрованные точки сочленения - они не могут "вырезать" блоки. - { - // Тут мы запретили собирать блок, т.к. вершина фильтрованная, однако это не принесет ущерба, - // если окажется что v - не точка сочленения. Вот почему: - /* - Если v - есть корень dfs-дерева, то возможны 2 варианта: v принадлежит одному блоку, - тогда v не точка сочленения; v принадлежит двум и более блокам, тогда v - есть точка сочленения. - В первом случае единственный блок, куда включена v, будет собран в конце текущего обхода dfs-дерева, - массив m_stackEdges полностью будет содержать этот блок. Во втором случае, если блок не - единственный, то v - есть точка сочленения, тогда очевидно запрет правомерен - в конце обхода дерева все, - что осталось в стеке ребер есть один блок. - */ - - PRECONDITION( !m_stackEdges.empty() ); - /* - std::vector::reverse_iterator vuIter = - std::find( m_stackEdges.rbegin(), m_stackEdges.rend(), edge(v,u) ); // Ищем с конца - PRECONDITION( vuIter != m_stackEdges.rend() ) // Это ребро обязано быть в стеке - m_bicompVis.BlockFounded( vuIter.base()-1, m_stackEdges.end(), *m_graph ); - // После извещения визитера - вычищаем блок из стека конца - m_stackEdges.erase( vuIter.base()-1, m_stackEdges.end() ); - */ - - const edge seek( v, u ); - typename std::vector::iterator first = m_stackEdges.begin(); - typename std::vector::iterator iter, last; - for ( iter = last = m_stackEdges.end(); iter != first; ) - { - --iter; - if ( *iter == seek ) - { - break; - } - } - - PRECONDITION( *iter == seek ); // Это ребро обязано быть в стеке - m_bicompVis.BlockFounded( iter, last, *m_graph ); - // После извещения визитера - вычищаем блок из стека конца - m_stackEdges.erase( iter, last ); - } - } - } - } - - /// Означает, что начато рассмотрение корневой вершины будущего дерева обхода - void StartNode( typename Graph::vertex_index v, const Graph & g ) - { - DEBUG_UNUSED_PARAMETER( v ); - _Init( g ); - PRECONDITION( father[v] == NO_VERTEX ); - PRECONDITION( num[v] == 0 && lval[v] == 0 ); - } - - /// Заход в ребро dfs-дерева, вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u - void TreeEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g ) - { - DEBUG_UNUSED_PARAMETER( g ); - PRECONDITION( m_graph == &g ); - PRECONDITION( father[u] == NO_VERTEX ); - m_stackEdges.push_back( edge(v,u) ); // Вставить ребро vu; - father[u] = v; // зафиксируем отца для вершины u; - } - -private: - /// Количество сыновей вершины - size_t _ChildrenNb( typename Graph::vertex_index u, const Graph & g ) const - { - PRECONDITION( m_graph == &g ); - // Оценить является ли u - точкой сочленения - size_t fatherNb = 0; // Сколько раз вершина u стала папой - std::pair adjIterPair = g.AdjacentVertices( u ); - for ( ; adjIterPair.first != adjIterPair.second; ++adjIterPair.first ) - { - if ( father[*adjIterPair.first] == u ) - { - ++fatherNb; - } - } - return fatherNb; - } - - void _Init( const Graph & graph ) - { - m_graph = &graph; - const typename Graph::vertices_size_t vertNb = graph.NumVertices(); - m_dfsCounter = 1; - num.assign( vertNb, 0 ); - father.assign( vertNb, NO_VERTEX ); - lval.assign( vertNb, 0 ); - m_stackEdges.clear(); - } - -private: - const Graph * m_graph; ///< Рассматриваемый граф, для которого ищутся точки сочленения - BicompVisitor & m_bicompVis; ///< Посетитель алгоритмов этого класса - ptrdiff_t m_dfsCounter; ///< Cчетчик вершин dfs-дерева - std::vector num; ///< Нумерация порядка обхода вершин d-дерева - std::vector lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6; - std::vector father;///< Отец вершины в dfs-дереве - std::vector m_stackEdges; ///< Cтек ребер для обслуживания нахождения блоков - -private: - BicompDFSVisitor & operator = ( const BicompDFSVisitor & ); -}; - -//---------------------------------------------------------------------------------------- -// Стековый элемент для алгоритма обхода в глубину. -// --- -template -struct DFSVertexInfo -{ -private: - typedef typename Graph::vertex_index vertex_index; - typedef typename Graph::adj_iterator adj_iterator; - -public: - vertex_index m_node; - adj_iterator m_iter; - adj_iterator m_last; - - DFSVertexInfo( vertex_index v, adj_iterator iter, adj_iterator last ) - : m_node( v ) - , m_iter( iter ) - , m_last( last ) - {} - - DFSVertexInfo( vertex_index v, const Graph & graph ) - : m_node( v ) - , m_iter() - , m_last() - { - tie(m_iter,m_last) = graph.AdjacentVertices( v ); - } - - DFSVertexInfo( const DFSVertexInfo & vi ) - : m_node( vi.m_node ) - , m_iter( vi.m_iter ) - , m_last( vi.m_last ) - {} - - DFSVertexInfo & operator = ( const DFSVertexInfo & vi ) - { - m_node = vi.m_node; - m_iter = vi.m_iter; - m_last = vi.m_last; - return *this; - } -}; - -//---------------------------------------------------------------------------------------- -/// Алгоритм обхода в глубину графа смежности -/** - Вычислительная сложность алгоритма практически линейная, если считать что - методы визитера выполняются за константное время. - - \param graph Граф смежности - \param vis Посетитель алгоритма -*/ -//--- - -template -void DepthFirstSearch( const Graph & graph, Visitor & vis ) -{ - typedef typename Graph::vertices_size_t vertices_size_t; - typedef typename Graph::vertex_index vertex_index; - typedef typename Graph::adj_iterator adj_iterator; - /* - enum Color // Разметка - { - col_white // не посещалась - , col_gray // в стеке - , col_black // - }; - */ - - const vertices_size_t vCount = graph.NumVertices(); - - std::vector> stack; - std::vector colourMap( vCount, white_color ); // отображение: вершина -> цвет - - // Пометить, как рассмотренные, игнорируемые вершины - for ( vertex_index xIdx = 0; xIdx(startNode,graph) ); - - while ( !stack.empty() ) - { - { - DFSVertexInfo & curr = stack.back(); - vIter = curr.m_iter; - vLast = curr.m_last; - srcNode = curr.m_node; - stack.pop_back(); - } - - while ( vIter != vLast ) - { - const vertex_index trgNode = *vIter; - ++vIter; - - vis.ExamineEdge( srcNode, trgNode, graph ); - - switch ( colourMap[trgNode] ) // Переход по дереву к следующей вершине - { - case white_color: - { - vis.TreeEdge( srcNode, trgNode, graph ); // "древесное" ребро - colourMap[trgNode] = gray_color; - stack.push_back( DFSVertexInfo( srcNode, vIter, vLast ) ); - vis.DiscoverNode( srcNode = trgNode, graph ); - tie( vIter, vLast ) = graph.AdjacentVertices( srcNode ); - break; - } - case gray_color: // Встетили обратное ребро - { - vis.BackEdge( srcNode, trgNode, graph ); - break; - } - default: // Встретили "прямое" или "кросс-ребро" в ориентированном графе - { - vis.ForwardOrCrossEdge( srcNode, trgNode, graph ); - break; - } - } - } - - // Событие завершения обхода текущей вершины - colourMap[srcNode] = black_color; - vis.FinishNode( srcNode, graph ); - } - } - } -} - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// Отображение реберных свойств для графов, поддерживающих концепцию смежности вершин (без явных ребер) -/** - Для графов с инцидентными ребрами лучше использовать другие типы отображений -*/ -////////////////////////////////////////////////////////////////////////////////////////// -/* -template -class EdgePropertyMap -{ - typedef Graph::vertex_descriptor vertex_descriptor; - typedef Graph::edge_descriptor edge_descriptor; - typedef std::pair pair; - class node - { - public: - node( const node & ); - node & operator = ( const node & ); - - private: - vertex_descriptor vertex; - std::vector props; - }; - - std::vector nodes; - -public: - const Prop & operator[]( edge_descriptor ) const; - Prop & operator[]( edge_descriptor ); -}; -*/ - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// Инкапсуляция алгоритма поиска 2-связных компонент и/или точек сочленения -/** - ПЛАНИРУЕТСЯ ЗАМЕНИТЬ ЭТОТ АЛГОРИТМ НА БОЛЕЕ ОБЩИЙ НО НЕ МЕНЕЕ ЭФФЕКТИВНЫЙ: - DepthFirstSearch + BicompDFSVisitor - - \par Определение - d-деревом называем ациклический подграф рассматриваеморго графа, состоящего - из вершин и ребер, которые обходит поиск в глубину, на основе которого построен - данный адгоритм. - Graph - тип, отвечающий требованиям обычного графа смежности по вершинам - - \par РЕФАКТОРИНГ - 1) Нужно обобщить это алгоритм с библиотекой MtGraph - 2) Возможно снабдить это класс-алгоритм посетителем поиска компонент. - Это, например, позволит генерировать два варианта алгоритма поиска блоков: - Вариант, когда нужно найти только вершины сочленения (без блоков) вариант, - когда нужно искать шарниры и/или блоки; - 2.1.) Возможны другие рецепты, как генерить шаблоном два похожих алгоритма. - 3) Алгоритм можно упростить, если переложить его на еще более общный - алгоритм обхода в глубину. -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -template -class MtBicompSearch -{ - // Ассоциативные типы - typedef typename Graph::vertex_index vertex_index; - typedef typename Graph::vertex_size_t vertex_size_t; - typedef typename Graph::adj_iterator adj_iterator; - -private: - const Graph & m_graph; - ptrdiff_t m_dfsCounter; - std::vector num; ///< Нумерация порядка обхода вершин d-дерева - std::vector father; ///< Отец вершины в d-дереве - std::vector lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6; - std::vector m_cutnodes; ///< Обнаруженные точки сочленения - std::vector m_cutnodeProp; ///< Признак точки сочленения для вершин - -public: - MtBicompSearch( const Graph & ); - /// Найти все точки сочленения - const std::vector & SearchCutnodes(); - -private: - /// Алгоритм реккурсивного вызова поиска блоков и точек сочленения в графе - void BiComp( vertex_index ); - /// Инициализировать все рабочие данные для нового поиска - void Init(); - /// Запустить алгоритм - void Perform(); -}; - -//---------------------------------------------------------------------------------------- -// -//--- -template -MtBicompSearch::MtBicompSearch( const Graph & g ) - : m_graph( g ) - , m_dfsCounter(1) - , num() - , father() - , lval() - , m_cutnodes() - , m_cutnodeProp() -{} - -//---------------------------------------------------------------------------------------- -/// Найти все точки сочленения -//--- -template -const std::vector & MtBicompSearch::SearchCutnodes() -{ - Init(); - Perform(); - return m_cutnodes; -} - -//---------------------------------------------------------------------------------------- -/// Инициализировать все рабочие данные для нового поиска -//--- -template -void MtBicompSearch::Init() -{ - const vertex_size_t vertNb = m_graph.NumVertecies(); - m_dfsCounter = 1; - num.assign( vertNb, 0 ); - father.assign( vertNb, -1 ); - lval.assign( vertNb, -1 ); - m_cutnodeProp.assign( vertNb, false ); - m_cutnodes.clear(); -} - -//---------------------------------------------------------------------------------------- -/// Запустить алгоритм -//--- -template -void MtBicompSearch::Perform() -{ - PRECONDITION( m_cutnodes.empty() ); - - const vertex_size_t vertNb = m_graph.NumVertecies(); - for ( vertex_index startIdx = 0; startIdx adjIterPair = m_graph.AdjacentVertices( startIdx ); - for ( ; adjIterPair.first!=adjIterPair.second; ++adjIterPair.first ) - { - if ( father[*adjIterPair.first] == startIdx ) - { - ++fatherNb; - } - } - if ( fatherNb > 1 ) - { - // Корневая вершина - есть точка сочленения - PRECONDITION( !m_cutnodeProp[startIdx] ); - m_cutnodes.push_back( startIdx ); - m_cutnodeProp[startIdx] = true; - } - } - } -} - -//---------------------------------------------------------------------------------------- -/// Алгоритм реккурентного вызова поиска блоков и точек сочленения в графе -/** - Теорию см.главе 8, стр.166, Графы, матроиды, алгоритмы [Asan]; - \param vIdx - вершина (индекс), с которой начинаем поиск, которая ещё не рассмотрена, т.е. - num[vIdx] = 0; - - \par Определения - d-дерево - ациклический подграф основного подграфа, образуемого при обходе - вершин во время поиска в глубину; - - \par Вычислительная сложность - Вычислительная сложность: O(n+m), где n-кол-во вершин, m-кол-во ребер. Это следует из - того факта, что каждая вершина посещается не более одного раза. -*/ -//--- -template -void MtBicompSearch::BiComp( const vertex_index vIdx ) -{ - PRECONDITION( num[vIdx] == 0 ); - num[vIdx] = lval[vIdx] = m_dfsCounter; - ++m_dfsCounter; - - // Цикл по всем смежным вершинам vert; - std::pair adjIterPair = m_graph.AdjacentVertices( vIdx ); - for ( ; adjIterPair.first!=adjIterPair.second; ++adjIterPair.first ) - { - const vertex_index uIdx = *adjIterPair.first; // Вершина - сын в d-дереве; - // const edge_descriptor vuEdg = m_graph.GetEdge( vIdx, uIdx ); - if ( num[uIdx] == 0 ) // uIdx - сын вершины vIdx - { - // stackE.push_back( vuEdg ); // Вставить ребро vu; - PRECONDITION( father[uIdx] == -1 ); - father[uIdx] = vIdx; // зафиксируем отца для данной вершины uIdx; - BiComp( uIdx ); - - // При выходе из рекурсии значение функции L[u] уже вычислено; - lval[vIdx] = min_of( lval[vIdx], lval[uIdx] ); // см.лемму 6; - if ( lval[uIdx] >= num[vIdx] ) - { - // Здесь можно получить новый блок, для чего достаточно вытолкнуть из - // стека все ребра, включая ребро vu. - - // (!) Если вершина vIdx не корень d-дерева, то можно утверждать, что она - есть точка сочленения; - // См. теорему 8.2. - if ( father[vIdx] != -1 ) // Первородитель - { - if ( !m_cutnodeProp[vIdx] ) - { - m_cutnodes.push_back( vIdx ); - m_cutnodeProp[vIdx] = true; - } - } - /* - PRECONDITION( !stackE.empty() ) - blocks.NewComp(); - - #pragma message ( __TODO__ "(**) Собирать ребра возможно не понадобится! Достаточно cutnodes;" ) - while( !stackE.empty() ) - { - edge_descriptor edge = stackE.back(); - blocks.AddEdge( edge ); - stackE.pop_back(); // вытолкнуть ребро из стека; - if ( edge == vuEdg ) - { - break; - } - } - */ - } - } - else if ( num[uIdx] < num[vIdx] && uIdx != father[vIdx] ) - { - // Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве; - // stackE.push_back( vuEdg ); // вставить ребро vu; - lval[vIdx] = min_of( lval[vIdx], num[uIdx] ); // см.лемму 6; - } - } -} - - -////////////////////////////////////////////////////////////////////////////////////////// -// -// Посетитель алгоритма поиска компонент сильной связности -// -////////////////////////////////////////////////////////////////////////////////////////// -struct DefaultSCVisitor -{ - // Вызывается алгоритмом перед началом обхода всего графа - template - inline void Start( const Graph & ) {} - // Вызывается, когда найден очередной компонент сильной связности в орграфе - /* - Аргументы: граф и пара вершинных итераторов, пробегающих подмножество компонента - */ - template - inline void Component( const Graph &, VertexIter, VertexIter ) {} - // Если IsFiltered = true, вершина считается исключенной из графа - template - inline bool IsFiltered( const Graph &, Vertex ) { return false; } -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// Алгоритм поиска компонент сильной связности в орграфе -/** - Напомним, что две вершины орграфа считаются сильно связанными, если - существует маршрут из первой вершины ко второй и обратный маршрут из второй - к первой. Подграф называется сильно связным, если любая пары его - вершин сильно связаны. Компонент сильной связности графа - это один из - его сильно сзязный подграфов G', для которого не существует сильно связной пары - вершин u и v, таких, что u-принадлежит G', а v не принадлежит G'. Другими словами, - вершины компонента сильной связости принадлежат классу взаимной достижимости вершин; - \note Алгоритм #MtStrongComponents имеет линейную сложность вычислений - \ingroup GCBase -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -template -class MtStrongComponents -{ -public: // Ассоциативные типы - typedef typename graph_traits::vertex vertex; - typedef typename graph_traits::edge edge; - typedef typename graph_traits::edge_iterator edge_iterator; - typedef typename graph_traits::vertex_iterator vertex_iterator; - -public: - MtStrongComponents( const Graph &, SCVisitor & ); - void operator() (); ///< Исполнить алгоритм поиска сильных компонентов - -private: - // DFS-алгоритм для поиска компонент сильной связности в графе ограничений - void StrongSearch( vertex, std::vector & ); - -private: - const Graph & m_diGraph; ///< Ориентированный граф - SCVisitor & m_vis; ///< Посетитель алгоритма поиска компонент сильной связности - size_t m_counter; ///< Порядок DFS-обхода - VertexPropertyMap num; ///< Вспомогательный массив порядковых номеров обхода в глубину - VertexPropertyMap lval; ///< Массив для промежуточных целочисленных вычислений - -private: - MtStrongComponents( const MtStrongComponents & ); - MtStrongComponents & operator = ( const MtStrongComponents & ); -}; - -//---------------------------------------------------------------------------------------- -// -//--- -template -MtStrongComponents::MtStrongComponents( const Graph & b_graph, Vis & vis ) - : m_diGraph( b_graph ) - , m_vis( vis ) - , num( b_graph.NumVertices() ) - , lval( b_graph.NumVertices() ) - , m_counter( 1 ) -{} - -//---------------------------------------------------------------------------------------- -// Главный алгоритм поиска компонент сильной связности в графе ограничений -//--- -template -void MtStrongComponents::operator() () -{ - m_vis.Start( m_diGraph ); - - std::vector stack; - stack.reserve( m_diGraph.NumVertices() ); - m_counter = 1; - - vertex_iterator vIter, vLast; - - for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) - { - num[*vIter] = 0; - } - - for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) - { - if ( num[*vIter] == 0 && !m_vis.IsFiltered(m_diGraph,*vIter) ) - StrongSearch( *vIter, stack ); - } -} - -//#define _RECURSIVE_STRONG_SEARCH 1 - -#ifdef _RECURSIVE_STRONG_SEARCH - -//---------------------------------------------------------------------------------------- -/// Алгоритм поиска компонент сильной связности в орграфе -/** - Алгоритм применяется для разбиения графа ограничений на независимо - решаемые подсистемы (сегменты). Рекурсивный вариант. Описание алгоритма приведено - в книжке Асанова по теории графов, стр.171.\n - \param vx - корневая вершина поддерева DFS - \param stack - стек рассмотренных вершин, для которых не установлена компонентная принадлежность -*/ -//--- -template -void MtStrongComponents::StrongSearch( vertex vx, std::vector & stack ) -{ - PRECONDITION( !m_vis.IsFiltered(m_diGraph,vx) ); - - num[vx] = m_counter; - lval[vx] = m_counter; - ++m_counter; - stack.push_back( vx ); - - edge_iterator eIter, eLast; // итераторы обхода инцидентных ребер - for ( tie(eIter,eLast) = m_diGraph.OutArcs(vx); eIter!=eLast; ++eIter ) - { - vertex w = m_diGraph.Target( *eIter ); // Выходящая вершина прямого ребра - PRECONDITION( w != vx ); // Граф не ориентированный !!! - if ( w != vx && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы; - { - if ( num[w] == 0 ) // - "древесная" дуга - { - StrongSearch( w, stack ); - if ( lval[w] < lval[vx] ) // При выходе из рекурсии значение l(w) должно быть уже насчитано; - lval[vx] = lval[w]; - } - else - { - const size_t wNum = num[w]; - if ( wNum < num[vx] && wNum < lval[vx] ) // - "поперечная" или "обратная" дуга - { - // Предположение: В стеке лежат вершины, из которых вершина vx достижима; - if ( std::find(stack.rbegin(), stack.rend(), w) != stack.rend() ) - { - lval[vx] = wNum; - } - } - } - } - } - - const size_t vNum = num[vx]; - if ( lval[vx] == vNum ) // vx - корневая вершина очередной компоненты сильной связности - { - // Обнаружен очередной сильный компонент - if ( !stack.empty() && num[stack.back()] >= vNum ) - { - // Посчитать размер компонента - typename std::vector::reverse_iterator vIter, vLast; - vIter = stack.rbegin(); - vLast = stack.rend(); - ptrdiff_t compSize = 0; - for ( ; vIter != vLast && num[*vIter] >= vNum; ++vIter, ++compSize ); - - // Передать диапазон компонента визитеру - typename std::vector::iterator cIter, cLast; - cIter = cLast = stack.end(); - std::advance( cIter, -compSize ); - m_vis.Component( m_diGraph, cIter, cLast ); - stack.erase( cIter, cLast ); // очистить верхушку стека - } - } -} - -#else // _RECURSIVE_STRONG_SEARCH - - -//---------------------------------------------------------------------------------------- -/// Стековый элемент для алгоритма обхода в глубину -//--- -template -struct DFS_element -{ - typedef typename Graph::vertices_size_t vertices_size_t; - typedef typename Graph::vertex vertex; - typedef typename Graph::edge_iterator edge_iterator; - - vertex node; - edge_iterator iter; - edge_iterator last; - - DFS_element( vertex v, const std::pair & pair ) - : node( v ) - , iter( pair.first ) - , last( pair.second ) - {} - - DFS_element( vertex v, const Graph & graph ) - : node( v ) - , iter() - , last() - { - tie( iter, last ) = graph.OutArcs( v ); - } - - DFS_element( const DFS_element & vi ) - : node( vi.node ) - , iter( vi.iter ) - , last( vi.last ) - {} - - DFS_element & operator = ( const DFS_element & vi ) - { - node = vi.node; - iter = vi.iter; - last = vi.last; - return *this; - } -}; - -//---------------------------------------------------------------------------------------- -/// Алгоритм поиска компонент сильной связности в орграфе -/** - Алгоритм применяется для разбиения графа ограничений на независимо-решаемые - подсистемы (сегменты). Описание алгоритма приведено в книжке Асанова по - теории графов, стр.171.\n - MA2013-02-22: Алгоритм переделан под нерекурсивный вариант; - \param rootVert - корневая вершина поддерева DFS - \param comStack - стек рассмотренных вершин, для которых не установлена компонентная принадлежность -*/ -//--- -template -void MtStrongComponents::StrongSearch( vertex rootVert - , std::vector & comStack ) -{ - typedef DFS_element DfsStackElem; - - PRECONDITION( !m_vis.IsFiltered(m_diGraph,rootVert) ); - std::vector dfsStack; - - num[rootVert] = lval[rootVert] = m_counter; - ++m_counter; - comStack.push_back( rootVert ); - dfsStack.push_back( DfsStackElem( rootVert, m_diGraph ) ); - DfsStackElem * topElem = &dfsStack.back(); - - while( !dfsStack.empty() ) // Цикл возвратов из стека (одна итерация - одно возвращение против древесного ребра ) - { - while ( topElem->iter != topElem->last ) - { - vertex w = m_diGraph.Target( *topElem->iter ); // Выходящая вершина прямого ребра - PRECONDITION( w != topElem->node ); // Граф не ориентированный !!! - if ( (w != topElem->node) && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы; - { - if ( num[w] == 0 ) // - "древесная" дуга - { - // Вместо рекурсии: StrongSearch( w, stack ); - num[w] = lval[w] = m_counter; - ++m_counter; - comStack.push_back( w ); - dfsStack.push_back( DfsStackElem(w, m_diGraph) ); - topElem = &dfsStack.back(); - continue; - } - else - { - const size_t wNum = num[w]; - if ( wNum < num[topElem->node] && wNum < lval[topElem->node] ) // - "поперечная" или "обратная" дуга - { - // Предположение: В стеке лежат вершины, из которых вершина vx достижима; - if ( std::find(comStack.rbegin(), comStack.rend(), w) != comStack.rend() ) - { - lval[topElem->node] = wNum; - } - } - } - } - ++topElem->iter; - } - - PRECONDITION( dfsStack.back().iter == dfsStack.back().last ); - PRECONDITION( topElem == &dfsStack.back() ); - - // Завершено посещение узла sElem->m_node - const size_t vNum = num[topElem->node/*vx*/]; - if ( lval[topElem->node/*vx*/] == vNum ) // vx - корневая вершина очередной компоненты сильной связности - { - // Обнаружен очередной сильный компонент - if ( !comStack.empty() && num[comStack.back()] >= vNum ) - { - // Посчитать размер компонента - typename std::vector::reverse_iterator vIter, vLast; - vIter = comStack.rbegin(); - vLast = comStack.rend(); - ptrdiff_t compSize = 0; - for ( ; vIter != vLast && num[*vIter] >= vNum; ++vIter, ++compSize ); - - // Передать диапазон компонента визитеру - typename std::vector::iterator cIter, cLast; - cIter = cLast = comStack.end(); - std::advance( cIter, -compSize ); - m_vis.Component( m_diGraph, cIter, cLast ); - comStack.erase( cIter, cLast ); // очистить верхушку стека - } - } - // Возвращение против древесного ребра , где w-просмотренная вершина, v-вершина из которой пришли в w; - { - const vertex w = topElem->node; - dfsStack.pop_back(); - - if ( !dfsStack.empty() ) - { - topElem = &dfsStack.back(); - const vertex vxPrev = dfsStack.back().node; - // При выходе из рекурсии значение lVal(w) должно быть уже насчитано; - if ( lval[w] < lval[vxPrev] ) - { - lval[vxPrev] = lval[w]; - } - } - } - } -} - -#endif // _RECURSIVE_STRONG_SEARCH - -#endif // __GRAPH_ALGORITHMS_H - -// eof +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Обобщенные алгоритмы на графах. + \en Generic graph algorithms. \~ + +*/ +/////////////////////////////////////////////////////////////////////// MA 25.10.2010 //// + +#ifndef __GRAPH_ALGORITHMS_H +#define __GRAPH_ALGORITHMS_H +// +#include +#include + +//---------------------------------------------------------------------------------------- +// +/// Пустой посетитель алгоритма обхода графа в глубину +/** + \ingroup MathGC_Algo + \attention Класс не предназначен для того, что бы применять статический + или динамический полиморфизм, т.е. не обязывает своих наследников + перегружать методы. +*/ +//--- +template +struct DefaultDFSVisitor +{ + typedef typename Graph::vertex_index vertex_index; + + /// Встретили "обратное" ребро (дуга, если орграф) dfs-дерева. + /** + Вызывается когда при посещении вершины v найдено исх.ребро, направленное к + ранее посещенной вершине. Другими словами, вершина u является предком + вершине v в dfs-дереве. + */ + void BackEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + /// Вызывается, когда впервые проходим через исходящую дугу v->u, вершину u еще не посещали + void ExamineEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + /// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться + void DiscoverNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + /// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены + void FinishNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + /// Встретили "поперечное" или "прямое" ребро + /** + Вызывается, когда находим дугу, идущую к другому dfs-дереву, либо прямую дугу, + идущую к потомку того же дерева, имеющему два и более отцов. + Для поперечного ребра вызывается только для ориентированных графов. + */ + void ForwardOrCrossEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} + /// Отвечает, что вершина исключена из рассмотрения + bool Ignored( vertex_index /*v*/, const Graph & /*g*/ ) const { return false; } + /// Означает, что начато рассмотрение корневой вершины будущего дерева обхода + void StartNode( vertex_index /*v*/, const Graph & /*g*/ ) {} + /// Ребро стало "древесным" (принадлежит dfs-дереву). Вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u + void TreeEdge( vertex_index /*v*/, vertex_index /*u*/, const Graph & /*g*/ ) {} +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// Посетитель алгоритма поиска блоков и точек сочленения в неориентированном графе +/** + Позволяет настроить алгоритм поиска блоков и точек сочленения под конкретные реализации. +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +template< class Graph > +struct DefaultBicompVisitor +{ + /// Найден блок, как последовательность ребер + template + void BlockFounded( EdgeIterator, EdgeIterator, const Graph & ) {} + + /// Обнаружена точка сочленения (articulation vertex) + template + void CutNode( Vertex, const Graph & ) {} + + /// Функция обратного вызова: Фильтрация для точек сочленения + /** + С момощью этой функции пользователь настраивает поведение алгорита поиска блоков. + Если визитер отвечает true, то алгоритм не учитывает данную вершину, + как вершину разреза, отделяющую блоки. Таким образом в результате + отфильтрованная точка сочленения всегда будет принадлежать одному блоку. + */ + template + bool IsFilteredCut( Vertex, const Graph & ) const { return false; } +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// Посетитель обхода в глубину для поиска блоков и точек сочленения +/** + Класс является автономным и не нуждается в уточнении наследованием от него. + Graph - предполагается, что это неориентированный граф. + BicompVisitor - надстроенный визитер, посетитель этого визитера, который + реализует события обнаружения блока, точки сочленения и + фильтрацию вершин, которые принудительно запрещается быть + точками сочленения. +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +template< class Graph, class BicompVisitor = DefaultBicompVisitor > +class BicompDFSVisitor: public DefaultDFSVisitor +{ +public: + typedef typename Graph::adj_iterator adj_iterator; + typedef typename Graph::edge edge; + +public: + static const typename Graph::vertex_index NO_VERTEX = (size_t)-1; + + BicompDFSVisitor( BicompVisitor & vis ) + : m_graph( c3d_null ) + , m_bicompVis( vis ) + , m_dfsCounter( 1 ) + , num() + , father() + , lval() + , m_stackEdges() + {} + + /// Встретили поперечное или прямое ребро + void ForwardOrCrossEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & ) + { + DEBUG_UNUSED_PARAMETER( u ); + DEBUG_UNUSED_PARAMETER( v ); + PRECONDITION( num[v] < num[u] ); + } + + /// Найдено обратное ребро dfs-дерева, вызывается когда при посещении вершины v найдено исх.ребро к ранее посещенной вершине + /** + Вершина u является предком вершине v в dfs-дереве. + */ + void BackEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g ) + { + DEBUG_UNUSED_PARAMETER( g ); + PRECONDITION( m_graph == &g ); + PRECONDITION( num[u] < num[v] ); + PRECONDITION( father[v] != NO_VERTEX ); + if ( u != father[v] ) + { + // Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве; + m_stackEdges.push_back( edge(v,u) ); // вставить ребро vu; + lval[v] = min_of( lval[v], num[u] ); // см.лемму 6; + } + } + + /// Посещение вершины: Вызывается один раз для каждой вершины, когда она впервые начинает просматриваться + void DiscoverNode( typename Graph::vertex_index v, const Graph & g ) + { + DEBUG_UNUSED_PARAMETER( g ); + C3D_ASSERT( m_graph == &g ); + PRECONDITION( num[v] == 0 ); + PRECONDITION( lval[v] == 0 ); + num[v] = lval[v] = m_dfsCounter++; + } + + /// Вершина рассмотрена: Означает, что все исходящие ребра вершины рассмотрены + void FinishNode( typename Graph::vertex_index u, const Graph & g ) + { + PRECONDITION( m_graph == &g ); + typename Graph::vertex_index v = father[u]; + if ( v == NO_VERTEX ) // СЛУЧАЙ 1: Вершина u - корневая, завершен обход fds-дерева + { + // Оценить является ли u - точкой сочленения + // Сколько раз стартовая вершина стала папой (столько же в ней стыкуется блоков) + if ( _ChildrenNb(u, g) > 1) + { + // В корневой вершине стыкуются 2 или более блоков - значит она же является и точкой сочленения + m_bicompVis.CutNode( u, g ); + } + // Извещение о найденном блоке + if ( !m_stackEdges.empty() ) // Все что есть в m_stackEdges - следует считать последним найденным блоком. + { + m_bicompVis.BlockFounded( m_stackEdges.begin(), m_stackEdges.end(), g ); + // После извещения визитера - вычищаем стек + m_stackEdges.clear(); + } + } + else // СЛУЧАЙ 2: u - не корневая вершина + { + lval[v] = min_of( lval[v], lval[u] ); // см. лемму 6; + if ( lval[u] >= num[v] ) + { + // Здесь можно получить новый блок, для чего достаточно вытолкнуть из + // стека все ребра, включая ребро vu. + + // (!) Если вершина v не корень d-дерева, то можно утверждать, что она - есть точка сочленения; + // См. теорему 8.2. + if ( father[v] != NO_VERTEX ) // если v корневая вершина, то оценки для неё делаются в конце обхода дерева + { + m_bicompVis.CutNode( v, *m_graph ); + } + + // Извещение о найденном блоке + if ( !m_bicompVis.IsFilteredCut(v,*m_graph) ) // Запрет на отфильтрованные точки сочленения - они не могут "вырезать" блоки. + { + // Тут мы запретили собирать блок, т.к. вершина фильтрованная, однако это не принесет ущерба, + // если окажется что v - не точка сочленения. Вот почему: + /* + Если v - есть корень dfs-дерева, то возможны 2 варианта: v принадлежит одному блоку, + тогда v не точка сочленения; v принадлежит двум и более блокам, тогда v - есть точка сочленения. + В первом случае единственный блок, куда включена v, будет собран в конце текущего обхода dfs-дерева, + массив m_stackEdges полностью будет содержать этот блок. Во втором случае, если блок не + единственный, то v - есть точка сочленения, тогда очевидно запрет правомерен - в конце обхода дерева все, + что осталось в стеке ребер есть один блок. + */ + + PRECONDITION( !m_stackEdges.empty() ); + /* + std::vector::reverse_iterator vuIter = + std::find( m_stackEdges.rbegin(), m_stackEdges.rend(), edge(v,u) ); // Ищем с конца + PRECONDITION( vuIter != m_stackEdges.rend() ) // Это ребро обязано быть в стеке + m_bicompVis.BlockFounded( vuIter.base()-1, m_stackEdges.end(), *m_graph ); + // После извещения визитера - вычищаем блок из стека конца + m_stackEdges.erase( vuIter.base()-1, m_stackEdges.end() ); + */ + + const edge seek( v, u ); + typename std::vector::iterator first = m_stackEdges.begin(); + typename std::vector::iterator iter, last; + for ( iter = last = m_stackEdges.end(); iter != first; ) + { + --iter; + if ( *iter == seek ) + { + break; + } + } + + PRECONDITION( *iter == seek ); // Это ребро обязано быть в стеке + m_bicompVis.BlockFounded( iter, last, *m_graph ); + // После извещения визитера - вычищаем блок из стека конца + m_stackEdges.erase( iter, last ); + } + } + } + } + + /// Означает, что начато рассмотрение корневой вершины будущего дерева обхода + void StartNode( typename Graph::vertex_index v, const Graph & g ) + { + DEBUG_UNUSED_PARAMETER( v ); + _Init( g ); + PRECONDITION( father[v] == NO_VERTEX ); + PRECONDITION( num[v] == 0 && lval[v] == 0 ); + } + + /// Заход в ребро dfs-дерева, вызывается перед переходом от посещенной вершины v к еще не посещенной вершине u + void TreeEdge( typename Graph::vertex_index v, typename Graph::vertex_index u, const Graph & g ) + { + DEBUG_UNUSED_PARAMETER( g ); + PRECONDITION( m_graph == &g ); + PRECONDITION( father[u] == NO_VERTEX ); + m_stackEdges.push_back( edge(v,u) ); // Вставить ребро vu; + father[u] = v; // зафиксируем отца для вершины u; + } + +private: + /// Количество сыновей вершины + size_t _ChildrenNb( typename Graph::vertex_index u, const Graph & g ) const + { + PRECONDITION( m_graph == &g ); + // Оценить является ли u - точкой сочленения + size_t fatherNb = 0; // Сколько раз вершина u стала папой + std::pair adjIterPair = g.AdjacentVertices( u ); + for ( ; adjIterPair.first != adjIterPair.second; ++adjIterPair.first ) + { + if ( father[*adjIterPair.first] == u ) + { + ++fatherNb; + } + } + return fatherNb; + } + + void _Init( const Graph & graph ) + { + m_graph = &graph; + const typename Graph::vertices_size_t vertNb = graph.NumVertices(); + m_dfsCounter = 1; + num.assign( vertNb, 0 ); + father.assign( vertNb, NO_VERTEX ); + lval.assign( vertNb, 0 ); + m_stackEdges.clear(); + } + +private: + const Graph * m_graph; ///< Рассматриваемый граф, для которого ищутся точки сочленения + BicompVisitor & m_bicompVis; ///< Посетитель алгоритмов этого класса + ptrdiff_t m_dfsCounter; ///< Cчетчик вершин dfs-дерева + std::vector num; ///< Нумерация порядка обхода вершин d-дерева + std::vector lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6; + std::vector father;///< Отец вершины в dfs-дереве + std::vector m_stackEdges; ///< Cтек ребер для обслуживания нахождения блоков + +private: + BicompDFSVisitor & operator = ( const BicompDFSVisitor & ); +}; + +//---------------------------------------------------------------------------------------- +// Стековый элемент для алгоритма обхода в глубину. +// --- +template +struct DFSVertexInfo +{ +private: + typedef typename Graph::vertex_index vertex_index; + typedef typename Graph::adj_iterator adj_iterator; + +public: + vertex_index m_node; + adj_iterator m_iter; + adj_iterator m_last; + + DFSVertexInfo( vertex_index v, adj_iterator iter, adj_iterator last ) + : m_node( v ) + , m_iter( iter ) + , m_last( last ) + {} + + DFSVertexInfo( vertex_index v, const Graph & graph ) + : m_node( v ) + , m_iter() + , m_last() + { + tie(m_iter,m_last) = graph.AdjacentVertices( v ); + } + + DFSVertexInfo( const DFSVertexInfo & vi ) + : m_node( vi.m_node ) + , m_iter( vi.m_iter ) + , m_last( vi.m_last ) + {} + + DFSVertexInfo & operator = ( const DFSVertexInfo & vi ) + { + m_node = vi.m_node; + m_iter = vi.m_iter; + m_last = vi.m_last; + return *this; + } +}; + +//---------------------------------------------------------------------------------------- +/// Алгоритм обхода в глубину графа смежности +/** + Вычислительная сложность алгоритма практически линейная, если считать что + методы визитера выполняются за константное время. + + \param graph Граф смежности + \param vis Посетитель алгоритма +*/ +//--- + +template +void DepthFirstSearch( const Graph & graph, Visitor & vis ) +{ + typedef typename Graph::vertices_size_t vertices_size_t; + typedef typename Graph::vertex_index vertex_index; + typedef typename Graph::adj_iterator adj_iterator; + /* + enum Color // Разметка + { + col_white // не посещалась + , col_gray // в стеке + , col_black // + }; + */ + + const vertices_size_t vCount = graph.NumVertices(); + + std::vector> stack; + std::vector colourMap( vCount, white_color ); // отображение: вершина -> цвет + + // Пометить, как рассмотренные, игнорируемые вершины + for ( vertex_index xIdx = 0; xIdx(startNode,graph) ); + + while ( !stack.empty() ) + { + { + DFSVertexInfo & curr = stack.back(); + vIter = curr.m_iter; + vLast = curr.m_last; + srcNode = curr.m_node; + stack.pop_back(); + } + + while ( vIter != vLast ) + { + const vertex_index trgNode = *vIter; + ++vIter; + + vis.ExamineEdge( srcNode, trgNode, graph ); + + switch ( colourMap[trgNode] ) // Переход по дереву к следующей вершине + { + case white_color: + { + vis.TreeEdge( srcNode, trgNode, graph ); // "древесное" ребро + colourMap[trgNode] = gray_color; + stack.push_back( DFSVertexInfo( srcNode, vIter, vLast ) ); + vis.DiscoverNode( srcNode = trgNode, graph ); + tie( vIter, vLast ) = graph.AdjacentVertices( srcNode ); + break; + } + case gray_color: // Встетили обратное ребро + { + vis.BackEdge( srcNode, trgNode, graph ); + break; + } + default: // Встретили "прямое" или "кросс-ребро" в ориентированном графе + { + vis.ForwardOrCrossEdge( srcNode, trgNode, graph ); + break; + } + } + } + + // Событие завершения обхода текущей вершины + colourMap[srcNode] = black_color; + vis.FinishNode( srcNode, graph ); + } + } + } +} + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// Отображение реберных свойств для графов, поддерживающих концепцию смежности вершин (без явных ребер) +/** + Для графов с инцидентными ребрами лучше использовать другие типы отображений +*/ +////////////////////////////////////////////////////////////////////////////////////////// +/* +template +class EdgePropertyMap +{ + typedef Graph::vertex_descriptor vertex_descriptor; + typedef Graph::edge_descriptor edge_descriptor; + typedef std::pair pair; + class node + { + public: + node( const node & ); + node & operator = ( const node & ); + + private: + vertex_descriptor vertex; + std::vector props; + }; + + std::vector nodes; + +public: + const Prop & operator[]( edge_descriptor ) const; + Prop & operator[]( edge_descriptor ); +}; +*/ + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// Инкапсуляция алгоритма поиска 2-связных компонент и/или точек сочленения +/** + ПЛАНИРУЕТСЯ ЗАМЕНИТЬ ЭТОТ АЛГОРИТМ НА БОЛЕЕ ОБЩИЙ НО НЕ МЕНЕЕ ЭФФЕКТИВНЫЙ: + DepthFirstSearch + BicompDFSVisitor + + \par Определение + d-деревом называем ациклический подграф рассматриваеморго графа, состоящего + из вершин и ребер, которые обходит поиск в глубину, на основе которого построен + данный адгоритм. + Graph - тип, отвечающий требованиям обычного графа смежности по вершинам + + \par РЕФАКТОРИНГ + 1) Нужно обобщить это алгоритм с библиотекой MtGraph + 2) Возможно снабдить это класс-алгоритм посетителем поиска компонент. + Это, например, позволит генерировать два варианта алгоритма поиска блоков: + Вариант, когда нужно найти только вершины сочленения (без блоков) вариант, + когда нужно искать шарниры и/или блоки; + 2.1.) Возможны другие рецепты, как генерить шаблоном два похожих алгоритма. + 3) Алгоритм можно упростить, если переложить его на еще более общный + алгоритм обхода в глубину. +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +template +class MtBicompSearch +{ + // Ассоциативные типы + typedef typename Graph::vertex_index vertex_index; + typedef typename Graph::vertex_size_t vertex_size_t; + typedef typename Graph::adj_iterator adj_iterator; + +private: + const Graph & m_graph; + ptrdiff_t m_dfsCounter; + std::vector num; ///< Нумерация порядка обхода вершин d-дерева + std::vector father; ///< Отец вершины в d-дереве + std::vector lval; ///< Массив значений функции L[v] на каждую вершину - см.теорию стр.166, [Asan], Лемма 6; + std::vector m_cutnodes; ///< Обнаруженные точки сочленения + std::vector m_cutnodeProp; ///< Признак точки сочленения для вершин + +public: + MtBicompSearch( const Graph & ); + /// Найти все точки сочленения + const std::vector & SearchCutnodes(); + +private: + /// Алгоритм реккурсивного вызова поиска блоков и точек сочленения в графе + void BiComp( vertex_index ); + /// Инициализировать все рабочие данные для нового поиска + void Init(); + /// Запустить алгоритм + void Perform(); +}; + +//---------------------------------------------------------------------------------------- +// +//--- +template +MtBicompSearch::MtBicompSearch( const Graph & g ) + : m_graph( g ) + , m_dfsCounter(1) + , num() + , father() + , lval() + , m_cutnodes() + , m_cutnodeProp() +{} + +//---------------------------------------------------------------------------------------- +/// Найти все точки сочленения +//--- +template +const std::vector & MtBicompSearch::SearchCutnodes() +{ + Init(); + Perform(); + return m_cutnodes; +} + +//---------------------------------------------------------------------------------------- +/// Инициализировать все рабочие данные для нового поиска +//--- +template +void MtBicompSearch::Init() +{ + const vertex_size_t vertNb = m_graph.NumVertecies(); + m_dfsCounter = 1; + num.assign( vertNb, 0 ); + father.assign( vertNb, -1 ); + lval.assign( vertNb, -1 ); + m_cutnodeProp.assign( vertNb, false ); + m_cutnodes.clear(); +} + +//---------------------------------------------------------------------------------------- +/// Запустить алгоритм +//--- +template +void MtBicompSearch::Perform() +{ + PRECONDITION( m_cutnodes.empty() ); + + const vertex_size_t vertNb = m_graph.NumVertecies(); + for ( vertex_index startIdx = 0; startIdx adjIterPair = m_graph.AdjacentVertices( startIdx ); + for ( ; adjIterPair.first!=adjIterPair.second; ++adjIterPair.first ) + { + if ( father[*adjIterPair.first] == startIdx ) + { + ++fatherNb; + } + } + if ( fatherNb > 1 ) + { + // Корневая вершина - есть точка сочленения + PRECONDITION( !m_cutnodeProp[startIdx] ); + m_cutnodes.push_back( startIdx ); + m_cutnodeProp[startIdx] = true; + } + } + } +} + +//---------------------------------------------------------------------------------------- +/// Алгоритм реккурентного вызова поиска блоков и точек сочленения в графе +/** + Теорию см.главе 8, стр.166, Графы, матроиды, алгоритмы [Asan]; + \param vIdx - вершина (индекс), с которой начинаем поиск, которая ещё не рассмотрена, т.е. + num[vIdx] = 0; + + \par Определения + d-дерево - ациклический подграф основного подграфа, образуемого при обходе + вершин во время поиска в глубину; + + \par Вычислительная сложность + Вычислительная сложность: O(n+m), где n-кол-во вершин, m-кол-во ребер. Это следует из + того факта, что каждая вершина посещается не более одного раза. +*/ +//--- +template +void MtBicompSearch::BiComp( const vertex_index vIdx ) +{ + PRECONDITION( num[vIdx] == 0 ); + num[vIdx] = lval[vIdx] = m_dfsCounter; + ++m_dfsCounter; + + // Цикл по всем смежным вершинам vert; + std::pair adjIterPair = m_graph.AdjacentVertices( vIdx ); + for ( ; adjIterPair.first!=adjIterPair.second; ++adjIterPair.first ) + { + const vertex_index uIdx = *adjIterPair.first; // Вершина - сын в d-дереве; + // const edge_descriptor vuEdg = m_graph.GetEdge( vIdx, uIdx ); + if ( num[uIdx] == 0 ) // uIdx - сын вершины vIdx + { + // stackE.push_back( vuEdg ); // Вставить ребро vu; + PRECONDITION( father[uIdx] == -1 ); + father[uIdx] = vIdx; // зафиксируем отца для данной вершины uIdx; + BiComp( uIdx ); + + // При выходе из рекурсии значение функции L[u] уже вычислено; + lval[vIdx] = min_of( lval[vIdx], lval[uIdx] ); // см.лемму 6; + if ( lval[uIdx] >= num[vIdx] ) + { + // Здесь можно получить новый блок, для чего достаточно вытолкнуть из + // стека все ребра, включая ребро vu. + + // (!) Если вершина vIdx не корень d-дерева, то можно утверждать, что она - есть точка сочленения; + // См. теорему 8.2. + if ( father[vIdx] != -1 ) // Первородитель + { + if ( !m_cutnodeProp[vIdx] ) + { + m_cutnodes.push_back( vIdx ); + m_cutnodeProp[vIdx] = true; + } + } + /* + PRECONDITION( !stackE.empty() ) + blocks.NewComp(); + + #pragma message ( __TODO__ "(**) Собирать ребра возможно не понадобится! Достаточно cutnodes;" ) + while( !stackE.empty() ) + { + edge_descriptor edge = stackE.back(); + blocks.AddEdge( edge ); + stackE.pop_back(); // вытолкнуть ребро из стека; + if ( edge == vuEdg ) + { + break; + } + } + */ + } + } + else if ( num[uIdx] < num[vIdx] && uIdx != father[vIdx] ) + { + // Здесь vu - есть обратное ребро входящее в вершину u, которая выше, чем v в d-дереве; + // stackE.push_back( vuEdg ); // вставить ребро vu; + lval[vIdx] = min_of( lval[vIdx], num[uIdx] ); // см.лемму 6; + } + } +} + + +////////////////////////////////////////////////////////////////////////////////////////// +// +// Посетитель алгоритма поиска компонент сильной связности +// +////////////////////////////////////////////////////////////////////////////////////////// +struct DefaultSCVisitor +{ + // Вызывается алгоритмом перед началом обхода всего графа + template + inline void Start( const Graph & ) {} + // Вызывается, когда найден очередной компонент сильной связности в орграфе + /* + Аргументы: граф и пара вершинных итераторов, пробегающих подмножество компонента + */ + template + inline void Component( const Graph &, VertexIter, VertexIter ) {} + // Если IsFiltered = true, вершина считается исключенной из графа + template + inline bool IsFiltered( const Graph &, Vertex ) { return false; } +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// Алгоритм поиска компонент сильной связности в орграфе +/** + Напомним, что две вершины орграфа считаются сильно связанными, если + существует маршрут из первой вершины ко второй и обратный маршрут из второй + к первой. Подграф называется сильно связным, если любая пары его + вершин сильно связаны. Компонент сильной связности графа - это один из + его сильно сзязный подграфов G', для которого не существует сильно связной пары + вершин u и v, таких, что u-принадлежит G', а v не принадлежит G'. Другими словами, + вершины компонента сильной связости принадлежат классу взаимной достижимости вершин; + \note Алгоритм #MtStrongComponents имеет линейную сложность вычислений + \ingroup GCBase +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +template +class MtStrongComponents +{ +public: // Ассоциативные типы + typedef typename graph_traits::vertex vertex; + typedef typename graph_traits::edge edge; + typedef typename graph_traits::edge_iterator edge_iterator; + typedef typename graph_traits::vertex_iterator vertex_iterator; + +public: + MtStrongComponents( const Graph &, SCVisitor & ); + void operator() (); ///< Исполнить алгоритм поиска сильных компонентов + +private: + // DFS-алгоритм для поиска компонент сильной связности в графе ограничений + void StrongSearch( vertex, std::vector & ); + +private: + const Graph & m_diGraph; ///< Ориентированный граф + SCVisitor & m_vis; ///< Посетитель алгоритма поиска компонент сильной связности + size_t m_counter; ///< Порядок DFS-обхода + VertexPropertyMap num; ///< Вспомогательный массив порядковых номеров обхода в глубину + VertexPropertyMap lval; ///< Массив для промежуточных целочисленных вычислений + +private: + MtStrongComponents( const MtStrongComponents & ); + MtStrongComponents & operator = ( const MtStrongComponents & ); +}; + +//---------------------------------------------------------------------------------------- +// +//--- +template +MtStrongComponents::MtStrongComponents( const Graph & b_graph, Vis & vis ) + : m_diGraph( b_graph ) + , m_vis( vis ) + , num( b_graph.NumVertices() ) + , lval( b_graph.NumVertices() ) + , m_counter( 1 ) +{} + +//---------------------------------------------------------------------------------------- +// Главный алгоритм поиска компонент сильной связности в графе ограничений +//--- +template +void MtStrongComponents::operator() () +{ + m_vis.Start( m_diGraph ); + + std::vector stack; + stack.reserve( m_diGraph.NumVertices() ); + m_counter = 1; + + vertex_iterator vIter, vLast; + + for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) + { + num[*vIter] = 0; + } + + for ( tie(vIter,vLast) = m_diGraph.Vertices(); vIter!=vLast; ++vIter ) + { + if ( num[*vIter] == 0 && !m_vis.IsFiltered(m_diGraph,*vIter) ) + StrongSearch( *vIter, stack ); + } +} + +//#define _RECURSIVE_STRONG_SEARCH 1 + +#ifdef _RECURSIVE_STRONG_SEARCH + +//---------------------------------------------------------------------------------------- +/// Алгоритм поиска компонент сильной связности в орграфе +/** + Алгоритм применяется для разбиения графа ограничений на независимо + решаемые подсистемы (сегменты). Рекурсивный вариант. Описание алгоритма приведено + в книжке Асанова по теории графов, стр.171.\n + \param vx - корневая вершина поддерева DFS + \param stack - стек рассмотренных вершин, для которых не установлена компонентная принадлежность +*/ +//--- +template +void MtStrongComponents::StrongSearch( vertex vx, std::vector & stack ) +{ + PRECONDITION( !m_vis.IsFiltered(m_diGraph,vx) ); + + num[vx] = m_counter; + lval[vx] = m_counter; + ++m_counter; + stack.push_back( vx ); + + edge_iterator eIter, eLast; // итераторы обхода инцидентных ребер + for ( tie(eIter,eLast) = m_diGraph.OutArcs(vx); eIter!=eLast; ++eIter ) + { + vertex w = m_diGraph.Target( *eIter ); // Выходящая вершина прямого ребра + PRECONDITION( w != vx ); // Граф не ориентированный !!! + if ( w != vx && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы; + { + if ( num[w] == 0 ) // - "древесная" дуга + { + StrongSearch( w, stack ); + if ( lval[w] < lval[vx] ) // При выходе из рекурсии значение l(w) должно быть уже насчитано; + lval[vx] = lval[w]; + } + else + { + const size_t wNum = num[w]; + if ( wNum < num[vx] && wNum < lval[vx] ) // - "поперечная" или "обратная" дуга + { + // Предположение: В стеке лежат вершины, из которых вершина vx достижима; + if ( std::find(stack.rbegin(), stack.rend(), w) != stack.rend() ) + { + lval[vx] = wNum; + } + } + } + } + } + + const size_t vNum = num[vx]; + if ( lval[vx] == vNum ) // vx - корневая вершина очередной компоненты сильной связности + { + // Обнаружен очередной сильный компонент + if ( !stack.empty() && num[stack.back()] >= vNum ) + { + // Посчитать размер компонента + typename std::vector::reverse_iterator vIter, vLast; + vIter = stack.rbegin(); + vLast = stack.rend(); + ptrdiff_t compSize = 0; + for ( ; vIter != vLast && num[*vIter] >= vNum; ++vIter, ++compSize ); + + // Передать диапазон компонента визитеру + typename std::vector::iterator cIter, cLast; + cIter = cLast = stack.end(); + std::advance( cIter, -compSize ); + m_vis.Component( m_diGraph, cIter, cLast ); + stack.erase( cIter, cLast ); // очистить верхушку стека + } + } +} + +#else // _RECURSIVE_STRONG_SEARCH + + +//---------------------------------------------------------------------------------------- +/// Стековый элемент для алгоритма обхода в глубину +//--- +template +struct DFS_element +{ + typedef typename Graph::vertices_size_t vertices_size_t; + typedef typename Graph::vertex vertex; + typedef typename Graph::edge_iterator edge_iterator; + + vertex node; + edge_iterator iter; + edge_iterator last; + + DFS_element( vertex v, const std::pair & pair ) + : node( v ) + , iter( pair.first ) + , last( pair.second ) + {} + + DFS_element( vertex v, const Graph & graph ) + : node( v ) + , iter() + , last() + { + tie( iter, last ) = graph.OutArcs( v ); + } + + DFS_element( const DFS_element & vi ) + : node( vi.node ) + , iter( vi.iter ) + , last( vi.last ) + {} + + DFS_element & operator = ( const DFS_element & vi ) + { + node = vi.node; + iter = vi.iter; + last = vi.last; + return *this; + } +}; + +//---------------------------------------------------------------------------------------- +/// Алгоритм поиска компонент сильной связности в орграфе +/** + Алгоритм применяется для разбиения графа ограничений на независимо-решаемые + подсистемы (сегменты). Описание алгоритма приведено в книжке Асанова по + теории графов, стр.171.\n + MA2013-02-22: Алгоритм переделан под нерекурсивный вариант; + \param rootVert - корневая вершина поддерева DFS + \param comStack - стек рассмотренных вершин, для которых не установлена компонентная принадлежность +*/ +//--- +template +void MtStrongComponents::StrongSearch( vertex rootVert + , std::vector & comStack ) +{ + typedef DFS_element DfsStackElem; + + PRECONDITION( !m_vis.IsFiltered(m_diGraph,rootVert) ); + std::vector dfsStack; + + num[rootVert] = lval[rootVert] = m_counter; + ++m_counter; + comStack.push_back( rootVert ); + dfsStack.push_back( DfsStackElem( rootVert, m_diGraph ) ); + DfsStackElem * topElem = &dfsStack.back(); + + while( !dfsStack.empty() ) // Цикл возвратов из стека (одна итерация - одно возвращение против древесного ребра ) + { + while ( topElem->iter != topElem->last ) + { + vertex w = m_diGraph.Target( *topElem->iter ); // Выходящая вершина прямого ребра + PRECONDITION( w != topElem->node ); // Граф не ориентированный !!! + if ( (w != topElem->node) && !m_vis.IsFiltered(m_diGraph,w) ) // игнорируем обратное ребро из w в vx, а также отфильтрованные узлы; + { + if ( num[w] == 0 ) // - "древесная" дуга + { + // Вместо рекурсии: StrongSearch( w, stack ); + num[w] = lval[w] = m_counter; + ++m_counter; + comStack.push_back( w ); + dfsStack.push_back( DfsStackElem(w, m_diGraph) ); + topElem = &dfsStack.back(); + continue; + } + else + { + const size_t wNum = num[w]; + if ( wNum < num[topElem->node] && wNum < lval[topElem->node] ) // - "поперечная" или "обратная" дуга + { + // Предположение: В стеке лежат вершины, из которых вершина vx достижима; + if ( std::find(comStack.rbegin(), comStack.rend(), w) != comStack.rend() ) + { + lval[topElem->node] = wNum; + } + } + } + } + ++topElem->iter; + } + + PRECONDITION( dfsStack.back().iter == dfsStack.back().last ); + PRECONDITION( topElem == &dfsStack.back() ); + + // Завершено посещение узла sElem->m_node + const size_t vNum = num[topElem->node/*vx*/]; + if ( lval[topElem->node/*vx*/] == vNum ) // vx - корневая вершина очередной компоненты сильной связности + { + // Обнаружен очередной сильный компонент + if ( !comStack.empty() && num[comStack.back()] >= vNum ) + { + // Посчитать размер компонента + typename std::vector::reverse_iterator vIter, vLast; + vIter = comStack.rbegin(); + vLast = comStack.rend(); + ptrdiff_t compSize = 0; + for ( ; vIter != vLast && num[*vIter] >= vNum; ++vIter, ++compSize ); + + // Передать диапазон компонента визитеру + typename std::vector::iterator cIter, cLast; + cIter = cLast = comStack.end(); + std::advance( cIter, -compSize ); + m_vis.Component( m_diGraph, cIter, cLast ); + comStack.erase( cIter, cLast ); // очистить верхушку стека + } + } + // Возвращение против древесного ребра , где w-просмотренная вершина, v-вершина из которой пришли в w; + { + const vertex w = topElem->node; + dfsStack.pop_back(); + + if ( !dfsStack.empty() ) + { + topElem = &dfsStack.back(); + const vertex vxPrev = dfsStack.back().node; + // При выходе из рекурсии значение lVal(w) должно быть уже насчитано; + if ( lval[w] < lval[vxPrev] ) + { + lval[vxPrev] = lval[w]; + } + } + } + } +} + +#endif // _RECURSIVE_STRONG_SEARCH + +#endif // __GRAPH_ALGORITHMS_H + +// eof diff --git a/C3d/Include/iges_basic.h b/C3d/Include/iges_basic.h index e1bcdaf..e9c08e0 100644 --- a/C3d/Include/iges_basic.h +++ b/C3d/Include/iges_basic.h @@ -1,353 +1,353 @@ -//////////////////////////////////////////////////////////////////////////////// -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IGES_BASIC_H -#define __IGES_BASIC_H - -#include - -#include - -#define IGS_DOUBLE_TO_STRING_NDEC 15 - - -//------------------------------------------------------------------------------ -// типы IGS псевдо объектов -// --- -typedef enum { - igs_CopiousData11 = 11, - igs_MetalHatch = 31, - igs_CeramicHatch = 32, - igs_Hatch33 = 33, - igs_Hatch34 = 34, - igs_Hatch35 = 35, - igs_Hatch36 = 36, - igs_NonMetalHatch = 37, - igs_BrickHatch = 38, - igs_WitnesLine = 40, - - igs_ItArcOrCircleIGES = 100, - igs_ItContourIGES = 102, - igs_ItConicIGES = 104, - igs_ItCopiousDataIGES = 106, - igs_ItPlaneIGES = 108, - igs_ItLineSegIGES = 110, - igs_ItSplineIGES = 112, - igs_ItParametricSplineSurfaceIGES = 114, - igs_ItPointIGES = 116, - igs_ItRuledSurfaceIGES = 118, - igs_ItSurfaceOfRevolutionIGES = 120, - igs_ItTabulatedCylinderIGES = 122, - igs_ItDirectionIGES = 123, - igs_ItTransformMatrixIGES = 124, - igs_ItRationalBSplineCurveIGES = 126, - igs_ItRationalBSplineSurfaceIGES = 128, - igs_ItOffsetSurfaceIGES = 140, - igs_ItBoundaryIGES = 141, - igs_ItCurveOnParametricSurfaceIGES = 142, - igs_ItBoundedSurfaceIGES = 143, - igs_ItTrimmedParametricSurfaceIGES = 144, - igs_ItManifoldSolidBRepIGES = 186, - igs_ItPlaneSurfaceIGES = 190, - igs_ItRCCylindricalSurfaceIGES = 192, - igs_ItRCConicalSurfaceIGES = 194, - igs_ItSphericalSurfaceIGES = 196, - igs_ItToroidalSurfaceIGES = 198, - - igs_AngularDim = 202, - igs_DiamDim = 206, - igs_Text = 212, - igs_Leader = 214, - igs_LinDim = 216, - igs_RadDim = 222, - - igs_ItSubfigureIGES = 308, - igs_ItColorIGES = 314, - igs_ItBlockIGES = 402, - igs_ItPropertyIGES = 406, - igs_ItSingularSubfigureInstanceIGES = 408, - igs_ItExternalReferenceIGES = 416, - igs_ItVertexListIGES = 502, - igs_ItEdgeListIGES = 504, - igs_ItLoopIGES = 508, - igs_ItFaceIGES = 510, - igs_ItShellIGES = 514, - igs_Surface, - igs_SpaceCurve, -} IGSGConverterType; - - -//----------------------------------------------------------------------------- -// -// --- -typedef enum { // секция - UndefSection, - FlagSection, // not always present - StartSection, - GlobalSection, - DirectoryEntrySection, - ParametrDataSection, - TerminateSection -} NameSectionIGES; - -#define LENGTH_STRING_FILE 80 -#define LENGTH_STRING_IGES 72 - -#define IGS_WIDTH 1000 // число градаций толщины - -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS 58 -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS_GOST 6 -//#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1001 30 -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1001 29 -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1002 34 -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1003 32 -#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS800 7 - - -#define IGS_BLOCK_GROUP 1 // + форма блока 1 -#define IGS_BLOCK_GROUP_WO_BACK_POINTERS 7 // + форма блока 7 - без обратных указателей - -#define IGS_DOUBLE_UNDEF -1e32 // - -#define ENTITY_LABEL_COUNT 8 ///< Длина поля entityLabel - -#define VDE_VISIBLE_YES 0 ///< Объект видим -#define VDE_VISIBLE_NO 1 ///< Объект невидим - -#define VDE_DEPEND_NO 0 ///< Объект независим -#define VDE_DEPEND_PHYS 1 ///< Объект зависим физически -#define VDE_DEPEND_LOG 2 ///< Объект зависим логически -#define VDE_DEPEND_BOTH 3 ///< Зависим физически и логически - -#define VDE_USE_GEOMETRY 0 ///< Объект геометрический -#define VDE_USE_ANNOT 1 ///< Объект аннотационный -#define VDE_USE_DEF 2 ///< Объект определение -#define VDE_USE_OTHER 3 ///< Объект вне классификации -#define VDE_USE_LOG_POS 4 ///< Объект логический / позиционирование -#define VDE_USE_2D_PARAM 5 ///< Объект параметрический 2D -#define VDE_USE_CONSTR_GM 6 ///< Объект конструктивной геометрии - -#define VDE_HIER_TOP_DOWN 0 ///< Сверху вниз -#define VDE_HIER_GLOB_DEFER 1 ///< Глобально -#define VDE_HIER_PROPERTY 2 ///< Свойство - - -//------------------------------------------------------------------------------- -// -// --- -struct VectorDE{ - unsigned short visible : 1;// 9 вектор состояния - unsigned short depend : 2;// 9 - unsigned short geometry : 3;// 9 - unsigned short hierarchy : 2;// 9 -}; - - -//----------------------------------------------------------------------------- -// -// --- -struct DirEntryParameter { -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// горячо рекомендую все изменения в структуре согласовывать с процедурой чтения -// ProcessingOneEntityDirEntrySection(), иначе есть очень реальный шанс все порушить, -// еще рекомендую крепко подумать, прежде чем делать виртуальные функции и наследников -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - int32 typeNumber; // 1 номер типа -// поле typeNumber должно идти первым - см. функцию Init этой структуры -// !!!!!!!!!!!!!!!!!!!! - ptrdiff_t numbParDataString; // 2 номер строки данных в секции Parametr Data - ptrdiff_t structure; // 3 инвертированный указатель на на строку в секции DirEntry обычно 0 - ptrdiff_t lineFontPattern; // 4 номер стандартного типа линии или указатель на строку с описанием нестандартного - ptrdiff_t level; // 5 номер слоя или указатель на строку с описанием слоя в секции DirEntry - ptrdiff_t view; // 6 указатель на строку с описанием вида в секции DirEntry - ptrdiff_t transformMatrix; // 7 указатель на строку с описанием матрицы преобразования в секции DirEntry - ptrdiff_t labelDisplayAssociativ;// 8 указатель на строку с ???? в секции DirEntry - // 9 вектор состояния - union { - VectorDE def; - unsigned short vector; - }; - ptrdiff_t numbString; // 10 номер строки - ptrdiff_t lineWeight; // 12 - 11 пропущен - градация толщины - ptrdiff_t color; // 13 номер цвета или указатель на строку с описанием цвета - ptrdiff_t lineCount; // 14 число строк под описание параметров в секции Parametr Data - int32 formNumber; // 15 - std::string entityLabel; // 18 метка - // SpAG K14 BUG_65022 - избавляемся от низкоуровневых абстракций - ptrdiff_t numerLabel; // 19 числовая метка - - DirEntryParameter( int32 type = 0 ): typeNumber( type ), numbParDataString( 0 ), structure( 0 ), lineFontPattern( 0 ), level( 0 ), - view( 0 ), transformMatrix( 0 ), labelDisplayAssociativ( 0 ), numbString( 0 ), lineWeight( 0 ), - color( 0 ), lineCount( 0 ), formNumber( 0 ), entityLabel( ENTITY_LABEL_COUNT, ' ' ), numerLabel( 0 ) { Init(); } // SpAG K13 SP1 анализаторы кода - - void Init() { - // SpAG - С точки зрения cppCheck должно быть гораздо более пристойно - def.visible = VDE_VISIBLE_YES; - def.depend = VDE_DEPEND_NO; - def.geometry = VDE_USE_DEF; - def.hierarchy = VDE_HIER_TOP_DOWN; - } - - void operator = ( const DirEntryParameter & o ) { - typeNumber = o.typeNumber; - numbParDataString = o.numbParDataString; - structure = o.structure; - lineFontPattern = o.lineFontPattern; - level = o.level; - view = o.view; - transformMatrix = o.transformMatrix; - labelDisplayAssociativ = o.labelDisplayAssociativ; - numbString = o.numbString; // BUG_71099 - lineWeight = o.lineWeight; - color = o.color; - lineCount = o.lineCount; - formNumber = o.formNumber; - entityLabel = o.entityLabel; // SpAG K14 BUG_65022 - numerLabel = o.numerLabel; - vector = o.vector; - } - - void Zero() { - typeNumber = 0; - numbParDataString = structure = lineFontPattern = level = view = transformMatrix = labelDisplayAssociativ = numbString = lineWeight = color = lineCount = numerLabel = 0; - formNumber = 0; - vector = 0; - entityLabel.assign( ENTITY_LABEL_COUNT, ' ' ); - } - - bool operator == ( DirEntryParameter & o ) const { return numbString == o.numbString; } - bool operator < ( DirEntryParameter & o ) const { return numbString < o.numbString; } -}; - - -//----------------------------------------------------------------------------- -// Данные общей секции. -// --- -struct GlobalSectionParameter { - int32 delimiter; // ограничитель параметров 1 - int32 recordDelimiter; // ограничитель записей 2 - std::string identifSendingSystem; // версия системы откуда 3 - std::string fileName; // 4 - std::string systemID; // идентификатор системы откуда 5 - std::string verPreProc; // версия препроцессора( на хрен она упала?) 6 - int32 numbBitsOnInt; // разрядность целого откуда 7 - int32 maxPowerFloat; // максимальная степень float откуда 8 - int32 numbSignFloat; // число значащих цифр float откуда 9 - int32 maxPowerDouble; // максимальная степень double откуда 10 - int32 numbSignDouble; // число значащих цифр double откуда 11 - std::string identifReceivngSystem;// версия системы куда 12 - double scale; // масштаб 13 - int32 unitFlag; // 14 1- дюймы 2 -мм 3- 4 -футы 5 -мили 6 -м 7 -км 8 -милидюймы 9- мкм 10- см 11 - микродюйм - std::string nameUnit; // 15 - int32 maxNumberOfLineWeightGrad; // 16 - double widthOfMaxLineWeight; // 17 - std::string dateAndTime; // 18 YYMMMDD.HHNNSS - double minResolution; // 19 - мин. разрешение системы - double maxAbsCoord; // 20 максимальное координата по модулю - std::string nameOfAuthor; // 21 автор - std::string authorsOrg; // 22 организация - int32 intVer; // 23 - int32 intDraftStandart; // 24 - std::string dateAndTimeMod; // 25 YYMMMDD.HHNNSS - - GlobalSectionParameter () { Init(); } - void Init() { - delimiter = ','; // ограничитель параметров 1 - recordDelimiter = ';'; // ограничитель записей 2 - identifSendingSystem = " "; // версия системы откуда 3 - fileName = " "; // 4 - systemID = " "; // идентификатор системы откуда 5 - verPreProc = " "; // версия препроцессора( на хрен она упала?) 6 - numbBitsOnInt = 32; // разрядность целого откуда 7 //-V112 - maxPowerFloat = 38; // максимальная степень float откуда 8 - numbSignFloat = 6; // число значащих цифр float откуда 9 - maxPowerDouble = 307; // максимальная степень double откуда 10 - numbSignDouble = 15; // число значащих цифр double откуда 11 - identifReceivngSystem = " "; // версия системы куда 12 - scale = 1.0; // масштаб 13 - unitFlag = 2; // 14 1- дюймы 2 -мм 3- 4 -футы 5 -мили 6 -м 7 -км 8 -милидюймы 9- мкм 10- см 11 - микродюйм - nameUnit = "MM"; // 15 - maxNumberOfLineWeightGrad = IGS_WIDTH;// 16 - widthOfMaxLineWeight = 1; // 17 - dateAndTime = ""; // 18 YYMMMDD.HHNNSS - minResolution = 0.001; // 19 - мин. разрешение системы - maxAbsCoord = 10000; // 20 максимальное координата по модулю - nameOfAuthor = " "; // 21 автор - authorsOrg = " "; // 22 организация - intVer = 0/*3*/; // 23 - intDraftStandart = 0; // 24 - dateAndTimeMod = " "; // 25 - } -}; - - -//------------------------------------------------------------------------------- -// структура для формирования отчета о записи в IGES -// --- -struct ReportEntity { - int32 kompasResNumHigh; // номер в ресурсе строки наименования того, что пришло из Компаса - int32 kompasResNumBase; // номер в ресурсе строки наименования подложки, которая пришла из Компаса - ptrdiff_t igesResNum; // номер в ресурсе строки наименования того, чем записали в IGES - ReportEntity( ptrdiff_t _igesResNum = 0 ) - : kompasResNumHigh( 0 ) - , kompasResNumBase( 0 ) - , igesResNum( _igesResNum ) - {} -}; - - -//------------------------------------------------------------------------------- -/// Базовый класс для IGES объектов -// --- -class CONV_CLASS BasicIGES { -public : - ptrdiff_t numStr; ///< место хранения - номер строки в секции DE - union { - VectorDE def; - unsigned short vector; - }; - ptrdiff_t color; - ptrdiff_t level; - ptrdiff_t matrix; - ptrdiff_t form; - ReportEntity report; - -private: - ptrdiff_t numType; // номер типа - -public : - BasicIGES( ptrdiff_t _numType, ptrdiff_t _form = 0 ) - : numStr (0) - , vector (0) - , color (0) - , level (0) - , matrix (0) - , form ( _form ) - , report ( _numType ) - , numType( _numType ) - {} - - BasicIGES( const BasicIGES & o ) - : numStr ( o.numStr ) - , vector ( o.vector ) - , color ( o.color ) - , level ( o.level ) - , matrix ( o.matrix ) - , form ( o.form ) - , report ( o.numType ) - , numType( o.numType ) - {} - - virtual ~BasicIGES() {} - - bool Less( const BasicIGES & o ) const { return numType < o.numType ? true : numType > o.numType ? false : form < o.form ? true : form > o.form ? false : matrix < o.matrix;} - bool Eq ( const BasicIGES & o ) const { return numType == o.numType && form == o.form && matrix == o.matrix;} - const ptrdiff_t GetTypeIGES() const { return numType; } - const ptrdiff_t GetFormIGES() const { return form; } - virtual bool operator == ( const BasicIGES & o ) const { return Eq( o ); } - virtual bool operator < ( const BasicIGES & o ) const { return Less( o ); } -}; - - -#endif // __IGES_BASIC_H +//////////////////////////////////////////////////////////////////////////////// +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IGES_BASIC_H +#define __IGES_BASIC_H + +#include + +#include + +#define IGS_DOUBLE_TO_STRING_NDEC 15 + + +//------------------------------------------------------------------------------ +// типы IGS псевдо объектов +// --- +typedef enum { + igs_CopiousData11 = 11, + igs_MetalHatch = 31, + igs_CeramicHatch = 32, + igs_Hatch33 = 33, + igs_Hatch34 = 34, + igs_Hatch35 = 35, + igs_Hatch36 = 36, + igs_NonMetalHatch = 37, + igs_BrickHatch = 38, + igs_WitnesLine = 40, + + igs_ItArcOrCircleIGES = 100, + igs_ItContourIGES = 102, + igs_ItConicIGES = 104, + igs_ItCopiousDataIGES = 106, + igs_ItPlaneIGES = 108, + igs_ItLineSegIGES = 110, + igs_ItSplineIGES = 112, + igs_ItParametricSplineSurfaceIGES = 114, + igs_ItPointIGES = 116, + igs_ItRuledSurfaceIGES = 118, + igs_ItSurfaceOfRevolutionIGES = 120, + igs_ItTabulatedCylinderIGES = 122, + igs_ItDirectionIGES = 123, + igs_ItTransformMatrixIGES = 124, + igs_ItRationalBSplineCurveIGES = 126, + igs_ItRationalBSplineSurfaceIGES = 128, + igs_ItOffsetSurfaceIGES = 140, + igs_ItBoundaryIGES = 141, + igs_ItCurveOnParametricSurfaceIGES = 142, + igs_ItBoundedSurfaceIGES = 143, + igs_ItTrimmedParametricSurfaceIGES = 144, + igs_ItManifoldSolidBRepIGES = 186, + igs_ItPlaneSurfaceIGES = 190, + igs_ItRCCylindricalSurfaceIGES = 192, + igs_ItRCConicalSurfaceIGES = 194, + igs_ItSphericalSurfaceIGES = 196, + igs_ItToroidalSurfaceIGES = 198, + + igs_AngularDim = 202, + igs_DiamDim = 206, + igs_Text = 212, + igs_Leader = 214, + igs_LinDim = 216, + igs_RadDim = 222, + + igs_ItSubfigureIGES = 308, + igs_ItColorIGES = 314, + igs_ItBlockIGES = 402, + igs_ItPropertyIGES = 406, + igs_ItSingularSubfigureInstanceIGES = 408, + igs_ItExternalReferenceIGES = 416, + igs_ItVertexListIGES = 502, + igs_ItEdgeListIGES = 504, + igs_ItLoopIGES = 508, + igs_ItFaceIGES = 510, + igs_ItShellIGES = 514, + igs_Surface, + igs_SpaceCurve, +} IGSGConverterType; + + +//----------------------------------------------------------------------------- +// +// --- +typedef enum { // секция + UndefSection, + FlagSection, // not always present + StartSection, + GlobalSection, + DirectoryEntrySection, + ParametrDataSection, + TerminateSection +} NameSectionIGES; + +#define LENGTH_STRING_FILE 80 +#define LENGTH_STRING_IGES 72 + +#define IGS_WIDTH 1000 // число градаций толщины + +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS 58 +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS_GOST 6 +//#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1001 30 +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1001 29 +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1002 34 +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS1003 32 +#define LENGTH_ARRAY_IGES_SPEC_SYMBOLS800 7 + + +#define IGS_BLOCK_GROUP 1 // + форма блока 1 +#define IGS_BLOCK_GROUP_WO_BACK_POINTERS 7 // + форма блока 7 - без обратных указателей + +#define IGS_DOUBLE_UNDEF -1e32 // + +#define ENTITY_LABEL_COUNT 8 ///< Длина поля entityLabel + +#define VDE_VISIBLE_YES 0 ///< Объект видим +#define VDE_VISIBLE_NO 1 ///< Объект невидим + +#define VDE_DEPEND_NO 0 ///< Объект независим +#define VDE_DEPEND_PHYS 1 ///< Объект зависим физически +#define VDE_DEPEND_LOG 2 ///< Объект зависим логически +#define VDE_DEPEND_BOTH 3 ///< Зависим физически и логически + +#define VDE_USE_GEOMETRY 0 ///< Объект геометрический +#define VDE_USE_ANNOT 1 ///< Объект аннотационный +#define VDE_USE_DEF 2 ///< Объект определение +#define VDE_USE_OTHER 3 ///< Объект вне классификации +#define VDE_USE_LOG_POS 4 ///< Объект логический / позиционирование +#define VDE_USE_2D_PARAM 5 ///< Объект параметрический 2D +#define VDE_USE_CONSTR_GM 6 ///< Объект конструктивной геометрии + +#define VDE_HIER_TOP_DOWN 0 ///< Сверху вниз +#define VDE_HIER_GLOB_DEFER 1 ///< Глобально +#define VDE_HIER_PROPERTY 2 ///< Свойство + + +//------------------------------------------------------------------------------- +// +// --- +struct VectorDE{ + unsigned short visible : 1;// 9 вектор состояния + unsigned short depend : 2;// 9 + unsigned short geometry : 3;// 9 + unsigned short hierarchy : 2;// 9 +}; + + +//----------------------------------------------------------------------------- +// +// --- +struct DirEntryParameter { +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// горячо рекомендую все изменения в структуре согласовывать с процедурой чтения +// ProcessingOneEntityDirEntrySection(), иначе есть очень реальный шанс все порушить, +// еще рекомендую крепко подумать, прежде чем делать виртуальные функции и наследников +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + int32 typeNumber; // 1 номер типа +// поле typeNumber должно идти первым - см. функцию Init этой структуры +// !!!!!!!!!!!!!!!!!!!! + ptrdiff_t numbParDataString; // 2 номер строки данных в секции Parametr Data + ptrdiff_t structure; // 3 инвертированный указатель на на строку в секции DirEntry обычно 0 + ptrdiff_t lineFontPattern; // 4 номер стандартного типа линии или указатель на строку с описанием нестандартного + ptrdiff_t level; // 5 номер слоя или указатель на строку с описанием слоя в секции DirEntry + ptrdiff_t view; // 6 указатель на строку с описанием вида в секции DirEntry + ptrdiff_t transformMatrix; // 7 указатель на строку с описанием матрицы преобразования в секции DirEntry + ptrdiff_t labelDisplayAssociativ;// 8 указатель на строку с ???? в секции DirEntry + // 9 вектор состояния + union { + VectorDE def; + unsigned short vector; + }; + ptrdiff_t numbString; // 10 номер строки + ptrdiff_t lineWeight; // 12 - 11 пропущен - градация толщины + ptrdiff_t color; // 13 номер цвета или указатель на строку с описанием цвета + ptrdiff_t lineCount; // 14 число строк под описание параметров в секции Parametr Data + int32 formNumber; // 15 + std::string entityLabel; // 18 метка + // SpAG K14 BUG_65022 - избавляемся от низкоуровневых абстракций + ptrdiff_t numerLabel; // 19 числовая метка + + DirEntryParameter( int32 type = 0 ): typeNumber( type ), numbParDataString( 0 ), structure( 0 ), lineFontPattern( 0 ), level( 0 ), + view( 0 ), transformMatrix( 0 ), labelDisplayAssociativ( 0 ), numbString( 0 ), lineWeight( 0 ), + color( 0 ), lineCount( 0 ), formNumber( 0 ), entityLabel( ENTITY_LABEL_COUNT, ' ' ), numerLabel( 0 ) { Init(); } // SpAG K13 SP1 анализаторы кода + + void Init() { + // SpAG - С точки зрения cppCheck должно быть гораздо более пристойно + def.visible = VDE_VISIBLE_YES; + def.depend = VDE_DEPEND_NO; + def.geometry = VDE_USE_DEF; + def.hierarchy = VDE_HIER_TOP_DOWN; + } + + void operator = ( const DirEntryParameter & o ) { + typeNumber = o.typeNumber; + numbParDataString = o.numbParDataString; + structure = o.structure; + lineFontPattern = o.lineFontPattern; + level = o.level; + view = o.view; + transformMatrix = o.transformMatrix; + labelDisplayAssociativ = o.labelDisplayAssociativ; + numbString = o.numbString; // BUG_71099 + lineWeight = o.lineWeight; + color = o.color; + lineCount = o.lineCount; + formNumber = o.formNumber; + entityLabel = o.entityLabel; // SpAG K14 BUG_65022 + numerLabel = o.numerLabel; + vector = o.vector; + } + + void Zero() { + typeNumber = 0; + numbParDataString = structure = lineFontPattern = level = view = transformMatrix = labelDisplayAssociativ = numbString = lineWeight = color = lineCount = numerLabel = 0; + formNumber = 0; + vector = 0; + entityLabel.assign( ENTITY_LABEL_COUNT, ' ' ); + } + + bool operator == ( DirEntryParameter & o ) const { return numbString == o.numbString; } + bool operator < ( DirEntryParameter & o ) const { return numbString < o.numbString; } +}; + + +//----------------------------------------------------------------------------- +// Данные общей секции. +// --- +struct GlobalSectionParameter { + int32 delimiter; // ограничитель параметров 1 + int32 recordDelimiter; // ограничитель записей 2 + std::string identifSendingSystem; // версия системы откуда 3 + std::string fileName; // 4 + std::string systemID; // идентификатор системы откуда 5 + std::string verPreProc; // версия препроцессора( на хрен она упала?) 6 + int32 numbBitsOnInt; // разрядность целого откуда 7 + int32 maxPowerFloat; // максимальная степень float откуда 8 + int32 numbSignFloat; // число значащих цифр float откуда 9 + int32 maxPowerDouble; // максимальная степень double откуда 10 + int32 numbSignDouble; // число значащих цифр double откуда 11 + std::string identifReceivngSystem;// версия системы куда 12 + double scale; // масштаб 13 + int32 unitFlag; // 14 1- дюймы 2 -мм 3- 4 -футы 5 -мили 6 -м 7 -км 8 -милидюймы 9- мкм 10- см 11 - микродюйм + std::string nameUnit; // 15 + int32 maxNumberOfLineWeightGrad; // 16 + double widthOfMaxLineWeight; // 17 + std::string dateAndTime; // 18 YYMMMDD.HHNNSS + double minResolution; // 19 - мин. разрешение системы + double maxAbsCoord; // 20 максимальное координата по модулю + std::string nameOfAuthor; // 21 автор + std::string authorsOrg; // 22 организация + int32 intVer; // 23 + int32 intDraftStandart; // 24 + std::string dateAndTimeMod; // 25 YYMMMDD.HHNNSS + + GlobalSectionParameter () { Init(); } + void Init() { + delimiter = ','; // ограничитель параметров 1 + recordDelimiter = ';'; // ограничитель записей 2 + identifSendingSystem = " "; // версия системы откуда 3 + fileName = " "; // 4 + systemID = " "; // идентификатор системы откуда 5 + verPreProc = " "; // версия препроцессора( на хрен она упала?) 6 + numbBitsOnInt = 32; // разрядность целого откуда 7 //-V112 + maxPowerFloat = 38; // максимальная степень float откуда 8 + numbSignFloat = 6; // число значащих цифр float откуда 9 + maxPowerDouble = 307; // максимальная степень double откуда 10 + numbSignDouble = 15; // число значащих цифр double откуда 11 + identifReceivngSystem = " "; // версия системы куда 12 + scale = 1.0; // масштаб 13 + unitFlag = 2; // 14 1- дюймы 2 -мм 3- 4 -футы 5 -мили 6 -м 7 -км 8 -милидюймы 9- мкм 10- см 11 - микродюйм + nameUnit = "MM"; // 15 + maxNumberOfLineWeightGrad = IGS_WIDTH;// 16 + widthOfMaxLineWeight = 1; // 17 + dateAndTime = ""; // 18 YYMMMDD.HHNNSS + minResolution = 0.001; // 19 - мин. разрешение системы + maxAbsCoord = 10000; // 20 максимальное координата по модулю + nameOfAuthor = " "; // 21 автор + authorsOrg = " "; // 22 организация + intVer = 0/*3*/; // 23 + intDraftStandart = 0; // 24 + dateAndTimeMod = " "; // 25 + } +}; + + +//------------------------------------------------------------------------------- +// структура для формирования отчета о записи в IGES +// --- +struct ReportEntity { + int32 kompasResNumHigh; // номер в ресурсе строки наименования того, что пришло из Компаса + int32 kompasResNumBase; // номер в ресурсе строки наименования подложки, которая пришла из Компаса + ptrdiff_t igesResNum; // номер в ресурсе строки наименования того, чем записали в IGES + ReportEntity( ptrdiff_t _igesResNum = 0 ) + : kompasResNumHigh( 0 ) + , kompasResNumBase( 0 ) + , igesResNum( _igesResNum ) + {} +}; + + +//------------------------------------------------------------------------------- +/// Базовый класс для IGES объектов +// --- +class CONV_CLASS BasicIGES { +public : + ptrdiff_t numStr; ///< место хранения - номер строки в секции DE + union { + VectorDE def; + unsigned short vector; + }; + ptrdiff_t color; + ptrdiff_t level; + ptrdiff_t matrix; + ptrdiff_t form; + ReportEntity report; + +private: + ptrdiff_t numType; // номер типа + +public : + BasicIGES( ptrdiff_t _numType, ptrdiff_t _form = 0 ) + : numStr (0) + , vector (0) + , color (0) + , level (0) + , matrix (0) + , form ( _form ) + , report ( _numType ) + , numType( _numType ) + {} + + BasicIGES( const BasicIGES & o ) + : numStr ( o.numStr ) + , vector ( o.vector ) + , color ( o.color ) + , level ( o.level ) + , matrix ( o.matrix ) + , form ( o.form ) + , report ( o.numType ) + , numType( o.numType ) + {} + + virtual ~BasicIGES() {} + + bool Less( const BasicIGES & o ) const { return numType < o.numType ? true : numType > o.numType ? false : form < o.form ? true : form > o.form ? false : matrix < o.matrix;} + bool Eq ( const BasicIGES & o ) const { return numType == o.numType && form == o.form && matrix == o.matrix;} + const ptrdiff_t GetTypeIGES() const { return numType; } + const ptrdiff_t GetFormIGES() const { return form; } + virtual bool operator == ( const BasicIGES & o ) const { return Eq( o ); } + virtual bool operator < ( const BasicIGES & o ) const { return Less( o ); } +}; + + +#endif // __IGES_BASIC_H diff --git a/C3d/Include/iges_structure.h b/C3d/Include/iges_structure.h index 91a6708..3967be8 100644 --- a/C3d/Include/iges_structure.h +++ b/C3d/Include/iges_structure.h @@ -1,535 +1,535 @@ -//////////////////////////////////////////////////////////////////////////////// -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IGES_STRUCTURES_H -#define __IGES_STRUCTURES_H - - -#include -#include -#include -#include "iges_basic.h" - - -//------------------------------------------------------------------------------- -// функции сравнения двух наследников от BasicIGES, которые не содержат -// динамических данных -// --- -template -inline bool Eq( const Type * t, const BasicIGES & o ) { - if ( !t->Eq( o ) ) - return false; - - const Type * r = dynamic_cast(&o); - if ( !r ) - return false; - - return ::IsEqualSArrayItems( t, r ); -} - - -//------------------------------------------------------------------------------- -// функции сравнения двух наследников от BasicIGES, которые не содержат -// динамических данных -// --- -template -inline bool Less( const Type * t, const BasicIGES & o ) { - if ( !t->Eq( o ) ) - return t->Less( o ); - - const Type * r = dynamic_cast(&o); - if ( !r ) - return false; - - return ::IsLessThanSArrayItems( t, r ); -} - - -//------------------------------------------------------------------------------- -// структура для сохранения типов линий -// --- -struct CONV_CLASS LTypeNameIGES { - uint16 number; // номер стиля в чертеже C3D - ptrdiff_t colorOrStr; // цвет или номер строки цвета в файле IGES - ptrdiff_t width; // толщина линии на бумаге * 1000 - ptrdiff_t numOrStr; // номер IGES-типа линии или номер строки типа в файле IGES - - LTypeNameIGES() : number(0), colorOrStr( 0 ), width(1), numOrStr(0){} - - bool operator == (const LTypeNameIGES & o) const { return number == o.number; } - bool operator < (const LTypeNameIGES & o) const { return number < o.number; } - - void Assign( const LTypeNameIGES & o ); -}; - - -//------------------------------------------------------------------------------- -// структура цвета и места его хранения -// --- -struct CONV_CLASS ColorIGES : public BasicIGES { - int32 trueColor; - - ColorIGES( int32 _color = 0 ); - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef ColorIGES * PCOLORIGES; -typedef const ColorIGES * PCCOLORIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCCOLORIGES &obj1, const PCCOLORIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< ColorIGES const* > ( ColorIGES const* const& obj1, ColorIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------ -// -// --- -struct CONV_CLASS ColourIGES : public BasicIGES { - double red, green, blue; - - ColourIGES( double, double, double ); -}; - - -//------------------------------------------------------------------------------- -// точка -// --- -struct CONV_CLASS PointIGES : public BasicIGES { - double x, y, z; - - PointIGES( double _x, double _y, double _z ); - PointIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef PointIGES * PPOINTIGES; -typedef const PointIGES * PCPOINTIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCPOINTIGES &obj1, const PCPOINTIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< PointIGES const* > ( PointIGES const* const& obj1, PointIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// базовый curve примитив -// --- -struct CONV_CLASS BasicCurveIGES : public BasicIGES { - LTypeNameIGES lt; // стиль - BasicCurveIGES( int32 _numType, int32 _form = 0 ) : BasicIGES( _numType, _form ), lt(){} -}; - - -//------------------------------------------------------------------------------- -// структура отрезка -// --- -struct CONV_CLASS LineSegIGES : public BasicCurveIGES { - double x1, y1, z1; // координаты 1 точки - double x2, y2, z2; // координаты 2 точки - - LineSegIGES(); - - LineSegIGES( double x1, double y1, double z1, // 3D - double x2, double y2, double z2 ); - LineSegIGES( double x1, double y1, // 2D - double x2, double y2 ); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// структура дуги и окружности -// --- -struct CONV_CLASS ArcOrCircleIGES : public BasicCurveIGES { - double dir; // напрвление - double xc, yc; // координаты центра - double x1, y1; // координаты 1 точки - double x2, y2; // координаты 2 точки - - ArcOrCircleIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// 104 IGS_CONIC_ARC коническая кривая ( эллипс, гипербола, парабола ) -// --- -struct CONV_CLASS EllipsIGES : public BasicCurveIGES { - double A, B, C, D, E, F, X1, Y1, X2, Y2, ZT; - - EllipsIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef EllipsIGES * PELLIPSIGES; -typedef const EllipsIGES * PCELLIPSIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCELLIPSIGES &obj1, const PCELLIPSIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< EllipsIGES const* > ( EllipsIGES const* const& obj1, EllipsIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// структура элемента текста -// --- -struct CONV_CLASS TextItemIGES { - double width; // ширина - double height; // высота - int32 fontCode; // код шрифта - double angleChar; // угол наклона букв - double angleStr; // угол наклона строки - int32 flagMirror;// флаг зеркальности - int32 horizont; // 0 - отсчет от горизонали 1 - от вертикали - double x, y, z; // координаты - std::string text; // текст - - TextItemIGES(); - - bool operator == ( const TextItemIGES & o ) const; - bool operator < ( const TextItemIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// структура текста -// --- -struct CONV_CLASS TextIGES : public BasicIGES { - PArray arr; - - TextIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef TextIGES * PTEXTIGES; -typedef const TextIGES * PCTEXTIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCTEXTIGES &obj1, const PCTEXTIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< TextIGES const* > ( TextIGES const* const& obj1, TextIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// 123 IGS_DIRECTION - вектор -// --- -struct CONV_CLASS DirectionIGES: public BasicIGES { - double x, y, z; - - DirectionIGES( double _x, double _y, double _z ); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef DirectionIGES * PDIRECTIONIGES; -typedef const DirectionIGES * PCDIRECTIONIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCDIRECTIONIGES &obj1, const PCDIRECTIONIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< DirectionIGES const* > ( DirectionIGES const* const& obj1, DirectionIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// 124 матрица трансформации -// --- -struct CONV_CLASS MatrixIGES : public BasicIGES { - SArray matr; - MatrixIGES(); - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// 126 IGS_RATIONAL_B_SPLINE_CURVE -// --- -struct CONV_CLASS RationalBSplineCurveIGES : public BasicCurveIGES { - ptrdiff_t upperIndexSum; // верхний индекс суммы - ptrdiff_t degree; // степень базовой функции - int32 planar; // 0 - пространственная 1 - плоская - int32 closed; // 1 - замкнутая 0 - незамкнутая - int32 polynominal; // 1 - Polynominal - // 0 - Rational - int32 periodic; // 1 - Периодическая - // 0 - Непериодическая -// Значения последовательностей узлов - SArray sequence; // значения от -degree до 1 + upperIndexSum - - // массив весовых коэффициентов размером 1 + upperIndexSum - SArray weight; - // массив координат контрольных точек размером 1 + upperIndexSum - SArray x; - SArray y; - SArray z; - double u0, u1; // начальное и конечное значение параметрических координат - double xNorm, yNorm, zNorm; - - RationalBSplineCurveIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// стрелка( или линия выноски ) IGS_LEADER -// --- -struct CONV_CLASS LeaderIGES : public BasicCurveIGES { - double arrowLen; // длина стрелки IGS_LENGTH_ARROW - double arrowWidth;// ширина стрелки IGS_WIDTH_ARROW - double zDepth; // глубина по z - // координаты стрелки - double xHead, yHead; - // координаты конца линии - SArray x; - SArray y; - int formArrow; // 0,4 никакой 1,2,3,11 обычная стрелка 9,10 засечка 5,6,7,8 точка - - LeaderIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef LeaderIGES * PLEADERIGES; -typedef const LeaderIGES * PCLEADERIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCLEADERIGES &obj1, const PCLEADERIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< LeaderIGES const* > ( LeaderIGES const* const& obj1, LeaderIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// вспомогательная линия -// --- -struct CONV_CLASS WitnessLineIGES : public BasicCurveIGES { - int32 interpretFlag; - double z; // displacement - // координаты конца линии N >= 3 и нечетное - SArray x; - SArray y; - - WitnessLineIGES(); - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef WitnessLineIGES * PWITNESSLINEIGES; -typedef const WitnessLineIGES * PCWITNESSLINEIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCWITNESSLINEIGES &obj1, const PCWITNESSLINEIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< WitnessLineIGES const* > ( WitnessLineIGES const* const& obj1, WitnessLineIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// структура линейного размера -// --- -struct CONV_CLASS LinDimensionIGES : public BasicIGES { - int32 text; // указатель на текст - int32 firstArrow; // первая стрелка( половина размерной линии ) - int32 secondArrow; // вторая стрелка( половина размерной линии ) - int32 firstLine; // первая выносная линия - int32 secondLine; // вторая выносная линия - LinDimensionIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef LinDimensionIGES * PLINDIMENSIONIGES; -typedef const LinDimensionIGES * PCLINDIMENSIONIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCLINDIMENSIONIGES &obj1, const PCLINDIMENSIONIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< LinDimensionIGES const* > ( LinDimensionIGES const* const& obj1, LinDimensionIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// структура диаметрального размера -// --- -struct CONV_CLASS DimDimensionIGES : public BasicIGES { - int32 text; // указатель на текст - int32 firstArrow; // первая стрелка( половина размерной линии ) - int32 secondArrow; // вторая стрелка( половина размерной линии ) - double x, y; - DimDimensionIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef DimDimensionIGES * PDIMDIMENSIONIGES; -typedef const DimDimensionIGES * PCDIMDIMENSIONIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCDIMDIMENSIONIGES &obj1, const PCDIMDIMENSIONIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< DimDimensionIGES const* > ( DimDimensionIGES const* const& obj1, DimDimensionIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// структура диаметрального размера -// --- -struct CONV_CLASS RadDimensionIGES : public BasicIGES { - int32 text; // указатель на текст - int32 arrow; // первая стрелка( половина размерной линии ) - double x, y; - RadDimensionIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef RadDimensionIGES * PRADDIMENSIONIGES; -typedef const RadDimensionIGES * PCRADDIMENSIONIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCRADDIMENSIONIGES &obj1, const PCRADDIMENSIONIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< RadDimensionIGES const* > ( RadDimensionIGES const* const& obj1, RadDimensionIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -//------------------------------------------------------------------------------- -// структура углового размера -// --- -struct CONV_CLASS AngDimensionIGES : public BasicIGES { - int32 text; // указатель на текст - int32 firstLine; // первая выносная линия - int32 secondLine; // вторая выносная линия - double x, y, r; - int32 firstArrow; // первая стрелка( половина размерной линии ) - int32 secondArrow; // вторая стрелка( половина размерной линии ) - AngDimensionIGES(); - - virtual bool operator == ( const BasicIGES & o ) const; - virtual bool operator < ( const BasicIGES & o ) const; -}; - - -//------------------------------------------------------------------------------- -// -// --- -typedef AngDimensionIGES * PANGDIMENSIONIGES; -typedef const AngDimensionIGES * PCANGDIMENSIONIGES; - - -//------------------------------------------------------------------------------- -// -// --- -#ifdef _MSC_VER // C3D_WINDOWS -inline bool IsLessThanSArrayItems ( const PCANGDIMENSIONIGES &obj1, const PCANGDIMENSIONIGES &obj2 ) { return obj1 < obj2; } -#else // C3D_WINDOWS -template<> bool IsLessThanSArrayItems< AngDimensionIGES const* > ( AngDimensionIGES const* const& obj1, AngDimensionIGES const* const& obj2 ); -#endif // C3D_WINDOWS - - -#endif // __IGES_STRUCTURES_H +//////////////////////////////////////////////////////////////////////////////// +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IGES_STRUCTURES_H +#define __IGES_STRUCTURES_H + + +#include +#include +#include +#include "iges_basic.h" + + +//------------------------------------------------------------------------------- +// функции сравнения двух наследников от BasicIGES, которые не содержат +// динамических данных +// --- +template +inline bool Eq( const Type * t, const BasicIGES & o ) { + if ( !t->Eq( o ) ) + return false; + + const Type * r = dynamic_cast(&o); + if ( !r ) + return false; + + return ::IsEqualSArrayItems( t, r ); +} + + +//------------------------------------------------------------------------------- +// функции сравнения двух наследников от BasicIGES, которые не содержат +// динамических данных +// --- +template +inline bool Less( const Type * t, const BasicIGES & o ) { + if ( !t->Eq( o ) ) + return t->Less( o ); + + const Type * r = dynamic_cast(&o); + if ( !r ) + return false; + + return ::IsLessThanSArrayItems( t, r ); +} + + +//------------------------------------------------------------------------------- +// структура для сохранения типов линий +// --- +struct CONV_CLASS LTypeNameIGES { + uint16 number; // номер стиля в чертеже C3D + ptrdiff_t colorOrStr; // цвет или номер строки цвета в файле IGES + ptrdiff_t width; // толщина линии на бумаге * 1000 + ptrdiff_t numOrStr; // номер IGES-типа линии или номер строки типа в файле IGES + + LTypeNameIGES() : number(0), colorOrStr( 0 ), width(1), numOrStr(0){} + + bool operator == (const LTypeNameIGES & o) const { return number == o.number; } + bool operator < (const LTypeNameIGES & o) const { return number < o.number; } + + void Assign( const LTypeNameIGES & o ); +}; + + +//------------------------------------------------------------------------------- +// структура цвета и места его хранения +// --- +struct CONV_CLASS ColorIGES : public BasicIGES { + int32 trueColor; + + ColorIGES( int32 _color = 0 ); + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef ColorIGES * PCOLORIGES; +typedef const ColorIGES * PCCOLORIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCCOLORIGES &obj1, const PCCOLORIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< ColorIGES const* > ( ColorIGES const* const& obj1, ColorIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------ +// +// --- +struct CONV_CLASS ColourIGES : public BasicIGES { + double red, green, blue; + + ColourIGES( double, double, double ); +}; + + +//------------------------------------------------------------------------------- +// точка +// --- +struct CONV_CLASS PointIGES : public BasicIGES { + double x, y, z; + + PointIGES( double _x, double _y, double _z ); + PointIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef PointIGES * PPOINTIGES; +typedef const PointIGES * PCPOINTIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCPOINTIGES &obj1, const PCPOINTIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< PointIGES const* > ( PointIGES const* const& obj1, PointIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// базовый curve примитив +// --- +struct CONV_CLASS BasicCurveIGES : public BasicIGES { + LTypeNameIGES lt; // стиль + BasicCurveIGES( int32 _numType, int32 _form = 0 ) : BasicIGES( _numType, _form ), lt(){} +}; + + +//------------------------------------------------------------------------------- +// структура отрезка +// --- +struct CONV_CLASS LineSegIGES : public BasicCurveIGES { + double x1, y1, z1; // координаты 1 точки + double x2, y2, z2; // координаты 2 точки + + LineSegIGES(); + + LineSegIGES( double x1, double y1, double z1, // 3D + double x2, double y2, double z2 ); + LineSegIGES( double x1, double y1, // 2D + double x2, double y2 ); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// структура дуги и окружности +// --- +struct CONV_CLASS ArcOrCircleIGES : public BasicCurveIGES { + double dir; // напрвление + double xc, yc; // координаты центра + double x1, y1; // координаты 1 точки + double x2, y2; // координаты 2 точки + + ArcOrCircleIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// 104 IGS_CONIC_ARC коническая кривая ( эллипс, гипербола, парабола ) +// --- +struct CONV_CLASS EllipsIGES : public BasicCurveIGES { + double A, B, C, D, E, F, X1, Y1, X2, Y2, ZT; + + EllipsIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef EllipsIGES * PELLIPSIGES; +typedef const EllipsIGES * PCELLIPSIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCELLIPSIGES &obj1, const PCELLIPSIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< EllipsIGES const* > ( EllipsIGES const* const& obj1, EllipsIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// структура элемента текста +// --- +struct CONV_CLASS TextItemIGES { + double width; // ширина + double height; // высота + int32 fontCode; // код шрифта + double angleChar; // угол наклона букв + double angleStr; // угол наклона строки + int32 flagMirror;// флаг зеркальности + int32 horizont; // 0 - отсчет от горизонали 1 - от вертикали + double x, y, z; // координаты + std::string text; // текст + + TextItemIGES(); + + bool operator == ( const TextItemIGES & o ) const; + bool operator < ( const TextItemIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// структура текста +// --- +struct CONV_CLASS TextIGES : public BasicIGES { + PArray arr; + + TextIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef TextIGES * PTEXTIGES; +typedef const TextIGES * PCTEXTIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCTEXTIGES &obj1, const PCTEXTIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< TextIGES const* > ( TextIGES const* const& obj1, TextIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// 123 IGS_DIRECTION - вектор +// --- +struct CONV_CLASS DirectionIGES: public BasicIGES { + double x, y, z; + + DirectionIGES( double _x, double _y, double _z ); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef DirectionIGES * PDIRECTIONIGES; +typedef const DirectionIGES * PCDIRECTIONIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCDIRECTIONIGES &obj1, const PCDIRECTIONIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< DirectionIGES const* > ( DirectionIGES const* const& obj1, DirectionIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// 124 матрица трансформации +// --- +struct CONV_CLASS MatrixIGES : public BasicIGES { + SArray matr; + MatrixIGES(); + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// 126 IGS_RATIONAL_B_SPLINE_CURVE +// --- +struct CONV_CLASS RationalBSplineCurveIGES : public BasicCurveIGES { + ptrdiff_t upperIndexSum; // верхний индекс суммы + ptrdiff_t degree; // степень базовой функции + int32 planar; // 0 - пространственная 1 - плоская + int32 closed; // 1 - замкнутая 0 - незамкнутая + int32 polynominal; // 1 - Polynominal + // 0 - Rational + int32 periodic; // 1 - Периодическая + // 0 - Непериодическая +// Значения последовательностей узлов + SArray sequence; // значения от -degree до 1 + upperIndexSum + + // массив весовых коэффициентов размером 1 + upperIndexSum + SArray weight; + // массив координат контрольных точек размером 1 + upperIndexSum + SArray x; + SArray y; + SArray z; + double u0, u1; // начальное и конечное значение параметрических координат + double xNorm, yNorm, zNorm; + + RationalBSplineCurveIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// стрелка( или линия выноски ) IGS_LEADER +// --- +struct CONV_CLASS LeaderIGES : public BasicCurveIGES { + double arrowLen; // длина стрелки IGS_LENGTH_ARROW + double arrowWidth;// ширина стрелки IGS_WIDTH_ARROW + double zDepth; // глубина по z + // координаты стрелки + double xHead, yHead; + // координаты конца линии + SArray x; + SArray y; + int formArrow; // 0,4 никакой 1,2,3,11 обычная стрелка 9,10 засечка 5,6,7,8 точка + + LeaderIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef LeaderIGES * PLEADERIGES; +typedef const LeaderIGES * PCLEADERIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCLEADERIGES &obj1, const PCLEADERIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< LeaderIGES const* > ( LeaderIGES const* const& obj1, LeaderIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// вспомогательная линия +// --- +struct CONV_CLASS WitnessLineIGES : public BasicCurveIGES { + int32 interpretFlag; + double z; // displacement + // координаты конца линии N >= 3 и нечетное + SArray x; + SArray y; + + WitnessLineIGES(); + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef WitnessLineIGES * PWITNESSLINEIGES; +typedef const WitnessLineIGES * PCWITNESSLINEIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCWITNESSLINEIGES &obj1, const PCWITNESSLINEIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< WitnessLineIGES const* > ( WitnessLineIGES const* const& obj1, WitnessLineIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// структура линейного размера +// --- +struct CONV_CLASS LinDimensionIGES : public BasicIGES { + int32 text; // указатель на текст + int32 firstArrow; // первая стрелка( половина размерной линии ) + int32 secondArrow; // вторая стрелка( половина размерной линии ) + int32 firstLine; // первая выносная линия + int32 secondLine; // вторая выносная линия + LinDimensionIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef LinDimensionIGES * PLINDIMENSIONIGES; +typedef const LinDimensionIGES * PCLINDIMENSIONIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCLINDIMENSIONIGES &obj1, const PCLINDIMENSIONIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< LinDimensionIGES const* > ( LinDimensionIGES const* const& obj1, LinDimensionIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// структура диаметрального размера +// --- +struct CONV_CLASS DimDimensionIGES : public BasicIGES { + int32 text; // указатель на текст + int32 firstArrow; // первая стрелка( половина размерной линии ) + int32 secondArrow; // вторая стрелка( половина размерной линии ) + double x, y; + DimDimensionIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef DimDimensionIGES * PDIMDIMENSIONIGES; +typedef const DimDimensionIGES * PCDIMDIMENSIONIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCDIMDIMENSIONIGES &obj1, const PCDIMDIMENSIONIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< DimDimensionIGES const* > ( DimDimensionIGES const* const& obj1, DimDimensionIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// структура диаметрального размера +// --- +struct CONV_CLASS RadDimensionIGES : public BasicIGES { + int32 text; // указатель на текст + int32 arrow; // первая стрелка( половина размерной линии ) + double x, y; + RadDimensionIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef RadDimensionIGES * PRADDIMENSIONIGES; +typedef const RadDimensionIGES * PCRADDIMENSIONIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCRADDIMENSIONIGES &obj1, const PCRADDIMENSIONIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< RadDimensionIGES const* > ( RadDimensionIGES const* const& obj1, RadDimensionIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +//------------------------------------------------------------------------------- +// структура углового размера +// --- +struct CONV_CLASS AngDimensionIGES : public BasicIGES { + int32 text; // указатель на текст + int32 firstLine; // первая выносная линия + int32 secondLine; // вторая выносная линия + double x, y, r; + int32 firstArrow; // первая стрелка( половина размерной линии ) + int32 secondArrow; // вторая стрелка( половина размерной линии ) + AngDimensionIGES(); + + virtual bool operator == ( const BasicIGES & o ) const; + virtual bool operator < ( const BasicIGES & o ) const; +}; + + +//------------------------------------------------------------------------------- +// +// --- +typedef AngDimensionIGES * PANGDIMENSIONIGES; +typedef const AngDimensionIGES * PCANGDIMENSIONIGES; + + +//------------------------------------------------------------------------------- +// +// --- +#ifdef _MSC_VER // C3D_WINDOWS +inline bool IsLessThanSArrayItems ( const PCANGDIMENSIONIGES &obj1, const PCANGDIMENSIONIGES &obj2 ) { return obj1 < obj2; } +#else // C3D_WINDOWS +template<> bool IsLessThanSArrayItems< AngDimensionIGES const* > ( AngDimensionIGES const* const& obj1, AngDimensionIGES const* const& obj2 ); +#endif // C3D_WINDOWS + + +#endif // __IGES_STRUCTURES_H diff --git a/C3d/Include/iges_write.h b/C3d/Include/iges_write.h index 5c4b9ad..f823d2e 100644 --- a/C3d/Include/iges_write.h +++ b/C3d/Include/iges_write.h @@ -1,215 +1,216 @@ -//////////////////////////////////////////////////////////////////////////////// -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IGES_WRITE_H -#define __IGES_WRITE_H - - -#include "iges_basic.h" -#include -#include - - -class ostream; -struct CONV_CLASS ColourIGES; -struct IGESData; -struct DirEntryParameter; // запись в DE -class CONV_CLASS BasicIGES; -struct CONV_CLASS BasicCurveIGES; -struct CONV_CLASS LTypeNameIGES; // структура для сохранения типов линий -struct CONV_CLASS TextItemIGES; // структура элемента текста - - -//------------------------------------------------------------------------------- -// -// --- -class CONV_CLASS IWIGES { -// тип функции - записи какого-то элемента - создан для передачи в параметрах -public: - typedef ptrdiff_t (IWIGES::*WriteEntityFunc)( BasicIGES & ); -private: - IGESData * data; - -public : - IWIGES( std::ostream & _os ); - ~IWIGES(); - - // добавить к строке преобразованый к строке и дополненый до 8 символов пробелами int32 - size_t AddLongToString( int32 l, char ch1 = 0 ); -#if defined(PLATFORM_64) - size_t AddLongToString( ptrdiff_t l, char ch1 = 0 ); -#endif // PLATFORM_64 - - // Преобразовать строковую константу к строковой константе IGES - std::string & AddString( std::string & s, std::string & d, std::string & delimiter ); - // Преобразовать double к строковой константе IGES - std::string & AddDouble( double d, std::string & s, std::string & delimiter ); - // Преобразовать int32 к строковой константе IGES - std::string & AddLong( int32 l, std::string & s, std::string & delimiter ); -#if defined(PLATFORM_64) - std::string & AddLong( ptrdiff_t l, std::string & s, std::string & delimiter ); -#endif // PLATFORM_64 - - // добавить к строке выовода другую строку, если длина превышает критическую - // вывести строку, обнулить ее и добавить к ней остаток. Если стоит флаг вывода - - // вывести остаток и обнулить строку - // применяется для глобальной секции и секции комментария - bool AddValToStrAndOut( std::string & outS, // добавляемая строка - ptrdiff_t & numStr, // номер строки в секции - char section, // символ секции - bool out = false );// флаг вывода - - - // добавить к строке выовода секции PD другую строку, если длина превышает критическую - // вывести строку, обнулить ее и добавить к ней остаток. Если стоит флаг вывода - - // вывести остаток и обнулить строку - ptrdiff_t AddValToStrAndOutPD( std::string & outS, - bool divide, // строку можно разделять, числа - нежелательно - bool out ); - // вывести в секцию PD int32 после него запятая - ptrdiff_t WriteLong( int32 v ); -#if defined(PLATFORM_64) - ptrdiff_t WriteLong( ptrdiff_t v ); -#endif // PLATFORM_64 - // вывести в секцию PD double после него запятая - ptrdiff_t WriteDouble( double v ); - // вывести в секцию PD х, Y, и z. после каждого запятая - ptrdiff_t WriteXY0ZPD( double x, double y, double z = 0 ); - // вывести в секцию PD х, y. после каждого запятая - ptrdiff_t WriteXYPD( double x, double y ); - // вывести в секцию PD дополнительные нулевые указатели, в конце - ";" - ptrdiff_t WriteAddNULLPointerPD(); - // Ищет такую структуру в массиве записанных в IGES стркутур. Если находит - // - уничтожает присланное и возвращает номер найденного, если нет - возвращает - // 0, в случае ошибки - возвращает -1 - ptrdiff_t FindOrAddBasicIGES( BasicIGES * b ); - // запись примитива. в параметре - процедура записи этого примитива и его структура. - // перед записью производится проверка - нет ли уже такой и если есть - присланная - // структура уничтожается, если нет - запускается процедура записи, - // возвращается номер строки DE - ptrdiff_t WriteEntity( WriteEntityFunc func, BasicIGES * ); - // подготовка к записи - применять в паре с функцией FinishRecord - только - // для записей, где не нужен стиль линии, уровень и номер формы - // возвращает запомненый указатель- начало записи в PD - ptrdiff_t PrepareRecord( BasicIGES & bi ); - // завершение записи - применять в паре с функцией PrepareRecord - только - // для записей, где не нужен стиль линии - // возвращает номер строки- начало записи в DE - ptrdiff_t FinishRecord( BasicIGES & bi ); - // завершение записи - применять в паре с функцией PrepareRecord - только - // для записей, где НУЖЕН стиль линии - // возвращает номер строки- начало записи в DE - ptrdiff_t FinishCurveRecord( BasicCurveIGES & bi ); - void ClearBuffer(); - - // заполнить структуру глобальной секции и секции комментария - ptrdiff_t Global( const c3d::path_string & fileName, - const double & gabarit, - const std::string & documentName, // Название документа - const std::string & author, - const std::string & organization, - const std::string & productComments, - double lenUnits ); - // Запись завершения в файл IGES - void Terminate(); - - // инициализировать DE - DirEntryParameter & InitDirEntry( ptrdiff_t type, - ptrdiff_t numPD, - ptrdiff_t level, - ptrdiff_t numForm, - ptrdiff_t color, - ptrdiff_t matrix, - unsigned short vectorDE ); - // инициализировать геом. DE - DirEntryParameter & InitCurveDirEntry( ptrdiff_t type, - ptrdiff_t numPD, - ptrdiff_t level, - LTypeNameIGES & lt, - ptrdiff_t numForm, - ptrdiff_t matrix, - unsigned short vectorDE ); - // сформировать запись 2х строк DirEntry - bool DirEntry( DirEntryParameter & de ); - - // записать цвет - ptrdiff_t Color( BasicIGES * color ); - ptrdiff_t Colour( ColourIGES & ); - - // вернуть структуру типа линии из массива - ptrdiff_t GetTypeLine ( ptrdiff_t num, LTypeNameIGES & lt ); - // найти номер структуры типа линии в массиве - ptrdiff_t FindTypeLine( LTypeNameIGES & lt ); - // добавить структуру типа линии в массив - LTypeNameIGES * AddTypeLine ( LTypeNameIGES & lt ); - - // вернуть буферную строку - std::string & BuffStr (); - // разделитель - std::string & Delimiter(); - // разделитель в записях - std::string & RecordDelimiter(); - - // число строк в записи - ptrdiff_t GetCountRowInRec(); - // запомнить и обнулить число строк в записи - void KeepInMindAndResetCountRowInRec(); - // восстановить число строк в записи - void RestoreCountRowInRec(); - // обнулить число строк в записи - void ResetCountRowInRec(); - - // счетчик строк секции DE - ptrdiff_t GetCountStringDE(); - - // счетчик строк секции PD - ptrdiff_t GetCountStringPD(); - - // вернуть массив пар номеров ресурса строк ( названия в Компасе и в IGES ) для формирования отчета -// void GetReport( int32 *& report, int & size ); - - // вернуть имя файла из которого пишется - std::string & GetSourceFileName(); - - // сброс геометрии - - // вектор - ptrdiff_t Direction( BasicIGES & ); - // матрица трансформации - ptrdiff_t Matrix( BasicIGES & ); - // Точка - ptrdiff_t Point( BasicIGES & p ); - // Отрезок - ptrdiff_t LineSeg( BasicIGES & ls ); - // Окружность - ptrdiff_t ArcOrCircle( BasicIGES & acs ); - // 104 IGS_CONIC_ARC коническая кривая ( эллипс, гипербола, парабола ) - ptrdiff_t Ellipse( BasicIGES & ); - // 126 IGS_RATIONAL_B_SPLINE_CURVE - ptrdiff_t RationalBSplineCurve( BasicIGES & b ); - // Элемент текста - void TextItem( TextItemIGES & ti ); - // Текст - ptrdiff_t Text( BasicIGES & t ); - // стрелка( или линия выноски ) IGS_LEADER - ptrdiff_t Leader( BasicIGES & l ); - // вспомогательная линия - ptrdiff_t WitnessLine( BasicIGES & w ); - // линейный размер - ptrdiff_t LinDimension( BasicIGES & b ); - // диаметральный размер - ptrdiff_t DimDimension( BasicIGES & b ); - // радиальный размер - ptrdiff_t RadDimension( BasicIGES & b ); - // угловой размер - ptrdiff_t AngDimension( BasicIGES & b ); - // номер строки DE записанного примитива - ptrdiff_t GetLastDE(); -private: - // записать глобальную секцию - ptrdiff_t WriteGlobal(); -}; - - -#endif // __IGES_WRITE_H +//////////////////////////////////////////////////////////////////////////////// +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IGES_WRITE_H +#define __IGES_WRITE_H + + +#include "iges_basic.h" +#include +#include + + +class ostream; +struct CONV_CLASS ColourIGES; +struct IGESData; +struct DirEntryParameter; // запись в DE +class CONV_CLASS BasicIGES; +struct CONV_CLASS BasicCurveIGES; +struct CONV_CLASS LTypeNameIGES; // структура для сохранения типов линий +struct CONV_CLASS TextItemIGES; // структура элемента текста + + +//------------------------------------------------------------------------------- +// +// --- +class CONV_CLASS IWIGES { +// тип функции - записи какого-то элемента - создан для передачи в параметрах +public: + typedef ptrdiff_t (IWIGES::*WriteEntityFunc)( BasicIGES & ); +private: + IGESData * data; + +public : + IWIGES( std::ostream & _os ); + ~IWIGES(); + + // добавить к строке преобразованый к строке и дополненый до 8 символов пробелами int32 + size_t AddLongToString( int32 l, char ch1 = 0 ); +#if defined(PLATFORM_64) + size_t AddLongToString( ptrdiff_t l, char ch1 = 0 ); +#endif // PLATFORM_64 + + // Преобразовать строковую константу к строковой константе IGES + std::string & AddString( std::string & s, std::string & d, std::string & delimiter ); + // Преобразовать double к строковой константе IGES + std::string & AddDouble( double d, std::string & s, std::string & delimiter ); + // Преобразовать int32 к строковой константе IGES + std::string & AddLong( int32 l, std::string & s, std::string & delimiter ); +#if defined(PLATFORM_64) + std::string & AddLong( ptrdiff_t l, std::string & s, std::string & delimiter ); +#endif // PLATFORM_64 + + // добавить к строке выовода другую строку, если длина превышает критическую + // вывести строку, обнулить ее и добавить к ней остаток. Если стоит флаг вывода - + // вывести остаток и обнулить строку + // применяется для глобальной секции и секции комментария + bool AddValToStrAndOut( std::string & outS, // добавляемая строка + ptrdiff_t & numStr, // номер строки в секции + char section, // символ секции + bool out = false );// флаг вывода + + + // добавить к строке выовода секции PD другую строку, если длина превышает критическую + // вывести строку, обнулить ее и добавить к ней остаток. Если стоит флаг вывода - + // вывести остаток и обнулить строку + ptrdiff_t AddValToStrAndOutPD( std::string & outS, + bool divide, // строку можно разделять, числа - нежелательно + bool out ); + // вывести в секцию PD int32 после него запятая + ptrdiff_t WriteLong( int32 v ); +#if defined(PLATFORM_64) + ptrdiff_t WriteLong( ptrdiff_t v ); +#endif // PLATFORM_64 + // вывести в секцию PD double после него запятая + ptrdiff_t WriteDouble( double v ); + // вывести в секцию PD х, Y, и z. после каждого запятая + ptrdiff_t WriteXY0ZPD( double x, double y, double z = 0 ); + // вывести в секцию PD х, y. после каждого запятая + ptrdiff_t WriteXYPD( double x, double y ); + // вывести в секцию PD дополнительные нулевые указатели, в конце - ";" + ptrdiff_t WriteAddNULLPointerPD(); + // Ищет такую структуру в массиве записанных в IGES стркутур. Если находит + // - уничтожает присланное и возвращает номер найденного, если нет - возвращает + // 0, в случае ошибки - возвращает -1 + ptrdiff_t FindOrAddBasicIGES( BasicIGES * b ); + // запись примитива. в параметре - процедура записи этого примитива и его структура. + // перед записью производится проверка - нет ли уже такой и если есть - присланная + // структура уничтожается, если нет - запускается процедура записи, + // возвращается номер строки DE + ptrdiff_t WriteEntity( WriteEntityFunc func, BasicIGES * ); + // подготовка к записи - применять в паре с функцией FinishRecord - только + // для записей, где не нужен стиль линии, уровень и номер формы + // возвращает запомненый указатель- начало записи в PD + ptrdiff_t PrepareRecord( BasicIGES & bi ); + // завершение записи - применять в паре с функцией PrepareRecord - только + // для записей, где не нужен стиль линии + // возвращает номер строки- начало записи в DE + ptrdiff_t FinishRecord( BasicIGES & bi ); + // завершение записи - применять в паре с функцией PrepareRecord - только + // для записей, где НУЖЕН стиль линии + // возвращает номер строки- начало записи в DE + ptrdiff_t FinishCurveRecord( BasicCurveIGES & bi ); + void ClearBuffer(); + + // заполнить структуру глобальной секции и секции комментария + ptrdiff_t Global( const c3d::path_string & fileName, + const double & gabarit, + const std::string & documentName, // Название документа + const std::string & author, + const std::string & organization, + const std::string & productComments, + const std::string & writingCADId, // Идентификация экспортирующей САПР + double lenUnits ); + // Запись завершения в файл IGES + void Terminate(); + + // инициализировать DE + DirEntryParameter & InitDirEntry( ptrdiff_t type, + ptrdiff_t numPD, + ptrdiff_t level, + ptrdiff_t numForm, + ptrdiff_t color, + ptrdiff_t matrix, + unsigned short vectorDE ); + // инициализировать геом. DE + DirEntryParameter & InitCurveDirEntry( ptrdiff_t type, + ptrdiff_t numPD, + ptrdiff_t level, + LTypeNameIGES & lt, + ptrdiff_t numForm, + ptrdiff_t matrix, + unsigned short vectorDE ); + // сформировать запись 2х строк DirEntry + bool DirEntry( DirEntryParameter & de ); + + // записать цвет + ptrdiff_t Color( BasicIGES * color ); + ptrdiff_t Colour( ColourIGES & ); + + // вернуть структуру типа линии из массива + ptrdiff_t GetTypeLine ( ptrdiff_t num, LTypeNameIGES & lt ); + // найти номер структуры типа линии в массиве + ptrdiff_t FindTypeLine( LTypeNameIGES & lt ); + // добавить структуру типа линии в массив + LTypeNameIGES * AddTypeLine ( LTypeNameIGES & lt ); + + // вернуть буферную строку + std::string & BuffStr (); + // разделитель + std::string & Delimiter(); + // разделитель в записях + std::string & RecordDelimiter(); + + // число строк в записи + ptrdiff_t GetCountRowInRec(); + // запомнить и обнулить число строк в записи + void KeepInMindAndResetCountRowInRec(); + // восстановить число строк в записи + void RestoreCountRowInRec(); + // обнулить число строк в записи + void ResetCountRowInRec(); + + // счетчик строк секции DE + ptrdiff_t GetCountStringDE(); + + // счетчик строк секции PD + ptrdiff_t GetCountStringPD(); + + // вернуть массив пар номеров ресурса строк ( названия в Компасе и в IGES ) для формирования отчета +// void GetReport( int32 *& report, int & size ); + + // вернуть имя файла из которого пишется + std::string & GetSourceFileName(); + + // сброс геометрии + + // вектор + ptrdiff_t Direction( BasicIGES & ); + // матрица трансформации + ptrdiff_t Matrix( BasicIGES & ); + // Точка + ptrdiff_t Point( BasicIGES & p ); + // Отрезок + ptrdiff_t LineSeg( BasicIGES & ls ); + // Окружность + ptrdiff_t ArcOrCircle( BasicIGES & acs ); + // 104 IGS_CONIC_ARC коническая кривая ( эллипс, гипербола, парабола ) + ptrdiff_t Ellipse( BasicIGES & ); + // 126 IGS_RATIONAL_B_SPLINE_CURVE + ptrdiff_t RationalBSplineCurve( BasicIGES & b ); + // Элемент текста + void TextItem( TextItemIGES & ti ); + // Текст + ptrdiff_t Text( BasicIGES & t ); + // стрелка( или линия выноски ) IGS_LEADER + ptrdiff_t Leader( BasicIGES & l ); + // вспомогательная линия + ptrdiff_t WitnessLine( BasicIGES & w ); + // линейный размер + ptrdiff_t LinDimension( BasicIGES & b ); + // диаметральный размер + ptrdiff_t DimDimension( BasicIGES & b ); + // радиальный размер + ptrdiff_t RadDimension( BasicIGES & b ); + // угловой размер + ptrdiff_t AngDimension( BasicIGES & b ); + // номер строки DE записанного примитива + ptrdiff_t GetLastDE(); +private: + // записать глобальную секцию + ptrdiff_t WriteGlobal(); +}; + + +#endif // __IGES_WRITE_H diff --git a/C3d/Include/instance.h b/C3d/Include/instance.h index 4f883dd..4534f19 100644 --- a/C3d/Include/instance.h +++ b/C3d/Include/instance.h @@ -68,10 +68,10 @@ public : // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en An object type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Whether the objects are equal? virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными? \en Whether the objects are similar? virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равными. \en Make the objects equal. @@ -124,11 +124,11 @@ public : virtual const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; // \ru Преобразовать согласно матрице c использованием регистратора содержимый объект, если он селектирован. \en Transform the contained object according to the matrix using the registrator if the object selected. - virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); + virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора с использованием регистратора содержимый объект, если он селектирован. \en Translate the contained object along the vector according to the matrix using the registrator if the object selected. - virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = NULL ); + virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси на заданный угол с использованием регистратора содержимый объект, если он селектирован. \en Translate the contained object about the axis according to the matrix using the registrator if the object selected. - virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); + virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); /// \ru Дать матрицу преобразования из локальной системы объекта. \en Get transform matrix from local coordinate system of object. virtual bool GetMatrixFrom( MbMatrix3D & from ) const; diff --git a/C3d/Include/io_buffer.h b/C3d/Include/io_buffer.h index 9157aa8..119654c 100644 --- a/C3d/Include/io_buffer.h +++ b/C3d/Include/io_buffer.h @@ -135,6 +135,8 @@ namespace io readAborted = 0x04000000L, /// \ru Файл в расширенном формате прочитан частично (неизвестные объекты пропущены). \en Partial read of file in extended format (unknown objects skipped). skippedUnknAttr = 0x08000000L, + /// \ru Файл нулевой длины. \en Zero-length file. + emptyFile = 0x10000000L, /// \ru Все ошибки. \en All errors. //AR all = 0xffffffe0L allMask = 0xffffffffL @@ -595,22 +597,22 @@ public: /// \ru Установить для записи FileSpace с заданным индексом (при необходимости создать новый). ///\en Set FileSpace with given index for writing (create if necessary). - virtual FileSpace * enterFileSpace ( uint8 ) { return NULL; } // не реализовано; not implemeneted + virtual FileSpace * enterFileSpace ( uint8 ) { return c3d_null; } // не реализовано; not implemeneted /// \ru Установить позицию для записи/чтения по заданному ClusterReference. /// Сохранить предыдущую позицию, если saveCurr = true. /// \en Set position for for writing/reading by given ClusterReference. /// If saveCurr = true, save previous position. - virtual FileSpace * enterFileSpace ( const ClusterReference & , bool ) { return NULL; } // не реализовано; not implemeneted + virtual FileSpace * enterFileSpace ( const ClusterReference & , bool ) { return c3d_null; } // не реализовано; not implemeneted /// \ru Установить позицию для записи/чтения по заданным FileSpace и ClusterReference. /// Внимание, здесь ClusterReference.clusterIndex должен содержать индекс в массиве индексов кластеров в FileSpace! /// Сохранить предыдущую позицию, если saveCurr = true. /// \en Set position for writing/reading by given FileSpace and ClusterReference. /// Warning: in this function, ClusterReference.clusterIndex should contain an index in array of cluster indices in FileSpace! /// If saveCurr = true, save previous position. - virtual FileSpace * enterFileSpace ( const ClusterReference &, FileSpace *, bool ) { return NULL; } // не реализовано; not implemeneted + virtual FileSpace * enterFileSpace ( const ClusterReference &, FileSpace *, bool ) { return c3d_null; } // не реализовано; not implemeneted /// \ru Установить предыдущий FileSpace для записи/чтения. ///\en Set previous FileSpace for writing/reading. - virtual FileSpace * returnToPreviousFileSpace() { return NULL; } // не реализовано; not implemeneted + virtual FileSpace * returnToPreviousFileSpace() { return c3d_null; } // не реализовано; not implemeneted /// \ru Получить текущую позицию в буфере. \en Get current position in the buffer. ClusterReference getCurrentClusterPos(); diff --git a/C3d/Include/io_memory_buffer.h b/C3d/Include/io_memory_buffer.h index 5a19467..2f3af0a 100644 --- a/C3d/Include/io_memory_buffer.h +++ b/C3d/Include/io_memory_buffer.h @@ -61,7 +61,7 @@ protected: ClusterReference _ref; FileSpace * _file; - FileStackEntry() : _file(NULL) {} + FileStackEntry() : _file(c3d_null) {} FileStackEntry ( ClusterReference r, FileSpace * f ) : _ref(r), _file(f) {} }; std::stack filesStack; @@ -84,18 +84,18 @@ public: bool isEmpty() const; /// \ru Записать в непрерывную память. /// Функция подразумевает вполне определенное толкование значений входных данных, поэтому она не должна вызываться с неинициализированными аргументами. - /// \param[in,out] memory - память, куда писать. Если memory == NULL, то память выделяется. + /// \param[in,out] memory - память, куда писать. Если memory == c3d_null, то память выделяется. /// \param[in] addSize - размер памяти, которую надо дополнительно выделить при выделении памяти. /// Смысл addSize зависит от начального значения параметра memory: - /// если memory != 0 (т.е.память уже распределена), то addSize должен быть равен размеру памяти (addSize >= getMemLen() !!!). - /// если memory == 0, то addSize определяет, столько байт дополнительно добавить (обнулив) в начале при выделении памяти. + /// если memory != c3d_null (т.е.память уже распределена), то addSize должен быть равен размеру памяти (addSize >= getMemLen() !!!). + /// если memory == c3d_null, то addSize определяет, столько байт дополнительно добавить (обнулив) в начале при выделении памяти. /// \en Write to contiguous memory. /// The function implies a well-defined interpretation of the input values, so it should not be called with uninitialized arguments. - /// \param[in,out] memory - memory to write to. If memory == NULL, then memory is allocated. + /// \param[in,out] memory - memory to write to. If memory == c3d_null, then memory is allocated. /// \param[in] addSize - size of memory, which should be allocated additionally when allocating memory. /// The meaning of addSize depends on the initial value of the parameter 'memory': - /// if memory != 0 (i.e. the memory is already allocated), then addSize should be equal to memory size (addSize >= getMemLen() !!!). - /// if memory == 0, then addSize defines a number of bytes to be added (and zeroed) at the beginning when allocating memory. + /// if memory != c3d_null (i.e. the memory is already allocated), then addSize should be equal to memory size (addSize >= getMemLen() !!!). + /// if memory == c3d_null, then addSize defines a number of bytes to be added (and zeroed) at the beginning when allocating memory. size_t toMemory( const char *& memory, size_t addSize = 0 ) const; /// \ru Прочитать из непрерывной памяти. \en Read from the contiguous memory. bool fromMemory( const char * memory ); diff --git a/C3d/Include/io_tape.h b/C3d/Include/io_tape.h index 2bb5079..844ad0e 100644 --- a/C3d/Include/io_tape.h +++ b/C3d/Include/io_tape.h @@ -466,7 +466,7 @@ public: size_t Add( const TapeBase * e ); /// \ru Выдать указатель на зарегистрированный объект по заданной позиции в кластере. \en Get the pointer of the registered object by the position in the cluster. - virtual TapeBase * Get( const ClusterReference & ) const { return NULL; } // unsupported + virtual TapeBase * Get( const ClusterReference & ) const { return c3d_null; } // unsupported /// \ru Выдать позицию в кластере по заданному индексу. \en Get position in the cluster by given index. virtual ClusterReference GetClusterRef( size_t ) const { return ClusterReference(); } // unsupported /// \ru Добавить позицию объекта в кластере. \en Add the object position in the cluster. @@ -732,7 +732,7 @@ public: /// \ru Читать каталог объектов. \en Read the object catalog. virtual void ReadObjectCatalog(); /// \ru Читать объект по позиции в кластере. \en Read an object by position in cluster. - virtual TapeBase * ReadObjectByPosition ( const ClusterReference & ) { return NULL; } + virtual TapeBase * ReadObjectByPosition ( const ClusterReference & ) { return c3d_null; } /// \ru Установить позицию чтения. \en Set reading position. virtual bool SetReadPosition ( ClusterReference & ) { return false; } // not supported @@ -750,7 +750,7 @@ public: virtual bool readBytes( void * bf, size_t len ); /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree() const { return NULL; } // not supported + virtual const c3d::IModelTree * GetModelTree() const { return c3d_null; } // not supported /// \ru Получить признак полного чтения текущего объекта. \en Get indicator of full reading of the current object. /// \ru Установить признак полного чтения текущего объекта. \en Set indicator of full reading of the current object. @@ -942,7 +942,7 @@ public: size_t __lenWchar( const TCHAR * s ); /// \ru Получить указатель на дерево модели. \en Get pointer to the model tree. - virtual const c3d::IModelTree * GetModelTree() const { return NULL; } // not supported + virtual const c3d::IModelTree * GetModelTree() const { return c3d_null; } // not supported protected: /// \ru Записать объект и тип. \en Write the object and type. @@ -1120,7 +1120,7 @@ struct TapeClassContainer static bool Add( TapeClass & tapeClass ) { if ( !StaticTapeClassContainer() ) - StaticTapeClassContainer() = new SFDPArray( 430, 1, TapeClass_Compare, NULL ); // \ru не владеет \en doesn't own + StaticTapeClassContainer() = new SFDPArray( 430, 1, TapeClass_Compare, c3d_null ); // \ru не владеет \en doesn't own return StaticTapeClassContainer()->AddExact( tapeClass ); } @@ -1891,9 +1891,18 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version //---------------------------------------------------------------------------------------- -/// \ru Удаление пробелов и записей перед пробелами. \en Deleting of spaces and records before spaces. \~ \ingroup Base_Tools_IO -// \ru Для совместимости с предыдущими компиляторами по именам возвращаемым typeid(a).name() \en For compatibility with the previous compilers by names returned by typeid(a).name() -// \ru Для определения того, что надо делать, скомпилируйте и запустите из консоли код \en Compile and run the following code from console to define what is to do +// \ru Удаление пробелов, записей перед пробелами, символов "<" и ">". +// \en Deleting of spaces, records before spaces, symbols "<" and ">". \~ +// \ingroup Base_Tools_IO +MATH_FUNC( const char * ) pureTemplateName( const char * name ); + +//---------------------------------------------------------------------------------------- +// \ru Удаление пробелов и записей перед пробелами. \en Deleting of spaces and records before spaces. \~ +// \ingroup Base_Tools_IO +// \ru Для совместимости с предыдущими компиляторами по именам возвращаемым typeid(a).name(). +// \en For compatibility with the previous compilers by names returned by typeid(a).name(). +// \ru Для определения того, что надо делать, скомпилируйте и запустите из консоли код: +// \en Compile and run the following code from console to define what is to do: // #include // #include // class CLASS_A { @@ -1910,28 +1919,35 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version // MS Visual C++ 6.0 ... 2010: "class CLASS_A" // gcc (Linux): "7CLASS_A" // Embarcadero C++ 7.20 for Win32 "$CLASS_A" -// \ru Интересующая нас функция должна выдавать "CLASS_A" \en The desired function must write "CLASS_A" +// \ru Интересующая нас функция должна выдавать "CLASS_A" \en The desired function must write "CLASS_A" +// +// \ru Для имени шаблонного класса функция возвращает строку, состоящую из имени класса и имен параметров. +// \en For a template class name, the function returns a string consisting of the class name and parameter names. +// \ru Например, для имени "class ClassX" функция возвращает "ClassXClassAClassB". +// \ru For example, for the name "class ClassX" the function returns "ClassXClassAClassB". // --- inline const char * pureName( const char * name ) { - if ( name && *name ) - { + if ( name && *name ) { + if ( name[strlen(name) - 1] == '>' ) { + return pureTemplateName( name ); + } + #ifdef _MSC_VER // \ru убираем ключевые слова "class", "struct" и т.д. в начале строки \en remove the keywords "class", "struct" and so on at the beginning of the string - ptrdiff_t i = strlen(name) - 1; + ptrdiff_t i = strlen( name ) - 1; for ( ; i >= 0 && name[i] != ' '; i-- ); - return ((i >= 0) && (name[i] == ' ')) ? &(name[i+1]) : name; + return ( (i >= 0) && (name[i] == ' ') ) ? &(name[i + 1]) : name; #else // _MSC_VER // \ru убираем длину имени в начале строки \en remove the name length at the beginning of the string for ( size_t i = 0, c = strlen(name); i < c; i++ ) if ( !(name[i] >= '0' && name[i] <= '9') ) - return &(name[i]); + return &( name[i] ); #endif // _MSC_VER } return name; } - //---------------------------------------------------------------------------------------- /// \ru Упаковать строку(имя класса) в uint16. \en Pack the string (class name) into uint16. \~ \ingroup Base_Tools_IO // --- @@ -1962,7 +1978,7 @@ inline uint16 hash( const char * name ) // --- inline reader & __readChar( reader & ps, char *& s ) { - s = NULL; + s = c3d_null; if ( ps.good() ) { @@ -1974,7 +1990,7 @@ inline reader & __readChar( reader & ps, char *& s ) (len > 0 && ps.eof()) || !ps.good() ) { - s = NULL; + s = c3d_null; } else // good { @@ -1990,7 +2006,7 @@ inline reader & __readChar( reader & ps, char *& s ) { // \ru прочли не все, скорее всего ошибка - очистить строку \en not everything has been read, must be an error - clear the string delete [] s; - s = NULL; + s = c3d_null; } } else @@ -2010,7 +2026,7 @@ inline reader & __readChar( reader & ps, char *& s ) // --- inline reader & __readWchar( reader & ps, TCHAR * & s ) { - s = NULL; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read + s = c3d_null; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read if ( ps.good() ) { uint32 len = 0; @@ -2028,7 +2044,7 @@ inline reader & __readWchar( reader & ps, TCHAR * & s ) else { // \ru прочли не все, скорее всего ошибка - очистить строку \en not everything has been read, must be an error - clear the string delete [] readBuf; - readBuf = NULL; + readBuf = c3d_null; } if ( readBuf ) { // is OK @@ -2065,7 +2081,7 @@ inline reader & __readWchar( reader & ps, TCHAR * & s ) // --- inline reader & __readWcharT( reader & ps, wchar_t * & s ) { - s = NULL; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read + s = c3d_null; // \ru на случай, если ничего не прочитаем \en for case if nothing will be read if ( ps.good() ) { uint32 len = 0; @@ -2083,7 +2099,7 @@ inline reader & __readWcharT( reader & ps, wchar_t * & s ) else { // \ru прочли не все, скорее всего ошибка - очистить строку \en not everything has been read, must be an error - clear the string delete [] readBuf; - readBuf = NULL; + readBuf = c3d_null; } if ( readBuf ) { // is OK @@ -2536,7 +2552,7 @@ inline reader & operator >> ( reader & ps, long double & l ) { template inline reader & operator >> ( reader & ps, SPtr<_Class> & sPtr ) { - _Class * ptr = NULL; + _Class * ptr = c3d_null; ps >> ptr; sPtr.assign( ptr ); return ps; @@ -2671,7 +2687,7 @@ inline void ReadTCHAR( reader & in, TCHAR *& ts, bool directSingleByte = false ) if ( directSingleByte || in.MathVersion() < UNICODE_VERSION ) { // \ru читаем WCHAR* из CHAR* \en read WCHAR* from CHAR* - char * s = NULL; + char * s = c3d_null; __readChar( in, s ); // \ru читаем строку в формате ANSI \en read string in ANSI format ts = _strNtcs( s ); // \ru создаем TCHAR из ANSI (если TCHAR == char, то просто дублируем) \en create TCHAR from ANSI (if TCHAR == char, then simply duplicate) delete [] s; @@ -3063,7 +3079,7 @@ inline reader & operator >> ( reader & ps, std::string & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { - char * str( NULL ); + char * str( c3d_null ); __readChar( ps, str ); // \ru читаем строку в формате ANSI \en read string in ANSI format if ( str ) s = str; @@ -3071,7 +3087,7 @@ inline reader & operator >> ( reader & ps, std::string & s ) s.clear(); delete [] str; } else { - wchar_t * p (NULL); + wchar_t * p (c3d_null); ReadWcharT( ps, p ); // \ru в зависимости от версии потока \en subject to the stream version if ( p ) { char* str = wcsnewmbs(p); @@ -3114,7 +3130,7 @@ inline reader & operator >> ( reader & ps, std::wstring & s ) { if ( ps.MathVersion() < UNICODE_VERSION ) { - char * str( NULL ); + char * str( c3d_null ); __readChar( ps, str ); // \ru читаем строку в формате ANSI \en read string in ANSI format wchar_t* p = mbsnewwcs( str ); if ( p ) @@ -3124,7 +3140,7 @@ inline reader & operator >> ( reader & ps, std::wstring & s ) delete [] p; delete [] str; } else { - wchar_t * p = NULL; + wchar_t * p = c3d_null; ReadWcharT( ps, p ); // \ru в зависимости от версии потока \en subject to the stream version if ( p ) s = p; @@ -3141,7 +3157,7 @@ inline reader & operator >> ( reader & ps, std::wstring & s ) //--- inline writer & operator << ( writer & ps, const std::wstring * s ) { - WriteWcharT( ps, (s ? s->c_str() : NULL) ); // \ru в зависимости от версии потока \en subject to the stream version + WriteWcharT( ps, (s ? s->c_str() : c3d_null) ); // \ru в зависимости от версии потока \en subject to the stream version return ps; } diff --git a/C3d/Include/io_tree.h b/C3d/Include/io_tree.h index 3591c45..e2967e3 100644 --- a/C3d/Include/io_tree.h +++ b/C3d/Include/io_tree.h @@ -153,7 +153,7 @@ protected: public: - IModelTree() : m_type ( mtt_Model ), m_nodeToAddFunc( NULL ), m_filterFunc( NULL ) {} + IModelTree() : m_type ( mtt_Model ), m_nodeToAddFunc( c3d_null ), m_filterFunc( c3d_null ) {} virtual ~IModelTree() {} // \ru Выдать тип дерева. \en Get the tree type. @@ -165,12 +165,12 @@ public: // \en Build a tree with nodes, selected by filters. In case of embodiment tree, the function works with the first embodiment. virtual std_unique_ptr GetFilteredTree ( const std::vector& filters ) const = 0; - // \ru Построить дерево по заданным узлам. Не применимо к дереву исполнений (в этом случае возвращает NULL). - // \en Build a tree for given nodes. Not applicable to embodiment tree (in this case, returns NULL). + // \ru Построить дерево по заданным узлам. Не применимо к дереву исполнений (в этом случае возвращает c3d_null). + // \en Build a tree for given nodes. Not applicable to embodiment tree (in this case, returns c3d_null). virtual std_unique_ptr GetFilteredTree ( std::vector& nodes ) const = 0; - // \ru Выдать указатель на дерево исполнений. Выдает NULL, если не применимо (нет исполнений). - // \en Get pointer to embodiments tree. Return NULL if not applicable (no embodiments). + // \ru Выдать указатель на дерево исполнений. Выдает c3d_null, если не применимо (нет исполнений). + // \en Get pointer to embodiments tree. Return c3d_null if not applicable (no embodiments). virtual const IEmbodimentTree* GetEmbodimentsTree() const = 0; // \ru Добавить узел. \en Add a node. @@ -244,7 +244,7 @@ public: IEmbodimentNode() {} virtual ~IEmbodimentNode() { for ( std::set::iterator i = m_children.begin(); i != m_children.end(); ++i ) - if ( *i != NULL ) delete *i; + if ( *i != c3d_null ) delete *i; } // \ru Построить поддерево модели, содержащееся в данном исполнении. diff --git a/C3d/Include/item_registrator.h b/C3d/Include/item_registrator.h index 53ee5d6..2c39ac3 100644 --- a/C3d/Include/item_registrator.h +++ b/C3d/Include/item_registrator.h @@ -29,10 +29,10 @@ class MATH_CLASS MbRefItem; */ // --- #define __REG_DUPLICATE_IMPL( __CLASS ) \ -MbRefItem * copyItem = NULL; \ -if ( iReg == NULL || !iReg->IsReg( this, copyItem ) ) { \ +MbRefItem * copyItem = c3d_null; \ +if ( iReg == c3d_null || !iReg->IsReg( this, copyItem ) ) { \ copyItem = new __CLASS; \ - if ( iReg != NULL ) \ + if ( iReg != c3d_null ) \ iReg->SetReg( this, copyItem ); \ } diff --git a/C3d/Include/legend.h b/C3d/Include/legend.h index f70eb86..136f13a 100644 --- a/C3d/Include/legend.h +++ b/C3d/Include/legend.h @@ -38,10 +38,10 @@ public: /* \ru Общие функции геометрического объе virtual MbeSpaceType IsA() const = 0; // \ru Тип объекта. \en Type of the object. virtual MbeSpaceType Type() const = 0; // \ru Тип объекта. \en Type of the object. virtual MbeSpaceType Family() const; // \ru Семейство элемента. \en Family of the element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными? \en Determine whether the objects are equal. virtual bool IsSimilar( const MbSpaceItem & init ) const = 0; // \ru Являются ли объекты подобными? \en Determine whether the objects are similar. virtual bool SetEqual ( const MbSpaceItem & init ) = 0; // \ru Сделать объекты равным. \en Make the objects equal. diff --git a/C3d/Include/lump.h b/C3d/Include/lump.h index 1219c08..a803bc2 100644 --- a/C3d/Include/lump.h +++ b/C3d/Include/lump.h @@ -67,7 +67,7 @@ typedef std::pair ConstLumpsSPtrSetRet; // --- struct MATH_CLASS MbLump: public MbRefItem { protected: - c3d::ConstSolidSPtr solid; ///< \ru Тело (всегда не NULL). \en Solid (always not NULL). + c3d::ConstSolidSPtr solid; ///< \ru Тело (всегда не c3d_null). \en Solid (always not c3d_null). MbMatrix3D from; ///< \ru Матрица преобразования из локальной системы координат. \en A transformation matrix from the local coordinate system. uint component; ///< \ru Идентификатор компонента, в котором определено тело. \en An identifier of a component which a solid is defined in. size_t identifier; ///< \ru Идентификатор нити. \en A thread identifier. @@ -79,7 +79,7 @@ private: MbLump( const MbLump & other, MbRegDuplicate * iReg ); public: /// \ru Пустой конструктор. \en Empty constructor. - MbLump() : solid( NULL ), from(), component( 0 ), identifier( SYS_MAX_T ), changed( true ) {} + MbLump() : solid( c3d_null ), from(), component( 0 ), identifier( SYS_MAX_T ), changed( true ) {} /// \ru Конструктор по данным. \en Constructor by data. MbLump( const MbSolid & _solid, const MbMatrix3D & _from, uint _comp = 0, size_t _ident = SYS_MAX_T, bool _changed = true ); /// \ru Деструктор. \en Destructor. @@ -96,7 +96,7 @@ public: /// \ru Разрезать тело в производном виде. \en Cut solid on derive view. virtual bool WillCutOnDeriveView() const { return true; } /// \ru Дублирование объекта. \en Duplication of an object. - virtual MbLump & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbLump & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; /// \ru Получить имя компонента. \en Get the name of a component. uint GetComponent() const { return component; } /// \ru Установить имя компонента. \en Set the name of a component. diff --git a/C3d/Include/map_create.h b/C3d/Include/map_create.h index 49aecba..af3547d 100644 --- a/C3d/Include/map_create.h +++ b/C3d/Include/map_create.h @@ -64,11 +64,11 @@ class MATH_CLASS MbMapBodiesPArray; class MATH_CLASS MbProjectionsObjects { public: - TPointer< RPArray > annCurves; ///< \ru Аннотационные кривые (может быть нулем). \en Annotation curves (can be NULL). - TPointer< RPArray > annotations; ///< \ru Аннотационные объекты (может быть нулем). \en Annotation objects (can be NULL). - TPointer< RPArray > symbolObjects; ///< \ru Условные обозначения (может быть нулем). \en Conventional notations (can be NULL). - TPointer< RPArray > pointsData; ///< \ru Пространственные точки (может быть нулем). \en Spatial points (can be NULL). - TPointer< RPArray > curvesData; ///< \ru Пространственные кривые (может быть нулем). \en Spatial curves (can be NULL). + TPointer< RPArray > annCurves; ///< \ru Аннотационные кривые (может быть нулем). \en Annotation curves (can be c3d_null). + TPointer< RPArray > annotations; ///< \ru Аннотационные объекты (может быть нулем). \en Annotation objects (can be c3d_null). + TPointer< RPArray > symbolObjects; ///< \ru Условные обозначения (может быть нулем). \en Conventional notations (can be c3d_null). + TPointer< RPArray > pointsData; ///< \ru Пространственные точки (может быть нулем). \en Spatial points (can be c3d_null). + TPointer< RPArray > curvesData; ///< \ru Пространственные кривые (может быть нулем). \en Spatial curves (can be c3d_null). public: /** \brief \ru Конструктор. @@ -78,11 +78,11 @@ public: \en Constructor of empty sets of projected objects.\n \~ */ MbProjectionsObjects() - : annCurves ( NULL ) - , annotations ( NULL ) - , symbolObjects( NULL ) - , pointsData ( NULL ) - , curvesData ( NULL ) + : annCurves ( c3d_null ) + , annotations ( c3d_null ) + , symbolObjects( c3d_null ) + , pointsData ( c3d_null ) + , curvesData ( c3d_null ) {} /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. MbProjectionsObjects( const MbProjectionsObjects & other, MbRegDuplicate * iReg ); @@ -104,7 +104,7 @@ public: } /// \ru Дать копию объекта. \en Get a copy of the object. - virtual MbProjectionsObjects & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbProjectionsObjects & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; /// \ru Отпустить все указатели. \en Detach all pointers. void Relinquish() @@ -173,9 +173,9 @@ public: size_t GetLumpsCount() const { return lumps.size(); } const MbLump * _GetLump( size_t k ) const { return lumps[k]; } - const MbLump * GetLump( size_t k ) const { return ((k < lumps.size()) ? lumps[k] : NULL); } + const MbLump * GetLump( size_t k ) const { return ((k < lumps.size()) ? lumps[k] : c3d_null); } MbLump * _SetLump( size_t k ) { return lumps[k]; } - MbLump * SetLump( size_t k ) { return ((k < lumps.size()) ? lumps[k] : NULL); } + MbLump * SetLump( size_t k ) { return ((k < lumps.size()) ? lumps[k] : c3d_null); } template void GetLumps( Lumps & _lumps ) const @@ -282,7 +282,7 @@ MATH_FUNC (MbResultType) GetVestiges ( const MbPlacement3D & place, const MbMapVisibilityMode & visMode, VERSION version = Math::DefaultMathVersion(), bool merge = true, - const std::vector * prevCubes = NULL ); + const std::vector * prevCubes = c3d_null ); //------------------------------------------------------------------------------ @@ -316,7 +316,7 @@ public: public: MbMapSettings( MbMapVisibilityMode mode, MbPlacement3D place = MbPlacement3D::global, - double znear = 0, bool merge = true, const LumpCubes * prevCubes = NULL ) + double znear = 0, bool merge = true, const LumpCubes * prevCubes = c3d_null ) : m_place ( place ) , m_zNear ( znear ) , m_visMode ( mode ) diff --git a/C3d/Include/map_implementation.h b/C3d/Include/map_implementation.h index da1d5eb..fbb0280 100644 --- a/C3d/Include/map_implementation.h +++ b/C3d/Include/map_implementation.h @@ -109,7 +109,7 @@ public: void CreateFirst( const RPArray & lumps, const MbMatrix3D & into, double znear, bool perspective, const MbMapVisibilityMode & visMode, VERSION version, - const std::vector * prevCubes = NULL ); + const std::vector * prevCubes = c3d_null ); /** \brief \ru Построение ассоциативных проекций. \en The construction of associative projections. \~ @@ -220,7 +220,7 @@ OBVIOUS_PRIVATE_COPY( MbMapBodiesPArray ) mvt_Cut - Разрез,\n mvt_Section - Сечечние;\n плоскость вида, разреза или сечения.\n - \en The information about basic view on witch a local view\cutaway is constructed:\n + \en The information about basic view on witch a local view(cutaway) is constructed:\n a view type:\n mvt_View - View,\n mvt_Cut - Cutaway,\n diff --git a/C3d/Include/map_lump.h b/C3d/Include/map_lump.h index 8290612..89e83e8 100644 --- a/C3d/Include/map_lump.h +++ b/C3d/Include/map_lump.h @@ -138,7 +138,7 @@ public: /// \ru Деструктор. \en Destructor. virtual ~CurveWType() {} /// \ru Сделать копию объекта. \en Create a copy of the object. - virtual CurveWType & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual CurveWType & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: @@ -229,7 +229,7 @@ public: explicit MbAnnCurves( const MbName & _name, uint _comp, size_t _ident ) : component ( _comp ) , identifier( _ident ) - , solid ( NULL ) + , solid ( c3d_null ) , name ( &_name ) , from ( ) , wtCurves ( 0, 1, true ) @@ -245,7 +245,7 @@ public: public: /// \ru Дать копию объекта. \en Get a copy of the object. - virtual MbAnnCurves & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbAnnCurves & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; /// \ru Получить имя компонента. \en Get the component name. uint GetComponent() const { return component; } @@ -265,12 +265,12 @@ public: \param[in, out] wtCurve - \ru Кривая. \en A curve. \~ */ - void AbsorbCurve( CurveWType *& wtCurve ) { wtCurves.Add( wtCurve ); wtCurve = NULL; } + void AbsorbCurve( CurveWType *& wtCurve ) { wtCurves.Add( wtCurve ); wtCurve = c3d_null; } /// \ru Количество кривых в наборе. \en The number of curves in the set. size_t GetCurvesCount() const { return wtCurves.Count(); } /// \ru Получить указатель на кривую. \en Get the pointer to the curve. - const CurveWType * GetCurve( size_t k ) const { return ((k < wtCurves.Count()) ? wtCurves[k] : NULL); } + const CurveWType * GetCurve( size_t k ) const { return ((k < wtCurves.Count()) ? wtCurves[k] : c3d_null); } private: DECLARE_PERSISTENT_CLASS_NEW_DEL ( MbAnnCurves ) @@ -317,7 +317,7 @@ public : public: /// \ru Дать копию объекта. \en Get a copy of the object. - virtual MbSimbolthThreadView & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbSimbolthThreadView & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public : /// \ru Получить аннотационные кривые для редактирования. \en Get annotative curves for editing. @@ -508,7 +508,7 @@ public: public: /// \ru Дать копию объекта. \en Get a copy of the object. - virtual MbSpacePoints & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbSpacePoints & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: @@ -659,16 +659,16 @@ public: \en Get the name. \~ \details \ru Получить имя по индексу.\n Если индекс некорректный, то есть не меньше числа точек, - вернет NULL. + вернет c3d_null. \en Get the name by an index.\n If the index is incorrect i.e. it isn't less than the number of points, - NULL is returned. \~ + c3d_null is returned. \~ \param[in] k - \ru Индекс имени. \en A name index. \~ \return \ru Имя по индексу из набора имен. \en A name by an index from the set of names. \~ */ - const MbName * GetName( size_t k ) const { return ((k < names.size()) ? names[k] : NULL); } + const MbName * GetName( size_t k ) const { return ((k < names.size()) ? names[k] : c3d_null); } /** \} */ DECLARE_PERSISTENT_CLASS_NEW_DEL ( MbSpacePoints ) @@ -786,7 +786,7 @@ private: public: /// \ru Дать копию объекта. \en Get a copy of the object. - virtual MbSpaceCurves & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbSpaceCurves & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /** \} */ @@ -908,11 +908,11 @@ public: \param[in] k - \ru Индекс кривой. \en A curve index. \~ \return \ru Указатель на кривую, если индекс меньше количества кривых,\n - иначе NULL. + иначе c3d_null. \en A pointer to a curve, if the index is less than the number of curves,\n - otherwise NULL is returned. \~ + otherwise c3d_null is returned. \~ */ - const MbCurve3D * GetCurve( size_t k ) const { return ((k < curves.size()) ? curves[k] : NULL); } + const MbCurve3D * GetCurve( size_t k ) const { return ((k < curves.size()) ? curves[k] : c3d_null); } /** \} */ /**\ru \name Доступ к именам. @@ -940,11 +940,11 @@ public: \param[in] k - \ru Индекс имени. \en A name index. \~ \return \ru Указатель на имя, если индекс меньше количества имен,\n - иначе NULL. + иначе c3d_null. \en A pointer to a name, if the index is less than the number of curves, - otherwise NULL is returned. \~ + otherwise c3d_null is returned. \~ */ - const MbName * GetName( size_t k ) const { return ((k < names.size()) ? names[k] : NULL); } ///< \ru Получить имя. \en Get the name. + const MbName * GetName( size_t k ) const { return ((k < names.size()) ? names[k] : c3d_null); } ///< \ru Получить имя. \en Get the name. /** \} */ DECLARE_PERSISTENT_CLASS_NEW_DEL ( MbSpaceCurves ) @@ -958,7 +958,7 @@ IMPL_PERSISTENT_OPS( MbSpaceCurves ) inline void MbSpaceCurves::AddNamedCurve( MbCurve3D * crv, MbName * nm, bool noSameCheck ) { - if ( crv != NULL && (noSameCheck || curves.FindIt( crv ) == SYS_MAX_T ) ) { + if ( crv != c3d_null && (noSameCheck || curves.FindIt( crv ) == SYS_MAX_T ) ) { curves.push_back( crv ); crv->AddRef(); names.push_back( nm ); @@ -1111,7 +1111,7 @@ public: */ MbMappingLumps( const MbSolid & _solid, const MbMatrix3D & _from, bool _willCut, uint _comp = 0, size_t _ident = SYS_MAX_T ) : MbCutLump ( _solid, _from, _comp, _ident ) - , lumps ( NULL ) + , lumps ( c3d_null ) , willCut ( _willCut ) { } @@ -1121,13 +1121,13 @@ public: \details \ru Конструктор по набору тел.\n Захватывает тело MbSolid из первого элемента _lumps и остальные элементы _lumps методом AddRef().\n - Если в _lumps один элемент, массив lumps остается NULL.\n - Если в _lumps нет элементов, тело MbSolid в базовом объекте = NULL. Таких объектов быть не должно. + Если в _lumps один элемент, массив lumps остается c3d_null.\n + Если в _lumps нет элементов, тело MbSolid в базовом объекте = c3d_null. Таких объектов быть не должно. \en Constructor by a set of solids.\n Captures MbSolid solid from the first element of the _lumps and the other elements of the _lumps by AddRef() method.\n - If the _lumps contains one element the lumps array remains NULL.\n - If the _lumps doesn't contain any elements the MbSolid solid in the base object = NULL. These objects should not be. \~ + If the _lumps contains one element the lumps array remains c3d_null.\n + If the _lumps doesn't contain any elements the MbSolid solid in the base object = c3d_null. These objects should not be. \~ \param[in] _lumps - \ru Контейнер тел с матрицами преобразования в глобальную систему координат,. не должен быть пустым контейнером. \en A container of solids with the matrices of transformation to the global coordinate system @@ -1136,13 +1136,13 @@ public: template MbMappingLumps( const LumpsVector & _lumps ) : MbCutLump() - , lumps( NULL ) + , lumps( c3d_null ) , willCut( false ) // конструктор по нескольким телам только в случае "не рассекать" { size_t count = _lumps.size(); - C3D_ASSERT( count > 0 && _lumps[0] != NULL ); + C3D_ASSERT( count > 0 && _lumps[0] != c3d_null ); - if ( count > 0 && _lumps[0] != NULL ) { + if ( count > 0 && _lumps[0] != c3d_null ) { from = _lumps[0]->GetMatrixFrom(); component = _lumps[0]->GetComponent(); identifier = _lumps[0]->GetIdentifier(); @@ -1154,7 +1154,7 @@ public: lumps = new c3d::LumpsSPtrVector(); for ( size_t i = 1; i < count; ++i ) { MbLump * lump = _lumps[i]; - if ( lump != NULL ) + if ( lump != c3d_null ) lumps->push_back( c3d::LumpSPtr(lump) ); } } @@ -1167,19 +1167,19 @@ public: /** \brief \ru Число тел. \en The number of solids. \~ \details \ru Число тел.\n - Минимальное количество - 1 тело. В этом случае массив lumps = NULL. - В случае, если массив lumps != NULL, количество тел равно количеству + Минимальное количество - 1 тело. В этом случае массив lumps = c3d_null. + В случае, если массив lumps != c3d_null, количество тел равно количеству элементов в массиве плюс один. \en The number of solids.\n - Minimal number = 1 solid. In this case the lumps array is NULL. - In a case when the lumps array isn't NULL the number of solids is equal to + Minimal number = 1 solid. In this case the lumps array is c3d_null. + In a case when the lumps array isn't c3d_null the number of solids is equal to the number of elements in the array plus one. \~ \return \ru Число тел. \en The number of solids. \~ */ size_t Count() const { size_t res = 1; - if ( lumps != NULL ) + if ( lumps != c3d_null ) res += lumps->size(); return res; } @@ -1190,21 +1190,21 @@ public: По индексу 0 выдается базовый объект.\n По индексу i выдается объект из массива lumps с индексом i-1.\n Индекс проверяется на корректность. - В случае некорректного индекса возвращает NULL. + В случае некорректного индекса возвращает c3d_null. \en A solid by an index.\n The basic object is given by the "0" index.\n An object with the index i - 1 from the lumps array is issued by the index i.\n An index is validated for correctness. - In a case of an incorrect index the method returns NULL. \~ + In a case of an incorrect index the method returns c3d_null. \~ \return \ru Указатель на тело с матрицей. \en A pointer to a solid with a matrix. \~ */ MbLump * operator []( size_t ind ) { if ( ind == 0 ) return static_cast( this ); - else if ( lumps != NULL && ind - 1 < lumps->size() ) + else if ( lumps != c3d_null && ind - 1 < lumps->size() ) return lumps->operator []( ind - 1 ); - return NULL; + return c3d_null; } /** \brief \ru Тело по индексу. @@ -1213,12 +1213,12 @@ public: По индексу 0 выдается базовый объект.\n По индексу i выдается объект из массива lumps с индексом i-1.\n Индекс проверяется на корректность. - В случае некорректного индекса возвращает NULL. + В случае некорректного индекса возвращает c3d_null. \en A solid by an index.\n The basic object is given by the "0" index.\n An object with the index i - 1 from the lumps array is issued by the index i.\n An index is validated for correctness. - In a case of an incorrect index the method returns NULL. \~ + In a case of an incorrect index the method returns c3d_null. \~ \return \ru Константный указатель на тело с матрицей. \en A constant pointer to a solid with a matrix. \~ */ @@ -1226,9 +1226,9 @@ public: { if ( ind == 0 ) return static_cast( this ); - else if ( lumps != NULL && ind - 1 < lumps->size() ) + else if ( lumps != c3d_null && ind - 1 < lumps->size() ) return lumps->operator []( ind - 1 ); - return NULL; + return c3d_null; } void ChangeLump( size_t ind, MbLump * newLump ) @@ -1239,7 +1239,7 @@ public: component = newLump->GetComponent(); identifier = newLump->GetIdentifier(); } - else if ( lumps != NULL && ind - 1 < lumps->size() ) { + else if ( lumps != c3d_null && ind - 1 < lumps->size() ) { (*lumps)[ind - 1] = newLump; } } @@ -1323,7 +1323,7 @@ public: } /// \ru Деструктор. \en Destructor. ~MbPolygon3DSolid() { - if ( polygon != NULL ) + if ( polygon != c3d_null ) delete polygon; } @@ -1332,7 +1332,7 @@ public: /// \ru Получить имя компонента. \en Get the name of a component. uint GetComponent() const { return component; } /// \ru Занулить полигон без удаления. \en Reset polygon without removal. - void DoNotDeletePolyg() { polygon = NULL; } + void DoNotDeletePolyg() { polygon = c3d_null; } OBVIOUS_PRIVATE_COPY( MbPolygon3DSolid ) }; @@ -1360,7 +1360,7 @@ enum MbeMapViewType { информации о виде при построении местного вида\разреза или выносного элемента. \en The information about an associative view. Used for transfer - The information about a view in constructing the local view\cutaway or + The information about a view in constructing the local view(cutaway) or detail view. \~ \ingroup Mapping */ diff --git a/C3d/Include/map_section.h b/C3d/Include/map_section.h index d3878f0..f7dffe2 100644 --- a/C3d/Include/map_section.h +++ b/C3d/Include/map_section.h @@ -87,7 +87,7 @@ public: \en Clear the array of contours if it isn't null. \~ */ void DetachContours() { - if ( arContours != NULL ) + if ( arContours != c3d_null ) arContours->Flush( noDelete ); } @@ -142,10 +142,10 @@ public: /** \brief \ru Добавить оболочку. \en Add a shell. \~ \details \ru Добавить оболочку в набор оболочек.\n - Добавляется, даже если равна NULL.\n + Добавляется, даже если равна c3d_null.\n Если не нулевая - захватывается. \en Add a shell into the set of shells.\n - A shell is added even if it is equal to NULL.\n + A shell is added even if it is equal to c3d_null.\n If a shell isn't null it is captured. \~ \param[in] secShell - \ru Оболочка. \en A shell. \~ @@ -331,7 +331,7 @@ public: \return \ru true, если массив точек не нулевой и не пустой. \en returns true if the array of points isn't null and isn't empty. \~ */ - bool IsSpacePoints() const { return (pointsData != NULL && pointsData->size() > 0); } + bool IsSpacePoints() const { return (pointsData != c3d_null && pointsData->size() > 0); } /** \brief \ru Есть ли в объекте кривые. \en Whether any curve is in an object. \~ @@ -340,7 +340,7 @@ public: \return \ru true, если массив кривых не нулевой и не пустой. \en returns true if the array of curves isn't null and isn't empty. \~ */ - bool IsSpaceCurves() const { return (curvesData != NULL && curvesData->size() > 0); } + bool IsSpaceCurves() const { return (curvesData != c3d_null && curvesData->size() > 0); } const RPArray * GetSpacePoints() const { return pointsData; } ///< \ru Получить указатель на пространственные точки. \en Get spatial points. const RPArray * GetSpaceCurves() const { return curvesData; } ///< \ru Получить указатель на пространственные кривые. \en Get spatial curves. diff --git a/C3d/Include/map_section_complex.h b/C3d/Include/map_section_complex.h index ae0e54b..48bd08a 100644 --- a/C3d/Include/map_section_complex.h +++ b/C3d/Include/map_section_complex.h @@ -233,13 +233,14 @@ MATH_FUNC(bool) FormFirstSectionPlane( const MbPlacement3D & m_place, const MbCu Нормаль плоскости вида направлена против вектора взгляда. \en The view plane convert to the plane of the projection. Normal to the view plane is directed against the view vector. \~ - \param[in\out] place - \ru Плоскость вида\Плоскость отображения проекции. - \en A view plane\A plane of the projection. \~ + \param[in,out] place - \ru Плоскость вида (отображения проекции). + \en A view plane (A plane of the projection). \~ \param[in] viewDir - \ru Вектор взгляда. \en A view vector. \~ */ // --- -inline void MappingVPtoMP( MbPlacement3D & place, const MbVector & viewDir ) +inline +void MappingVPtoMP( MbPlacement3D & place, const MbVector & viewDir ) { if ( ::fabs(viewDir.x) > Math::lengthEpsilon || ::fabs(viewDir.y) > Math::lengthEpsilon ) { MbVector vDir( viewDir ); diff --git a/C3d/Include/map_vestige.h b/C3d/Include/map_vestige.h index bc4e949..e05ce3b 100644 --- a/C3d/Include/map_vestige.h +++ b/C3d/Include/map_vestige.h @@ -154,7 +154,7 @@ protected: , ident ( otherIdent ) , style ( SYS_MAX_UINT16 ) , attrData ( ) - , item ( NULL ) + , item ( c3d_null ) , name ( &otherName ) { name.SetOwn( false ); } /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. @@ -164,13 +164,13 @@ protected: : comp ( 0 ) , ident ( SYS_MAX_T ) , style ( SYS_MAX_UINT16 ) - , item ( NULL ) - , name ( NULL ) + , item ( c3d_null ) + , name ( c3d_null ) { name.SetOwn(false); } virtual ~MbBaseVestige() {} public: - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; ///< \ru Создать копию объекта. \en Create a copy of the object. + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; ///< \ru Создать копию объекта. \en Create a copy of the object. public: uint GetComponent() const { return comp; } size_t GetIdentifier() const { return ident; } @@ -268,7 +268,7 @@ protected: {} public: /// \ru Создать копию объекта. \en Create a copy of the object. - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /// \ru Тип отображения. \en Mapping type. Type GetType() const { return (Type)vesType; } @@ -304,11 +304,11 @@ void ReplaceCurveVestigeDuplicates( MbCurveVestige & ); // --- struct MATH_CLASS MbCurveVestige : public TapeBase { protected: - SPtr totalPrj; ///< \ru Полная проекция (может быть NULL). \en A full projection (can be NULL). \~ \internal \ru Владеет. \en Owns. \~ \endinternal + SPtr totalPrj; ///< \ru Полная проекция (может быть c3d_null). \en A full projection (can be c3d_null). \~ \internal \ru Владеет. \en Owns. \~ \endinternal std::vector arTotal; ///< \ru Все проекции в упорядоченной форме. \en All projections in an ordered form. \~ \internal \ru Не владеет. \en Doesn't own. \~ \endinternal // \ru Двумерные кривые лежат копиями, поэтому массивы владеющие. \en Two-dimensional uv-curves are copies therefore arrays are owners - // \ru Если кривых нет то указатель останется нулевым. \en If no curves then the pointer remains NULL. + // \ru Если кривых нет то указатель останется нулевым. \en If no curves then the pointer remains c3d_null. TPointer< PArray > arVisPrj; ///< \ru Видимые проекции. \en Visible projections. TPointer< PArray > arHidPrj; ///< \ru Не видимые проекции. \en Invisible projections. @@ -321,10 +321,10 @@ public: Creates an object with the null projection. \~ */ MbCurveVestige() - : totalPrj( NULL ) + : totalPrj( c3d_null ) , arTotal ( ) - , arVisPrj( NULL ) - , arHidPrj( NULL ) + , arVisPrj( c3d_null ) + , arHidPrj( c3d_null ) {} /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. MbCurveVestige( const MbCurveVestige & other, MbRegDuplicate * iReg ); @@ -332,7 +332,7 @@ public: virtual ~MbCurveVestige() { ClearAll(); } public: /// \ru Создать копию объекта. \en Create a copy of the object. - virtual MbCurveVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbCurveVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /** \brief \ru Очистить проекции. @@ -347,14 +347,14 @@ public: void ClearAll() { arTotal.clear(); - totalPrj = NULL; - arVisPrj = NULL; - arHidPrj = NULL; + totalPrj = c3d_null; + arVisPrj = c3d_null; + arHidPrj = c3d_null; } /// \ru Пустое ли отображение кривой? \en Is an empty curve vestige? bool IsEmpty() const { - return ( totalPrj == NULL ) && + return ( totalPrj == c3d_null ) && ( arTotal.size() < 1 ) && ( !arVisPrj || arVisPrj->empty() ) && ( !arHidPrj || arHidPrj->empty() ); @@ -372,9 +372,9 @@ public: bool IsHiddenCurvesArray () const { return !!arHidPrj; } /// \ru Получить видимую часть проекции. \en Get visible part of projection. - const MbCurve * _GetVisibleCurve( size_t k ) const { return (( !!arVisPrj ) ? (*arVisPrj)[k] : NULL); } + const MbCurve * _GetVisibleCurve( size_t k ) const { return (( !!arVisPrj ) ? (*arVisPrj)[k] : c3d_null); } /// \ru Получить невидимую часть проекции. \en Get hidden part of projection. - const MbCurve * _GetHiddenCurve ( size_t k ) const { return (( !!arHidPrj ) ? (*arHidPrj)[k] : NULL); } + const MbCurve * _GetHiddenCurve ( size_t k ) const { return (( !!arHidPrj ) ? (*arHidPrj)[k] : c3d_null); } /// \ru Положить в массив указатели видимых частей проекции. \en Put pointers of visible parts of projection into the array. template @@ -414,7 +414,7 @@ public: \details \ru Забрать все проекционные кривые из структуры и очистить ее. \en Pick up all curves of this structure and clear it. \~ */ - bool PickUpMapCurves( RPArray & crvArr, SArray & visArr ); + bool PickUpMapCurves( RPArray & crvArr, c3d::BoolVector & visArr ); /// \ru Забрать видимую часть проекции (не обнуляет в массиве всех проекций). \en Pick up visible part of projection (it doesn't set zero in all projections array). MbCurve * _PickupVisibleCurve( size_t ); /// \ru Забрать невидимую часть проекции (не обнуляет в массиве всех проекций). \en Pick up hidden part of projection (it doesn't set zero in all projections array). @@ -433,7 +433,7 @@ public: bool RepairSpecificCorrespondence( bool uncertainIsVisible ); /// \ru Есть ли указатель на полную проекцию? \en Is there a pointer to the full projection? - bool IsTotalProjection() const { return (totalPrj != NULL); } + bool IsTotalProjection() const { return (totalPrj != c3d_null); } /// \ru Указатель на полную проекцию. \en The pointer to a full projection. MbCurve * DetachTotalProjection() { return ::DetachItem( totalPrj ); } /// \ru Установить полную проекцию. \en Set a full projection. @@ -466,7 +466,7 @@ const MbCurve * MbCurveVestige::GetFullProjection() const MbCurve * curve = totalPrj; - if ( curve == NULL ) { + if ( curve == c3d_null ) { if ( !!arVisPrj && (arVisPrj->size() == 1) ) curve = arVisPrj->operator[]( 0 ); else if ( !!arHidPrj && (arHidPrj->size() == 1) ) @@ -480,15 +480,15 @@ const MbCurve * MbCurveVestige::GetFullProjection() const //--- inline MbCurve * MbCurveVestige::_PickupVisibleCurve( size_t k ) { - if ( arVisPrj != NULL ) { + if ( arVisPrj != c3d_null ) { PArray & crvs = *arVisPrj; MbCurve * crv = crvs[k]; ::AddRefItem( crv ); // захват и отпускание на случай перехода на владение по счетчику ссылок - crvs[k] = NULL; + crvs[k] = c3d_null; ::DecRefItem( crv ); return crv; } - return NULL; + return c3d_null; } //------------------------------------------------------------------------------ @@ -496,15 +496,15 @@ inline MbCurve * MbCurveVestige::_PickupVisibleCurve( size_t k ) //--- inline MbCurve * MbCurveVestige::_PickupHiddenCurve( size_t k ) { - if ( arHidPrj != NULL ) { + if ( arHidPrj != c3d_null ) { PArray & crvs = *arHidPrj; MbCurve * crv = crvs[k]; ::AddRefItem( crv ); // захват и отпускание на случай перехода на владение по счетчику ссылок - crvs[k] = NULL; + crvs[k] = c3d_null; ::DecRefItem( crv ); return crv; } - return NULL; + return c3d_null; } //------------------------------------------------------------------------------ @@ -513,11 +513,11 @@ inline MbCurve * MbCurveVestige::_PickupHiddenCurve( size_t k ) inline void MbCurveVestige::DetachAllCurves( PArray *& visCurves, PArray *& hidCurves, SPtr & wholePrj ) { wholePrj = totalPrj; - totalPrj = NULL; + totalPrj = c3d_null; arTotal.clear(); - visCurves = !!arVisPrj ? arVisPrj.Relinquish() : NULL; - hidCurves = !!arHidPrj ? arHidPrj.Relinquish() : NULL; + visCurves = !!arVisPrj ? arVisPrj.Relinquish() : c3d_null; + hidCurves = !!arHidPrj ? arHidPrj.Relinquish() : c3d_null; } //------------------------------------------------------------------------------ @@ -634,7 +634,7 @@ protected: , vesSubType( vst_None ) {} public: - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /// \ru Получить тип отображения. \en Get mapping type. Type GetType() const { return (Type)vesType; } @@ -735,7 +735,7 @@ protected: /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. MbFaceVestige( const MbFaceVestige & other, MbRegDuplicate * iReg ); public: - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /// \ru Тип отображения. \en Mapping type. Type GetType() const { return (Type)vesType; } @@ -796,7 +796,7 @@ protected: MbAnnotationEdgeVestige( const MbAnnotationEdgeVestige & other, MbRegDuplicate * iReg ); public: - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /// \ru Тип отображения. \en Mapping type. @@ -886,7 +886,7 @@ protected: MbSymbolVestige( uint otherComp, size_t otherIdent, const MbTopologyItem * otherItem, const MbName & otherName, bool _bvisible = true ) : MbBaseVestige( otherComp, otherIdent, otherName, otherItem ) , bvisible( _bvisible ) - , matrix ( NULL ) + , matrix ( c3d_null ) {} /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. MbSymbolVestige( const MbSymbolVestige & other, MbRegDuplicate * iReg ); @@ -894,12 +894,12 @@ protected: MbSymbolVestige() : MbBaseVestige() , bvisible( true ) - , matrix ( NULL ) + , matrix ( c3d_null ) {} public: virtual ~MbSymbolVestige() {} - virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbBaseVestige & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; public: /// \ru Это видимая точка? \en Is point visible? @@ -924,8 +924,8 @@ IMPL_PERSISTENT_OPS( MbSymbolVestige ) // --- inline void MbSymbolVestige::SetMatrix( const MbMatrix & initMatrix ) { - C3D_ASSERT( matrix == NULL ); - if ( matrix == NULL ) + C3D_ASSERT( matrix == c3d_null ); + if ( matrix == c3d_null ) matrix = new MbMatrix( initMatrix ); else *matrix = initMatrix; @@ -970,7 +970,7 @@ public: public: /// \ru Создать копию объекта. \en Create a copy of the object. - virtual MbVEFVestiges & Duplicate( MbRegDuplicate * iReg = NULL ) const; + virtual MbVEFVestiges & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; /// \ru Очистить массивы следов. \en Clear arrays of vestiges. void SetEmpty() { @@ -1209,16 +1209,16 @@ inline MbEdgeVestige * MbVEFVestiges::AddVestigeCurve( uint otherComp, size_t ot inline MbEdgeVestige * MbVEFVestiges::AddVestigeCurve( uint otherComp, size_t otherIdent, const RPArray & mapCurves, bool visible, const MbName & otherName ) { - MbEdgeVestige * ev = NULL; + MbEdgeVestige * ev = c3d_null; ev = ::AddVestigeCurve( otherComp, otherIdent, otherName, curveVestiges, false, false ); // BUG_93683 ev = ::AddVestigeEdge( otherComp, otherIdent, otherName, MbBaseVestige::vt_Edge, edgeVestiges ); - if ( ev != NULL ) { + if ( ev != c3d_null ) { MbCurveVestige & vc = ev->curveInfo; for ( size_t m = 0, mapCurvesCnt = mapCurves.Count(); m < mapCurvesCnt; m++ ) { MbCurve * mapCurve = mapCurves[m]; - if ( mapCurve != NULL ) + if ( mapCurve != c3d_null ) vc.AddSegment( *mapCurve, visible ); } } diff --git a/C3d/Include/marker.h b/C3d/Include/marker.h index 49b7d18..94cbd38 100644 --- a/C3d/Include/marker.h +++ b/C3d/Include/marker.h @@ -76,10 +76,10 @@ public: // \ru Общие функции геометрического объекта \en Common functions of a geometric object virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en Type of the object. virtual MbeSpaceType Type() const; // \ru Тип объекта. \en Type of the object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными? \en Determine whether objects are similar. virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равным. \en Make objects equal. diff --git a/C3d/Include/math_define.h b/C3d/Include/math_define.h index c4fca86..6749456 100644 --- a/C3d/Include/math_define.h +++ b/C3d/Include/math_define.h @@ -39,49 +39,59 @@ namespace c3d // namespace C3D { -typedef std::pair IndicesPair; ///< \ru Пара целочисленных неотрицательных индексов. \en Pair of non-negative integer indices. -typedef std::pair NumbersPair; ///< \ru Пара целочисленных номеров. \en Pair of integer numbers. -typedef std::pair UintPair; ///< \ru Пара 32-битных целочисленных неотрицательных индексов. \en Pair of 32-bit non-negative integer indices. -typedef std::pair BoolPair; ///< \ru Пара флагов. \en Bool pair. -typedef std::pair DoublePair; ///< \ru Пара действительных чисел двойной точности с плавающей запятой. \en Pair of doubles. -typedef std::pair IndicesPairDouble; ///< \ru Пара индексов и числа. \en A pair of indices and double. -typedef std::pair DoubleIndicesPair; ///< \ru Число и пара индексов. \en Double and a pair of indices. +typedef std::pair IndicesPair; ///< \ru Пара целочисленных неотрицательных индексов. \en Pair of non-negative integer indices. +typedef std::pair NumbersPair; ///< \ru Пара целочисленных номеров. \en Pair of integer numbers. +typedef std::pair UintPair; ///< \ru Пара 32-битных целочисленных неотрицательных индексов. \en Pair of 32-bit non-negative integer indices. +typedef std::pair BoolPair; ///< \ru Пара флагов. \en Bool pair. +typedef std::pair DoublePair; ///< \ru Пара действительных чисел двойной точности с плавающей запятой. \en Pair of doubles. +typedef std::pair IndicesPairDouble; ///< \ru Пара индексов и числа. \en A pair of indices and double. +typedef std::pair DoubleIndicesPair; ///< \ru Число и пара индексов. \en Double and a pair of indices. -typedef std::pair IndexBool; ///< \ru Пара номер-флаг. \en Index-double pair. -typedef std::pair BoolIndex; ///< \ru Пара флаг-номер. \en Double-index pair. -typedef std::pair IndexDouble; ///< \ru Пара номер-число. \en Index-double pair. -typedef std::pair DoubleIndex; ///< \ru Пара число-номер. \en Double-index pair. -typedef std::pair FlagDouble; ///< \ru Пара флаг-число. \en Flag-double pair. -typedef std::pair DoubleFlag; ///< \ru Пара число-флаг. \en Double-flag pair. -typedef FlagDouble BoolDouble; ///< \ru Пара флаг-число. \en Flag-double pair. -typedef DoubleFlag DoubleBool; ///< \ru Пара число-флаг. \en Double-flag pair. +typedef std::pair IndexBool; ///< \ru Пара номер-флаг. \en Index-double pair. +typedef std::pair BoolIndex; ///< \ru Пара флаг-номер. \en Double-index pair. +typedef std::pair IndexDouble; ///< \ru Пара номер-число. \en Index-double pair. +typedef std::pair DoubleIndex; ///< \ru Пара число-номер. \en Double-index pair. +typedef std::pair FlagDouble; ///< \ru Пара флаг-число. \en Flag-double pair. +typedef std::pair DoubleFlag; ///< \ru Пара число-флаг. \en Double-flag pair. +typedef FlagDouble BoolDouble; ///< \ru Пара флаг-число. \en Flag-double pair. +typedef DoubleFlag DoubleBool; ///< \ru Пара число-флаг. \en Double-flag pair. -typedef std::vector IndicesVector; ///< \ru Вектор целочисленных неотрицательных индексов. \en Vector of non-negative integer indices. -typedef std::vector NumbersVector; ///< \ru Вектор целочисленных номеров. \en Vector of integer numbers. -typedef std::vector UintVector; ///< \ru Вектор 32-битных целочисленных неотрицательных индексов. \en Vector of 32-bit non-negative integer indices. -typedef std::vector BoolVector; ///< \ru Вектор флагов. \en Bool vector. -typedef std::vector DoubleVector; ///< \ru Вектор double. \en Double vector. +typedef std::vector IndicesVector; ///< \ru Вектор целочисленных неотрицательных индексов. \en Vector of non-negative integer indices. +typedef std::vector NumbersVector; ///< \ru Вектор целочисленных номеров. \en Vector of integer numbers. +typedef std::vector UintVector; ///< \ru Вектор 32-битных целочисленных неотрицательных индексов. \en Vector of 32-bit non-negative integer indices. +typedef std::vector BoolVector; ///< \ru Вектор флагов. \en Bool vector. +typedef std::vector DoubleVector; ///< \ru Вектор double. \en Double vector. -typedef std::vector< IndicesPair > IndicesPairsVector; ///< \ru Вектор пар целочисленных неотрицательных индексов. \en Vector of pairs of non-negative integer indices. -typedef std::vector< NumbersPair > NumbersPairsVector; ///< \ru Вектор пар целочисленных индексов. \en Vector of pairs of integer indices. -typedef std::vector< DoublePair > DoublePairsVector; ///< \ru Вектор пар double. \en Vector of double pairs. +typedef std::vector IndicesPairsVector; ///< \ru Вектор пар целочисленных неотрицательных индексов. \en Vector of pairs of non-negative integer indices. +typedef std::vector NumbersPairsVector; ///< \ru Вектор пар целочисленных индексов. \en Vector of pairs of integer indices. +typedef std::vector DoublePairsVector; ///< \ru Вектор пар double. \en Vector of double pairs. -typedef std::set IndicesSet; ///< \ru Набор целочисленных неотрицательных индексов. \en Set of non-negative integer indices. -typedef IndicesSet::iterator IndicesSetIt; -typedef IndicesSet::const_iterator IndicesSetConstIt; -typedef std::pair IndicesSetRet; +typedef std::set IndicesSet; ///< \ru Набор целочисленных неотрицательных индексов. \en Set of non-negative integer indices. +typedef IndicesSet::iterator IndicesSetIt; +typedef IndicesSet::const_iterator IndicesSetConstIt; +typedef std::pair IndicesSetRet; -typedef std::set NumbersSet; ///< \ru Набор целочисленных номеров. \en Set of integer numbers. -typedef NumbersSet::iterator NumbersSetIt; -typedef NumbersSet::const_iterator NumbersSetConstIt; -typedef std::pair NumbersSetRet; +typedef std::set NumbersSet; ///< \ru Набор целочисленных номеров. \en Set of integer numbers. +typedef NumbersSet::iterator NumbersSetIt; +typedef NumbersSet::const_iterator NumbersSetConstIt; +typedef std::pair NumbersSetRet; -typedef std::set UintSet; ///< \ru Набор 32-битных целочисленных неотрицательных индексов. \en Set of 32-bit non-negative integer indices. -typedef UintSet::iterator UintSetIt; -typedef UintSet::const_iterator UintSetConstIt; -typedef std::pair UintSetRet; +typedef std::set UintSet; ///< \ru Набор 32-битных целочисленных неотрицательных индексов. \en Set of 32-bit non-negative integer indices. +typedef UintSet::iterator UintSetIt; +typedef UintSet::const_iterator UintSetConstIt; +typedef std::pair UintSetRet; -typedef std::pair IndicesPairsPair; ///< \ru Пара индексных пар. \en Pair of indices' pair. +typedef std::set UintPairsSet; ///< \ru Набор пар 32-битных целочисленных неотрицательных индексов. \en Set of pairs of 32-bit non-negative integer indices. +typedef UintPairsSet::iterator UintPairsSetIt; +typedef UintPairsSet::const_iterator UintPairsSetConstIt; +typedef std::pair UintPairsSetRet; + +typedef std::set IndicesPairsSet; ///< \ru Набор пар целочисленных неотрицательных индексов. \en Set of pairs of non-negative integer indices. +typedef IndicesPairsSet::iterator IndicesPairsSetIt; +typedef IndicesPairsSet::const_iterator IndicesPairsSetConstIt; +typedef std::pair IndicesPairsSetRet; + +typedef std::pair IndicesPairsPair; ///< \ru Пара индексных пар. \en Pair of indices' pair. //------------------------------------------------------------------------------ @@ -89,7 +99,7 @@ typedef std::pair IndicesPairsPair; ///< \ru Пара // --- template bool IsNullPointer( const ItemPtr * itemPtr ) { - return ((C3D_NULL_PTR == itemPtr) ? true : false); + return ((c3d_null == itemPtr) ? true : false); } //------------------------------------------------------------------------------ @@ -258,7 +268,7 @@ private: \ // // \ru примеры: \en examples: // \ru #pragma message( __TODO__ "Восстановить закрытый код" ) \en #pragma message( __TODO__ "Restore the private code" ) -// \ru #pragma message( __WARN__ "Отсутствует проверка на NULL" ) \en #pragma message( __WARN__ "There is no check for NULL" ) +// \ru #pragma message( __WARN__ "Отсутствует проверка на c3d_null" ) \en #pragma message( __WARN__ "There is no check for c3d_null" ) //--- #ifdef _MSC_VER // __TODO__ / __WARN__ @@ -319,12 +329,6 @@ private: \ #define CONV_FUNC MATH_FUNC #define CONV_FUNC_EX MATH_FUNC_EX -// \ru Поддержка кода. \en Support of the code. -#ifndef NULL -#define NULL 0 -#endif - - namespace c3d // namespace C3D { diff --git a/C3d/Include/math_version.h b/C3d/Include/math_version.h index b2d3c52..4ddc40d 100644 --- a/C3d/Include/math_version.h +++ b/C3d/Include/math_version.h @@ -83,8 +83,9 @@ #define MATH_19_START_VERSION 0x13000000L ///< \ru Версия файла - 19.0 (начало версии). \en The file version - 19.0 (start of version). \~ \ingroup Base_Tools #define MATH_18_SP1_VERSION 0x13000005L ///< \ru Версия файла - 18.1. \en The file version - 18.1. \~ \ingroup Base_Tools #define C3D_2019_VERSION 0x1300000FL ///< \ru Версия файла - C3D 2019. \en The file version - C3D 2019. \~ \ingroup Base_Tools -#define MATH_19_VERSION 0x13000101L ///< \ru Версия файла - 19.0. \en The file version - 19.0. \~ \ingroup Base_Tools +#define MATH_19_VERSION 0x13000101L ///< \ru Версия файла - 19.0. \en The file version - 19.0. \~ \ingroup Base_Tools #define C3D_2020_VERSION 0x13001004L ///< \ru Версия файла - C3D 2020. \en The file version - C3D 2020. \~ \ingroup Base_Tools +#define MATH_20_VERSION 0x14000012L ///< \ru Версия файла - 20.0. \en The file version - 20.0. \~ \ingroup Base_Tools //------------------------------------------------------------------------------ @@ -112,7 +113,7 @@ MATH_FUNC (VERSION) GetCurrentMathFileVersion(); //------------------------------------------------------------------------------ /// \ru Можно ли потенциально сохранить в заданную версию? \en Can it be saved to this math version? \~ \ingroup Base_Tools // --- -MATH_FUNC( bool ) CanWriteToMathFileVersion( VERSION dstVertsion, bool * canUseWriterEx = NULL ); +MATH_FUNC( bool ) CanWriteToMathFileVersion( VERSION dstVertsion, bool * canUseWriterEx = c3d_null ); //------------------------------------------------------------------------------ @@ -131,9 +132,11 @@ enum MbeWritableReleaseVersion wrv_MATH_18_SP1 = MATH_18_SP1_VERSION, ///< \ru Версия файла - 18.1. \en The file version - 18.1. wrv_C3D_2019 = C3D_2019_VERSION, ///< \ru Версия файла - C3D 2019. \en The file version - C3D 2019. wrv_MATH_19 = MATH_19_VERSION, ///< \ru Версия файла - 19.0. \en The file version - 19.0. + wrv_C3D_2020 = C3D_2020_VERSION, ///< \ru Версия файла - C3D 2020. \en The file version - C3D 2020. + wrv_MATH_20 = MATH_20_VERSION, ///< \ru Версия файла - 20.0 TR2. \en The file version - 20.0 TR2. - wrv_PrevRelease = wrv_MATH_18_SP1, ///< \ru Версия потока предпоследнего релиза. \en The previous release version. - wrv_LastRelease = wrv_C3D_2019, ///< \ru Версия потока последнего релиза. \en The last release version. + wrv_PrevRelease = wrv_MATH_19, ///< \ru Версия потока предпоследнего релиза. \en The previous release version. + wrv_LastRelease = wrv_C3D_2020, ///< \ru Версия потока последнего релиза. \en The last release version. wrv_MaxPossible = SYS_MAX_UINT32 ///< \ru Использовать последнюю версия потока. \en Use current working version. }; diff --git a/C3d/Include/mb_class_traits.h b/C3d/Include/mb_class_traits.h index f2572c6..9ef6082 100644 --- a/C3d/Include/mb_class_traits.h +++ b/C3d/Include/mb_class_traits.h @@ -57,7 +57,7 @@ struct _IsInstant template inline bool operator()( const ParentType * obj, const ClassEnum _typeId ) { - return obj == NULL ? true : obj->IsA() == _typeId; + return obj == c3d_null ? true : obj->IsA() == _typeId; } }; @@ -69,7 +69,7 @@ struct _IsFamily template inline bool operator()( const ParentType * obj, const ClassEnum _typeId ) { - return obj == NULL ? true : obj->Family() == _typeId; + return obj == c3d_null ? true : obj->Family() == _typeId; } }; @@ -154,7 +154,7 @@ inline DerivedPtr _IsaCast( ParentType * obj ) { return static_cast( obj ); } - return static_cast( NULL ); + return static_cast( c3d_null ); } //---------------------------------------------------------------------------------------- @@ -202,7 +202,7 @@ DerivedPtr isa_cast( ParentType * obj ) template< class DerivedPtr > DerivedPtr isa_cast( const MbRefItem * obj ) { - DerivedPtr resPtr = NULL; + DerivedPtr resPtr = c3d_null; return _IsaCast( obj, resPtr ); } @@ -214,7 +214,7 @@ DerivedPtr isa_cast( const MbRefItem * obj ) template< class DerivedPtr > DerivedPtr isa_cast( MbRefItem * obj ) { - DerivedPtr resPtr = NULL; + DerivedPtr resPtr = c3d_null; return _IsaCast( obj, resPtr ); } diff --git a/C3d/Include/mb_cross_point.h b/C3d/Include/mb_cross_point.h index bedf5de..4076aba 100644 --- a/C3d/Include/mb_cross_point.h +++ b/C3d/Include/mb_cross_point.h @@ -55,7 +55,7 @@ public: template MbPointOnCurve::MbPointOnCurve() : t ( 0.0 ) - , curve( NULL ) + , curve( c3d_null ) {} diff --git a/C3d/Include/mb_cube_tree.h b/C3d/Include/mb_cube_tree.h index 7851312..d1e341b 100644 --- a/C3d/Include/mb_cube_tree.h +++ b/C3d/Include/mb_cube_tree.h @@ -242,9 +242,9 @@ inline MbCubeTree::MbCubeTree( const std::vector & , direction ( eda_anyDirection ) , dmType ( dm ) , leafObjects( ) - , midstBranch( NULL ) - , lowerBranch( NULL ) - , upperBranch( NULL ) + , midstBranch( c3d_null ) + , lowerBranch( c3d_null ) + , upperBranch( c3d_null ) { size_t cnt = objects.size(); C3D_ASSERT( Cube::GetDimension() == Point::GetDimension() ); @@ -252,7 +252,7 @@ inline MbCubeTree::MbCubeTree( const std::vector & if ( cnt > 0 ) { // Инициализация дерева Cube gabarit; for ( size_t i = 0; i < cnt; ++i ) { - if ( objects[i].first != NULL ) + if ( objects[i].first != c3d_null ) gabarit |= objects[i].first->GetCube(); } InitTree( objects, gabarit, eda_anyDirection, 0, 0 ); @@ -273,9 +273,9 @@ inline MbCubeTree::MbCubeTree( const std::vector & , direction ( eda_anyDirection ) , dmType ( dm ) , leafObjects( ) - , midstBranch( NULL ) - , lowerBranch( NULL ) - , upperBranch( NULL ) + , midstBranch( c3d_null ) + , lowerBranch( c3d_null ) + , upperBranch( c3d_null ) { C3D_ASSERT( Cube::GetDimension() == Point::GetDimension() ); InitTree( objects, gabarit, eda_anyDirection, 0, 0 ); @@ -295,9 +295,9 @@ inline MbCubeTree::MbCubeTree( DistanceMeasure dm ) , direction ( eda_anyDirection ) , dmType ( dm ) , leafObjects( ) - , midstBranch( NULL ) - , lowerBranch( NULL ) - , upperBranch( NULL ) + , midstBranch( c3d_null ) + , lowerBranch( c3d_null ) + , upperBranch( c3d_null ) { } @@ -311,7 +311,7 @@ inline void MbCubeTree::Clear() delete midstBranch; delete lowerBranch; delete upperBranch; - midstBranch = lowerBranch = upperBranch = NULL; + midstBranch = lowerBranch = upperBranch = c3d_null; midst = minimum = maximum = lower = upper = 0.0; direction = eda_anyDirection; leafObjects.clear(); @@ -566,7 +566,7 @@ inline void MbCubeTree::SetBranches( const std::vectorGetCube(); double pMin = UNDEFINED_DBL; double pMax = UNDEFINED_DBL; @@ -606,22 +606,22 @@ inline void MbCubeTree::SetBranches( const std::vector 0) || (upperCount > 0) ) { if ( lowerCount > 0 ) { // нижняя ветвь / lower branch - C3D_ASSERT ( lowerBranch == NULL ); - if ( lowerBranch == NULL ) + C3D_ASSERT ( lowerBranch == c3d_null ); + if ( lowerBranch == c3d_null ) lowerBranch = new MbCubeTree( dmType ); lowerBranch->InitTree( lowerArray, lowerGabarit, eda_anyDirection, tier+1, 0 ); lowerArray.clear(); } if ( upperCount > 0 ) { // верхняя ветвь / upper branch - C3D_ASSERT( upperBranch == NULL ); - if ( upperBranch == NULL ) + C3D_ASSERT( upperBranch == c3d_null ); + if ( upperBranch == c3d_null ) upperBranch = new MbCubeTree( dmType ); upperBranch->InitTree( upperArray, upperGabarit, eda_anyDirection, tier+1, 0 ); upperArray.clear(); } if ( midstCount > 0 ) { // центральная ветвь / central branch - C3D_ASSERT( midstBranch == NULL ); - if ( midstBranch == NULL ) + C3D_ASSERT( midstBranch == c3d_null ); + if ( midstBranch == c3d_null ) midstBranch = new MbCubeTree( dmType ); midstBranch->InitTree( midstArray, midstGabarit, direction, tier+1, 0 ); midstArray.clear(); @@ -650,7 +650,7 @@ inline void MbCubeTree::SetBranches( const std::vector::FillLeaf( const std::vector::FillLeaf( const std::vector inline bool MbCubeTree::IsReady() const { - return ( (midstBranch != NULL) || - (lowerBranch != NULL) || - (upperBranch != NULL) || + return ( (midstBranch != c3d_null) || + (lowerBranch != c3d_null) || + (upperBranch != c3d_null) || (leafObjects.size() > 0) ); } @@ -733,11 +733,11 @@ template inline size_t MbCubeTree::Count() const { size_t cnt = leafObjects.size(); - if ( midstBranch != NULL ) + if ( midstBranch != c3d_null ) cnt += midstBranch->Count(); - if ( lowerBranch != NULL ) + if ( lowerBranch != c3d_null ) cnt += lowerBranch->Count(); - if ( upperBranch != NULL ) + if ( upperBranch != c3d_null ) cnt += upperBranch->Count(); return cnt; } @@ -750,7 +750,7 @@ template inline void MbCubeTree::GetContainsObjects( const Point & pnt, double epsilon, std::vector & items ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -765,13 +765,13 @@ inline void MbCubeTree::GetContainsObjects( const Point & pnt if ( (w < (minimum - epsilon)) || ((maximum + epsilon) < w) ) return; // вне области / out of region - if ( (w < (midst + epsilon)) && (lowerBranch != NULL) ) { + if ( (w < (midst + epsilon)) && (lowerBranch != c3d_null) ) { lowerBranch->GetContainsObjects( pnt, epsilon, items ); } - if ( ((midst - epsilon) < w) && (upperBranch != NULL) ) { + if ( ((midst - epsilon) < w) && (upperBranch != c3d_null) ) { upperBranch->GetContainsObjects( pnt, epsilon, items ); } - if ( ((lower - epsilon) < w) && (w < (upper + epsilon)) && (midstBranch != NULL) ) { + if ( ((lower - epsilon) < w) && (w < (upper + epsilon)) && (midstBranch != c3d_null) ) { midstBranch->GetContainsObjects( pnt, epsilon, items ); } } @@ -780,7 +780,7 @@ inline void MbCubeTree::GetContainsObjects( const Point & pnt items.reserve( items.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { if ( obj.first->GetCube().Contains( pnt, epsilon ) ) items.push_back( obj.first ); } @@ -796,7 +796,7 @@ template inline void MbCubeTree::GetContainsObjects( const Point & pnt, double epsilon, c3d::IndicesVector & indices ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -811,13 +811,13 @@ inline void MbCubeTree::GetContainsObjects( const Point & pnt if ( (w < (minimum - epsilon)) || ((maximum + epsilon) < w) ) return; // вне области / out of region - if ( (w < (midst + epsilon)) && (lowerBranch != NULL) ) { + if ( (w < (midst + epsilon)) && (lowerBranch != c3d_null) ) { lowerBranch->GetContainsObjects( pnt, epsilon, indices ); } - if ( ((midst - epsilon) < w) && (upperBranch != NULL) ) { + if ( ((midst - epsilon) < w) && (upperBranch != c3d_null) ) { upperBranch->GetContainsObjects( pnt, epsilon, indices ); } - if ( ((lower - epsilon) < w) && (w < (upper + epsilon)) && (midstBranch != NULL) ) { + if ( ((lower - epsilon) < w) && (w < (upper + epsilon)) && (midstBranch != c3d_null) ) { midstBranch->GetContainsObjects( pnt, epsilon, indices ); } } @@ -826,7 +826,7 @@ inline void MbCubeTree::GetContainsObjects( const Point & pnt indices.reserve( indices.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { if ( obj.first->GetCube().Contains( pnt, epsilon ) ) indices.push_back( obj.second ); } @@ -843,7 +843,7 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab std::vector & items, bool skipOwnself ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double wMin = MB_MAXDOUBLE; double wMax = -MB_MAXDOUBLE; @@ -856,13 +856,13 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab if ( (wMax < minimum) || (maximum < wMin) ) return; // вне области / out of region - if ( (wMin < midst) && (lowerBranch != NULL) ) { + if ( (wMin < midst) && (lowerBranch != c3d_null) ) { lowerBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } - if ( (midst < wMax) && (upperBranch != NULL) ) { + if ( (midst < wMax) && (upperBranch != c3d_null) ) { upperBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } - if ( (lower < wMax) && (wMin < upper) && (midstBranch != NULL) ) { + if ( (lower < wMax) && (wMin < upper) && (midstBranch != c3d_null) ) { midstBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } } @@ -871,7 +871,7 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab items.reserve( items.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { if ( !skipOwnself || (&gabarit != &static_cast(obj.first->GetCube()) ) ) { // KOMPAS-20871 if ( obj.first->GetCube().Intersect( gabarit, epsilon ) ) items.push_back( obj.first ); @@ -890,7 +890,7 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab c3d::IndicesVector & items, bool skipOwnself ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double wMin = MB_MAXDOUBLE; double wMax = -MB_MAXDOUBLE; @@ -906,13 +906,13 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab if ( (wMax < minimum) || (maximum < wMin) ) return; // вне области / out of region - if ( (wMin < midst) && (lowerBranch != NULL) ) { + if ( (wMin < midst) && (lowerBranch != c3d_null) ) { lowerBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } - if ( (midst < wMax) && (upperBranch != NULL) ) { + if ( (midst < wMax) && (upperBranch != c3d_null) ) { upperBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } - if ( (lower < wMax) && (wMin < upper) && (midstBranch != NULL) ) { + if ( (lower < wMax) && (wMin < upper) && (midstBranch != c3d_null) ) { midstBranch->GetIntersectObjects( gabarit, epsilon, items, skipOwnself ); } } @@ -921,7 +921,7 @@ inline void MbCubeTree::GetIntersectObjects( const Cube & gab items.reserve( items.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { if ( !skipOwnself || (&gabarit != &static_cast(obj.first->GetCube()) ) ) { // KOMPAS-20871 if ( obj.first->GetCube().Intersect( gabarit, epsilon ) ) items.push_back( obj.second ); @@ -961,7 +961,7 @@ inline double MbCubeTree::GetDistance( const Type & object, c template inline void MbCubeTree::FindNearestObject( const Cube & gabarit, double & distance, const Type *& item, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double wMin = MB_MAXDOUBLE; double wMax = -MB_MAXDOUBLE; @@ -977,20 +977,20 @@ inline void MbCubeTree::FindNearestObject( const Cube & gabar if ( (wMax < (minimum-distance)) || ((maximum+distance) < wMin) ) return; // вне области / out of region - if ( (wMin < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (wMin < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->FindNearestObject( gabarit, distance, item, eps ); } - if ( ((midst-distance) < wMax) && (upperBranch != NULL) ) { + if ( ((midst-distance) < wMax) && (upperBranch != c3d_null) ) { upperBranch->FindNearestObject( gabarit, distance, item, eps ); } - if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->FindNearestObject( gabarit, distance, item, eps ); } } else { // содержимое конечной ветви / final branch content for ( size_t i = 0, iCount = leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = obj.first->GetCube().DistanceToCube( gabarit, eps ); if ( distance > d - eps ) { item = obj.first; @@ -1008,7 +1008,7 @@ inline void MbCubeTree::FindNearestObject( const Cube & gabar template inline void MbCubeTree::FindNearestObject( const Cube & gabarit, double & distance, size_t & index, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double wMin = MB_MAXDOUBLE; double wMax = -MB_MAXDOUBLE; @@ -1024,20 +1024,20 @@ inline void MbCubeTree::FindNearestObject( const Cube & gabar if ( (wMax < (minimum-distance)) || ((maximum+distance) < wMin) ) return; // вне области / out of region - if ( (wMin < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (wMin < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->FindNearestObject( gabarit, distance, index, eps ); } - if ( ((midst-distance) < wMax) && (upperBranch != NULL) ) { + if ( ((midst-distance) < wMax) && (upperBranch != c3d_null) ) { upperBranch->FindNearestObject( gabarit, distance, index, eps ); } - if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->FindNearestObject( gabarit, distance, index, eps ); } } else { // содержимое конечной ветви / final branch content for ( size_t i = 0, iCount = leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = obj.first->GetCube().DistanceToCube( gabarit, eps ); if ( distance > d - eps ) { index = obj.second; @@ -1057,7 +1057,7 @@ inline void MbCubeTree::GetNearestObjects( const Cube & gabar std::vector & itemDistances, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double wMin = MB_MAXDOUBLE; double wMax = -MB_MAXDOUBLE; @@ -1073,20 +1073,20 @@ inline void MbCubeTree::GetNearestObjects( const Cube & gabar if ( (wMax < (minimum-distance)) || ((maximum+distance) < wMin) ) return; // вне области / out of region - if ( (wMin < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (wMin < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->GetNearestObjects( gabarit, distance, itemDistances, eps ); } - if ( ((midst-distance) < wMax) && (upperBranch != NULL) ) { + if ( ((midst-distance) < wMax) && (upperBranch != c3d_null) ) { upperBranch->GetNearestObjects( gabarit, distance, itemDistances, eps ); } - if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < wMax) && (wMin < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->GetNearestObjects( gabarit, distance, itemDistances, eps ); } } else { // содержимое конечной ветви / final branch content for ( size_t i = 0, iCount = leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = obj.first->GetCube().DistanceToCube( gabarit, eps ); if ( distance > d - eps ) { IndexDistance itemDistance( obj.second, d ); @@ -1104,7 +1104,7 @@ inline void MbCubeTree::GetNearestObjects( const Cube & gabar template inline void MbCubeTree::FindNearestObject( const Point & pnt, double & distance, const Type *& item, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -1119,20 +1119,20 @@ inline void MbCubeTree::FindNearestObject( const Point & pnt, if ( (w < (minimum-distance)) || ((maximum+distance) < w) ) return; // вне области / out of region - if ( (w < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (w < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->FindNearestObject( pnt, distance, item ); } - if ( ((midst-distance) < w) && (upperBranch != NULL) ) { + if ( ((midst-distance) < w) && (upperBranch != c3d_null) ) { upperBranch->FindNearestObject( pnt, distance, item ); } - if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->FindNearestObject( pnt, distance, item ); } } else { // содержимое конечной ветви / final branch content for ( size_t i = 0, iCount = leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = GetDistance( *obj.first, pnt, false ); if ( distance > d - eps ) { item = obj.first; @@ -1150,7 +1150,7 @@ inline void MbCubeTree::FindNearestObject( const Point & pnt, template inline void MbCubeTree::FindNearestObject( const Point & pnt, double & distance, size_t & index, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -1165,20 +1165,20 @@ inline void MbCubeTree::FindNearestObject( const Point & pnt, if ( (w < (minimum-distance)) || ((maximum+distance) < w) ) return; // вне области / out of region - if ( (w < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (w < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->FindNearestObject( pnt, distance, index ); } - if ( ((midst-distance) < w) && (upperBranch != NULL) ) { + if ( ((midst-distance) < w) && (upperBranch != c3d_null) ) { upperBranch->FindNearestObject( pnt, distance, index ); } - if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->FindNearestObject( pnt, distance, index ); } } else { // содержимое конечной ветви / final branch content for ( size_t i = 0, iCount = leafObjects.size(); i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = GetDistance( *obj.first, pnt, false ); if ( distance > d - eps ) { index = obj.second; @@ -1198,7 +1198,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, std::vector & itemDistances, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -1213,13 +1213,13 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, if ( (w < (minimum-distance)) || ((maximum+distance) < w) ) return; // вне области / out of region - if ( (w < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (w < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((midst-distance) < w) && (upperBranch != NULL) ) { + if ( ((midst-distance) < w) && (upperBranch != c3d_null) ) { upperBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->GetNearestObjects( pnt, distance, itemDistances ); } } @@ -1228,7 +1228,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, itemDistances.reserve( itemDistances.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = GetDistance( *obj.first, pnt, true ); if ( distance > d - eps ) { ItemDistance itemDistance( obj.first, d ); @@ -1248,7 +1248,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, std::vector & itemDistances, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -1263,13 +1263,13 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, if ( (w < (minimum-distance)) || ((maximum+distance) < w) ) return; // вне области / out of region - if ( (w < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (w < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((midst-distance) < w) && (upperBranch != NULL) ) { + if ( ((midst-distance) < w) && (upperBranch != c3d_null) ) { upperBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->GetNearestObjects( pnt, distance, itemDistances ); } } @@ -1278,7 +1278,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, itemDistances.reserve( itemDistances.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = GetDistance( *obj.first, pnt, true ); if ( distance > d - eps ) { IndexDistance itemDistance( obj.second, d ); @@ -1298,7 +1298,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, c3d::IndicesVector & itemDistances, double eps ) const { - if ( (lowerBranch != NULL) || (upperBranch != NULL) || (midstBranch != NULL) ) { + if ( (lowerBranch != c3d_null) || (upperBranch != c3d_null) || (midstBranch != c3d_null) ) { double w = -MB_MAXDOUBLE; switch ( direction ) { @@ -1313,13 +1313,13 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, if ( (w < (minimum-distance)) || ((maximum+distance) < w) ) return; // вне области / out of region - if ( (w < (midst+distance)) && (lowerBranch != NULL) ) { + if ( (w < (midst+distance)) && (lowerBranch != c3d_null) ) { lowerBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((midst-distance) < w) && (upperBranch != NULL) ) { + if ( ((midst-distance) < w) && (upperBranch != c3d_null) ) { upperBranch->GetNearestObjects( pnt, distance, itemDistances ); } - if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != NULL) ) { + if ( ((lower-distance) < w) && (w < (upper+distance)) && (midstBranch != c3d_null) ) { midstBranch->GetNearestObjects( pnt, distance, itemDistances ); } } @@ -1328,7 +1328,7 @@ inline void MbCubeTree::GetNearestObjects( const Point & pnt, itemDistances.reserve( itemDistances.size() + iCount ); for ( size_t i = 0; i < iCount; ++i ) { const ItemIndex & obj = leafObjects[i]; - if ( obj.first != NULL ) { + if ( obj.first != c3d_null ) { double d = GetDistance( *obj.first, pnt, true ); if ( distance > d - eps ) { itemDistances.push_back( obj.second ); diff --git a/C3d/Include/mb_data.h b/C3d/Include/mb_data.h index 6627a43..98b6b2a 100644 --- a/C3d/Include/mb_data.h +++ b/C3d/Include/mb_data.h @@ -545,12 +545,12 @@ public: 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). double realAccuracyVCurve; ///< \ru Точность построения V-кривой (заданная и фактическая). \en The accuracy of creating the V-curve (given and actual). - /// \ru Параметры аппроксимации V-кривой. \en Params of Approximation of V-curve. - bool switchEndTangents; ///< \ru Флаги учета значений концевых касательных. \en Flags accounting tangents values. - bool switchEndCurvature; ///< \ru Флаги учета значений кривизны. \en Flags accounting curvature values. - MbVector3D firstTangent; ///< \ru Касательная в начальной точке. \en Tangent in the first point. - MbVector3D lastTangent; ///< \ru Касательная в конечной точке. \en Tangent in the last point. - double firstCurvature; ///< \ru Значение кривизны в начальной точке. \en Curvature in the first point. + /// \ru Параметры аппроксимации V-кривой. \en Params of Approximation of V-curve. + bool switchEndTangents; ///< \ru Флаги учета значений концевых касательных. \en Flags accounting tangents values. + bool switchEndCurvature; ///< \ru Флаги учета значений кривизны. \en Flags accounting curvature values. + MbVector3D firstTangent; ///< \ru Касательная в начальной точке. \en Tangent in the first point. + MbVector3D lastTangent; ///< \ru Касательная в конечной точке. \en Tangent in the last point. + double firstCurvature; ///< \ru Значение кривизны в начальной точке. \en Curvature in the first point. double lastCurvature; ///< \ru Значение кривизны в конечной точке. \en Curvature in the last point. @@ -561,17 +561,19 @@ public: public: /// \ru Пустой конструктор. \en Empty constructor. MbFairCurveData() : - closed( false ), fairing( false ), arrange( false ), subdivision( fairSubdiv_Single ), + //closed( false ), fairing( false ), arrange( false ), subdivision( fairSubdiv_Single ), + closed( false ), fairing( true ), arrange( false ), subdivision( fairSubdiv_Single ), //DEBUG 2020 25 accountCurvature( fairCur_No ), accountInflexVector( fairVector_SegmentDir ), fixPntTng( fixPntTng_NotFix ), - approx( fairApprox_KnotsSpline ), create( 1 ), degreeBSpline( 8 ), + //approx( fairApprox_KnotsSpline ), create( 1 ), degreeBSpline( 8 ), + approx( fairApprox_IsoNurbs ), create( 1 ), degreeBSpline( 8 ), //DEBUG 2020 25 initFormat( fairFormat_Open ), outFormat( fairFormat_Close ), nSegments( 4 ), numSegment( 0 ), tParam( 0.5 ), warning( fwarn_Success ), error( rt_Success ), clothoidRMin( 50.0 ), clothoidLMax( 200.0 ), clothoidSegms( 10 ), numberOfIterationsBSpl( 500 ), numberOfIterationsVCurve( 192 ), #ifdef C3D_DEBUG_FAIR_CURVES - prt( C3D_NULL_PTR ), + prt( c3d_null ), #endif realAccuracyBSpl( METRIC_ACCURACY ), realAccuracyVCurve( METRIC_EPSILON ), switchEndTangents( false ), switchEndCurvature( false ), @@ -600,19 +602,56 @@ public: clothoidRMin = other.clothoidRMin; clothoidLMax = other.clothoidLMax; clothoidSegms = other.clothoidSegms; - numberOfIterationsBSpl = other.numberOfIterationsBSpl; - numberOfIterationsVCurve = other.numberOfIterationsVCurve; - realAccuracyBSpl = other.realAccuracyBSpl; - realAccuracyVCurve = other.realAccuracyVCurve; - switchEndTangents = other.switchEndTangents; - switchEndCurvature = other.switchEndCurvature; - firstTangent = other.firstTangent; - lastTangent = other.lastTangent; - firstCurvature = other.firstCurvature; + numberOfIterationsBSpl = other.numberOfIterationsBSpl; + numberOfIterationsVCurve = other.numberOfIterationsVCurve; + realAccuracyBSpl = other.realAccuracyBSpl; + realAccuracyVCurve = other.realAccuracyVCurve; + switchEndTangents = other.switchEndTangents; + switchEndCurvature = other.switchEndCurvature; + firstTangent = other.firstTangent; + lastTangent = other.lastTangent; + firstCurvature = other.firstCurvature; lastCurvature = other.lastCurvature; return *this; } }; // MbFairCurveData +//------------------------------------------------------------------------------ +/** \brief \ru Параметры для проверки, является ли кривая плоской. + \en Parameters for checking if the curve is planar. \~ + \details \ru Параметры для проверки, является ли кривая плоской. + \en Parameters for checking if the curve is planar. \~ +*/ +// --- +struct PlanarCheckParams { + double accuracy; + VERSION version; + + /// \ru Конструктор по умолчанию. \en Default constructor. + PlanarCheckParams() + : accuracy( METRIC_EPSILON ) + , version( Math::DefaultMathVersion() ) + {} + + /// \ru Конструктор. \en Constructor. + explicit PlanarCheckParams( double accuracy_ ) + : accuracy( accuracy_ ) + , version( Math::DefaultMathVersion() ) + {} + + /// \ru Конструктор. \en Constructor. + PlanarCheckParams( double accuracy_, VERSION version_ ) + : accuracy( accuracy_ ) + , version( version_ ) + {} + + /// \ru Конструктор копирования. \en Copy-constructor. + PlanarCheckParams( const PlanarCheckParams & other ) + : accuracy( other.accuracy ) + , version( other.version ) + {} +}; + + #endif // __MB_DATA_H diff --git a/C3d/Include/mb_dimension.h b/C3d/Include/mb_dimension.h index f48fa9c..70a5bd6 100644 --- a/C3d/Include/mb_dimension.h +++ b/C3d/Include/mb_dimension.h @@ -83,12 +83,12 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA() const; - virtual MbSpaceItem & Duplicate(MbRegDuplicate * = NULL) const; + virtual MbSpaceItem & Duplicate(MbRegDuplicate * = c3d_null) const; virtual bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const; virtual bool SetEqual(const MbSpaceItem &); - virtual void Transform(const MbMatrix3D &, MbRegTransform * = NULL); - virtual void Move(const MbVector3D &, MbRegTransform * = NULL); - virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = NULL); + virtual void Transform(const MbMatrix3D &, MbRegTransform * = c3d_null); + virtual void Move(const MbVector3D &, MbRegTransform * = c3d_null); + virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = c3d_null); virtual double DistanceToPoint(const MbCartPoint3D &) const; virtual void AddYourGabaritTo(MbCube &) const; virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. @@ -155,12 +155,12 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA() const; - virtual MbSpaceItem & Duplicate(MbRegDuplicate * = NULL) const; + virtual MbSpaceItem & Duplicate(MbRegDuplicate * = c3d_null) const; virtual bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const; virtual bool SetEqual(const MbSpaceItem &); - virtual void Transform(const MbMatrix3D &, MbRegTransform * = NULL); - virtual void Move(const MbVector3D &, MbRegTransform * = NULL); - virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = NULL); + virtual void Transform(const MbMatrix3D &, MbRegTransform * = c3d_null); + virtual void Move(const MbVector3D &, MbRegTransform * = c3d_null); + virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = c3d_null); virtual double DistanceToPoint(const MbCartPoint3D &) const; virtual void AddYourGabaritTo(MbCube &) const; virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. @@ -231,12 +231,12 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA() const; - virtual MbSpaceItem & Duplicate(MbRegDuplicate * = NULL) const; + virtual MbSpaceItem & Duplicate(MbRegDuplicate * = c3d_null) const; virtual bool IsSame(const MbSpaceItem & /*other*/, double /*accuracy*/ = LENGTH_EPSILON) const; virtual bool SetEqual(const MbSpaceItem &); - virtual void Transform(const MbMatrix3D &, MbRegTransform * = NULL); - virtual void Move(const MbVector3D &, MbRegTransform * = NULL); - virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = NULL); + virtual void Transform(const MbMatrix3D &, MbRegTransform * = c3d_null); + virtual void Move(const MbVector3D &, MbRegTransform * = c3d_null); + virtual void Rotate(const MbAxis3D &, double, MbRegTransform * = c3d_null); virtual double DistanceToPoint(const MbCartPoint3D &) const; virtual void AddYourGabaritTo(MbCube &) const; virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. diff --git a/C3d/Include/mb_homogeneous.h b/C3d/Include/mb_homogeneous.h index a07fbc1..88a184d 100644 --- a/C3d/Include/mb_homogeneous.h +++ b/C3d/Include/mb_homogeneous.h @@ -513,12 +513,12 @@ namespace c3d // namespace C3D */ // --- template< typename ParamContainer, typename PointContainer > -void SplitHomoVector( const SArray & hList, PointContainer & uvList, ParamContainer * tList = NULL ) +void SplitHomoVector( const SArray & hList, PointContainer & uvList, ParamContainer * tList = c3d_null ) { const size_t sz = hList.size(); uvList.clear(); uvList.reserve( sz ); - if ( tList != NULL ) { + if ( tList != c3d_null ) { tList->clear(); tList->reserve( sz ); for ( size_t n = 0; n < sz; n++ ) { diff --git a/C3d/Include/mb_matrix3d.h b/C3d/Include/mb_matrix3d.h index 56e4819..21eb18c 100644 --- a/C3d/Include/mb_matrix3d.h +++ b/C3d/Include/mb_matrix3d.h @@ -845,7 +845,7 @@ inline bool MbMatrix3D::IsSame( const MbMatrix3D & m2, double accuracy ) const /** \brief \ru Извлечь углы Эйлера из ротационной подматрицы R = Rx*Ry*Rz. \en Extract the Euler angles from the rotational submatrix R = Rx*Ry*Rz. \param[in] trans - \ru Матрица преобразования, содержащая подматрицу вращения. - \en The transformaton matrix containig the rotational submatrix. \~ + \en The transformation matrix containing the rotational sub-matrix. \~ \param[out] alpha - \ru Угол поворота вокруг оси "X", извлеченный из матрицы вращения. \en Angle of rotation around the "X" axis extracted from the rotation matrix. \~ \param[out] betta - \ru Угол поворота вокруг оси "Y", извлеченный из матрицы вращения. @@ -855,22 +855,22 @@ inline bool MbMatrix3D::IsSame( const MbMatrix3D & m2, double accuracy ) const \details \ru Функция разлагает подматрицу вращения на элементарные повороты вокруг осей R = Rx*Ry*Rz, заданные в виде угловых значений, а именно значения в радианах, определяющую присланную матрицу вращения R - в виде комбинации (произведения) из трех элементарных поворотов: R = Rx*Ry*Rz<\b>, где\n + в виде комбинации (произведения) из трех элементарных поворотов: R = Rx*Ry*Rz, где\n Rx = Rx(alpha) - поворот вокруг оси "X", \n Ry = Ry(betta) - поворот вокруг оси "Y", \n Rz = Rz(gamma) - поворот вокруг оси "Z" и \n - R - ротационная подматрица 3x3 из матрицы trans<\b>. - Матрица trans может содержать любые преобразования, вклячая масштабирование и сдвиг. + R - ротационная подматрица 3x3 из матрицы trans. + Матрица trans может содержать любые преобразования, включая масштабирование и сдвиг. Метод ExtractEulerAngles извлечет из данной матрицы вращающий компонент и разложит его на три вращения: Rx(alpha), Ry(betta), Rz(gamma). \en The function factorizes the rotation submatrix into elementary rotations about the axes: R = Rx * Ry * Rz, - given in the form of angular values, namely the values in radians, specifing the rotation submatrix R of the given trans<\b> - in the form of a combination (product) of three elementary rotations: R = Rx * Ry * Rz <\b>, where \n + given in the form of angular values, namely the values in radians, specifying the rotation sub-matrix R of the given trans + in the form of a combination (product) of three elementary rotations: R = Rx * Ry * Rz , where \n Rx = Rx(alpha) - rotation around X-axis, \n Ry = Ry(betta) - rotation around Y-axis, \n Rz = Rz(gamma) - rotation around Z-axis and \n - R is a rotational 3x3 submatrix from the matrix trans<\b>. + R is a rotational 3x3 sub-matrix from the matrix trans. The matrix trans can contain any transformations including the scaling and the shear. The ExtractEulerAngles method extracts from the given matrix a rotating component and decomposes it into three rotations: Rx( alpha ), Ry( betta ), Rz( gamma ). diff --git a/C3d/Include/mb_matrixnn.h b/C3d/Include/mb_matrixnn.h index b88d6a3..5ff3916 100644 --- a/C3d/Include/mb_matrixnn.h +++ b/C3d/Include/mb_matrixnn.h @@ -29,12 +29,12 @@ private : protected: /// \ru Конструктор. \en Constructor. - MatrixNN() : parr( NULL ), n( 0 ) {} + MatrixNN() : parr( c3d_null ), n( 0 ) {} /// \ru Конструктор по заданной размерности. \en The constructor by a given dimension. - MatrixNN( size_t dim ) : parr( NULL ), n( 0 ) { SetSize( dim ); } + MatrixNN( size_t dim ) : parr( c3d_null ), n( 0 ) { SetSize( dim ); } public: /// \ru Конструктор ограниченной размерности. \en The constructor of restricted dimension. - MatrixNN ( const uint16 & dim ) : parr( NULL ), n( 0 ) { SetSize( dim ); } + MatrixNN ( const uint16 & dim ) : parr( c3d_null ), n( 0 ) { SetSize( dim ); } /// \ru Конструктор копирования. \en The copy constructor. explicit MatrixNN ( const MatrixNN & ); /// \ru Деструктор. \en Destructor. @@ -116,10 +116,10 @@ private: */ // --- template -MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, ProgressBarWrapper * baseProgBar = NULL ) +MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, ProgressBarWrapper * baseProgBar = c3d_null ) { - ProgressBarWrapper * progBar = NULL; - if ( baseProgBar != NULL ) { + ProgressBarWrapper * progBar = c3d_null; + if ( baseProgBar != c3d_null ) { StrData strData( pbarId_Solve_LinearEquationsSystem ); progBar = &baseProgBar->CreateChildAddRef( strData ); } @@ -235,6 +235,174 @@ MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, Pro } // GaussEquation +//------------------------------------------------------------------------------ +/** \brief \ru Решение системы линейных уравнений методом исключения Гаусса. + \en System of linear equations is solved by the Gauss method. \~ + \details \ru Решение системы линейных уравнений методом исключения Гаусса. \n + \en System of linear equations is solved by the Gauss method. \n \~ + \param[in] a - \ru Матрица коэффициентов при неизвестных + \en Coefficient matrix \~ + \param[in] b - \ru Массив правых частей, в него же помещается результат решения + \en Array of right parts, on output it contains the result of the solution \~ + \param[in] epsilon - \ru Погрешность решения + \en Tolerance of solution \~ + \param[in] baseProgBar - \ru Индикатор процесса решения + \en Progress indicator of solution \~ + \return \ru Код ошибки: если nr_Success (+1), то система решена, если nr_Special, то нет решений или система вырождена. + \en Error code: if nr_Success (+1), then the system is solved, if nr_Special, there is no solution or the system is degenerate. \~ + \ingroup Base_Items +*/ +// --- +template +MbeNewtonResult TypedGaussEquationWithBandMatrix( SparseMatrix & a, Type * b, double epsilon, ProgressBarWrapper * baseProgBar = c3d_null ) +{ + ProgressBarWrapper * progBar = c3d_null; + if ( baseProgBar != c3d_null ) { + StrData strData( pbarId_Solve_LinearEquationsSystem ); + progBar = &baseProgBar->CreateChildAddRef( strData ); + } + + ptrdiff_t count = (ptrdiff_t)std_min( a.Lines(), a.Columns() ); + C3D_ASSERT( a.Lines() == a.Columns() ); + + if ( count < 1 ) { + ::FinishProgressBar( progBar ); + ::ReleaseItem( progBar ); + return nr_Special; + } + + ptrdiff_t i, j, k; + + ptrdiff_t halfCount = count / 2; + + std::vector nzIndices; + c3d::IndicesPair searchRange; + + a.NzUpdate(); + + for ( k = 0; k < count - 1; k++ ) { + // \ru Переставить уравнения так, чтобы a[k][k] != 0 \en Swap equations so that a[k][k] != 0 + ptrdiff_t l = k; + double tmp = ::fabs( a.GetElem( k, k ) ); + for ( i = k + 1; i < count; i++ ) { + double faik = ::fabs( a.GetElem( i, k ) ); + if ( faik > tmp ) { + l = i; + tmp = faik; + } + } + + if ( k == halfCount ) + ::SetProgressBarValue( progBar, 25 ); + if ( ::StopProgressBar( progBar ) ) { // \ru Остановка по запросу \en Stop by request + ::ReleaseItem( progBar ); + return nr_Special; + } + + if ( l != k ) { + a.SwapLines( k, l ); + std::swap( b[k], b[l] ); + } + + if ( ::StopProgressBar( progBar ) ) { // \ru Остановка по запросу \en Stop by request + ::ReleaseItem( progBar ); + return nr_Special; + } + + tmp = a.GetElem(k, k); + + if ( ::fabs( tmp ) < epsilon ) { + ::FinishProgressBar( progBar ); + ::ReleaseItem( progBar ); + return nr_Special; // \ru Система не имеет решений \en System doesn't have solutions + } + + tmp = 1.0 / tmp; + + for ( i = k + 1; i < count; i++ ) { + double aik = a.GetElem( i, k ); + if ( ::fabs(aik) > NULL_EPSILON ) { + double m = aik * tmp; + a.SetElem( i, k, 0.0 ); + aik = 0.0; + + nzIndices.clear(); + if ( k + 1 < count ) { + // [k+1,count) + searchRange.first = (k + 1); + searchRange.second = (count - 1); + a.NzIndices( k, searchRange, nzIndices ); + } + size_t nzCnt = nzIndices.size(); + + for ( size_t nzInd = 0; nzInd < nzCnt; ++nzInd ) { + j = nzIndices[nzInd]; + double ae = a.GetElem( k, j ) * m; + if ( ::fabs(ae) > NULL_EPSILON ) { + ae = a.GetElem( i, j ) - ae; + a.SetElem( i, j, ae ); + } + } + b[i] -= b[k] * m; + } + } + + if ( ::StopProgressBar( progBar ) ) { // \ru Остановка по запросу \en Stop by request + ::ReleaseItem( progBar ); + return nr_Special; + } + } + + a.NzUpdate(); + + ::SetProgressBarValue( progBar, 50 ); + + if ( ::fabs( a.GetElem(k, k) ) < epsilon ) { + ::FinishProgressBar( progBar ); + ::ReleaseItem( progBar ); + return nr_Special; // \ru Система не имеет решений \en System doesn't have solutions + } + + // \ru Обратная подстановка \en Back-substitution + i = count - 1; + b[i] *= 1.0 / a.GetElem(i, i); + + Type be; + for ( i = count - 2; i >= 0; i-- ) { + j = i + 1; + be = b[j] * a.GetElem( i, j ); + + nzIndices.clear(); + if ( i + 2 < count ) { + // [i+2,count) + searchRange.first = (i + 2); + searchRange.second = (count - 1); + a.NzIndices( i, searchRange, nzIndices ); + } + size_t nzCnt = nzIndices.size(); + + for ( size_t nzInd = 0; nzInd < nzCnt; ++nzInd ) { + j = nzIndices[nzInd]; + be += b[j] * a.GetElem( i, j ); + } + double m = 1.0 / a.GetElem( i, i ); + b[i] = ( b[i] - be ) * m; + + if ( i == halfCount ) + ::SetProgressBarValue( progBar, 75 ); + if ( ::StopProgressBar( progBar ) ) { // \ru Остановка по запросу \en Stop by request + ::ReleaseItem( progBar ); + return nr_Special; + } + } + + ::SetProgressBarValue( progBar, 100 ); + ::FinishProgressBar( progBar ); + ::ReleaseItem( progBar ); + return nr_Success; +} // GaussEquation + + //------------------------------------------------------------------------------ /** \brief \ru Решение системы линейных уравнений с трехдиагональной матрицей методом прогонки. @@ -249,8 +417,8 @@ MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, Pro \en Main diagonal of a tridiagonal matrix is an array of doubles of size "n" \~ \param[in] b - \ru Верхняя диагональ, размерность n-1 \en Upper diagonal, dimension is n-1 \~ - \param[in] \ru С - нижняя диагональ, размерность n-1 - \en C- lower diagonal, dimension is n-1 \~ + \param[in] c - \ru c - нижняя диагональ, размерность n-1 + \en c - lower diagonal, dimension is n-1 \~ \param[in] r - \ru Вектор правой части, массив точек или векторов размерности n; должна быть определена операция умножения на double справа \en Vector of the right part is an array of points or vectors of dimension n; the multiplication operation by the double value on the right must be defined \~ \param[in] solution - \ru Массив решений (точек, векторов), размерности n diff --git a/C3d/Include/mb_nurbs_function.h b/C3d/Include/mb_nurbs_function.h index 5651beb..a9d48ca 100644 --- a/C3d/Include/mb_nurbs_function.h +++ b/C3d/Include/mb_nurbs_function.h @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -343,7 +344,8 @@ double GetParamDistance( const Type & p1, const Type & p2, MbeSplineParamType sp \ingroup Base_Algorithms */ // --- -inline bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt ) +inline +bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt ) { // \ru 1. Порядок B-сплайна должен быть не менее 2. \en 1. The order of B-spline must be at least 2. // \ru 2а. Для незамкнутой кривой количество точек не меньше порядка сплайна. \en 2a. The number of open curve points isn't less than the order of spline. @@ -370,7 +372,8 @@ inline bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt ) \ingroup Base_Algorithms */ // --- -inline bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt, size_t wcnt ) +inline +bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt, size_t wcnt ) { // \ru 1. Порядок B-сплайна должен быть не менее 2. \en 1. The order of B-spline must be at least 2. // \ru 2а. Для незамкнутой кривой количество точек не меньше порядка сплайна. \en 2a. The number of open curve points isn't less than the order of spline. @@ -401,7 +404,8 @@ inline bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt, size_t \ingroup Base_Algorithms */ // --- -inline bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt, size_t wcnt, size_t kcnt ) +inline +bool IsValidNurbsParams( size_t degree, bool closed, size_t pcnt, size_t wcnt, size_t kcnt ) { // \ru 1. Порядок B-сплайна должен быть не менее 2. \en 1. The order of B-spline must be at least 2. // \ru 2а. Для незамкнутой кривой количество точек не меньше порядка сплайна. \en 2a. The number of open curve points isn't less than the order of spline. @@ -446,7 +450,7 @@ bool IsValidNurbsParamsExt( size_t degree, bool closed, size_t pcnt, ( knots.size() == (degree + pcnt + (closed ? (degree - 1) : 0)) ); if ( res ) { - if ( !c3d::IsMonotonic(knots, true, true) ) + if ( !c3d::IsMonotonic( knots, true, true ) ) res = false; // SD#7118498 } @@ -476,7 +480,7 @@ bool IsValidNurbsParamsExt( size_t degree, bool closed, size_t pcnt, template bool IsValidNurbsParamsExt( size_t degree, bool closed, const PointVector & pnts, const DoubleVector * wts, - const DoubleVector * knots = NULL ) + const DoubleVector * knots = c3d_null ) { // \ru 1. Порядок B-сплайна должен быть не менее 2. \en 1. The order of B-spline must be at least 2. // \ru 2а. Для незамкнутой кривой количество точек не меньше порядка сплайна. \en 2a. The number of open curve points isn't less than the order of spline. @@ -487,11 +491,11 @@ bool IsValidNurbsParamsExt( size_t degree, bool closed, const PointVector & pnts size_t pcnt = pnts.size(); bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && - ( (wts == NULL) || (wts->size() == pcnt) ) && - ( (knots == NULL) || (knots->size() == (degree + pcnt + (closed ? (degree - 1) : 0))) ); + ( (wts == c3d_null) || (wts->size() == pcnt) ) && + ( (knots == c3d_null) || (knots->size() == (degree + pcnt + (closed ? (degree - 1) : 0))) ); - if ( res && (knots != NULL) ) { - if ( !c3d::IsMonotonic(*knots, true, true) ) + if ( res && (knots != c3d_null) ) { + if ( !c3d::IsMonotonic( *knots, true, true ) ) res = false; // SD#7118498 } @@ -523,10 +527,11 @@ bool IsValidNurbsKnots( const KnotsVector & knots, double eps = EXTENT_EPSILON ) return false; eps = ::fabs(eps); - if ( ::fabs(knots[cnt-1] - knots[0]) < eps ) + if ( ::fabs( knots.back() - knots.front() ) < eps ) return false; - for ( size_t i = 0; i < (cnt - 1); i++ ) { + size_t maxInd = cnt - 1; + for ( size_t i = 0; i < maxInd; ++i ) { if ( knots[i+1] < knots[i] - eps ) return false; } @@ -669,9 +674,92 @@ ptrdiff_t DefineKnotsVector( ptrdiff_t degree, bool closed, ptrdiff_t uppPointsI \ingroup Base_Algorithms */ // --- -MATH_FUNC (bool) DefineKnotsVector( size_t degree, bool closed, size_t count, // \ru Порядок, замкнутость, количество точек \en Order, closedness, number of points - const SArray * params, // \ru Параметры точек (для замкнутого count+1) \en Points parameters (for closed spline - "count"+1) - SArray & knots ); // \ru Формируемый узловой вектор \en Generated knot vector +template +bool DefineKnotsVector( size_t degree, + bool closed, + size_t count, + const ParamsVector * paramsPtr, + KnotsVector & knots ) +{ + bool isDone = false; + + if ( degree > 1 && count >= (closed ? 3 : degree) ) { + knots.clear(); + size_t knotsCount = (degree + count + (closed ? (degree - 1) : 0)); + knots.reserve( knotsCount ); + + double knot = 0.0; + + if ( (paramsPtr == c3d_null) || (*paramsPtr).empty() ) { + for ( size_t i = 0; i < knotsCount; ++i ) { + if ( closed ) // Замкнутый В-сплайн. + knot = (double)(ptrdiff_t)(i - degree + 1); + else { + if ( i < degree ) + knot = 0.0; + else if ( i < count + 1 ) + knot = (knots[i - 1] + 1.0); + else + knot = knots[i - 1]; + } + knots.push_back( knot ); + } + isDone = true; + } + else if ( paramsPtr->size() == count + (closed ? 1 : 0) ) { + const ParamsVector & params = (*paramsPtr); + + double pmin = params.front(); + double pmax = params.back(); + double prng = pmax - pmin; + + if ( closed ) { // замкнутый В-сплайн + /* BUG_45280 + for ( size_t i = 0; i < knotsCount; ++i ) { + knot = pmin + (prng / count) * (i - degree + 1); + knots.push_back( knot ); + } */ + + size_t cnt = count + 1; + + for ( size_t i = 0; i < knotsCount; ++i ) { + ptrdiff_t ind = (ptrdiff_t)(i - degree + 1); + + if ( i < degree ) + knot = params[(ind + count) % cnt] - prng; + else if ( i < count + degree ) + knot = params[ind]; + else + knot = prng + params[(ind + 1) % cnt]; + + knots.push_back( knot ); + } + } + else { + for ( size_t i = 0; i < knotsCount; ++i ) { + if ( i < degree ) + knot = pmin; + else if ( i < count ) { + knot = 0.0; + for ( size_t j = i - degree + 1; j < i; ++j ) + knot += params[j]; + knot /= (double)(degree - 1); + } + else + knot = pmax; + + knots.push_back( knot ); + } + } + isDone = true; + } + else { + C3D_ASSERT_UNCONDITIONAL( false ); + } + } + + return isDone; +} //------------------------------------------------------------------------------ @@ -836,14 +924,14 @@ template void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const double * W, size_t pointCount, const NurbsVector * PW, ptrdiff_t d, ptrdiff_t r1, ptrdiff_t r2, NurbsVector * PK ) { - C3D_ASSERT( (P != NULL && W != NULL) != (PW != NULL) ); + C3D_ASSERT( (P != c3d_null && W != c3d_null) != (PW != c3d_null) ); ptrdiff_t r = ( r2 - r1 ); ptrdiff_t degree = ( p + 1 ); ptrdiff_t i, k, icount; NurbsVector & PK0 = PK[0]; - if ( PW != NULL ) { + if ( PW != c3d_null ) { for ( i = 0; i <= r; i++ ) PK0.Set( i, *PW, (r1 + i) ); } @@ -886,14 +974,14 @@ template void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const double w, size_t pointCount, const NurbsVector * PW, ptrdiff_t d, ptrdiff_t r1, ptrdiff_t r2, NurbsVector * PK ) { - C3D_ASSERT( (P != NULL) != (PW != NULL) ); + C3D_ASSERT( (P != c3d_null) != (PW != c3d_null) ); ptrdiff_t r = ( r2 - r1 ); ptrdiff_t degree = ( p + 1 ); ptrdiff_t i, k, icount; NurbsVector & PK0 = PK[0]; - if ( PW != NULL ) { + if ( PW != c3d_null ) { for ( i = 0; i <= r; i++ ) PK0.Set( i, *PW, (r1 + i) ); } @@ -936,16 +1024,16 @@ template void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const double * W, size_t pointCount, const NurbsVector * PW, ptrdiff_t d, ptrdiff_t r1, ptrdiff_t r2, DoubleTriple ** DT, double ** WT ) { - C3D_ASSERT( ( P != NULL && W != NULL ) != ( PW != NULL ) ); + C3D_ASSERT( ( P != c3d_null && W != c3d_null ) != ( PW != c3d_null ) ); ptrdiff_t r = ( r2 - r1 ); ptrdiff_t degree = ( p + 1 ); ptrdiff_t i, k, icount; DoubleTriple * DT0 = DT[0]; double * WT0 = WT[0]; - bool useWeight = WT0 != NULL; + bool useWeight = WT0 != c3d_null; - if ( PW != NULL ) { + if ( PW != c3d_null ) { if ( !useWeight ) { for ( i = 0; i <= r; i++ ) DT0[i].Init( (*PW)[r1 + i] ); @@ -973,8 +1061,8 @@ void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const } } - double * WTMin = NULL; - double * WTPls = NULL; + double * WTMin = c3d_null; + double * WTPls = c3d_null; for ( k = 1; k <= d; k++ ) { DoubleTriple * DTMin = DT[k - 1]; DoubleTriple * DTPls = DT[k]; @@ -1008,16 +1096,16 @@ template void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const double w, size_t pointCount, const NurbsVector * PW, ptrdiff_t d, ptrdiff_t r1, ptrdiff_t r2, DoubleTriple ** DT, double ** WT ) { - C3D_ASSERT( ( P != NULL ) != ( PW != NULL ) ); + C3D_ASSERT( ( P != c3d_null ) != ( PW != c3d_null ) ); ptrdiff_t r = ( r2 - r1 ); ptrdiff_t degree = ( p + 1 ); ptrdiff_t i, k, icount; DoubleTriple * DT0 = DT[0]; double * WT0 = WT[0]; - bool useWeight = WT0 != NULL; + bool useWeight = WT0 != c3d_null; - if ( PW != NULL ) { + if ( PW != c3d_null ) { if ( !useWeight ) { for ( i = 0; i <= r; i++ ) DT0[i].Init( (*PW)[r1 + i] ); @@ -1046,8 +1134,8 @@ void CurveDeriveCpts( ptrdiff_t p, const KnotsVector & U, const Point * P, const } } - double * WTMin = NULL; - double * WTPls = NULL; + double * WTMin = c3d_null; + double * WTPls = c3d_null; for ( k = 1; k <= d; k++ ) { DoubleTriple * DTMin = DT[k - 1]; DoubleTriple * DTPls = DT[k]; @@ -1087,7 +1175,7 @@ void CurveDeriveCpts( ptrdiff_t p, const double * U, const Point * P, const doub for ( i = 0; i <= r; i++ ) { k = ( (r1 + i) % pointCount ); - if ( W != NULL ) + if ( W != c3d_null ) H0[i].Init( P[k], W[k] ); else H0[i].Init( P[k], 1.0 ); @@ -1233,10 +1321,13 @@ ptrdiff_t CalculateSplines( size_t degree, //------------------------------------------------------------------------------ // \ru Вычисление характеристических точек pointList для прохождения NURBS-кривой через points[i] при params[i] \en Calculation of characteristic points "pointList" of NURBS-curve passing through points[i] with params[i] // --- -template -MbeNewtonResult CalculatePointList( const DoubleVector & params, const PointVector & points, - size_t degree, bool closed, const DoubleVector & knots, - PointVector & pointList ) +template +MbeNewtonResult CalculatePointList( const ParamsVector & params, + const SrcPointsVector & points, + size_t degree, + bool closed, + const KnotsVector & knots, + DstPointsVector & pointList ) { MbeNewtonResult res = nr_Failure; @@ -1245,38 +1336,36 @@ MbeNewtonResult CalculatePointList( const DoubleVector & params, const PointVect if ( pointsCount > 1 && degree > 1 && knots.size() > 1 ) { // \ru Инициализация опорных точек. \en Initialization of support points. - if ( &pointList != &points ) { + if ( reinterpret_cast( &pointList ) != reinterpret_cast( &points ) ) { pointList.clear(); pointList = points; } ptrdiff_t uppIndex = (ptrdiff_t)pointList.size() - 1; // \ru Количество точек. \en The count of points if ( closed && (uppIndex > 1) && - c3d::EqualPoints( pointList[0], pointList[uppIndex], METRIC_REGION ) ) { + c3d::EqualPoints( pointList.front(), pointList.back(), METRIC_REGION ) ) { pointList.erase( pointList.begin() + uppIndex ); pointsCount = pointList.size(); } DPtr matrixPtr( MatrixNN::Create(pointsCount) ); // \ru Матрица системы уравнений для прохождения NURBS при params[i] через points[i] \en Matrix of equation system for constructing the NURBS-curve passing through the points[i] with params[i] - if ( matrixPtr != NULL && ::IsValidNurbsParamsExt(degree, closed, pointList.size(), knots) ) { + if ( matrixPtr != c3d_null && ::IsValidNurbsParamsExt(degree, closed, pointList.size(), knots) ) { MatrixNN & matrix = *matrixPtr; - std::vector bSplines; // \ru Ненулевые B-сплайны \en Non-zero B-splines + c3d::DoubleVector bSplines; // \ru Ненулевые B-сплайны \en Non-zero B-splines bSplines.resize( degree ); - std::vector lrVect; + c3d::DoubleVector lrVect; - for ( size_t i = 0; i < pointsCount; i++ ) { // \ru Заполняем строки матрицы \en Fills matrix rows + for ( size_t i = 0; i < pointsCount; ++i ) { // \ru Заполняем строки матрицы \en Fills matrix rows double t = params[i]; ptrdiff_t k = 0; ptrdiff_t ind = ::CalculateSplines( degree, knots, closed, t, bSplines, lrVect ); // \ru Заполняем i-ю строку \en Fill the i-th row - for ( k = 0; k < ind; k++ ) - matrix( i, k ) = 0.0; - for ( k = ind; k < ind + (ptrdiff_t)degree; k++ ) - matrix( i, k%pointsCount ) = bSplines[k - ind]; // \ru Ненулевые элементы строки. \en Non-zero elements of row - for ( k = ind + degree; k < (ptrdiff_t)pointsCount; k++ ) + for ( k = 0; k < (ptrdiff_t)pointsCount; ++k ) matrix( i, k ) = 0.0; + for ( k = ind; k < ind + (ptrdiff_t)degree; ++k ) + matrix( i, k % pointsCount ) += bSplines[k - ind]; // \ru Ненулевые элементы строки. \en Non-zero elements of row } double epsilon = PARAM_EPSILON; @@ -1291,23 +1380,88 @@ MbeNewtonResult CalculatePointList( const DoubleVector & params, const PointVect //------------------------------------------------------------------------------ -// \ru Вычисление характеристических точек pointList для прохождения NURBS-кривой через points[i] при params[i] \en Calculation of characteristic points "pointList" of NURBS-curve passing through points[i] with params[i] +// \ru Вычисление характеристических точек pointList для прохождения NURBS-кривой через points[i] при params[i]. \en Calculation of characteristic points "pointList" of NURBS-curve passing through points[i] with params[i]. // --- -template -MATH_FUNC (MbeNewtonResult) CalculatePointListWithBandMatrix( const DoubleVector & params, const PointsVector & points, - size_t degree, bool closed, const DoubleVector & knots, - PointsVector & pointList ); +template +MbeNewtonResult CalculatePointListWithBandMatrix( const ParamsVector & params, + const SrcPointsVector & points, + size_t degree, + bool closed, + const KnotsVector & knots, + DstPointsVector & pointList ) +{ + MbeNewtonResult res = nr_Failure; + + size_t pointsCount = points.size(); + + if ( pointsCount > 1 && degree > 1 && knots.size() > 1 ) { + // \ru Инициализация опорных точек. \en Initialization of support points. + if ( reinterpret_cast( &pointList ) != reinterpret_cast( &points ) ) { + pointList.clear(); + pointList = points; + } + ptrdiff_t uppIndex = (ptrdiff_t)pointList.size() - 1; // \ru Количество точек. \en The count of points. + if ( closed && (uppIndex > 1) && + c3d::EqualPoints( pointList.front(), pointList.back(), METRIC_REGION ) ) { + pointList.erase( pointList.begin() + uppIndex ); + pointsCount = pointList.size(); + } + + // \ru Матрица системы уравнений для прохождения NURBS при params[i] через points[i]. \en Matrix of equation system for constructing the NURBS-curve passing through the points[i] with params[i]. + DPtr< SparseArray2 > matrixPtr( SparseArray2::Create( pointsCount, pointsCount ) ); + + if ( matrixPtr != c3d_null && ::IsValidNurbsParamsExt( degree, closed, pointList.size(), knots ) ) { + SparseArray2 & matrix = *matrixPtr; + + c3d::DoubleVector bSplines; // \ru Ненулевые B-сплайны. \en Non-zero B-splines. + bSplines.resize( degree ); + + c3d::DoubleVector lrVect; + std::vector nzElems; + + c3d::DoubleVector nzBuffer; + for ( size_t i = 0; i < pointsCount; ++i ) { // \ru Заполняем строки матрицы. \en Fills matrix rows. + double t = params[i]; + + ptrdiff_t ind = ::CalculateSplines( degree, knots, closed, t, bSplines, lrVect ); + + nzElems.clear(); + nzBuffer.assign( pointsCount, 0.0 ); + + // \ru Заполняем i-ю строку. \en Fill the i-th row. + ptrdiff_t k; + for ( k = ind; k < ind + (ptrdiff_t)degree; ++k ) { + size_t curInd = k % pointsCount; + nzBuffer[curInd] += bSplines[k - ind]; + } + for ( k = 0; k < (ptrdiff_t)pointsCount; ++k ) { + if ( nzBuffer[k] != 0.0 ) { + nzElems.push_back( std::make_pair( k, nzBuffer[k] ) ); + } + } + matrix.SetLine( i, nzElems ); + } + + double epsilon = PARAM_EPSILON; + // \ru Решаем систему уравнений относительно характеристических точек pointList. \en Solve the system of equations for the characteristic points "pointList". + // \ru Правая часть системы = адрес начала массива опорных точек pointList.begin(). \en The right system part = address of beginning of support point array pointList.begin(). + res = ::TypedGaussEquationWithBandMatrix( matrix, &pointList[0], epsilon ); + } + } + + return res; +} //------------------------------------------------------------------------------ // \ru Установить касательность сплайна к вектору \en Set tangency of spline to vector //--- template -bool AttachNurbsG1( TypedNurbs & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline +bool AttachNurbsG1( TypedNurbs & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline const TypedVector & tang, // \ru Касательный вектор \en Tangent vector - bool begin, // \ru Сопряжение выставлено в начале \en Conjugation is defined for the start - bool modify, // \ru Можно ли менять существующие полюса \en Whether it is possible to modify the existing pole - bool isC1 ) // \ru Нужно сохранить длину касательного вектора \en Need to save the length of the tangent vector + bool begin, // \ru Сопряжение выставлено в начале \en Conjugation is defined for the start + bool modify, // \ru Можно ли менять существующие полюса \en Whether it is possible to modify the existing pole + bool isC1 ) // \ru Нужно сохранить длину касательного вектора \en Need to save the length of the tangent vector { bool res = false; @@ -1468,13 +1622,13 @@ bool SetLimitFirstDerivatives( const Curve & curve, bool setBeg, bool setEnd, Nu // \ru Установить точки так, чтобы совпала касательная и главная нормаль \en Set points such that tangent and principal normal are coincident //--- template -bool AttachNurbsG2( TypedNurbs & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline +bool AttachNurbsG2( TypedNurbs & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline const TypedVector & tang, // \ru Касательный вектор \en Tangent vector const TypedVector & tangDiff, // \ru Производная касательного вектора \en The derivative of a tangent vector - bool begin, // \ru Сопряжение выставлено в начале \en Conjugation is defined for the start - bool modify, // \ru Можно ли менять существующие полюса \en Whether it is possible to modify the existing poles - double * wDiff1, - double * wDiff2 ) + bool begin, // \ru Сопряжение выставлено в начале \en Conjugation is defined for the start + bool modify, // \ru Можно ли менять существующие полюса \en Whether it is possible to modify the existing poles + double * wDiff1, + double * wDiff2 ) { bool res = false; @@ -1618,9 +1772,9 @@ bool AttachNurbsG2( TypedNurbs & nurbs, // \ru Модифицируемый сп // \ru Сохраняем вычисленные производные \en Save the calculated derivatives if ( res ) { - if ( wDiff1 != NULL ) + if ( wDiff1 != c3d_null ) *wDiff1 = weightDiff1; - if ( wDiff2 != NULL && res ) + if ( wDiff2 != c3d_null && res ) *wDiff2 = weightDiff2; } @@ -1804,8 +1958,10 @@ bool CreateClosedNURBS4( Nurbs & nurbs, const SArray & initPoints, const // \ru Получить массив параметров по точкам \en Get an array of parameters given the points // --- template -bool CreateSplineParameters( const PointsVector & points, MbeSplineParamType spType, bool cls, - DoubleVector & params ) +bool CreateSplineParameters( const PointsVector & points, + MbeSplineParamType spType, + bool cls, + DoubleVector & params ) { bool isDone = false; params.clear(); @@ -2241,7 +2397,7 @@ size_t DefineApproxPointsOpen( const Curve & curve, size_t pCount, double pmin, \en Construction of closed spline. \~ \details \ru Построение замкнутого сплайна, аппроксимирующего набор точек, с помощью метода наименьших квадратов. \n \en Construction of closed spline which approximates a set of points by the method of least squares. \n \~ - \param[in/out] nurbs - \ru Модифицируемый сплайн. + \param[in,out] nurbs - \ru Модифицируемый сплайн. \en Modifiable spline. \~ \param[in] aDegree - \ru Порядок сплайна. \en The spline order. \~ @@ -2264,7 +2420,7 @@ MATH_FUNC (bool) CreateNurbsLSMClosed( SPtr & nurbs, // \ru Мод const ptrdiff_t pCount, const PointsVector & aPoints, const DoubleVector & aKnots, - const DoubleVector * aParams = NULL ); + const DoubleVector * aParams = c3d_null ); //------------------------------------------------------------------------------ @@ -2272,7 +2428,7 @@ MATH_FUNC (bool) CreateNurbsLSMClosed( SPtr & nurbs, // \ru Мод \en Construction of non-closed spline. \~ \details \ru Построение незамкнутого сплайна, аппроксимирующего набор точек, с помощью метода наименьших квадратов. \n \en Construction of non-closed spline which approximates a set of points by the method of least squares. \n \~ - \param[in/out] nurbs - \ru Модифицируемый сплайн. + \param[in,out] nurbs - \ru Модифицируемый сплайн. \en Modifiable spline. \~ \param[in] aDegree - \ru Порядок сплайна. \en The spline order. \~ @@ -2295,7 +2451,7 @@ MATH_FUNC (bool) CreateNurbsLSM( SPtr & nurbs, // \ru Модифи const ptrdiff_t pCount, const PointsVector & aPoints, const DoubleVector & aKnots, - const DoubleVector * aParams = NULL ); + const DoubleVector * aParams = c3d_null ); //------------------------------------------------------------------------------- @@ -2305,7 +2461,7 @@ template Nurbs * CreateLineOutRgn( const Curve & curve, double tn1, double tn2, double t1, double t2, const MbCurveIntoNurbsInfo & nci ) { - Nurbs * nurbs = NULL; + Nurbs * nurbs = c3d_null; if ( !curve.IsClosed() && nci.ExtendRange() && ((tn2 - tn1) > Math::paramEpsilon) ) { SArray points ( 2, 1 ); diff --git a/C3d/Include/mb_operation_result.h b/C3d/Include/mb_operation_result.h index 3d4ceec..dcb39c9 100644 --- a/C3d/Include/mb_operation_result.h +++ b/C3d/Include/mb_operation_result.h @@ -88,7 +88,7 @@ enum MbResultType { // \ru Начало "нездорового" диапазона ошибок, НИКОГДА НЕ ВЗВОДИТЬ ЭТУ ОШИБКУ \en Beginning of "unhealthy" range of errors, NEVER TO RAISE THIS ERROR rt_BeginOfInvalidRange, - // \ru K8+из 3Д, там хранить нельзя так как они записываются и потом читаются \en K8+from 3D, it is forbidden to store there since they register and then are read + // \ru K8+из 3D, там хранить нельзя так как они записываются и потом читаются \en K8+from 3D, it is forbidden to store there since they register and then are read rt_ErBodyCloosed = rt_TopologyError + 2, ///< \ru Тело детали не определено. \en Solid of part is undefined. rt_OneEdge = rt_ErBodyCloosed + 2, ///< \ru У выбранного угла нет общего ребра. \en The selected corner has no common edge. rt_SomeEdge = rt_OneEdge + 1, ///< \ru У одного из выбранных углов нет общего ребра. \en One of chosen corners has no common edge. @@ -239,6 +239,36 @@ enum MbResultType { rt_BuildSheetBySolidError, ///< \ru Ошибка построения листового тела по произвольному телу. \en Build sheet solid based on an arbitary solid error. rt_BendEdgeError, ///< \ru Ребро не может быть использовано как ребро сгиба. \en The edge can't be processed as bend edge. + rt_StampToolPositionError, ///< \ru Ошибочное положение инструмента относительно листового тела. \en Illegal position of the tool body related to the sheet body. + + // \ru Ошибки построения поверхности переменного сечения. \en Build failure of the swept mutable section surface. + rt_NoEdgesForBuild, ///< \ru Отсутствуют рёбра для построения. \en No edges for build. + rt_NoCurvesForBuild, ///< \ru Отсутствуют кривые для построения. \en No curves for build. + rt_NotCorrectDataForBuild, ///< \ru Некорректные данные. \en Not correct data for build. + rt_NotEnoughDataForBuild, ///< \ru Не хватает данных для построения. \en Not enough data for build. + rt_ReferenceCurveError, ///< \ru Ошибочная опорная кривая. \en Illegal reference curve. + rt_GuideCurveError, ///< \ru Ошибочная направляющая кривая. \en Illegal guide curve. + rt_ApexCurveError, ///< \ru Ошибочная вершинная кривая. \en Illegal apex curve. + rt_DiscriminantFunctionError, ///< \ru Ошибочная дискриминантная функция. \en Illegal discriminant function. + rt_DiscriminantCurveError, ///< \ru Ошибочная дискриминантная кривая. \en Illegal discriminant curve. + rt_DiscriminantSurfaceError, ///< \ru Ошибочная дискриминантная поверхность. \en Illegal discriminant surface. + rt_AngleFunctionError, ///< \ru Ошибочная функция угла. \en Illegal angle function. + rt_ReferenceCurveBuildFailed, ///< \ru Опорную кривую не удалось построить. \en Reference curve build was failed. + rt_GuideCurveBuildFailed, ///< \ru Направляющую кривую не удалось построить. \en Guide curvebuild was failed. + rt_ApexCurveBuildFailed, ///< \ru Вершинную кривую не удалось построить. \en Apex curve build was failed. + rt_VertexCurveBuildFailed, ///< \ru Контрольную кривую не удалось построить. \en Vertex curve build was failed. + rt_ApexDiscriminantBuildFailed, ///< \ru Вершинную кривую и дискриминант не удалось построить. \en Apex curve and discriminant build was failed. + rt_DiscriminantBuildFailed, ///< \ru Дискриминантную функцию не удалось построить. \en Discriminant function build was failed. + rt_PatternCurveError, ///< \ru Ошибочная образующая кривая. \en Illegal generatrix curve. + rt_SynchronizeParameterError, ///< \ru Не удалось синхронизировать параметры. \en Failed to synchronize parameters. + rt_ReparamBuildFailed, ///< \ru Не удалось выполнить репараметризацию. \en Reparameter build was failed. + rt_TriangleSectionFailed, ///< \ru Треугольник сечения поверхности не может быть определен. \ en The triangle section of the surface cannot be determined. + rt_DiscriminantFunctionWrong, ///< \ru Функция дискриминанта для задания формы сечения не обеспечивает построение поверхности. \en The discriminant function for setting the cross section shape does not provide the surface construction. + rt_DiscriminantCurveWrong, ///< \ru Кривая для задания формы сечения не обеспечивает построение поверхности. \en The curve for setting the cross section shape does not provide the surface construction. + rt_DiscriminantSurfaceWrong, ///< \ru Касательная поверхность для задания формы сечения не обеспечивает построение поверхности. \en The tangent surface for setting the cross section shape does not provide the surface construction. + rt_SectionMovementWrong, ///< \ru Движение сечения не совместимо с направляющими. \en The cross section movement is not compatible with the guides. + 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 !!! INSERT LINES STRICTLY BEFORE THIS LINE !!!! rt_ErrorTotal // \ru НИЖЕ НЕ ДОБАВЛЯТЬ! \en DON'T ADD BELOW! }; diff --git a/C3d/Include/mb_placement3d.h b/C3d/Include/mb_placement3d.h index 83c40d0..09e6b04 100644 --- a/C3d/Include/mb_placement3d.h +++ b/C3d/Include/mb_placement3d.h @@ -133,7 +133,7 @@ private: mutable uint8 flag; public: - ///< \ru Константа глобальной системы координат. \en A constant of the global coordinate system. + /// \ru Константа глобальной системы координат. \en A constant of the global coordinate system. static const MbPlacement3D global; public: /** \ru \name Конструкторы. @@ -392,7 +392,7 @@ public: /** \} /// \ru Пересчитать СК по измененным внутренним данным. \en Recalculate the coordinate system for changed internal data. void Reset (); /// \ru Инвертировать. \en Invert. - void Invert( MbMatrix * = NULL ); + void Invert( MbMatrix * = c3d_null ); /// \ru Найти ближайшую точку пересечения с линией. \en Find the nearest point of intersection with line. bool LineIntersectionPoint( const MbCartPoint3D & pc, const MbVector3D & axis, MbCartPoint3D & p, double & d, double eps = ANGLE_EPSILON ) const; diff --git a/C3d/Include/mb_point_mating.h b/C3d/Include/mb_point_mating.h index a4af357..aee71bd 100644 --- a/C3d/Include/mb_point_mating.h +++ b/C3d/Include/mb_point_mating.h @@ -23,7 +23,7 @@ /// \ru Параметры сопряжения в точке \en Parameters of conjugation at point //--- template -class MbPntMatingData { +class MbPntMatingData : public MbRefItem { private: // \ru данные \en data Vector * tangent; ///< \ru Направляющий касательный вектор. \en Guide tangent vector. Vector * tangentDer1; ///< \ru Первая производная касательного вектора. \en First derivative of tangent vector. @@ -37,10 +37,13 @@ public: /// \ru Конструктор по умолчанию. \en Default constructor. MbPntMatingData(); /// \ru Конструктор по всем параметрам сопряжения в точке. \en Constructor by all parameters of conjugation at point. - MbPntMatingData( const MbeMatingType type, const Vector * tang, - const Vector * tangDer1, const Vector * tangDer2, - SArray *& changedPnts, - bool movePnts, bool isAttach ); + MbPntMatingData( const MbeMatingType type, + const Vector * tang, + const Vector * tangDer1, + const Vector * tangDer2, + SArray *& changedPnts, + bool movePnts, + bool isAttach ); /// \ru Конструктор копирования. \en Copy-constructor. MbPntMatingData( const MbPntMatingData & ); /// \ru Деструктор. \en Destructor. @@ -48,10 +51,13 @@ public: public: /// \ru Инициализировать по всем параметрам сопряжения в точке. \en Initialize by all parameters of conjugation at point. - void Init( const MbeMatingType type, const Vector * tang, - const Vector * tangDer1, const Vector * tangDer2, - SArray *& changedPnts, - bool movePnts, bool isAttach ); + void Init( const MbeMatingType type, + const Vector * tang, + const Vector * tangDer1, + const Vector * tangDer2, + SArray *& changedPnts, + bool movePnts, + bool isAttach ); /// \ru Инициализировать по другому объекту параметров сопряжения в точке. \en Initialize by another parameters object of conjugation at point. bool Init( const MbPntMatingData & ); @@ -101,10 +107,11 @@ private: // \ru не реализовано \en not implemented //--- template MbPntMatingData::MbPntMatingData() - : tangent ( C3D_NULL_PTR ) - , tangentDer1 ( C3D_NULL_PTR ) - , tangentDer2 ( C3D_NULL_PTR ) - , changedPnts ( C3D_NULL_PTR ) + : MbRefItem ( ) + , tangent ( c3d_null ) + , tangentDer1 ( c3d_null ) + , tangentDer2 ( c3d_null ) + , changedPnts ( c3d_null ) , type ( trt_Position ) , movePnts ( false ) , attach ( false ) @@ -123,13 +130,14 @@ MbPntMatingData::MbPntMatingData( const MbeMatingType nType, SArray *& nChangedPnts, bool nMovePnts, bool nAttach ) - : type ( nType ) - , tangent ( (nTang != C3D_NULL_PTR) ? new Vector( *nTang ) : C3D_NULL_PTR ) - , tangentDer1 ( (nTangDer1 != C3D_NULL_PTR) ? new Vector( *nTangDer1 ) : C3D_NULL_PTR ) - , tangentDer2 ( (nTangDer2 != C3D_NULL_PTR) ? new Vector( *nTangDer2 ) : C3D_NULL_PTR ) - , movePnts ( nMovePnts ) - , changedPnts ( nChangedPnts ) - , attach ( nAttach ) + : MbRefItem ( ) + , type ( nType ) + , tangent ( (nTang != c3d_null) ? new Vector( *nTang ) : c3d_null ) + , tangentDer1 ( (nTangDer1 != c3d_null) ? new Vector( *nTangDer1 ) : c3d_null ) + , tangentDer2 ( (nTangDer2 != c3d_null) ? new Vector( *nTangDer2 ) : c3d_null ) + , movePnts ( nMovePnts ) + , changedPnts ( nChangedPnts ) + , attach ( nAttach ) { if ( type <= trt_Position ) { // BUG_52162 ::DeleteMatItem( tangent ); @@ -144,13 +152,14 @@ MbPntMatingData::MbPntMatingData( const MbeMatingType nType, //--- template MbPntMatingData::MbPntMatingData( const MbPntMatingData & d ) - : type ( d.type ) - , tangent ( (d.tangent != C3D_NULL_PTR) ? new Vector( *d.tangent ) : C3D_NULL_PTR ) - , tangentDer1 ( (d.tangentDer1 != C3D_NULL_PTR) ? new Vector( *d.tangentDer1 ) : C3D_NULL_PTR ) - , tangentDer2 ( (d.tangentDer2 != C3D_NULL_PTR) ? new Vector( *d.tangentDer2 ) : C3D_NULL_PTR ) - , movePnts ( d.movePnts ) - , changedPnts ( d.changedPnts ) - , attach ( d.attach ) + : MbRefItem ( ) + , type ( d.type ) + , tangent ( (d.tangent != c3d_null) ? new Vector( *d.tangent ) : c3d_null ) + , tangentDer1 ( (d.tangentDer1 != c3d_null) ? new Vector( *d.tangentDer1 ) : c3d_null ) + , tangentDer2 ( (d.tangentDer2 != c3d_null) ? new Vector( *d.tangentDer2 ) : c3d_null ) + , movePnts ( d.movePnts ) + , changedPnts ( d.changedPnts ) + , attach ( d.attach ) { } @@ -181,25 +190,25 @@ void MbPntMatingData::Init( const MbeMatingType nType, { type = nType; - if ( tangent != C3D_NULL_PTR && nTang != C3D_NULL_PTR ) // \ru касательный вектор \en tangent vector + if ( tangent != c3d_null && nTang != c3d_null ) // \ru касательный вектор \en tangent vector tangent->Init( *nTang ); - else if ( nTang != C3D_NULL_PTR ) + else if ( nTang != c3d_null ) tangent = new Vector( *nTang ); - else if ( tangent != C3D_NULL_PTR ) + else if ( tangent != c3d_null ) ::DeleteMatItem( tangent ); - if ( tangentDer1 != C3D_NULL_PTR && nTangDer1 != C3D_NULL_PTR ) // \ru первая производная касательного вектора \en first derivative of tangent vector + if ( tangentDer1 != c3d_null && nTangDer1 != c3d_null ) // \ru первая производная касательного вектора \en first derivative of tangent vector tangentDer1->Init( *nTangDer1 ); - else if ( nTangDer1 != C3D_NULL_PTR ) + else if ( nTangDer1 != c3d_null ) tangentDer1 = new Vector( *nTangDer1 ); - else if ( tangentDer1 != C3D_NULL_PTR ) + else if ( tangentDer1 != c3d_null ) ::DeleteMatItem( tangentDer1 ); - if ( tangentDer2 != C3D_NULL_PTR && nTangDer2 != C3D_NULL_PTR ) // \ru вторая производная касательного вектора \en second derivative of tangent vector + if ( tangentDer2 != c3d_null && nTangDer2 != c3d_null ) // \ru вторая производная касательного вектора \en second derivative of tangent vector tangentDer2->Init( *nTangDer2 ); - else if ( nTangDer2 != C3D_NULL_PTR ) + else if ( nTangDer2 != c3d_null ) tangentDer2 = new Vector( *nTangDer2 ); - else if ( tangentDer2 != C3D_NULL_PTR ) + else if ( tangentDer2 != c3d_null ) ::DeleteMatItem( tangentDer2 ); if ( type <= trt_Position ) { // BUG_52162 @@ -208,7 +217,7 @@ void MbPntMatingData::Init( const MbeMatingType nType, ::DeleteMatItem( tangentDer2 ); } - if ( changedPnts != C3D_NULL_PTR ) + if ( changedPnts != c3d_null ) changedPnts->clear(); movePnts = nMovePnts; @@ -223,10 +232,10 @@ void MbPntMatingData::Init( const MbeMatingType nType, template bool MbPntMatingData::Init( const MbPntMatingData & d ) { - C3D_ASSERT( changedPnts == C3D_NULL_PTR ); + C3D_ASSERT( changedPnts == c3d_null ); if ( this != &d ) { - SArray * dummyInds = C3D_NULL_PTR; + SArray * dummyInds = c3d_null; Init( d.type, d.tangent, d.tangentDer1, d.tangentDer2, dummyInds, d.movePnts, d.attach ); return true; } @@ -265,9 +274,9 @@ bool MbPntMatingData::IsValid() const if ( type >= trt_Position ) { double lenEps = LENGTH_EPSILON; - bool isTang = (tangent != C3D_NULL_PTR); - bool isTangDer1 = (tangentDer1 != C3D_NULL_PTR); - bool isTangDer2 = (tangentDer2 != C3D_NULL_PTR); + bool isTang = (tangent != c3d_null); + bool isTangDer1 = (tangentDer1 != c3d_null); + bool isTangDer2 = (tangentDer2 != c3d_null); bool isTangLen = (isTang && tangent->Length() > lenEps); switch( type ) { @@ -308,8 +317,8 @@ size_t MbPntMatingData::GetSmoothDegree() const res = 1; break; case trt_Normal : - if ( tangentDer1 != C3D_NULL_PTR ) res = 2; - else if ( tangent != C3D_NULL_PTR ) res = 1; + if ( tangentDer1 != c3d_null ) res = 2; + else if ( tangent != c3d_null ) res = 1; break; case trt_SmoothG2: res = 2; @@ -331,18 +340,18 @@ void MbPntMatingData::SetVector( ptrdiff_t i, const Vector & vect ) { switch ( i ) { case 0 : { - if ( tangent != C3D_NULL_PTR ) tangent->Init( vect ); - else tangent = new Vector( vect ); + if ( tangent != c3d_null ) tangent->Init( vect ); + else tangent = new Vector( vect ); break; } case 1 : { - if ( tangentDer1 != C3D_NULL_PTR ) tangentDer1->Init( vect ); - else tangentDer1 = new Vector( vect ); + if ( tangentDer1 != c3d_null ) tangentDer1->Init( vect ); + else tangentDer1 = new Vector( vect ); break; } case 2 : { - if ( tangentDer2 != C3D_NULL_PTR ) tangentDer2->Init( vect ); - else tangentDer2 = new Vector( vect ); + if ( tangentDer2 != c3d_null ) tangentDer2->Init( vect ); + else tangentDer2 = new Vector( vect ); break; } } @@ -355,7 +364,7 @@ void MbPntMatingData::SetVector( ptrdiff_t i, const Vector & vect ) template void MbPntMatingData::NormalizeAttachTangent() { - if ( attach && tangent != C3D_NULL_PTR ) { + if ( attach && tangent != c3d_null ) { double tangLen = tangent->Length(); if ( tangLen > LENGTH_EPSILON ) (*tangent) /= tangLen; @@ -386,11 +395,11 @@ void MbPntMatingData::GetProperties( MbProperties & properties ) properties.Add( new StringProperty( IDS_PROP_0901, typeName, false ) ); */ - if ( tangent != C3D_NULL_PTR ) + if ( tangent != c3d_null ) properties.Add( new MathItemProperty( IDS_PROP_0908, tangent, true ) ); - if ( tangentDer1 != C3D_NULL_PTR ) + if ( tangentDer1 != c3d_null ) properties.Add( new MathItemProperty( IDS_PROP_0909, tangentDer1, true ) ); - if ( tangentDer2 != C3D_NULL_PTR ) + if ( tangentDer2 != c3d_null ) properties.Add( new MathItemProperty( IDS_PROP_0910, tangentDer2, true ) ); properties.Add( new BoolProperty( IDS_PROP_0911, movePnts, false ) ); @@ -415,7 +424,7 @@ bool IsMatingDefined( const MbPntMatingData * data ) { bool isDefined = false; - if ( data != C3D_NULL_PTR && data->IsValid() ) { + if ( data != c3d_null && data->IsValid() ) { if ( data->GetType() > trt_Position ) // \ru по позиции и так выполнится, поэтому считаем не заданным \en would be held at position, so assumed as undefined isDefined = true; } @@ -427,8 +436,8 @@ bool IsMatingDefined( const MbPntMatingData * data ) //------------------------------------------------------------------------------ // \ru определены ли сопряжение \en whether conjugation is defined //--- -template -bool IsAnyMatingDefined( const RPArray< MbPntMatingData > & data ) +template +bool IsAnyMatingDefined( const PointMatingDataPtrVector & data ) { bool isDefined = false; @@ -448,16 +457,16 @@ bool IsAnyMatingDefined( const RPArray< MbPntMatingData > & data ) //------------------------------------------------------------------------------ // \ru копировать сопряжения \en copy conjugations //--- -template -bool CopyMating( const RPArray< MbPntMatingData > & src, RPArray< MbPntMatingData > & dst ) +template +bool CopyMating( const PointMatingDataPtrVector & src, PointMatingDataPtrVector & dst ) { bool isDone = false; if ( src.size() > 0 && dst.size() < 1 ) { isDone = true; - for ( size_t k = 0, cnt = src.size(); k < cnt && isDone; k++ ) { - MbPntMatingData * copyItem = C3D_NULL_PTR; - if ( src[k] != C3D_NULL_PTR ) { + for ( size_t k = 0, cnt = src.size(); k < cnt && isDone; ++k ) { + MbPntMatingData * copyItem = c3d_null; + if ( src[k] != c3d_null ) { copyItem = new MbPntMatingData(); isDone = copyItem->Init( *src[k] ); } @@ -474,8 +483,8 @@ bool CopyMating( const RPArray< MbPntMatingData > & src, RPArray< MbPntM //------------------------------------------------------------------------------ // \ru Являются ли объекты равными? \en Determine whether an object is equal? //--- -template -bool IsSame( const RPArray< MbPntMatingData > & data, const RPArray< MbPntMatingData > & other, double accuracy ) +template +bool IsSame( const PointMatingDataPtrVector & data, const PointMatingDataPtrVector & other, double accuracy ) { bool isSame = false; @@ -495,25 +504,25 @@ bool IsSame( const RPArray< MbPntMatingData > & data, const RPArray< MbP //------------------------------------------------------------------------------ // \ru трансформировать сопряжения \en transform conjugations //--- -template -void TransformMating( const RPArray< MbPntMatingData > & data, const Matrix & matr ) +template +void TransformMating( const PointMatingDataPtrVector & data, const Matrix & matr ) { Vector vect; - for ( size_t k = 0, kcnt = data.size(); k < kcnt; ++k ) { + for ( size_t k = 0, cnt = data.size(); k < cnt; ++k ) { MbPntMatingData * dataItem = data[k]; - if ( dataItem != C3D_NULL_PTR ) { - if ( dataItem->GetTangent() != C3D_NULL_PTR ) { + if ( dataItem != c3d_null ) { + if ( dataItem->GetTangent() != c3d_null ) { vect = *dataItem->GetTangent(); vect.Transform( matr ); dataItem->SetVector( 0, vect ); } - if ( dataItem->GetTangentDer1() != C3D_NULL_PTR ) { + if ( dataItem->GetTangentDer1() != c3d_null ) { vect = *dataItem->GetTangentDer1(); vect.Transform( matr ); dataItem->SetVector( 1, vect ); } - if ( dataItem->GetTangentDer2() != C3D_NULL_PTR ) { + if ( dataItem->GetTangentDer2() != c3d_null ) { vect = *dataItem->GetTangentDer2(); vect.Transform( matr ); dataItem->SetVector( 2, vect ); @@ -526,24 +535,24 @@ void TransformMating( const RPArray< MbPntMatingData > & data, const Mat //------------------------------------------------------------------------------ // \ru вращать сопряжения \en rotate conjugations //--- -template -void RotateMating( const RPArray< MbPntMatingData > & data, const Axis & axis, double angle ) +template +void RotateMating( const PointMatingDataPtrVector & data, const Axis & axis, double angle ) { Vector vect; - for ( size_t i = 0; i < data.size(); ++i ) { + for ( size_t i = 0, cnt = data.size(); i < cnt; ++i ) { MbPntMatingData * dataItem = data[i]; - if ( dataItem->GetTangent() != C3D_NULL_PTR ) { + if ( dataItem->GetTangent() != c3d_null ) { vect = *dataItem->GetTangent(); vect.Rotate( axis, angle ); dataItem->SetVector( 0, vect ); } - if ( dataItem->GetTangentDer1() != C3D_NULL_PTR ) { + if ( dataItem->GetTangentDer1() != c3d_null ) { vect = *dataItem->GetTangentDer1(); vect.Rotate( axis, angle ); dataItem->SetVector( 1, vect ); } - if ( dataItem->GetTangentDer2() != C3D_NULL_PTR ) { + if ( dataItem->GetTangentDer2() != c3d_null ) { vect = *dataItem->GetTangentDer2(); vect.Rotate( axis, angle ); dataItem->SetVector( 2, vect ); @@ -555,8 +564,8 @@ void RotateMating( const RPArray< MbPntMatingData > & data, const Axis & //------------------------------------------------------------------------------ // \ru запись массива данных сопряжений \en conjugation data array writing //--- -template -void WriteMating( writer & out, const RPArray< MbPntMatingData > & data ) +template +void WriteMating( writer & out, const PointMatingDataPtrVector & data ) { if ( out.good() ) { size_t cnt = data.size(); @@ -564,10 +573,10 @@ void WriteMating( writer & out, const RPArray< MbPntMatingData > & data for ( size_t k = 0; k < cnt && out.good(); k++ ) { const MbPntMatingData * item = data[k]; // \ru наличие сопряжения \en presence of conjugation - bool isItem = (item != NULL); + bool isItem = (item != c3d_null); out << isItem; - if ( isItem && item->GetChangedPoints() != C3D_NULL_PTR ) { + if ( isItem && item->GetChangedPoints() != c3d_null ) { C3D_ASSERT_UNCONDITIONAL( false ); // \ru KYA массив индексов должен быть пуст, т.к. он общий для всех сопряжений, им владеет заказчик операции \en KYA array of indices should be empy because it is shared between all of conjugations and owned by user of operation out.setState( io::cantWriteObject ); } @@ -577,17 +586,17 @@ void WriteMating( writer & out, const RPArray< MbPntMatingData > & data uint32 type = (uint32)item->GetType(); out << type; // \ru касательный вектор \en tangent vector - isItem = (item->GetTangent() != C3D_NULL_PTR); + isItem = (item->GetTangent() != c3d_null); out << isItem; if ( isItem ) out << (*item->GetTangent()); // \ru первая производная касательного вектора \en first derivative of tangent vector - isItem = (item->GetTangentDer1() != C3D_NULL_PTR); + isItem = (item->GetTangentDer1() != c3d_null); out << isItem; if ( isItem ) out << (*item->GetTangentDer1()); // \ru вторая производная касательного вектора \en second derivative of tangent vector - isItem = (item->GetTangentDer2() != C3D_NULL_PTR); + isItem = (item->GetTangentDer2() != c3d_null); out << isItem; if ( isItem ) out << (*item->GetTangentDer2()); @@ -603,16 +612,16 @@ void WriteMating( writer & out, const RPArray< MbPntMatingData > & data //------------------------------------------------------------------------------ // \ru чтение массива данных сопряжений \en conjugation data array reading //--- -template -void ReadMating( reader & in, RPArray< MbPntMatingData > & data ) +template +void ReadMating( reader & in, PointMatingDataPtrVector & data ) { if ( in.good() ) { ::DeleteMatItems( data ); size_t cnt = ReadCOUNT( in ); if ( cnt > 0 ) { - data.Reserve( cnt ); - SArray * dummyInds = C3D_NULL_PTR; + data.reserve( data.size() + cnt ); + SArray * dummyInds = c3d_null; for ( size_t k = 0; k < cnt && in.good(); k++ ) { // \ru наличие сопряжения \en presence of conjugation @@ -624,9 +633,9 @@ void ReadMating( reader & in, RPArray< MbPntMatingData > & data ) uint32 type = uint32(trt_None); in >> type; - MbVector3D * v1 = C3D_NULL_PTR; - MbVector3D * v2 = C3D_NULL_PTR; - MbVector3D * v3 = C3D_NULL_PTR; + MbVector3D * v1 = c3d_null; + MbVector3D * v2 = c3d_null; + MbVector3D * v3 = c3d_null; // \ru касательный вектор \en tangent vector in >> isItem; @@ -654,14 +663,14 @@ void ReadMating( reader & in, RPArray< MbPntMatingData > & data ) MbPntMatingData * item = new MbPntMatingData(); item->Init( (MbeMatingType)type, v1, v2, v3, dummyInds, movePnts, attach ); - data.Add( item ); + data.push_back( item ); ::DeleteMatItem( v1 ); ::DeleteMatItem( v2 ); ::DeleteMatItem( v3 ); } else { - data.Add( NULL ); + data.push_back( c3d_null ); } } } @@ -682,21 +691,21 @@ void CopyPntMatingData( const MbPntMatingData & srcData, MbPntMatingD size_t dim = std_min( SrcVector::GetDimension(), DstVector::GetDimension() ); - DstVector * tangent = C3D_NULL_PTR; - DstVector * tangentDer1 = C3D_NULL_PTR; - DstVector * tangentDer2 = C3D_NULL_PTR; + DstVector * tangent = c3d_null; + DstVector * tangentDer1 = c3d_null; + DstVector * tangentDer2 = c3d_null; - if ( srcData.GetTangent() != C3D_NULL_PTR ) { + if ( srcData.GetTangent() != c3d_null ) { tangent = new DstVector; for ( size_t k = 0; k < dim; k++ ) (*tangent)[k] = (*srcData.GetTangent())[k]; } - if ( srcData.GetTangentDer1() != C3D_NULL_PTR ) { + if ( srcData.GetTangentDer1() != c3d_null ) { tangentDer1 = new DstVector; for ( size_t k = 0; k < dim; k++ ) (*tangentDer1)[k] = (*srcData.GetTangentDer1())[k]; } - if ( srcData.GetTangentDer2() != C3D_NULL_PTR ) { + if ( srcData.GetTangentDer2() != c3d_null ) { tangentDer2 = new DstVector; for ( size_t k = 0; k < dim; k++ ) (*tangentDer2)[k] = (*srcData.GetTangentDer2())[k]; @@ -710,4 +719,14 @@ void CopyPntMatingData( const MbPntMatingData & srcData, MbPntMatingD } +class MATH_CLASS MbVector; +class MATH_CLASS MbVector3D; + +namespace c3d // namespace C3D +{ +typedef MbPntMatingData PntMatingData2D; +typedef MbPntMatingData PntMatingData3D; +} // namespace C3D + + #endif diff --git a/C3d/Include/mb_property.h b/C3d/Include/mb_property.h index 4e226a4..3e8529b 100644 --- a/C3d/Include/mb_property.h +++ b/C3d/Include/mb_property.h @@ -96,86 +96,93 @@ class MbProperties; // --- enum PrePropType { - pt_UndefinedProp, ///< \ru Свойство неизвестного типа данных. \en Property of unknown datatype. \n + pt_UndefinedProp = 0, ///< \ru Свойство неизвестного типа данных. \en Property of unknown data type. \n // \ru Атомарные свойства. \en Atomic properties. - pt_BoolProp, ///< \ru Логическое значение. \en Logical value. - pt_IntProp, ///< \ru Целое значение. \en Integer value. - pt_UIntProp, ///< \ru Беззнаковое целое значение. \en Unsigned integer value. - pt_DoubleProp, ///< \ru Действительное значение. \en Real value. - pt_StringProp, ///< \ru Строковое значение. \en String value. - pt_CharProp, ///< \ru Строковое значение. \en String value. - pt_VersionProp, ///< \ru Свойство-версия. \en Version property. \n + pt_BoolProp = 1, ///< \ru Логическое значение. \en Logical value. + pt_IntProp = 2, ///< \ru Целое значение. \en Integer value. + pt_UIntProp = 3, ///< \ru Беззнаковое целое значение. \en Unsigned integer value. + pt_DoubleProp = 4, ///< \ru Действительное значение. \en Real value. + pt_NDoubleProp = 5, ///< \ru Действительное значение с номером. \en Real value and index. + pt_StringProp = 6, ///< \ru Строковое значение. \en String value. + pt_CharProp = 7, ///< \ru Строковое значение. \en String value. + pt_VersionProp = 8, ///< \ru Свойство-версия. \en Version property. \n + pt_AtomicPropLast = 20, ///< \ru Атомарные свойства вставлять перед этим значением. \en Atomic properties should be inserted before this value. \n // \ru Комплексные свойства плоских объектов . \en Complex properties of planar objects. - pt_CartPointProp, ///< \ru Cвойство точки. \en Property of point. - pt_VectorProp, ///< \ru Cвойство вектора. \en Property of vector. - pt_DirectionProp, ///< \ru Cвойство вектора. \en Property of vector. - pt_PlacementProp, ///< \ru Cвойство системы координат. \en Property of coordinate system. - pt_MatrixProp, ///< \ru Cвойство матрицы. \en Property of matrix. - pt_CurveProp, ///< \ru Cвойство кривой. \en Property of curve. - pt_MultilineProp, ///< \ru Свойство мультилинии. \en Property of multiline. - pt_RegionProp, ///< \ru Свойство региона. \en Property of region. - pt_PntMatingProp, ///< \ru Свойство сопряжения в точке. \en Property of conjugation at a point. \n + pt_CartPointProp = 21, ///< \ru Свойство точки. \en Property of point. + pt_VectorProp = 22, ///< \ru Свойство вектора. \en Property of vector. + pt_DirectionProp = 23, ///< \ru Свойство вектора. \en Property of vector. + pt_PlacementProp = 24, ///< \ru Свойство системы координат. \en Property of coordinate system. + pt_MatrixProp = 25, ///< \ru Свойство матрицы. \en Property of matrix. + pt_CurveProp = 26, ///< \ru Свойство кривой. \en Property of curve. + pt_MultilineProp = 27, ///< \ru Свойство мультилинии. \en Property of multiline. + pt_RegionProp = 28, ///< \ru Свойство региона. \en Property of region. + pt_PntMatingProp = 29, ///< \ru Свойство сопряжения в точке. \en Property of conjugation at a point. \n + pt_PlanarPropLast = 50, ///< \ru Свойства плоских объектов вставлять перед этим значением. \en Properties of planar objects should be inserted before this value. \n // \ru Комплексные свойства пространственных объектов. \en Complex properties of spatial objects. - pt_CartPoint3DProp, ///< \ru Cвойство точки. \en Property of point. - pt_Vector3DProp, ///< \ru Cвойство вектора. \en Property of vector. - pt_Placement3DProp, ///< \ru Cвойство системы. \en Property of coordinate system. - pt_Matrix3DProp, ///< \ru Cвойство матрицы. \en Property of matrix. - pt_FloatPointProp, ///< \ru Cвойство параметра. \en Property of parameter. - pt_FloatPoint3DProp, ///< \ru Cвойство точки. \en Property of point. - pt_FloatVector3DProp, ///< \ru Cвойство вектора. \en Property of vector. - pt_TriangleProp, ///< \ru Cвойство треугольника. \en Property of triangle. - pt_QuadrangleProp, ///< \ru Cвойство четырехугольника. \en Property of quadrangle. - pt_ElementProp, ///< \ru Cвойство элемента. \en Property of element. - pt_Apex3DProp, ///< \ru Cвойство аперса. \en Property of apex. - pt_Polygon3DProp, ///< \ru Cвойство полигона. \en Property of polygon. - pt_GridProp, ///< \ru Cвойство триангуляции. \en Property of triangulation. \n + pt_CartPoint3DProp = 51, ///< \ru Свойство точки. \en Property of point. + pt_Vector3DProp = 52, ///< \ru Свойство вектора. \en Property of vector. + pt_Placement3DProp = 53, ///< \ru Свойство системы. \en Property of coordinate system. + pt_Matrix3DProp = 54, ///< \ru Свойство матрицы. \en Property of matrix. + pt_FloatPointProp = 55, ///< \ru Свойство параметра. \en Property of parameter. + pt_FloatPoint3DProp = 56, ///< \ru Свойство точки. \en Property of point. + pt_FloatVector3DProp = 57, ///< \ru Свойство вектора. \en Property of vector. + pt_TriangleProp = 58, ///< \ru Свойство треугольника. \en Property of triangle. + pt_QuadrangleProp = 59, ///< \ru Свойство четырехугольника. \en Property of quadrangle. + pt_ElementProp = 60, ///< \ru Свойство элемента. \en Property of element. + pt_Apex3DProp = 61, ///< \ru Свойство аперса. \en Property of apex. + pt_Polygon3DProp = 62, ///< \ru Свойство полигона. \en Property of polygon. + pt_GridProp = 63, ///< \ru Свойство триангуляции. \en Property of triangulation. \n + pt_SpatialPropLast = 90, ///< \ru Свойства пространственных объектов вставлять перед этим значением. \en Properties of spatial objects should be inserted before this value. \n // \ru Комплексные свойства геометрических объектов. \en Complex properties of geometric objects. - pt_FunctionProp, ///< \ru Cвойство функции. \en Property of function. - pt_Curve3DProp, ///< \ru Cвойство кривой. \en Property of curve. - pt_SurfaceProp, ///< \ru Cвойство поверхности. \en Property of surface. - pt_Point3DProp, ///< \ru Cвойство точки. \en Property of point. - pt_MarkerProp, ///< \ru Cвойство маркера ("точка присоединения"). \en Property of marker ("point of joint"). - pt_SymbolProp, ///< \ru Cвойство условного обозначения. \en Property of conventional notation. - pt_ThreadProp, ///< \ru Cвойство резьбы. \en Property of thread. - pt_Pnt3DMatingProp, ///< \ru Cвойство сопряжения в точке. \en Property of conjugation at a point. \n + pt_FunctionProp = 91, ///< \ru Свойство функции. \en Property of function. + pt_Curve3DProp = 92, ///< \ru Свойство кривой. \en Property of curve. + pt_SurfaceProp = 93, ///< \ru Свойство поверхности. \en Property of surface. + pt_Point3DProp = 94, ///< \ru Свойство точки. \en Property of point. + pt_MarkerProp = 95, ///< \ru Свойство маркера ("точка присоединения"). \en Property of marker ("point of joint"). + pt_SymbolProp = 96, ///< \ru Свойство условного обозначения. \en Property of conventional notation. + pt_ThreadProp = 97, ///< \ru Свойство резьбы. \en Property of thread. + pt_Pnt3DMatingProp = 98, ///< \ru Свойство сопряжения в точке. \en Property of conjugation at a point. \n + pt_GeomPropLast = 120, ///< \ru Свойства геометрических объектов вставлять перед этим значением. \en Properties of geometric objects should be inserted before this value. \n // \ru Комплексные свойства тел и топологических объектов. \en Complex properties of solids and topological objects. - pt_CreatorProp, ///< \ru Cвойство строителя тела. \en Property of solid creator. - pt_VertexProp, ///< \ru Cвойство вершины. \en Property of vertex. - pt_EdgeProp, ///< \ru Cвойство ребра-кривой. \en Property of edge curve. - pt_CurveEdgeProp, ///< \ru Cвойство ребра грани. \en Property of face edge. - pt_OrientedEdgeProp, ///< \ru Cвойство ориентированного ребра. \en Property of oriented edge. - pt_LoopProp, ///< \ru Cвойство цикла. \en Property of loop. - pt_FaceProp, ///< \ru Cвойство грани. \en Property of face. - pt_FaceShellProp, ///< \ru Cвойство оболочки. \en Property of shell. - pt_NameProp, ///< \ru Cвойство имени. \en Property of name. \n + pt_CreatorProp = 121, ///< \ru Свойство строителя тела. \en Property of solid creator. + pt_VertexProp = 122, ///< \ru Свойство вершины. \en Property of vertex. + pt_EdgeProp = 123, ///< \ru Свойство ребра-кривой. \en Property of edge curve. + pt_CurveEdgeProp = 124, ///< \ru Свойство ребра грани. \en Property of face edge. + pt_OrientedEdgeProp = 125, ///< \ru Свойство ориентированного ребра. \en Property of oriented edge. + pt_LoopProp = 126, ///< \ru Свойство цикла. \en Property of loop. + pt_FaceProp = 127, ///< \ru Свойство грани. \en Property of face. + pt_FaceShellProp = 128, ///< \ru Свойство оболочки. \en Property of shell. + pt_NameProp = 129, ///< \ru Свойство имени. \en Property of name. \n + pt_TopologyPropLast = 150, ///< \ru Свойства тел и топологических объектов вставлять перед этим значением. \en Properties of solids and topological objects should be inserted before this value. \n // \ru Комплексные свойства объектов модели. \en Complex properties of model objects. - pt_AssistingItemProp, ///< \ru Cвойство вспомогательного объекта. \en Property of assisting item. - pt_CollectionProp, ///< \ru Cвойство коллекции 3D элементов. \en Property of the collection of 3D elements. \n - pt_PointFrameProp, ///< \ru Cвойство точечного каркаса. \en Property of point frame. - pt_WireFrameProp, ///< \ru Cвойство проволочного каркаса. \en Property of wire frame. - pt_SolidProp, ///< \ru Cвойство тела. \en Property of solid. - pt_InstanceProp, ///< \ru Cвойство вставки объекта. \en Property of object instance. - pt_AssemblyProp, ///< \ru Cвойство сборочной единицы. \en Property of assembly unit. - pt_ConstraintSystem, ///< \ru Cвойство системы ограничений. \en Property of constraint system. - pt_MeshProp, ///< \ru Cвойство сетки. \en Property of mesh. - pt_SpaceInstanceProp, ///< \ru Cвойство объекта. \en Property of object. - pt_PlaneInstanceProp, ///< \ru Cвойство плоского объекта. \en Property of flat object. - pt_ConstraintModelProp, ///< \ru Cвойство схемы сопряжений. \en Property of conjugation scheme. - pt_ItemProp, ///< \ru Cвойство объекта. \en Property of object. - pt_ModelProp, ///< \ru Cвойство объектной модели. \en Property of object model. - pt_TransactionsProp, ///< \ru Cвойство журнала построения. \en Property of build log. - pt_AttributeContainerProp, ///< \ru Cвойство контейнера атрибутов. \en Property of attribute container. - pt_AttributeProp, ///< \ru Cвойство атрибута. \en Property of attribute. - pt_NamedAttributeContainerProp, ///< \ru Cвойство именованного контейнера атрибутов. \en Property of named attribute container. - pt_AttributeActionProp, ///< \ru Cвойство атрибута. \en Property of attribute. \n + pt_AssistingItemProp = 151, ///< \ru Свойство вспомогательного объекта. \en Property of assisting item. + pt_CollectionProp = 152, ///< \ru Свойство коллекции 3D элементов. \en Property of the collection of 3D elements. \n + pt_PointFrameProp = 153, ///< \ru Свойство точечного каркаса. \en Property of point frame. + pt_WireFrameProp = 154, ///< \ru Свойство проволочного каркаса. \en Property of wire frame. + pt_SolidProp = 155, ///< \ru Свойство тела. \en Property of solid. + pt_InstanceProp = 156, ///< \ru Свойство вставки объекта. \en Property of object instance. + pt_AssemblyProp = 157, ///< \ru Свойство сборочной единицы. \en Property of assembly unit. + pt_ConstraintSystem = 158, ///< \ru Свойство системы ограничений. \en Property of constraint system. + pt_MeshProp = 159, ///< \ru Свойство сетки. \en Property of mesh. + pt_SpaceInstanceProp = 160, ///< \ru Свойство объекта. \en Property of object. + pt_PlaneInstanceProp = 161, ///< \ru Свойство плоского объекта. \en Property of flat object. + pt_ConstraintModelProp = 162, ///< \ru Свойство схемы сопряжений. \en Property of conjugation scheme. + pt_ItemProp = 163, ///< \ru Свойство объекта. \en Property of object. + pt_ModelProp = 164, ///< \ru Свойство объектной модели. \en Property of object model. + pt_TransactionsProp = 165, ///< \ru Свойство журнала построения. \en Property of build log. + pt_AttributeContainerProp = 166, ///< \ru Свойство контейнера атрибутов. \en Property of attribute container. + pt_AttributeProp = 167, ///< \ru Свойство атрибута. \en Property of attribute. + pt_NamedAttributeContainerProp = 168, ///< \ru Свойство именованного контейнера атрибутов. \en Property of named attribute container. + pt_AttributeActionProp = 169, ///< \ru Свойство атрибута. \en Property of attribute. \n + pt_ModelPropLast = 300, ///< \ru Свойства объектов модели вставлять перед этим значением. \en Properties of model objects should be inserted before this value. \n - pt_LastPropType, ///< \ru Последний тип свойства, все остальные добавлять перед ним. \en Last type of property, any other ones must be added before. + pt_LastPropType = 1000, ///< \ru Последний тип свойства, все остальные добавлять перед ним. \en Last type of property, any other ones must be added before. }; @@ -267,19 +274,50 @@ private: bool changeable; ///< \ru Признак редактируемости. \en Attribute of editability. public: - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ MbProperty( MbePrompt name, bool change = true ) : prompt( name ), changeable( change ) {} /// \ru Деструктор. \en Destructor. virtual ~MbProperty(); /// \ru Выдать тип свойства. \en Get type of property. virtual PrePropType IsA() const = 0; - /// \ru Выдать строковое значение свойства. \en Get string value of the property. - virtual void GetCharValue( TCHAR * v ) const = 0; + /// \ru Выдать строковое значение свойства. Устаревший метод, вместо него используйте GetCharValue_s() в сочетании с GetCharLen(). + /// \en Get string value of the property. Deprecated method, use GetCharValue_s() in combination with GetCharLen() instead. + //DEPRECATE_DECLARE + virtual void GetCharValue( TCHAR * ) const = 0; + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * /* v */, size_t /* size */ ) const { return false; /* Not implemented. */ } + /// \ru Выдать значение свойства. \en Get value of the property. - virtual void _GetPropertyValue( void * v, size_t size ) const = 0; + virtual void _GetPropertyValue( void *, size_t size ) const = 0; /// \ru Установить новое значение свойства. \en Set the new value of the property. - virtual void SetPropertyValue( TCHAR * v ) = 0; + virtual void SetPropertyValue( TCHAR * ) = 0; /// \ru Выдать кортеж свойств составного свойства (не атомарный объект). \en Get tuple of the complex property (non-atomic object). virtual void GetProperties( MbProperties & ) {} /// \ru Задать кортеж свойств составного свойства (не атомарный объект). \en Set tuple of the complex property (non-atomic object). @@ -307,7 +345,17 @@ class MATH_CLASS BoolProperty : public MbProperty { public : bool value; ///< \ru Значение. \en Value. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Значение. + \en Value. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ BoolProperty( MbePrompt name, bool initValue, bool change = true ) : MbProperty( name, change ) , value( initValue ) @@ -317,7 +365,27 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. - virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. + virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. OBVIOUS_PRIVATE_COPY( BoolProperty ) @@ -336,7 +404,17 @@ class MATH_CLASS IntProperty : public MbProperty { public : int64 value; ///< \ru Значение. \en Value. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Значение. + \en Value. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ IntProperty( MbePrompt name, int64 initValue, bool change = true ) : MbProperty( name, change ) , value( (int64)initValue ) @@ -347,6 +425,26 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. @@ -366,7 +464,17 @@ class MATH_CLASS UIntProperty : public MbProperty { public : uint64 value; ///< \ru Значение. \en Value. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Значение. + \en Value. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ UIntProperty( MbePrompt name, size_t initValue, bool change = true ) : MbProperty( name, change ) , value( (uint64)initValue ) @@ -377,6 +485,26 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. @@ -396,7 +524,17 @@ class MATH_CLASS DoubleProperty : public MbProperty { public : double value; ///< \ru Значение. \en Value. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Значение. + \en Value. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ DoubleProperty( MbePrompt name, double initValue, bool change = true ) : MbProperty( name, change ) , value( initValue ) @@ -406,6 +544,26 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. @@ -421,15 +579,25 @@ OBVIOUS_PRIVATE_COPY( DoubleProperty ) \ingroup Model_Properties */ // --- -class MATH_CLASS NDoubleProperty : public MbProperty { +class MATH_CLASS NDoubleProperty : public DoubleProperty { public : - double value; ///< \ru Значение. \en Value. uint32 number; ///< \ru Номер. \en Number. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Значение. + \en Value. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + \param[in] n - \ru Номер. + \en Number. \~ + */ NDoubleProperty( MbePrompt name, double initValue, bool change = true, uint32 n = 0 ) - : MbProperty( name, change ) - , value( initValue ) + : DoubleProperty( name, initValue, change ) , number( n ) {} /// \ru Деструктор. \en Destructor. @@ -437,6 +605,26 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. @@ -457,13 +645,47 @@ class MATH_CLASS StringProperty : public MbProperty TCHAR * value; ///< \ru Значение. \en Value. public: - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. + Максимальная длина строки ограничена 128 символами. + Если длина строки инициализации больше, то строка-значение обрезается.\n + \en Constructor by parameters. + The maximum string length is limited to 128 characters. + If the length of the initialization string is longer, the string-value is truncated. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Строка инициализации. + \en Initialization string. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of editability. \~ + */ StringProperty( MbePrompt name, const TCHAR * initValue, bool change = true ); /// \ru Деструктор. \en Destructor. virtual ~StringProperty(); virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + /** + \brief \ru Получить размер буфера, достаточный для размещения строкового значения свойства. + \en Get buffer size, sufficient to accommodate the string value of the property. \~ + \details \ru Возвращает размер буфера, достаточный для размещения строкового значения свойства без учета нуль-терминатора. \n + \en Returns buffer size, sufficient to accommodate the string value of the property, excluding the terminal null. \n \~ + */ + virtual size_t GetCharLen() const; + /** + \brief \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. + \en Get the string value of the property as a string with a terminal null. \~ + \details \ru Выдать строковое значение свойства в виде строки с нуль-терминатором. \n + \en Get the string value of the property as a string with a terminal null. \n \~ + \param[in] v - \ru Указатель на символьный массив, куда копировать. + \en A pointer to a destination buffer to copy to. \~ + \param[in] size - \ru Размер символьного массива. + \en The size of the destination buffer. \~ + \return \ru true в случае успеха, иначе - false. + \en true if successful; otherwise, false. \~ + */ + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. const TCHAR * CharValue() const { return value; } @@ -487,7 +709,17 @@ class MATH_CLASS VersionProperty : public MbProperty { public : VERSION value; ///< \ru Значение. \en Value. - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Версия. + \en Version. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + */ VersionProperty( MbePrompt name, VERSION initValue, bool change = true ) : MbProperty( name, change ) , value( initValue ) @@ -497,6 +729,8 @@ public : virtual PrePropType IsA() const; // \ru Выдать тип свойства. \en Get type of property. virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get string value of the property. + virtual size_t GetCharLen() const; // \ru Выдать размер буфера для строкового значения свойства (без учета нуль-терминатора). \en Get buffer size for string value of the property (excluding the terminal null). + virtual bool GetCharValue_s( TCHAR * v, size_t size ) const; // \ru Выдать строковое значение свойства, возвращает true при успехе или false. \en Get string value of the property. Returns true if successful; otherwise, false. virtual void _GetPropertyValue( void * v, size_t size ) const; // \ru Выдать значение свойства. \en Get value of the property. virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. @@ -517,8 +751,8 @@ OBVIOUS_PRIVATE_COPY( VersionProperty ) template inline void GetCharValue( const PropType *, const FieldType *, uint32 n, TCHAR * v ) { - C3D_ASSERT( v != NULL ); - if ( v != NULL ) { + C3D_ASSERT( v != c3d_null ); + if ( v != c3d_null ) { if ( n == 0 ) { v[0] = _T(' '); v[1] = _T('\0'); @@ -540,8 +774,8 @@ inline void GetCharValue( const PropType *, const FieldType *, uint32 n, TCHAR * template inline void GetCharValue( const PropType *, const MbCartPoint * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { + C3D_ASSERT( value != c3d_null && v != c3d_null ); + if ( value != c3d_null && v != c3d_null ) { if ( n == 0 ) _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); else @@ -561,8 +795,8 @@ inline void GetCharValue( const PropType *, const MbCartPoint * value, uint32 n, template inline void GetCharValue( const PropType *, const MbVector * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { + C3D_ASSERT( value != c3d_null && v != c3d_null ); + if ( value != c3d_null && v != c3d_null ) { if ( n == 0 ) _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); else @@ -582,8 +816,8 @@ inline void GetCharValue( const PropType *, const MbVector * value, uint32 n, TC template inline void GetCharValue( const PropType *, const MbDirection * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { + C3D_ASSERT( value != c3d_null && v != c3d_null ); + if ( value != c3d_null && v != c3d_null ) { double angle(0.0); if ( value->ax==0 && value->ay==0 ) angle = 0.0; @@ -608,8 +842,8 @@ inline void GetCharValue( const PropType *, const MbDirection * value, uint32 n, template inline void GetCharValue( const PropType *, const MbCartPoint3D * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { + C3D_ASSERT( value != c3d_null && v != c3d_null ); + if ( value != c3d_null && v != c3d_null ) { if ( n == 0 ) _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); else @@ -629,8 +863,8 @@ inline void GetCharValue( const PropType *, const MbCartPoint3D * value, uint32 template inline void GetCharValue( const PropType *, const MbVector3D * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { + C3D_ASSERT( value != c3d_null && v != c3d_null ); + if ( value != c3d_null && v != c3d_null ) { if ( n == 0 ) _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); else @@ -650,9 +884,9 @@ inline void GetCharValue( const PropType *, const MbVector3D * value, uint32 n, template inline void GetCharValue( const PropType *, const MbName * value, uint32 n, TCHAR * v ) { - C3D_ASSERT( v != NULL ); - if ( v != NULL ) { - if ( value != NULL ) { + C3D_ASSERT( v != c3d_null ); + if ( v != c3d_null ) { + if ( value != c3d_null ) { c3d::string_t str; value->ToString( str ); @@ -683,7 +917,19 @@ public : uint32 number; ///< \ru Номер. \en Number. public : - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Указатель на объект. + \en Object pointer. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + \param[in] n - \ru Номер. + \en Number. \~ + */ MathItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) : MbProperty( name, change ) , value( initValue ) @@ -725,7 +971,19 @@ public: uint32 number; ///< \ru Номер. \en Number. public: - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Объект. + \en Object. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + \param[in] n - \ru Номер. + \en Number. \~ + */ MathItemCopyProperty( MbePrompt name, const Type & initValue, bool change, uint32 n = 0 ) : MbProperty( name, change ) , value( initValue ) @@ -751,7 +1009,7 @@ OBVIOUS_PRIVATE_COPY( MathItemCopyProperty ) //------------------------------------------------------------------------------ -/** \brief \ru Cвойство объекта. +/** \brief \ru Свойство объекта. \en The property of the object. \~ \details \ru Обертка, реализующая свойство объекта со счетчиком ссылок.\n \en Wrapper that implements property of an object with reference counter.\n \~ @@ -765,7 +1023,19 @@ public : uint32 number; ///< \ru Номер. \en Number. public : - /// \ru Конструктор. \en Constructor. + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by parameters. \n \~ + \param[in] name - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] initValue - \ru Объект. + \en Object. \~ + \param[in] change - \ru Признак редактируемости. + \en The flag of edibility. \~ + \param[in] n - \ru Номер. + \en Number. \~ + */ RefItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) : MbProperty( name, change ) , value ( initValue ) @@ -807,7 +1077,8 @@ public: /// \ru Конструктор. \en Constructor. MbProperties() : PArray() - , name( IDS_ITEM_0000 ) {} + , name( IDS_ITEM_0000 ) + {} public: /// \ru Выдать имя объекта. \en Get name of object. @@ -816,14 +1087,42 @@ public: size_t GetName() const { return (size_t)name; } /// \ru Выдать имя объекта. \en Get name of object. MbePrompt Name() const { return name; } - /// \ru Установить имя объекта. \en Set name of the object. + /** \brief \ru Установить имя объекта. + \en Set name of the object. \~ + \details \ru Установить имя объекта. \n + \en Set name of the object. \n \~ + \param[in] s - \ru Номер подсказки. + \en Number of hint string. \~ + */ void SetName( MbePrompt s ) { name = s; } - /// \ru Установить имя объекта. \en Set name of the object. + /** \brief \ru Установить имя объекта. + \en Set name of the object. \~ + \details \ru Установить имя объекта. \n + \en Set name of the object. \n \~ + \param[in] s - \ru Номер подсказки. + \en Number of hint string. \~ + */ void SetName( size_t s ) { name = (MbePrompt)s; } - /// \ru Найти свойство по имени и типу. \en Find property by name and type. - MbProperty * FindByPrompt( MbePrompt, uint type ) const; - /// \ru Найти индекс свойства в массиве по имени и типу. \en Find index of property in array by name and type. - size_t FindByPrompt( uint type, MbePrompt ) const; + /** \brief \ru Найти свойство. + \en Find property. \~ + \details \ru Найти свойство по имени и типу. \n + \en Find property by name and type. \n \~ + \param[in] p - \ru Номер подсказки. + \en Number of hint string. \~ + \param[in] type - \ru Тип свойства. + \en Property type. \~ + */ + MbProperty * FindByPrompt( MbePrompt p, uint type ) const; + /** \brief \ru Найти индекс свойства в массиве. + \en Find index of property in array. \~ + \details \ru Найти индекс свойства в массиве по имени и типу. \n + \en Find index of property in array by name and type. \n \~ + \param[in] type - \ru Тип свойства. + \en Property type. \~ + \param[in] p - \ru Номер подсказки. + \en Number of hint string. \~ + */ + size_t FindByPrompt( uint type, MbePrompt p ) const; OBVIOUS_PRIVATE_COPY( MbProperties ) }; // MbProperties diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index 501a2ce..c1e9caf 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -86,6 +86,10 @@ enum MbePrompt IDS_ITEM_0103, ///< \ru Матрица преобразования. \en Transformation matrix. IDS_ITEM_0104, ///< \ru Локальная система координат. \en Local coordinate system. + IDS_ITEM_0107, ///< \ru Перемещение. \en Translation. + IDS_ITEM_0108, ///< \ru Вращение. \en Rotation. + IDS_ITEM_0109, ///< \ru Трансформация. \en Transformation. + // \ru Типы функций \en Types of functions IDS_ITEM_0111, ///< \ru Kонстантная функция. \en Constant Function. @@ -137,10 +141,16 @@ enum MbePrompt IDS_ITEM_0251, ///< \ru Первое направляющее ребро. \en First Guide Edge. IDS_ITEM_0252, ///< \ru Первая направляющая кривая. \en First Guide Curve. IDS_ITEM_0253, ///< \ru Первая грань для стыковки. \en First Mating Face. - + IDS_ITEM_0254, ///< \ru Первая контрольная кривая. \en First Control Curve. + IDS_ITEM_0255, ///< \ru Первая угловая функция. \en First Angle Function. IDS_ITEM_0256, ///< \ru Второе направляющее ребро. \en Second Guide Edge. IDS_ITEM_0257, ///< \ru Вторая направляющая кривая. \en Second Guide Curve. IDS_ITEM_0258, ///< \ru Вторая грань для стыковки. \en Second Mating Face. + IDS_ITEM_0259, ///< \ru Вторая контрольная кривая. \en Second Control Curve. + IDS_ITEM_0260, ///< \ru Вторая угловая функция. \en Second Angle Function. + IDS_ITEM_0261, ///< \ru Угол к хорде. \en Angle from Chord. + IDS_ITEM_0262, ///< \ru Угол к касательной поверхности. \en Angle from Surface Tangent. + IDS_ITEM_0263, ///< \ru Угол к нормали поверхности. \en Angle from Surface Normal. // \ru Типы параметрических поверхностей. \en Types of parametric surfaces. @@ -346,11 +356,11 @@ enum MbePrompt IDS_ITEM_0651, ///< \ru Разрез тела. \en Solid Cutting. IDS_ITEM_0652, ///< \ru Сечение тела. \en Solid Section. - IDS_ITEM_0653, ///< \ru Размножение тела. \en Duplication of solids. + IDS_ITEM_0653, ///< \ru Копия объекта. \en Object copy. // \ru Вспомогательный объект. \en The helper object. - IDS_ITEM_0669, ///< \ru Вспомогательный объект. \en The helper object. + IDS_ITEM_0669, ///< \ru Вспомогательный объект. \en The Helper Object. // \ru Резьба. \en A thread. @@ -358,70 +368,70 @@ enum MbePrompt // \ru Обозначение \en Notation - IDS_ITEM_0671, ///< \ru Условное обозначение. \en Symbolic notation. + IDS_ITEM_0671, ///< \ru Условное обозначение. \en Symbolic Notation. // \ru Объекты. \en Objects. - IDS_ITEM_0700, ///< \ru Геометрический объект. \en Geometric object. - IDS_ITEM_0701, ///< \ru Переменная уравнения. \en Equation variable. - IDS_ITEM_0702, ///< \ru Объект на плоскости. \en Object on a plane. - IDS_ITEM_0703, ///< \ru Объект в пространстве. \en Object in space. - IDS_ITEM_0704, ///< \ru Объект модели. \en Model object. - IDS_ITEM_0705, ///< \ru Сборочная единица. \en Assembly unit. - IDS_ITEM_0706, ///< \ru Вспомогательный объект. \en Auxiliary object. - IDS_ITEM_0707, ///< \ru Вставка объекта. \en Object instance. - IDS_ITEM_0708, ///< \ru Количество элементов. \en Number of elements. - IDS_ITEM_0709, ///< \ru Геометрическая модель. \en Geometric model. + IDS_ITEM_0700, ///< \ru Геометрический объект. \en Geometric Object. + IDS_ITEM_0701, ///< \ru Переменная уравнения. \en Equation Variable. + IDS_ITEM_0702, ///< \ru Объект на плоскости. \en Object on a Plane. + IDS_ITEM_0703, ///< \ru Объект в пространстве. \en Object in Space. + IDS_ITEM_0704, ///< \ru Объект модели. \en Model Object. + IDS_ITEM_0705, ///< \ru Сборочная единица. \en Assembly Unit. + IDS_ITEM_0706, ///< \ru Вспомогательный объект. \en Auxiliary Object. + IDS_ITEM_0707, ///< \ru Вставка объекта. \en Object Instance. + IDS_ITEM_0708, ///< \ru Количество элементов. \en Number of Elements. + IDS_ITEM_0709, ///< \ru Геометрическая модель. \en Geometric Model. // \ru Атрибуты \en Attributes - IDS_ITEM_0729, ///< \ru Атрибуты модели. \en Model attributes. - IDS_ITEM_0730, ///< \ru Поставщик атрибутов. \en Attributes provider. - IDS_ITEM_0731, ///< \ru Атрибуты объекта. \en Object attributes. + IDS_ITEM_0729, ///< \ru Атрибуты модели. \en Model Attributes. + IDS_ITEM_0730, ///< \ru Поставщик атрибутов. \en Attributes Provider. + IDS_ITEM_0731, ///< \ru Атрибуты объекта. \en Object Attributes. IDS_ITEM_0732, ///< \ru Атрибут. \en Attribute. - IDS_ITEM_0733, ///< \ru Имя примитива. \en Primitive name. - IDS_ITEM_0734, ///< \ru Поведение атрибутов. \en Attributes behavior. + IDS_ITEM_0733, ///< \ru Имя примитива. \en Primitive Name. + IDS_ITEM_0734, ///< \ru Поведение атрибутов. \en Attributes Behavior. - IDS_ITEM_0751, ///< \ru Механические характеристики. \en Mechanical properties. + IDS_ITEM_0751, ///< \ru Механические характеристики. \en Mechanical Properties. IDS_ITEM_0754, ///< \ru Деформации. \en Strains. - IDS_ITEM_0761, ///< \ru Исполнение (вариант реализации модели). \en Embodiment (variant of model implementation). - IDS_ITEM_0762, ///< \ru Количество u-линий и v-линий отрисовочной сетки. \en The number of u-mesh and v-mesh lines. + IDS_ITEM_0761, ///< \ru Исполнение (вариант реализации модели). \en Embodiment (Variant of Model Implementation). + IDS_ITEM_0762, ///< \ru Количество u-линий и v-линий отрисовочной сетки. \en The Number of u-mesh and v-mesh Lines. IDS_ITEM_0763, ///< \ru Плотность. \en Density. IDS_ITEM_0764, ///< \ru Цвет. \en Color. IDS_ITEM_0765, ///< \ru Толщина. \en Thickness. IDS_ITEM_0766, ///< \ru Стиль. \en Style. - IDS_ITEM_0767, ///< \ru Визуальные свойства. \en Visual properties. + IDS_ITEM_0767, ///< \ru Визуальные свойства. \en Visual Properties. IDS_ITEM_0768, ///< \ru Идентификатор. \en Identifier. IDS_ITEM_0769, ///< \ru Селектированность. \en Selectivity. IDS_ITEM_0770, ///< \ru Видимость. \en Visibility. IDS_ITEM_0771, ///< \ru Измененность. \en Modification. - IDS_ITEM_0772, ///< \ru Топологическое имя. \en Topological name. + IDS_ITEM_0772, ///< \ru Топологическое имя. \en Topological Name. IDS_ITEM_0773, ///< \ru Якорь. \en Anchor. - IDS_ITEM_0774, ///< \ru Геометрический атрибут. \en Geometric attribute. - IDS_ITEM_0775, ///< \ru Метка времени обновления. \en Label of update time. - IDS_ITEM_0776, ///< \ru Уникальность ключей. \en Keys uniqueness. + IDS_ITEM_0774, ///< \ru Геометрический атрибут. \en Geometric Attribute. + IDS_ITEM_0775, ///< \ru Метка времени обновления. \en Label of Update Time. + IDS_ITEM_0776, ///< \ru Уникальность ключей. \en Keys Uniqueness. IDS_ITEM_0777, ///< \ru Имя объекта в модели. \en Name of object in the model. IDS_ITEM_0778, ///< \ru Данные об изделии. \en Product data. IDS_ITEM_0779, ///< \ru Атрибут ребра жесткости листового тела. \en Attribute of stamp rib of sheet solid. IDS_ITEM_0780, ///< \ru Атрибут отбортовки листового тела. \en Swept flange attribute of a sheet solid. - IDS_ITEM_0782, ///< \ru Атрибут пользовательский. \en Custom attribute. - IDS_ITEM_0783, ///< \ru Атрибут обобщенный. \en Generalized attribute. - IDS_ITEM_0784, ///< \ru Атрибут булев. \en Boolean attribute. - IDS_ITEM_0785, ///< \ru Атрибут целочисленный (32-битный). \en (32 bit ) Integer attribute. - IDS_ITEM_0786, ///< \ru Атрибут действительный. \en Real attribute. - IDS_ITEM_0787, ///< \ru Атрибут строковый. \en String attribute. - IDS_ITEM_0788, ///< \ru Атрибут элементарный. \en Elementary attribute. + IDS_ITEM_0782, ///< \ru Атрибут пользовательский. \en Custom Attribute. + IDS_ITEM_0783, ///< \ru Атрибут обобщенный. \en Generalized Attribute. + IDS_ITEM_0784, ///< \ru Атрибут булев. \en Boolean Attribute. + IDS_ITEM_0785, ///< \ru Атрибут целочисленный (32-битный). \en (32 bit ) Integer Attribute. + IDS_ITEM_0786, ///< \ru Атрибут действительный. \en Real Attribute. + IDS_ITEM_0787, ///< \ru Атрибут строковый. \en String Attribute. + IDS_ITEM_0788, ///< \ru Атрибут элементарный. \en Elementary Attribute. IDS_ITEM_0789, ///< \ru Пояснение. \en Prompt. - IDS_ITEM_0790, ///< \ru Атрибут int64. \en Int64 attribute. - IDS_ITEM_0791, ///< \ru Атрибут бинарный. \en Binary attribute. + IDS_ITEM_0790, ///< \ru Атрибут int64. \en Int64 Attribute. + IDS_ITEM_0791, ///< \ru Атрибут бинарный. \en Binary Attribute. // \ru Сообщения. \en Messages. IDS_ITEM_0900, ///< \ru ! Ошибка !. \en ! Error ! - IDS_ITEM_0901, ///< \ru Остановлено. \en Stopped. - IDS_ITEM_0902, ///< \ru Пропущено. \en Missed. + IDS_ITEM_0901, ///< \ru Остановлено. \en Stopped. + IDS_ITEM_0902, ///< \ru Пропущено. \en Missed. // \ru Состав объектов \en Structure of objects @@ -510,10 +520,10 @@ enum MbePrompt IDS_PROP_0152, ///< \ru Смещение зазора. \en Gap displacement. IDS_PROP_0153, ///< \ru Перемещение. \en Translation. IDS_PROP_0154, ///< \ru Вращение. \en Rotation. - IDS_PROP_0155, ///< \ru Общий масштаб. \en Common scale. + IDS_PROP_0155, ///< \ru Масштабирование. \en Scaling. IDS_PROP_0156, ///< \ru Зеркальность. \en Specularity. IDS_PROP_0157, ///< \ru Только ортогональность. \en Orthogonality only. - IDS_PROP_0158, ///< \ru Объект общего вида. \en General object. + IDS_PROP_0158, ///< \ru Трансформация. \en Transformation. IDS_PROP_0159, ///< \ru Перспектива. \en Perspective. IDS_PROP_0160, ///< \ru Локальная система координат. \en Local coordinate system. IDS_PROP_0161, ///< \ru Начальное значение. \en Start value. @@ -547,7 +557,10 @@ enum MbePrompt IDS_PROP_0188, ///< \ru Направление (вниз/вверх). \en Direction (down/up). IDS_PROP_0189, ///< \ru Радиус дуги. \en Arc radius. - IDS_PROP_0190, ///< \ru Функция дискриминанта. \en Discriminant function. + IDS_PROP_0190, ///< \ru Дискриминантная функция. \en Discriminant function. + IDS_PROP_0191, ///< \ru Дискриминантная скривая. \en Discriminant cueve. + IDS_PROP_0192, ///< \ru Дискриминантная поверхность. \en Discriminant surface. + IDS_PROP_0193, ///< \ru Дискриминантная оболочка. \en Discriminant shell. // \ru Параметры. \en Parameters. @@ -658,10 +671,10 @@ enum MbePrompt IDS_PROP_0328, ///< \ru Форма. \en Shape. IDS_PROP_0329, ///< \ru Закрепление границы поверхности. \en Surface boundary fixation. IDS_PROP_0330, ///< \ru Отличается от базовой поверхности. \en Differs from the base surface. - IDS_PROP_0331, ///< \ru Видимая длина Xmin. \en Visible length Xmin. - IDS_PROP_0332, ///< \ru Видимая длина Ymin. \en Visible length Ymin. - IDS_PROP_0333, ///< \ru Видимая длина Xmax. \en Visible length Xmax. - IDS_PROP_0334, ///< \ru Видимая длина Ymax. \en Visible length Ymax. + IDS_PROP_0331, ///< \ru Граничное значение Xmin. \en Boundary value Xmin. + IDS_PROP_0332, ///< \ru Граничное значение Ymin. \en Boundary value Ymin. + IDS_PROP_0333, ///< \ru Граничное значение Xmax. \en Boundary value Xmax. + IDS_PROP_0334, ///< \ru Граничное значение Ymax. \en Boundary value Ymax. IDS_PROP_0336, ///< \ru Число узлов по U. \en Number of knots by U. IDS_PROP_0337, ///< \ru Значение U узла. \en Value of U knot. IDS_PROP_0338, ///< \ru Число узлов по V. \en Number of knots by V. @@ -696,7 +709,7 @@ enum MbePrompt IDS_PROP_0370, ///< \ru Кривая на поверхности 0. \en Curve on surface 0. IDS_PROP_0371, ///< \ru Кривая на поверхности 1. \en Curve on surface 1. IDS_PROP_0372, ///< \ru Кривая на поверхности 2. \en Curve on surface 2. - IDS_PROP_0373, ///< \ru Кривая вершин. \en Curve of vertices. + IDS_PROP_0373, ///< \ru Кривая вершин. \en Apex Curve. IDS_PROP_0374, ///< \ru Параметр Umin. \en Parameter Umin. IDS_PROP_0375, ///< \ru Параметр Umax. \en Parameter Umax. IDS_PROP_0376, ///< \ru Параметр Vmin. \en Parameter Vmin. @@ -770,6 +783,7 @@ enum MbePrompt IDS_PROP_0517, ///< \ru Количество угловых шагов. \en Number of angular step. IDS_PROP_0518, ///< \ru Элемент. \en Element. IDS_PROP_0519, ///< \ru Сегмент полигональной сетки. \en Segment of polygonal mesh. + IDS_PROP_0520, ///< \ru Направляющая поверхность. \en Guide surface. IDS_PROP_0521, ///< \ru Длина Lx. \en Length Lx. IDS_PROP_0522, ///< \ru Ширина Ly. \en Width Ly. @@ -779,7 +793,7 @@ enum MbePrompt IDS_PROP_0526, ///< \ru Толщина стенки. \en Wall thickness. IDS_PROP_0527, ///< \ru Число вскрытых граней. \en Number of opened faces. IDS_PROP_0528, ///< \ru Форма. \en Shape. - IDS_PROP_0529, ///< \ru Сохранять кромку\поверхность\автоопределение. \en Keep the boundary\surface\auto. + IDS_PROP_0529, ///< \ru Сохранять кромку, поверхность или режим автоопределения. \en Keep the boundary, surface or auto mode. IDS_PROP_0530, ///< \ru Продолжить далее. \en Continue. IDS_PROP_0531, ///< \ru Катет 1. \en Cathetus 1. IDS_PROP_0532, ///< \ru Катет 2. \en Cathetus 2. @@ -870,7 +884,7 @@ enum MbePrompt IDS_PROP_0614, ///< \ru Номер по порядку. \en Number by and index. IDS_PROP_0615, ///< \ru Сортировка. \en Sorting. IDS_PROP_0616, ///< \ru Пуансон или матрица. \en Punch or die. - IDS_PROP_0617, ///< \ru Постоянность толщины штамповки. \en Stamp constant thickness. + IDS_PROP_0617, ///< \ru Скруглять острые ребра инструмента. \en Fillet sharp edges of tool solid. IDS_PROP_0651, ///< \ru Разрезанное тело. \en Cutting solid. IDS_PROP_0652, ///< \ru Плоскость раскроя. \en Cutting plane. IDS_PROP_0654, ///< \ru Наличие штриховки. \en Whether there is hatching. diff --git a/C3d/Include/mb_rough.h b/C3d/Include/mb_rough.h index 336d668..87b1d0f 100644 --- a/C3d/Include/mb_rough.h +++ b/C3d/Include/mb_rough.h @@ -62,7 +62,7 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA () const; - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); @@ -133,12 +133,12 @@ public: \{ */ virtual MbeSpaceType IsA () const; - virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = NULL ) const; + virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = c3d_null ) const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); - virtual void Transform ( const MbMatrix3D &, MbRegTransform * = NULL ); - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); + virtual void Transform ( const MbMatrix3D &, MbRegTransform * = c3d_null ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); virtual void GetProperties( MbProperties & ); virtual void SetProperties( const MbProperties & ); diff --git a/C3d/Include/mb_symbol.h b/C3d/Include/mb_symbol.h index 7e7f730..4846a28 100644 --- a/C3d/Include/mb_symbol.h +++ b/C3d/Include/mb_symbol.h @@ -123,13 +123,13 @@ public: \{ */ virtual MbeSpaceType IsA() const = 0; virtual MbeSpaceType Type() const; - virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = NULL ) const = 0; + virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = c3d_null ) const = 0; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; virtual bool IsSimilar ( const MbSpaceItem & ) const; virtual bool SetEqual ( const MbSpaceItem & ) = 0; - virtual void Transform ( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ) = 0; + virtual void Transform ( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ) = 0; virtual double DistanceToPoint ( const MbCartPoint3D & ) const; virtual void AddYourGabaritTo ( MbCube & ) const {}; virtual void CalculateMesh ( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; @@ -239,12 +239,12 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA () const; - virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = NULL ) const; + virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = c3d_null ) const; virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); - virtual void Transform ( const MbMatrix3D &, MbRegTransform * = NULL ); - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); + virtual void Transform ( const MbMatrix3D &, MbRegTransform * = c3d_null ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. diff --git a/C3d/Include/mb_thread.h b/C3d/Include/mb_thread.h index 0ac9375..7d6d709 100644 --- a/C3d/Include/mb_thread.h +++ b/C3d/Include/mb_thread.h @@ -284,13 +284,13 @@ public: \{ */ virtual MbeSpaceType IsA() const; virtual MbeSpaceType Type() const; - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; virtual bool IsSimilar ( const MbSpaceItem & ) const; virtual bool SetEqual( const MbSpaceItem & ); - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); virtual double DistanceToPoint ( const MbCartPoint3D & ) const; virtual void AddYourGabaritTo( MbCube & ) const; virtual void Refresh(); @@ -379,7 +379,7 @@ public : \return \ru true, если имя есть и оно не пустое. \en True if there is name and it is not empty. \~ */ - bool IsName() const { return ((name != NULL) ? name->IsEmpty() : false); } + bool IsName() const { return ((name != c3d_null) ? name->IsEmpty() : false); } /** \} */ /**\ru \name Функции работы с телами, на которых нарезана резьба. @@ -562,7 +562,7 @@ public : */ bool IsMatedTo( const MbThread & otherThread, const MbThreadedJointCheckParameters & checkParams, - ThreadedJointErrors * thrJointErrors = NULL ) const; + ThreadedJointErrors * thrJointErrors = c3d_null ) const; /// \ru Принадлежит ли резьба грани. \en Check if thread belongs to face. bool IsFaceThread( const MbFace *, const MbMatrix3D & ) const; @@ -583,8 +583,8 @@ public : \en True if thread belongs to one of solid faces. \~ */ bool IsBodyThread( const MbSolid & solid, const MbMatrix3D & matrix, - c3d::IndicesVector * simObjNumbers = NULL, - c3d::IndicesVector * intObjNumbers = NULL ) const; + c3d::IndicesVector * simObjNumbers = c3d_null, + c3d::IndicesVector * intObjNumbers = c3d_null ) const; /** \brief \ru Принадлежит ли резьба телу. \en Check if thread belongs to solid. \~ @@ -612,7 +612,7 @@ public : \return \ru true в случае успеха операции. \en True if the operation is successful. \~ */ - bool AdaptToBody( const MbSolid & solid, const MbMatrix3D & matrix, MbeThrAdapt thrAdapt, const ThreadLimiters * limiters = NULL ); + bool AdaptToBody( const MbSolid & solid, const MbMatrix3D & matrix, MbeThrAdapt thrAdapt, const ThreadLimiters * limiters = c3d_null ); /** \brief \ru Выдать начало и конец изменённой резьбы относительно исходной. \en Get limit positions of the modified thread in regard to an initial thread. \~ @@ -737,7 +737,7 @@ bool MbThread::FindThreadBodies( const SolidsVector & solids, const MatricesVect MbCube solidCube; for ( size_t i = 0; i < solidsCnt; ++i ) { const MbSolid * solid = solids[i]; - if ( solid != NULL && solid->GetShell() != NULL ) { + if ( solid != c3d_null && solid->GetShell() != c3d_null ) { solidCube.SetEmpty(); solid->AddYourGabaritTo( solidCube ); if ( cube.Intersect( solidCube ) && IsBodyThread( *solid, matrices[i] ) ) @@ -788,32 +788,32 @@ bool CheckThreads( ThreadsVector & threads, const MbPlacement3D * placeSec, bool for ( size_t i = threads.size(); i--; ) { MbThread * thr = threads[i]; - if ( (thr == C3D_NULL_PTR) || !thr->IsValid() ) { + if ( (thr == c3d_null) || !thr->IsValid() ) { threads.erase( threads.begin() + i ); - thr = C3D_NULL_PTR; + thr = c3d_null; } - else if ( checkThreadNames && (thr->GetName() == C3D_NULL_PTR) ) { // C3D-695 : KOMPAS-25125 + else if ( checkThreadNames && (thr->GetName() == c3d_null) ) { // C3D-695 : KOMPAS-25125 threads.erase( threads.begin() + i ); - thr = C3D_NULL_PTR; + thr = c3d_null; } else { if ( threads.size() > 1 ) { for ( ptrdiff_t j = i - 1; j >= 0; j-- ) { if ( thr == threads[j] ) { - threads[i] = C3D_NULL_PTR; + threads[i] = c3d_null; threads.erase( threads.begin() + i ); C3D_ASSERT_UNCONDITIONAL( false ); // Error case! - thr = C3D_NULL_PTR; + thr = c3d_null; break; } } } } - if ( thr != C3D_NULL_PTR ) // KOMPAS-37171 + if ( thr != c3d_null ) // KOMPAS-37171 thr->DetachWrongBodies(); } - if ( !threads.empty() && (placeSec != C3D_NULL_PTR) ) { + if ( !threads.empty() && (placeSec != c3d_null) ) { const MbVector3D & axisZsec = placeSec->GetAxisZ(); for ( size_t i = threads.size(); i--; ) { const MbThread * thr = threads[i]; diff --git a/C3d/Include/mb_variables.h b/C3d/Include/mb_variables.h index e7320d9..7d4fec9 100644 --- a/C3d/Include/mb_variables.h +++ b/C3d/Include/mb_variables.h @@ -243,6 +243,8 @@ c3d_constexpr uint8 MB_UNSET = 0x80; ///< \ru Битовые флаг class MATH_CLASS MbRefItem; class VersionContainer; +// \ru Управление реализацией переменных в Math. \en Managing variables implemenetation in Math. +#define USE_VAR_CLASSES //------------------------------------------------------------------------------ /** \brief \ru Общие статические данные алгоритмов и функций. @@ -270,22 +272,21 @@ public: /// unpredictable results when using parallel calculations. static void SetUserValue( int index, double value ); - +#ifdef USE_VAR_CLASSES //------------------------------------------------------------------------------ - // \ru Классы переменных, которые могут меняться с помощью функций SetVarValue(), RestoreVarValue() и SetDefaultValues(). + // \ru Классы переменных, значения которых могут меняться с помощью функций SetVarValue(), RestoreVarValue() и SetDefaultValues(). // \en Classes of variables which can be changed using SetVarValue(), RestoreVarValue() and SetDefaultValues() functions. //--- class MATH_CLASS DoubleVariable { protected: - size_t _id; - double * _value; + std::vector _values; ///< \ru Значения переменной для потоков. \en The variable values for threads. public: - DoubleVariable( double v ); + DoubleVariable( double value ); - const double & operator()() { return *_value; } - double operator()() const { return *_value; } - operator double() const { return *_value; } + const double & operator()() { if (_values.size() == 1 ) return _values[0]; return Get(); } + double operator()() const { if (_values.size() == 1 ) return _values[0]; return Get(); } + operator double() const { if (_values.size() == 1 ) return _values[0]; return Get(); } void SetVarValue( double val ); void RestoreVarValue(); @@ -296,19 +297,20 @@ public: DoubleVariable(); DoubleVariable & operator=( double v ); DoubleVariable & operator=( const DoubleVariable & v ); + const double & Get() const; + double & Get(); }; class MATH_CLASS SizeVariable { protected: - size_t _id; - size_t * _value; + std::vector _values; ///< \ru Значения переменной для потоков. \en The variable values for threads. public: - SizeVariable( size_t v ); + SizeVariable( size_t val ); - const size_t & operator()() { return *_value; } - size_t operator()() const { return *_value; } - operator size_t() const { return *_value; } + const size_t & operator()() { if ( _values.size() == 1 ) return _values[0]; return Get(); } + size_t operator()() const { if ( _values.size() == 1 ) return _values[0]; return Get(); } + operator size_t() const { if ( _values.size() == 1 ) return _values[0]; return Get(); } void SetVarValue( size_t val ); void RestoreVarValue(); @@ -319,6 +321,8 @@ public: SizeVariable(); SizeVariable & operator=( size_t v ); SizeVariable & operator=( const SizeVariable & v ); + const size_t & Get() const; + size_t & Get(); }; //------------------------------------------------------------------------------ @@ -329,7 +333,7 @@ public: { DoubleVariable _var; public: - GroupVariable( double v ) : _var( v ) {} + GroupVariable( double val ) : _var( val ) {} const double & operator()() { return _var(); } double operator()() const { return _var(); } @@ -340,14 +344,14 @@ public: protected: void SetVarValue( double val ) { _var.SetVarValue( val ); } + void RestoreVarValue(); private: GroupVariable(); GroupVariable & operator=( double v ); GroupVariable & operator=( const GroupVariable & v ); - void RestoreVarValue(); }; - +#endif //------------------------------------------------------------------------------ // \ru Константы. \en Constants. @@ -398,6 +402,7 @@ public: // \ru Изменяемые переменные. \en Controlled variables. //--- public: +#ifdef USE_VAR_CLASSES // \ru Изменяются только в группе с помощью функций SetUserValue() и SetDefaultValues(). // \en Can be changed only in a group using functions SetUserValue() and SetDefaultValues(). static GroupVariable LengthEps; ///< \ru Точность вычисления длины (PARAM_PRECISION). \en Length calculation tolerance (PARAM_PRECISION). @@ -424,7 +429,31 @@ public: static SizeVariable curveDegree; ///< \ru Порядок кривой (NURBS_DEGREE). \en Curve degree (NURBS_DEGREE). static SizeVariable uSurfaceDegree; ///< \ru Порядок поверхности по U. \en Surface degree by U. static SizeVariable vSurfaceDegree; ///< \ru Порядок поверхности по V. \en Surface degree by V. +#else + static double LengthEps; ///< \ru Точность вычисления длины (PARAM_PRECISION). \en Length calculation tolerance (PARAM_PRECISION). + static double AngleEps; ///< \ru Точность вычисления угла. \en Angular tolerance. + static double NewtonEps; ///< \ru Точность численного решения уравнений. \en Tolerance of numerical solution of equation. + static double NewtonReg; ///< \ru Точность проверки решения уравнений. \en Solution of equation checking tolerance. + + static double paramEpsilon; ///< \ru Точность параметра кривой. \en Curve parameter tolerance. + static double paramRegion; ///< \ru Точность проверки параметра кривой. \en Curve parameter checking tolerance. + static double paramPrecision; ///< \ru Параметрическая погрешность. \en Parametric tolerance. + static double paramAccuracy; ///< \ru Наибольшая параметрическая погрешность. \en The largest parametric tolerance. + static double paramNear; ///< \ru Параметрическая близость. \en Parametric proximity. + + static double lowRenderAng; ///< \ru Угол для минимального количества отображаемых сегментов. \en Angle for minimum mapping segments count. + static double higRenderAng; ///< \ru Угол для максимального количества отображаемых сегментов. \en Angle for maximum mapping segments count. + + static double deviateSag; ///< \ru Угловая толерантность. \en Angular tolerance. + static double visualSag; ///< \ru Величина стрелки прогиба для визуализации. \en Value of sag for visualization. + + static size_t newtonCount; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. + static size_t newtonLimit; ///< \ru Количество итераций решения системы уравнений методом Newton. \en Iterations count for solving system of equations by Newton method. + static size_t curveDegree; ///< \ru Порядок кривой (NURBS_DEGREE). \en Curve degree (NURBS_DEGREE). + static size_t uSurfaceDegree; ///< \ru Порядок поверхности по U. \en Surface degree by U. + static size_t vSurfaceDegree; ///< \ru Порядок поверхности по V. \en Surface degree by V. +#endif //------------------------------------------------------------------------------ // \ru Временные переменные. \en Temporary variables. @@ -547,6 +576,29 @@ public: }; // Math +#ifndef USE_VAR_CLASSES + +#define LengthEps() LengthEps +#define deviateSag() deviateSag +#define AngleEps() AngleEps +#define paramRegion() paramRegion +#define paramEpsilon() paramEpsilon +#define NewtonEps() NewtonEps +#define NewtonReg() NewtonReg +#define paramPrecision() paramPrecision +#define paramAccuracy() paramAccuracy +#define paramNear() paramNear +#define lowRenderAng() lowRenderAng +#define higRenderAng() higRenderAng +#define deviateSag() deviateSag +#define visualSag() visualSag +#define newtonCount() newtonCount +#define newtonLimit() newtonLimit +#define curveDegree() curveDegree +#define uSurfaceDegree() uSurfaceDegree +#define vSurfaceDegree() vSurfaceDegree + +#endif //------------------------------------------------------------------------------ // Оставить от пути только имя файла. @@ -567,7 +619,7 @@ MATH_FUNC(const char *) C3DFileNameOnly( const char * path ); #ifdef C3D_DEBUG #define C3D_ASSERT_UNCONDITIONAL(expr) \ - { const c3d::eAssertViolationNotify notify = Math::CheckAssertNotify(); \ + { const c3d::eAssertViolationNotify notify = ::Math::CheckAssertNotify(); \ if ( c3d::avn_ASSERT == notify ) { _ASSERT(false); } \ else if ( c3d::avn_CERR == notify ) { C3D_ASSERT_AS_CERR(expr) } \ } @@ -594,8 +646,8 @@ extern "C" \en Pointer to the beginning of the buffer. \~ \param[in] bufferSize - \ru Размер буфера, в символах. \en The size of the buffer in characters. \~ - \return \ru Возвращает количество скопированных символов, без учета null-символа. Если buffer == nullptr возвращается необходимый размер буфера без учета null-символа. - \en Returns the number of copied characters, excluding the null character. If buffer = = null ptr returns the required buffer size without the null character. \~ + \return \ru Возвращает количество скопированных символов, без учета null-символа. Если buffer == c3d_null возвращается необходимый размер буфера без учета null-символа. + \en Returns the number of copied characters, excluding the null character. If buffer = = c3d_null returns the required buffer size without the null character. \~ */ extern MATH_FUNC(size_t) GetC3dVersionInfo( char * const buffer, size_t bufferSize ); ///< \ru Информация о версии c3d.dll \en c3d.dll version information @@ -608,8 +660,8 @@ extern "C" \en Pointer to the beginning of the buffer. \~ \param[in] bufferSize - \ru Размер буфера, в символах. \en The size of the buffer in characters. \~ - \return \ru Возвращает количество скопированных символов, без учета null-символа. Если buffer == nullptr возвращается необходимый размер буфера без учета null-символа. - \en Returns the number of copied characters, excluding the null character. If buffer = = null ptr returns the required buffer size without the null character. \~ + \return \ru Возвращает количество скопированных символов, без учета null-символа. Если buffer == c3d_null возвращается необходимый размер буфера без учета null-символа. + \en Returns the number of copied characters, excluding the null character. If buffer = = c3d_null returns the required buffer size without the null character. \~ */ extern MATH_FUNC(size_t) GetC3dBuildInfo( char * const buffer, size_t bufferSize ); ///< \ru Информация о сборке c3d.dll \en c3d.dll building information @@ -630,7 +682,7 @@ inline std::string GetC3dLibInfo( bool needVersionInfo = true ) size_t( *GetLibInfo )( char * const buffer, size_t bufferSize ); GetLibInfo = ( needVersionInfo ) ? GetC3dVersionInfo : GetC3dBuildInfo; - std::vector buffer( GetLibInfo( C3D_NULL_PTR, 1 ) ); + std::vector buffer( GetLibInfo( c3d_null, 1 ) ); GetLibInfo( &buffer[0], buffer.size() ); diff --git a/C3d/Include/mesh.h b/C3d/Include/mesh.h index e1bf88f..9020c54 100644 --- a/C3d/Include/mesh.h +++ b/C3d/Include/mesh.h @@ -112,10 +112,10 @@ public: // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en Type of the object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равным. \en Make equal objects. virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. @@ -181,7 +181,7 @@ public: gridsVector.reserve( gridsVector.size() + grids.size() ); for( size_t i = 0, iCount = grids.size(); i < iCount; ++i ) { MbGrid * gr = grids[i]; - if ( gr != NULL ) { + if ( gr != c3d_null ) { gr->DecRef(); gridsVector.push_back( gr ); } @@ -193,9 +193,9 @@ public: cube.SetEmpty(); } /// \ru Вернуть указатель на триангуляцию по её номеру. \en Return pointer to triangulation by it number. - const MbGrid * GetGrid( size_t i ) const { return ( (i < grids.size()) ? grids[i]: NULL ); } + const MbGrid * GetGrid( size_t i ) const { return ( (i < grids.size()) ? grids[i]: c3d_null ); } /// \ru Вернуть указатель на триангуляцию по её номеру для модификации. \en Return the pointer to triangulation by its number to be modified. - MbGrid * SetGrid( size_t i ) { return ( (i < grids.size()) ? grids[i]: NULL ); } + MbGrid * SetGrid( size_t i ) { return ( (i < grids.size()) ? grids[i]: c3d_null ); } /// \ru Получить указатели на триангуляции. \en Get pointers to triangulations. template void GetGrids( GridsVector & gridsVector ) const { @@ -220,7 +220,7 @@ public: polyVector.reserve( polyVector.size() + wires.size() ); for( size_t i = 0, iCount = wires.size(); i < iCount; ++i ) { MbPolygon3D * pl = wires[i]; - if ( pl != NULL ) { + if ( pl != c3d_null ) { pl->DecRef(); polyVector.push_back( pl ); } @@ -232,9 +232,9 @@ public: cube.SetEmpty(); } /// \ru Вернуть указатель на полигон по его номеру. \en Return the pointer to polygon by its number. - const MbPolygon3D * GetPolygon( size_t i ) const { return ( (i < wires.size()) ? wires[i]: NULL ); } + const MbPolygon3D * GetPolygon( size_t i ) const { return ( (i < wires.size()) ? wires[i]: c3d_null ); } /// \ru Вернуть указатель на полигон по его номеру. \en Return the pointer to polygon by its number. - MbPolygon3D * SetPolygon( size_t i ) { return ( (i < wires.size()) ? wires[i]: NULL ); } + MbPolygon3D * SetPolygon( size_t i ) { return ( (i < wires.size()) ? wires[i]: c3d_null ); } /// \ru Получить указатели на полигоны. \en Get pointers to polygons. template void GetPolygons( PolygonsVector & polyVector ) const { @@ -259,7 +259,7 @@ public: peakVector.reserve( peakVector.size() + peaks.size() ); for( size_t i = 0, iCount = peaks.size(); i < iCount; ++i ) { MbApex3D * peak = peaks[i]; - if ( peak != NULL ) { + if ( peak != c3d_null ) { peak->DecRef(); peakVector.push_back( peak ); } @@ -271,9 +271,9 @@ public: cube.SetEmpty(); } /// \ru Вернуть указатель на апекс по его номеру. \en Return the pointer to apex by its number. - const MbApex3D * GetApex( size_t i ) const { return ( (i < peaks.size()) ? peaks[i]: NULL ); } + const MbApex3D * GetApex( size_t i ) const { return ( (i < peaks.size()) ? peaks[i]: c3d_null ); } /// \ru Вернуть указатель на апекс по его номеру для модификации. \en Return the pointer to apex by its number to be modified. - MbApex3D * SetApex( size_t i ) { return ( (i < peaks.size()) ? peaks[i]: NULL ); } + MbApex3D * SetApex( size_t i ) { return ( (i < peaks.size()) ? peaks[i]: c3d_null ); } /// \ru Получить указатели на вершины. \en Get pointers to apexes. template void GetApexes( ApexesVector & peakVector ) const { @@ -294,14 +294,14 @@ public: bool AddMesh( const MbMesh &, bool checkSamePointers ); /// \ru Получить пространственный объект, для которого построен полигональный объект. \en Get a spatial object for which a polygonal object is constructed. - const MbSpaceItem * SpaceItem() const { return ((item != NULL && item->RefType() == rt_SpaceItem) ? (const MbSpaceItem *)item : NULL); } + const MbSpaceItem * SpaceItem() const { return ((item != c3d_null && item->RefType() == rt_SpaceItem) ? (const MbSpaceItem *)item : c3d_null); } /// \ru Получить двумерный объект, для которого построен полигональный объект. \en Get a two-dimensional object for which a polygonal object is constructed. - const MbPlaneItem * PlaneItem() const { return ((item != NULL && item->RefType() == rt_PlaneItem) ? (const MbPlaneItem *)item : NULL); } + const MbPlaneItem * PlaneItem() const { return ((item != c3d_null && item->RefType() == rt_PlaneItem) ? (const MbPlaneItem *)item : c3d_null); } /// \ru Получить объект геометрической модели, для которого построен полигональный объект. \en Get a model geometric object for which a polygonal object is constructed. const MbItem * Item() const { - const MbItem * modelItem = NULL; - if ( item != NULL ) { + const MbItem * modelItem = c3d_null; + if ( item != c3d_null ) { MbeRefType refType = item->RefType(); if ( refType == rt_SpaceItem ) { if ( static_cast(item)->Family() == st_Item ) diff --git a/C3d/Include/mesh_grid.h b/C3d/Include/mesh_grid.h index 0f3d9e1..7c9da46 100644 --- a/C3d/Include/mesh_grid.h +++ b/C3d/Include/mesh_grid.h @@ -57,7 +57,7 @@ public: // \ru \name Общие функции примитива. \en \name Common functions of primitive. virtual MbePrimitiveType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbExactGrid & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbExactGrid & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ); // \ru Преобразовать сетку согласно матрице. \en Transform mesh according to the matrix. virtual void Move ( const MbVector3D & to ); // \ru Сдвиг сетки. \en Move mesh. virtual void Rotate ( const MbAxis3D & axis, double angle ); // \ru Поворот сетки вокруг оси. \en Rotation of mesh about an axis. @@ -321,11 +321,11 @@ public: /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. virtual const MbCartPoint * GetExactParamsAddr() const { return &(params[0]); } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbFloatPoint3D * GetFloatPointsAddr() const { return NULL; } + virtual const MbFloatPoint3D * GetFloatPointsAddr() const { return c3d_null; } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbFloatVector3D * GetFloatNormalsAddr() const { return NULL; } + virtual const MbFloatVector3D * GetFloatNormalsAddr() const { return c3d_null; } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbFloatPoint * GetFloatParamsAddr() const { return NULL; } + virtual const MbFloatPoint * GetFloatParamsAddr() const { return c3d_null; } private : // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. @@ -371,7 +371,7 @@ public: // \ru \name Общие функции примитива. \en \name Common functions of primitive. virtual MbePrimitiveType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbFloatGrid & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbFloatGrid & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ); // \ru Преобразовать сетку согласно матрице. \en Transform mesh according to the matrix. virtual void Move ( const MbVector3D & to ); // \ru Сдвиг сетки. \en Move mesh. virtual void Rotate ( const MbAxis3D & axis, double angle ); // \ru Поворот сетки вокруг оси. \en Rotation of mesh about an axis. @@ -629,11 +629,11 @@ public: virtual void Init( const MbGrid & grid ); /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbCartPoint3D * GetExactPointsAddr() const { return NULL; } + virtual const MbCartPoint3D * GetExactPointsAddr() const { return c3d_null; } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbVector3D * GetExactNormalsAddr() const { return NULL; } + virtual const MbVector3D * GetExactNormalsAddr() const { return c3d_null; } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - virtual const MbCartPoint * GetExactParamsAddr() const { return NULL; } + virtual const MbCartPoint * GetExactParamsAddr() const { return c3d_null; } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. virtual const MbFloatPoint3D * GetFloatPointsAddr() const { return &(points[0]); } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. diff --git a/C3d/Include/mesh_plane_grid.h b/C3d/Include/mesh_plane_grid.h index 10328c4..190f256 100644 --- a/C3d/Include/mesh_plane_grid.h +++ b/C3d/Include/mesh_plane_grid.h @@ -215,7 +215,7 @@ private: intptr_t size; ///< \ru Количество вершин. \en Count of vertices. public: - TriPoly() : vertex( NULL ), size( 0 ) {} + TriPoly() : vertex( c3d_null ), size( 0 ) {} TriPoly( TriVertex * vert ) : vertex( vert ), size( 0 ) { Resize(); } public: @@ -223,7 +223,7 @@ public: public: intptr_t Size() const { return size; } ///< \ru Размер цепочки вершин \en Size of vertex chain - size_t Index() const { return (vertex != NULL) ? vertex->Index() : SYS_MAX_T; } ///< \ru Индекс вершины \en Index of vertex + size_t Index() const { return (vertex != c3d_null) ? vertex->Index() : SYS_MAX_T; } ///< \ru Индекс вершины \en Index of vertex TriVertex * This() const { return vertex; } ///< \ru Текущая вершина \en Current vertex TriVertex * Next() const; ///< \ru Следующая вершина \en Next vertex @@ -301,7 +301,7 @@ protected: // \ru 2 - смедный через ребра на вершинах 2,0 \en 2 - adjacent at edge with vertices 2,0 public: - MbLinkedTri() : MbTri() { neighbors[0] = neighbors[1] = neighbors[2] = NULL; }; + MbLinkedTri() : MbTri() { neighbors[0] = neighbors[1] = neighbors[2] = c3d_null; }; ~MbLinkedTri() {}; public: MbTri * GetNeighbor( size_t n ) const { return neighbors[n % 3]; } @@ -317,9 +317,9 @@ OBVIOUS_PRIVATE_COPY( MbLinkedTri ) // --- inline bool MbLinkedTri::IsBoundary() const { - bool isBoundary = (neighbors[0] == NULL) || - (neighbors[1] == NULL) || - (neighbors[2] == NULL); + bool isBoundary = (neighbors[0] == c3d_null) || + (neighbors[1] == c3d_null) || + (neighbors[2] == c3d_null); return isBoundary; } // */ diff --git a/C3d/Include/mesh_polygon.h b/C3d/Include/mesh_polygon.h index 915bfcc..0cbafd6 100644 --- a/C3d/Include/mesh_polygon.h +++ b/C3d/Include/mesh_polygon.h @@ -51,7 +51,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType IsA() const; // \ru Вернуть тип объекта \en Get the object type. - virtual MbExactPolygon3D & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта \en Create a copy of the object + virtual MbExactPolygon3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта \en Create a copy of the object virtual void Transform( const MbMatrix3D & ); // \ru Преобразовать полигон согласно матрице \en Transform polygon according to the matrix virtual void Move ( const MbVector3D & ); // \ru Сдвиг полигона \en Translation of the polygon. virtual void Rotate ( const MbAxis3D &, double angle ); // \ru Поворот полигона вокруг оси \en Rotation of the polygon around an axis @@ -177,7 +177,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType IsA() const; // \ru Вернуть тип объекта \en Get the object type. - virtual MbFloatPolygon3D & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта \en Create a copy of the object + virtual MbFloatPolygon3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта \en Create a copy of the object virtual void Transform( const MbMatrix3D & ); // \ru Преобразовать полигон согласно матрице \en Transform polygon according to the matrix virtual void Move ( const MbVector3D & ); // \ru Сдвиг полигона \en Translation of the polygon. virtual void Rotate ( const MbAxis3D &, double angle ); // \ru Поворот полигона вокруг оси \en Rotation of the polygon around an axis diff --git a/C3d/Include/mesh_primitive.h b/C3d/Include/mesh_primitive.h index 2dfc6f2..31fdd9f 100644 --- a/C3d/Include/mesh_primitive.h +++ b/C3d/Include/mesh_primitive.h @@ -29,6 +29,7 @@ class MATH_CLASS MbPolygon3D; class MATH_CLASS MbPolygon; class MATH_CLASS MbFloatAxis3D; class MATH_CLASS MbFloatPoint3D; +class MATH_CLASS MbGrid; namespace c3d // namespace C3D @@ -36,6 +37,9 @@ namespace c3d // namespace C3D typedef SPtr PrimitiveSPtr; typedef SPtr ConstPrimitiveSPtr; +typedef SPtr GridSPtr; +typedef SPtr ConstGridSPtr; + typedef std::vector PrimitivesVector; typedef std::vector ConstPrimitivesVector; @@ -51,6 +55,12 @@ typedef std::set ConstPrimitivesSet; typedef ConstPrimitivesSet::iterator ConstPrimitivesSetIt; typedef ConstPrimitivesSet::const_iterator ConstPrimitivesSetConstIt; typedef std::pair ConstPrimitivesSetRet; + +typedef std::vector GridsVector; +typedef std::vector ConstGridsVector; + +typedef std::vector GridsSPtrVector; +typedef std::vector ConstGridsSPtrVector; } @@ -138,7 +148,7 @@ public: \return \ru Копия объекта. \en The object copy. \~ */ - virtual MbPrimitive & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; + virtual MbPrimitive & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; /** \brief \ru Преобразовать примитив согласно матрице. \en Transform primitive according to the matrix. \~ @@ -235,13 +245,13 @@ public: bool NearestType( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType ) const; /// \ru Получить пространственный объект, для которого построен примитив. \en Get spatial object for which the primitive is constructed. - const MbSpaceItem * SpaceItem() const { return ((parentItem != NULL && parentItem->RefType() == rt_SpaceItem) ? (const MbSpaceItem *)parentItem : NULL); } + const MbSpaceItem * SpaceItem() const { return ((parentItem != c3d_null && parentItem->RefType() == rt_SpaceItem) ? (const MbSpaceItem *)parentItem : c3d_null); } /// \ru Получить двумерный объект, для которого построен примитив. \en Get two-dimensional object for which the primitive is constructed. - const MbPlaneItem * PlaneItem() const { return ((parentItem != NULL && parentItem->RefType() == rt_PlaneItem) ? (const MbPlaneItem *)parentItem : NULL); } + const MbPlaneItem * PlaneItem() const { return ((parentItem != c3d_null && parentItem->RefType() == rt_PlaneItem) ? (const MbPlaneItem *)parentItem : c3d_null); } /// \ru Получить топологический объект, для которого построен примитив. \en Get the topological object for which the primitive is constructed. - const MbTopItem * TopItem() const { return ((parentItem != NULL && parentItem->RefType() == rt_TopItem) ? (const MbTopItem *)parentItem : NULL); } + const MbTopItem * TopItem() const { return ((parentItem != c3d_null && parentItem->RefType() == rt_TopItem) ? (const MbTopItem *)parentItem : c3d_null); } /// \ru Получить объект геометрической модели, для которого построен примитив. \en Get geometric model object for which the primitive is constructed. - const MbItem * Item() const { return ((parentItem != NULL && parentItem->RefType() == rt_SpaceItem) ? (static_cast(parentItem)) : NULL); } + const MbItem * Item() const { return ((parentItem != c3d_null && parentItem->RefType() == rt_SpaceItem) ? (static_cast(parentItem)) : c3d_null); } /// \ru Чтение примитива из потока. \en Reading of primitive from the stream. void PrimitiveRead ( reader & in ); @@ -280,7 +290,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType Type() const; // \ru Тип объекта. \en A type of an object. virtual MbePrimitiveType IsA() const = 0; // \ru Тип объекта. \en A type of an object. - virtual MbApex3D & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbApex3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. virtual void Move ( const MbVector3D & to ) = 0; // \ru Сдвинуть вдоль вектора. \en Translate along a vector. virtual void Rotate ( const MbAxis3D & axis, double angle ) = 0; // \ru Повернуть вокруг оси на угол. \en Rotate about an axis by an angle. @@ -345,7 +355,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbExactApex3D & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbExactApex3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. virtual void Move ( const MbVector3D & to ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. virtual void Rotate ( const MbAxis3D & axis, double angle ); // \ru Повернуть вокруг оси на угол. \en Rotate about an axis by an angle. @@ -411,7 +421,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbFloatApex3D & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbFloatApex3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. virtual void Move ( const MbVector3D & to ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. virtual void Rotate ( const MbAxis3D & axis, double angle ); // \ru Повернуть вокруг оси на угол. \en Rotate about an axis by an angle. @@ -482,7 +492,7 @@ public: // \ru Общие функции примитива. \en Common functions of the primitive. virtual MbePrimitiveType Type() const; // \ru Вернуть тип объекта \en Get the object type. virtual MbePrimitiveType IsA() const = 0; // \ru Вернуть тип объекта \en Get the object type. - virtual MbPolygon3D & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; // \ru Создать копию объекта \en Create a copy of the object + virtual MbPolygon3D & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; // \ru Создать копию объекта \en Create a copy of the object virtual void Transform( const MbMatrix3D & ) = 0; // \ru Преобразовать полигон согласно матрице \en Transform polygon according to the matrix virtual void Move ( const MbVector3D & ) = 0; // \ru Сдвиг полигона \en Translation of the polygon. virtual void Rotate ( const MbAxis3D &, double angle ) = 0; // \ru Поворот полигона вокруг оси \en Rotation of the polygon around an axis @@ -660,7 +670,7 @@ public: \{ */ virtual MbePrimitiveType Type() const; // \ru Тип объекта. \en A type of an object. virtual MbePrimitiveType IsA() const = 0;; // \ru Тип объекта. \en A type of an object. - virtual MbGrid & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; // \ru Создать копию объекта. \en Create a copy of the object. + virtual MbGrid & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; // \ru Создать копию объекта. \en Create a copy of the object. virtual void Transform( const MbMatrix3D & matr ) = 0; // \ru Преобразовать сетку согласно матрице. \en Transform mesh according to the matrix. virtual void Move ( const MbVector3D & to ) = 0; // \ru Сдвиг сетки. \en Move mesh. virtual void Rotate ( const MbAxis3D & axis, double angle ) = 0; // \ru Поворот сетки вокруг оси. \en Rotation of mesh about an axis. @@ -999,9 +1009,9 @@ public: virtual void Init( const MbGrid & grid ) = 0; /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - const MbTriangle * GetTrianglesAddr() const { return (!triangles.empty() ? &(triangles[0]) : NULL); } + const MbTriangle * GetTrianglesAddr() const { return (!triangles.empty() ? &(triangles[0]) : c3d_null); } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - const MbQuadrangle * GetQuadranglesAddr() const { return (!quadrangles.empty() ? &(quadrangles[0]) : NULL); } + const MbQuadrangle * GetQuadranglesAddr() const { return (!quadrangles.empty() ? &(quadrangles[0]) : c3d_null); } /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. virtual const MbCartPoint3D * GetExactPointsAddr() const = 0; /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. diff --git a/C3d/Include/mip_curve_properties.h b/C3d/Include/mip_curve_properties.h index c7dded8..d6a3bad 100644 --- a/C3d/Include/mip_curve_properties.h +++ b/C3d/Include/mip_curve_properties.h @@ -113,9 +113,9 @@ inline void MIProperties::Init() { \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const MbCurve * curve, - MIProperties & mp, - double deviateAngle = Math::deviateSag ); +MATH_FUNC (void) MassInertiaProperties( const MbCurve * curve, + MIProperties & mp, + double deviateAngle = Math::deviateSag ); //------------------------------------------------------------------------------ @@ -141,9 +141,9 @@ MATH_FUNC (void) MassInertiaProperties( const MbCurve * curve, */ // --- MATH_FUNC (void) MassInertiaProperties( const RPArray & curves, - const SArray & bodies, - MIProperties & mp, - double deviateAngle = Math::deviateSag ); + const c3d::BoolVector & bodies, + MIProperties & mp, + double deviateAngle = Math::deviateSag ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/mip_solid_mass_inertia.h b/C3d/Include/mip_solid_mass_inertia.h index 881f1a9..f1b360a 100644 --- a/C3d/Include/mip_solid_mass_inertia.h +++ b/C3d/Include/mip_solid_mass_inertia.h @@ -332,7 +332,7 @@ private : const MbSolid & solid; ///< \ru Тело. \en A solid. double density; ///< \ru Плотность или удельная масса на единицу площади. \en Density or mass per unit square. MbMatrix3D matrix; ///< \ru Матрица преобразования тела в систему ближайшей сборки (хозяина). \en A matrix of solid transformation to the coordinate system of nearest assembly (owner). - InertiaProperties * properties; ///< \ru Характеристики тела (может быть NULL). \en Solid properties (can be NULL). + InertiaProperties * properties; ///< \ru Характеристики тела (может быть c3d_null). \en Solid properties (can be c3d_null). bool ready; ///< \ru Флаг, показывающий, что характеристики не требуется считать. \en Flag of already calculated properties. public: @@ -395,7 +395,7 @@ public: \en A run progress indicator. For termination of slow computations. \~ */ void CalculateAdditiveValues( double deviateAngle, InertiaProperties & mp, - IfProgressIndicator * progress = NULL ) const; + IfProgressIndicator * progress = c3d_null ) const; /** \} */ // \ru Объявление конструктора копирования и оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration without Implementation of the copy constructor and assignment operator to prevent an assignment by default. @@ -416,7 +416,7 @@ private : RPArray assemblies; ///< \ru Подсборки. \en Subassemblies. RPArray solids; ///< \ru Тела сборки. \en Solids in an assembly. MbMatrix3D matrix; ///< \ru Матрица преобразования сборки в систему ближайшей сборки (хозяина). \en A matrix of assembly transformation to the coordinate system of nearest assembly (owner). - InertiaProperties * properties; ///< \ru Характеристики сборки (может быть NULL). \en Assembly properties (can be NULL). + InertiaProperties * properties; ///< \ru Характеристики сборки (может быть c3d_null). \en Assembly properties (can be c3d_null). bool ready; ///< \ru Характеристики не требуется считать. \en Properties already calculated. public: @@ -488,7 +488,7 @@ public: \en A run progress indicator. For termination of slow computations. \~ */ void CalculateAdditiveValues( double deviateAngle, InertiaProperties & mp, - IfProgressIndicator * progress = NULL ) const; + IfProgressIndicator * progress = c3d_null ) const; /** \} */ // \ru Объявление конструктора копирования и оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration without Implementation of the copy constructor and assignment operator to prevent an assignment by default. @@ -516,11 +516,11 @@ public: \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const MbSolid * solid, - double density, - double deviateAngle, // (0.35 - 0.01) - InertiaProperties & mp, - IfProgressIndicator * progress = NULL ); +MATH_FUNC (void) MassInertiaProperties( const MbSolid * solid, + double density, + double deviateAngle, // (0.35 - 0.01) + InertiaProperties & mp, + IfProgressIndicator * progress = c3d_null ); //------------------------------------------------------------------------------ @@ -540,9 +540,9 @@ MATH_FUNC (void) MassInertiaProperties( const MbSolid * solid, Количество элементов в массиве должно совпадать с количеством тел. \en Matrices of solids transformation to global coordinate system.\n Count of elements in array must be equal to count of solids. \~ - \param[in] mpSolids - \ru Имеющиеся характеристики тел. Может содержать NULL.\n + \param[in] mpSolids - \ru Имеющиеся характеристики тел. Может содержать c3d_null.\n Количество элементов в массиве должно совпадать с количеством тел. - \en Calculated properties of solids. Can contain NULL.\n + \en Calculated properties of solids. Can contain c3d_null.\n Count of elements in array must be equal to count of solids. \~ \param[in] deviateAngle - \ru Параметр управления точностью расчёта - угловое отклонение нормали поверхности или касательных кривой на участке численного интегрирования. \en Tolerance - the angular deviation of surface or curve in the neighboring points on the region of numerical integration. \~ @@ -553,13 +553,13 @@ MATH_FUNC (void) MassInertiaProperties( const MbSolid * solid, \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const RPArray & solids, - const SArray & densities, - const SArray & matrs, +MATH_FUNC (void) MassInertiaProperties( const RPArray & solids, + const SArray & densities, + const SArray & matrs, const RPArray & mpSolids, - double deviateAngle, // (0.35 - 0.01) - InertiaProperties & mp, - IfProgressIndicator * progress = NULL ); + double deviateAngle, // (0.35 - 0.01) + InertiaProperties & mp, + IfProgressIndicator * progress = c3d_null ); //------------------------------------------------------------------------------ @@ -580,10 +580,10 @@ MATH_FUNC (void) MassInertiaProperties( const RPArray & solids, \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const AssemblyMIAttire & assembly, - double deviateAngle, // (0.35 - 0.01) - InertiaProperties & mp, - IfProgressIndicator * progress = NULL ); +MATH_FUNC (void) MassInertiaProperties( const AssemblyMIAttire & assembly, + double deviateAngle, // (0.35 - 0.01) + InertiaProperties & mp, + IfProgressIndicator * progress = c3d_null ); //------------------------------------------------------------------------------ @@ -593,7 +593,7 @@ MATH_FUNC (void) MassInertiaProperties( const AssemblyMIAttire & assembly, \en Calculation mass-inertial properties of polygonal object. \~ \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ - \param[in] solid - \ru Полигональный объект. + \param[in] mesh - \ru Полигональный объект. \en A polygonal object. \~ \param[in] density - \ru Плотность или удельная масса на единицу площади. \en Density or mass per unit square. \~ @@ -602,9 +602,9 @@ MATH_FUNC (void) MassInertiaProperties( const AssemblyMIAttire & assembly, \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const MbMesh * mesh, - double density, - InertiaProperties & mp ); +MATH_FUNC (void) MassInertiaProperties( const MbMesh * mesh, + double density, + InertiaProperties & mp ); //------------------------------------------------------------------------------ @@ -614,13 +614,13 @@ MATH_FUNC (void) MassInertiaProperties( const MbMesh * mesh, \en Calculation of mass-inertial properties of polygonal objects. \~ \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ - \param[in] solids - \ru Множество полигональных объектов. + \param[in] meshes - \ru Множество полигональных объектов. \en Set of polygonal objects. \~ \param[in] densities - \ru Плотности объектов или удельная масса на единицу площади.\n Количество элементов в массиве должно совпадать с количеством объектов. \en Density of solids or mass per unit square of polygonal objects.\n Count of elements in array must be equal to count of polygonal objects. \~ - \param[in] matrs - \ru Матрицы преобразования полигональных объектов в глобальную систему координат.\n + \param[in] matrices - \ru Матрицы преобразования полигональных объектов в глобальную систему координат.\n Количество элементов в массиве должно совпадать с количеством объектов. \en Matrices of solids transformation to global coordinate system.\n Count of elements in array must be equal to count of polygonal objects. \~ @@ -629,10 +629,10 @@ MATH_FUNC (void) MassInertiaProperties( const MbMesh * mesh, \ingroup Inertia_Computation */ // --- -MATH_FUNC (void) MassInertiaProperties( const std::vector & solids, - const std::vector & densities, - const std::vector & matrix, - InertiaProperties & mp ); +MATH_FUNC (void) MassInertiaProperties( const std::vector & meshes, + const std::vector & densities, + const std::vector & matrices, + InertiaProperties & mp ); #endif // __MIP_SOLID_MASS_INERTIA_H diff --git a/C3d/Include/model.h b/C3d/Include/model.h index 32062f1..655ef74 100644 --- a/C3d/Include/model.h +++ b/C3d/Include/model.h @@ -83,13 +83,13 @@ public : virtual MbeImplicationType ImplicationType() const; /// \ru Создать копию. \en Create a copy. - MbModel & Duplicate( MbRegDuplicate * = NULL ) const; + MbModel & Duplicate( MbRegDuplicate * = c3d_null ) const; /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); + void Transform( const MbMatrix3D &, MbRegTransform * iReg = c3d_null ); /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. - void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); + void Move ( const MbVector3D &, MbRegTransform * iReg = c3d_null ); /// \ru Повернуть вокруг оси. \en Rotate about an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = c3d_null ); /// \ru Вычислить расстояние до точки. \en Calculate the distance to a point. double DistanceToPoint ( const MbCartPoint3D & ) const; /// \ru Добавь свой габарит в габаритный куб. \en Include your own bounding box into bounding box. @@ -459,11 +459,11 @@ public : \en General-purpose algorithm traversing the model graph in depth. */ void Traverse( ItModelVisitor & ) const; /// \ru Преобразовать селектирование объекты по матрице. \en Transform selected objects by matrix. - void TransformSelected( const MbMatrix3D &, MbRegTransform * = NULL ); + void TransformSelected( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть выбранные объекты. \en Move selected objects. - void MoveSelected( const MbVector3D &, MbRegTransform * = NULL ); + void MoveSelected( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть выбранные объекты вокруг оси. \en Rotate selected objects around an axis. - void RotateSelected( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void RotateSelected( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /** \brief \ru Отцепить все выбранные объекты. \en Detach all selected objects. \~ @@ -592,7 +592,7 @@ void MbModel::GetItems( Items & items ) const { items.reserve( modelItems.size() ); for ( NameItemArray::const_iterator iter = modelItems.begin(); iter != modelItems.end(); ++iter ) { - if ( iter->second != NULL ) + if ( iter->second != c3d_null ) items.push_back( iter->second ); } } @@ -608,7 +608,7 @@ void MbModel::DetachItems( Items & items ) NameItemArray::const_iterator endItem = modelItems.end(); for ( ; iter != endItem; ++iter ) { MbItem * item = iter->second; - if ( item != NULL ) { + if ( item != c3d_null ) { item->DecRef(); items.push_back( item ); } diff --git a/C3d/Include/model_item.h b/C3d/Include/model_item.h index f426b35..b97b564 100644 --- a/C3d/Include/model_item.h +++ b/C3d/Include/model_item.h @@ -1,609 +1,608 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Объект геометрической модели. - \en A model geometric object. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MODEL_ITEM_H -#define __MODEL_ITEM_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbItem; -namespace c3d // namespace C3D -{ -typedef SPtr ItemSPtr; -typedef SPtr ConstItemSPtr; - -typedef std::vector ItemsVector; -typedef std::vector ConstItemsVector; - -typedef std::vector ItemsSPtrVector; -typedef std::vector ConstItemsSPtrVector; - -typedef std::set ItemsSet; -typedef ItemsSet::iterator ItemsSetIt; -typedef ItemsSet::const_iterator ItemsSetConstIt; -typedef std::pair ItemsSetRet; - -typedef std::set ConstItemsSet; -typedef ConstItemsSet::iterator ConstItemsSetIt; -typedef ConstItemsSet::const_iterator ConstItemsSetConstIt; -typedef std::pair ConstItemsSetRet; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Объект геометрической модели. - \en A model geometric object. \~ - \details \ru Родительский класс объектов геометрической модели. \n - Наследниками являются: \n - локальная система координат MbAssistingItem,\n - точечный каркас MbPointFrame,\n - проволочный каркас MbWireFrame,\n - твёрдое тело MbSolid,\n - полигональный объект MbMesh,\n - вставка объекта в локальной системе координат MbInstance,\n - сборка объектов в локальной системе координат MbAssembly,\n - вставка трехмерного объекта MbSpaceInstance,\n - вставка двумерного объекта MbPlaneInstance в плоскости XY локальной системы координат.\n - Объект содержит последовательность и способы своего построения MbTransactions.\n - Объект содержит не геометрические свойства в виде контейнера атрибутов MbAttributeContainer.\n - Имя объекта геометрической модели представляет собой контейнер простых имён. - В начале контейнера содержится простое имя SimpleName, присвоенное объекту геометрической моделью MbModel. \n - Если объект не держит в себе других объектов, то контейнер содержит одно простое имя SimpleName. - Ели объект держит в себе другие объекты (MbAssembly или MbInstance), - то имя внутренних объектов представляет собой контейнер, содержащий как минимум два простых имени. - Количество элементов имени объекта отражают количество уровней вложенности объект относительно модели. - \en Parent class of model geometric objects. \n - Inheritors are: \n - local coordinate system of MbAssistingItem,\n - MbPointFrame point-frame,\n - MbWireFrame wireframe,\n - MbSolid solid,\n - MbMesh polygonal planar object,\n - MbInstance instance of object in the local coordinate system,\n - MbAssembly assembly of objects in the local coordinate system,\n - MbSpaceInstance instance of three-dimensional object,\n - MbPlaneInstance instance of a two-dimensional object in the XY-plane of a local coordinate system.\n - Object contains MbTransactions sequence and ways to construct itself.\n - Object contains non-geometric properties as MbAttributeContainer attribute container.\n - The name of an object of a geometric model is represented as a container of simple names. - In the beginning of the container there is a SimpleName simple name assigned to object by MbModel geometric model. \n - If the object doesn't contain other objects, then the container contains one SimpleName simple name. - If the object contains other objects (MbAssembly or MbInstance), - then the internal objects name is represented as a container with at least two simple names. - Number of the elements of an object's name corresponds to the number of levels of objects inclusion relative to the model. \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbItem : public MbSpaceItem, - public MbTransactions, - public MbAttributeContainer, - public MbSyncItem { - -private: - SimpleName name; ///< \ru Имя объекта геометрической модели. \en Name of a geometric model object. - -protected: - /// \ru Конструктор копирования с регистратором дублирования. \en Copy-constructor with duplication registrator. - explicit MbItem( const MbItem &, MbRegDuplicate * ); -public: - /// \ru Конструктор. \en Constructor. - MbItem(); - /// \ru Деструктор. \en Destructor. - virtual ~MbItem(); - -public : - VISITING_CLASS( MbItem ); - - /** \ru \name Общие функции геометрического объекта. - \en \name Common functions of a geometric object. - \{ */ - virtual MbeSpaceType IsA() const = 0; // \ru Тип объекта. \en A type of an object. - virtual MbeSpaceType Type() const; // \ru Групповой тип объекта. \en Group type of object. - virtual MbeSpaceType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbeImplicationType ImplicationType() const; // \ru Тип контейнера атрибутов - классификатор наследников. \en Type of an attribute container is a classifier of inheritors. - virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = NULL ) const = 0; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate about an axis. - virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными? \en Are the objects equal? - virtual bool SetEqual ( const MbSpaceItem & init ) = 0; // \ru Сделать объекты равными. \en Make the objects equal. - virtual double DistanceToPoint ( const MbCartPoint3D & ) const = 0; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. - virtual void AddYourGabaritTo( MbCube & r ) const = 0; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. - virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const = 0; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. - - virtual MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create a custom property. - virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties( const MbProperties & properties ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - virtual void GetBasisPoints( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - /** - \brief \ru Получить систему координат объекта, если она есть. - \en Get the coordinate system of an item if it is exist. - \return \ru Функция вернет true, если объект имеет собственную подсистему координат, - иначе считается, что ЛСК объекта всегда "стандартная" (MbPlacement3D::global). - \en The function returns true, if the object have its own local coordinate system, - otherwise it is considered that the object LCS is always "standard" (MbPlacement3D :: global). - */ - virtual bool GetPlacement( MbPlacement3D & p ) const { p = MbPlacement3D::global; return false; } - /// \ru Установить систему координат объекта, если возможно. \en Set the coordinate system of an item if it is possible. - virtual bool SetPlacement( const MbPlacement3D & ) { return false; } - - /** \brief \ru Построить полигональную копию mesh. - \en Build polygonal copy mesh. \~ - \details \ru Построить полигональную копию данного объекта, представленную полигонами, или/и плоскими пластинами. - \en Build a polygonal copy of the object that is represented by polygons or/and fasets. \~ - \param[in] stepData - \ru Данные для вычисления шага при построении полигонального. - \en Data for еру step calculation for polygonal object. \~ - \param[in] note - \ru Способ построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \param[in, out] mesh - \ru Построенный полигональный объект. - \en The builded polygonal object. - */ - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const = 0; - /** \} */ - - /** \ru \name Общие функции объекта геометрической модели - \en \name Common functions of object of geometric model. - \{ */ - - /** \brief \ru Перестроить объект по журналу построения. - \en Reconstruct object according to the history tree. \~ - \details \ru Создать заново объект по журналу построения. - \en Create object by the history tree. \~ - \param[in] sameShell - \ru Полнота копирования элементов. - \en Whether to perform complete copying of elements while constructing. \~ - \param[out] items - \ru Контейнер для складывания элементов невыполненных построений (может быть NULL). - \en Container for the elements of not performed constructions (can be NULL). \~ - \return \ru Перестроен ли объект. - \en Whether an object is constructed. \~ - \ingroup Model_Items - */ - virtual bool RebuildItem( MbeCopyMode sameShell, RPArray * items, IProgressIndicator * progInd ); - - /** \brief \ru Создать полигональный объект. - \en Create polygonal object. \~ - \details \ru Создать полигональный объект - упрощенную копию данного объекта. - \en Create a polygonal object - a polygonal copy of the given object. \~ - \param[in] stepData - \ru Данные для вычисления шага при триангуляции. - \en Data for step calculation during triangulation. \~ - \param[in] note - \ru Способ построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \return \ru Построенный полигональный объект. - \en Created polygonal object. \~ - \ingroup Model_Items - */ - virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const = 0; - - /** \brief \ru Добавить полигональный объект. - \en Add polygonal object. \~ - \details \ru Добавить свою полигональную копию в присланный полигональный объект. - \en Add your own polygonal copy to the given polygonal object. \~ - \param[in] stepData - \ru Данные для вычисления шага при триангуляции. - \en Data for step calculation during triangulation. \~ - \param[in] note - \ru Способ построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \param[out] mesh - \ru Присланный полигональный объект. - \en Given polygonal object. \~ - \return \ru Добавлен ли объект. - \en Whether the object is added. \~ - \ingroup Model_Items - */ - virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; - - /** \brief \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. - \en Cut the polygonal object by one or two parallel planes. \~ - \details \ru Построить полигональный объект из части исходного полигонального объекта, - лежащей под плоскостью XY локальной системы координат на заданном расстоянии.\n - Функция "режет" только полигональный объект MbMesh. - Функция "режет" объект двумя плоскостями: - плоскостью XY локальной системы координат place и плоскостью, параллельной ей и - расположенной на расстоянии distance ниже неё. - Если distance<=0, то функция "режет" объект только одной плоскостью XY локальной системы.\n - Содержимое объекта, необходимое для построения разрезанного объекта и не затронутое режущими плоскостями, - добавляется в возвращаемый разрезанный объект без копирования.\n - \en Create polygonal object from a part of source polygonal object - which located under XY-plane of local coordinate system at given distance.\n - Function 'cuts' only MbMesh polygonal object. - Function 'cuts' the object by two planes: - XY plane of 'place' local coordinate system and plane parallel to it and - located at 'distance' distance below it. - If 'distance' is less than or equal to zero, then the function "cuts" an object only by one XY plane of local coordinate system.\n - Contents of an object that are necessary for creation of cut object and not affected by cutting planes - are added to returned cut object without copying.\n \~ - \param[in] place - \ru Локальная система координат, плоскость XY которой задаёт режущую плоскость. - \en A local coordinate system which XY plane defines a cutting plane. \~ - \param[in] distance - \ru Расстояние до параллельной режущей плоскости откладывается в отрицательную сторону оси Z локальной системы. - \en Distance to a parallel cutting plane is measured in negative direction of Z-axis of local coordinate system. \~ - \result \ru Возвращает новый полигональный объект, лежащий под плоскость XY локальной системы координат на заданном расстоянии. - \en Returns new polygonal object that located under XY-plane of local coordinate system at given distance. \~ - \ingroup Model_Items - */ - virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; - - /** \brief \ru Найти ближайший объект или имя ближайшего объекта. - \en Find the nearest object or name of the nearest object. \~ - \details \ru Найти ближайший трехмерный объект или его имя по типу объекта и - составляющий элемент искомого объекта или его имя по топологическому или двумерному типу элемента (по требованию) - на расстоянии от прямой, не превышающем заданной величины. - Функция предназначена для идентификации геометрического объекта, породившего полигональный объект. - Реальный поиск выполняется для элементов MbPrimitive полигонального объекта MbMesh, - у которых берётся информация о породившем примитив геометрическом объекте. - \en Find the nearest three-dimensional object or its name by type of object and - component of the required object or its name by topological or two-dimensional type of the element (on demand) - at distance from line less than or equal to the given value. - Function is intended for identification of a geometric object which is begetter of a polygonal object. - The real search is performed for MbMesh polygonal object's MbPrimitive elements - from which the information is taken about geometric object which is begetter of the primitive. \~ - \param[in] sType - \ru Тип искомого объекта. - \en Type of required object. \~ - \param[in] tType - \ru Топологический тип составляющего элемента искомого объекта. - \en Topological type of the required object's component. \~ - \param[in] pType - \ru Двумерный тип составляющего элемента искомого объекта. - \en Two-dimensional type of the required object's component. \~ - \param[in] axis - \ru Прямая поиска. - \en Line of search. \~ - \param[in] maxDistance - \ru Расстояние от прямой, на котором ищется объект. - \en Distance from the line on which the object is looked for. \~ - \param[in] gridPriority - \ru Повышенный приоритет триангуляционной сетки при поиске. - \en Increased priority triangulation grid when searching. \~ - \param[out] t - \ru Параметр прямой для найденной точки. - \en Parameter of found point on line. \~ - \param[out] dMin - \ru Найденное расстояние объекта от прямой. - \en Found distance from line to an object. \~ - \param[out] find - \ru Найденный объект. - \en Found object. \~ - \param[out] findName - \ru Имя найденного объекта. - \en Name of the found object. \~ - \param[out] element - \ru Найденный составляющий элемент объекта. - \en Found component of the object. \~ - \param[out] elementName - \ru Имя найденного составляющего элемента объекта. - \en Name of found component of the object. \~ - \param[out] path - \ru Путь положения объекта в модели. - \en Object's path in the model. \~ - \param[out] from - \ru Матрица преобразования найденного объекта в глобальную систему координат. - \en Transformation matrix of the found object to the global coordinate system. \~ - \return \ru Найден ли объект или его имя. - \en Whether the object or its name is found. \~ - \ingroup Model_Items - */ - virtual bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, - const MbAxis3D & axis, double maxDistance, bool gridPriority, double & t, double & dMin, - MbItem *& find, SimpleName & findName, - MbRefItem *& element, SimpleName & elementName, - MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Дать все объекты указанного типа. - \en Get all objects by type. \~ - \details \ru Дать все объекты указанного типа, - а также матрицы преобразования их в глобальную систему координат. \n - \en Get all objects by type - and get transformation matrix to the global coordinate system. \n \~ - \param[in] type - \ru Тип объекта. - \en Object's type. \~ - \param[in] from - \ru Исходная матрица преобразования в глобальную систему координат. - \en Initial transformation matrix to the global coordinate system. \~ - \param[out] items - \ru Множество найденных объектов. - \en Found objects. \~ - \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. - \en Transformation matrix of found objects to the global coordinate system. \~ - \return \ru Добавлен ли данный объект. - \en Whether add this object. \~ - \ingroup Model_Items - */ - virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, - RPArray & items, SArray & matrs ); - /** \brief \ru Дать все уникальные объекты указанного типа. - \en Get all unique objects by type. \~ - \details \ru Дать все уникальные объекты указанного типа. \n - \en Get all unique objects by type. \n \~ - \param[in] type - \ru Тип объекта. - \en Object's type. \~ - \param[out] items - \ru Множество найденных объектов. - \en Found objects. \~ - \return \ru Добавлен ли данный объект. - \en Whether add this object. \~ - \ingroup Model_Items - */ - virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; - - /** \brief \ru Дать объект по его пути. - \en Get the object by its path. \~ - \details \ru Дать объект по его пути положения в модели и - дать матрицу преобразования объекта в глобальную систему координат. - Объект может содержаться в другом объекте (в сборке или вставке). - \en Get the object by path of its position in the model and - get transformation matrix of the object to the global coordinate system. - Object can be contained in other object (in assembly or in instance). \~ - \param[in] path - \ru Путь объекта. - \en Path of object. \~ - \param[in] ind - \ru Индекс требуемого объекта в path. - \en Index of the desired object in 'path'. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \param[in] currInd - \ru Индекс текущего объекта в path. - \en Index of current object in path. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; - - /** \brief \ru Найти объект по геометрическому объекту. - \en Find object by geometric object. \~ - \details \ru Найти объект по геометрическому объекту, - а также получить путь к объекту в модели - и матрицу преобразования в глобальную систему координат. \n - \en Find object by geometric object - and also get the path to the object in model - and get transformation matrix to the global coordinate system. \n \~ - \param[in] s - \ru Геометрический объект. - \en Geometric object. \~ - \param[out] path - \ru Путь к объекту в модели. - \en Path to object in the model. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Найти объект по геометрическому объекту. - \en Find object by geometric object. \~ - \details \ru Найти объект по геометрическому объекту, - а также получить путь к объекту в модели - и матрицу преобразования в глобальную систему координат. \n - \en Find object by geometric object - and also get the path to the object in model - and get transformation matrix to the global coordinate system. \n \~ - \param[in] s - \ru Геометрический объект. - \en Geometric object. \~ - \param[out] path - \ru Путь к объекту в модели. - \en Path to object in the model. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Найти объект по объекту геометрической модели. - \en Find object by object of geometric model \~ - \details \ru Найти объект по объекту геометрической модели. - а также получить путь к объекту в модели - и матрицу преобразования в глобальную систему координат. \n - \en Find object by object of geometric model - and also get the path to the object in model - and get transformation matrix to the global coordinate system. \n \~ - \param[in] s - \ru Геометрический объект. - \en Geometric object. \~ - \param[out] path - \ru Путь к объекту в модели. - \en Path to object in the model. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Найти объект по имени. - \en Find object by name. \~ - \details \ru Найти объект по имени, а также получить путь к объекту в модели - и матрицу преобразования в глобальную систему координат. \n - \en Find object by name and also get path to object in model - and get transformation matrix to the global coordinate system. \n \~ - \param[in] n - \ru Имя объекта. - \en A name of an object. \~ - \param[out] path - \ru Путь к объекту в модели. - \en Path to object in the model. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Преобразовать выбранный объект согласно матрице. - \en Transform selected object according to the matrix. \~ - \details \ru Преобразовать выбранный простой объект согласно матрице c использованием регистратора. - Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. - \en Transform selected simple object according to the matrix using the registrator. - If object contains other objects of geometric model then selected contents will be transformed. \~ - \param[in] matr - \ru Матрица преобразования. - \en A transformation matrix. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - \ingroup Model_Items - */ - virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - - /** \brief \ru Сдвинуть выбранный объект вдоль вектора. - \en Move selected object along a vector. \~ - \details \ru Сдвинуть вдоль вектора с использованием регистратора выбранный простой объект. - Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. - \en Move selected simple object along the vector using the registrator. - If object contains other objects of geometric model then selected contents will be transformed. \~ - \param[in] to - \ru Вектор сдвига. - \en Translation vector. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - \ingroup Model_Items - */ - virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = NULL ); - - /** \brief \ru Повернуть выбранный объект вокруг оси на заданный угол. - \en Rotate selected object by a given angle about an axis. \~ - \details \ru Повернуть вокруг оси на заданный угол с использованием регистратора выбранный простой объект. - Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. - \en Rotate selected simple object about the axis by the given angle using the registrator. - If object contains other objects of geometric model then selected contents will be transformed. \~ - \param[in] axis - \ru Ось поворота. - \en The rotation axis. \~ - \param[in] angle - \ru Угол поворота. - \en The rotation angle. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - \ingroup Model_Items - */ - virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - - /// \ru Дать матрицу преобразования из локальной системы объекта. \en Get transform matrix from local coordinate system of object. - virtual bool GetMatrixFrom( MbMatrix3D & from ) const; - /// \ru Дать матрицу преобразования в локальную систему объекта. \en Get transform matrix into local coordinate system of object. - virtual bool GetMatrixInto( MbMatrix3D & into ) const; - - /// \ru Копировать строители и атрибуты. \en Copy creators and attributes. - void Assign( const MbItem & other ); - /// \ru Копировать имя объекта. \en Copy the name of an object. - void CopyItemName( const MbItem & other ) { name = other.GetItemName(); } - /// \ru Выдать имя объекта. \en Get name of object. - SimpleName GetItemName() const { return name; } - /// \ru Установить имя объекта. \en Set name of the object. - void SetItemName( SimpleName n ) { name = n; } - /// \ru Соответствует ли знаковый атрибут объекту? \en Whether a sign attribute matches an object? - bool IsAttributeEqual( int attribute ); - - /** \} */ - -protected: - /// \ru Захватить объект, если ядро работает в многопоточном режиме. \en Catch object if multithreading mode is on. - void LockItem() const; - /// \ru Освободить объект, если ядро работает в многопоточном режиме. \en Release object if multithreading mode is on. - void UnlockItem() const; - -private: - /** \brief \ru Построить путь положения объекта. - \en Create path of object's position. \~ - \details \ru Построить путь положения объекта в модели и - дать матрицу преобразования объекта в глобальную систему координат. - Объект может содержаться в другом объекте (в сборке или вставке). - \en Create path of object's position in the model and - get transformation matrix of the object to the global coordinate system. - Object can be contained in other object (in assembly or in instance). \~ - \param[in] obj - \ru Объект. - \en Object. \~ - \param[out] path - \ru Путь объекта. - \en Path of object. \~ - \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. - \en Transformation matrix of object to the global coordinate system. \~ - \return \ru Найден ли путь и матрица объекта. - \en Whether the path and the matrix of object are found. \~ - \ingroup Model_Items - */ - virtual bool MakePath( const MbItem & obj, MbPath & path, MbMatrix3D & from ) const; - -public: - DECLARE_PERSISTENT_CLASS( MbItem ); - OBVIOUS_PRIVATE_COPY( MbItem ); -}; // MbItem - -IMPL_PERSISTENT_OPS( MbItem ) - - -//---------------------------------------------------------------------------------------- -// The functor implementing less operator of two model objects. -//--- -struct LessName -{ - bool operator()( const MbItem * _Left, const MbItem * _Right ) const - { - return (_Left->GetItemName() < _Right->GetItemName()); - } - bool operator()( const MbItem * _Left, SimpleName _Right ) const - { - return _Left->GetItemName() < _Right; - } - bool operator()( SimpleName _Left, const MbItem * _Right ) const - { - return _Left < _Right->GetItemName(); - } -}; - - -namespace c3d // namespace C3D -{ - -//------------------------------------------------------------------------------ -/// \ru Удалить копии построителей в объектах. \en Delete creators' copies. -// --- -template -bool DeleteCreatorsCopies( ItemsVector & items, double eps = LENGTH_EPSILON ) -{ - bool changed = false; - - size_t itemsCnt = items.size(); - c3d::CreatorsSPtrVector creators1, creators2; - - if ( itemsCnt > 1 ) { - for ( size_t i = 0; i < itemsCnt; ++i ) { - MbItem * item1 = items[i]; - if ( item1 == NULL ) - continue; - creators1.clear(); - item1->GetCreators( creators1 ); - size_t creatorsCnt1 = creators1.size(); - - if ( creatorsCnt1 > 0 ) { - for ( size_t j = i + 1; j < itemsCnt; ++j ) { - MbItem * item2 = items[j]; - if ( item2 == NULL ) - continue; - creators2.clear(); - item2->GetCreators( creators2 ); - size_t creatorsCnt2 = creators2.size(); - - if ( creatorsCnt2 > 0 ) { - bool replace = false; - for ( size_t k1 = 0; k1 < creatorsCnt1; ++k1 ) { - MbCreator * creator1 = creators1[k1]; - if ( creator1 == NULL ) - continue; - for ( size_t k2 = k1 + 1; k2 < creatorsCnt2; ++k2 ) { - MbCreator * creator2 = creators2[k2]; - if ( creator2 == NULL ) - continue; - if ( (creator1 != creator2) && creator1->IsSame( *creator2, eps ) ) { - creators2[k2] = creators1[k1]; - replace = true; - } - } - } - if ( replace ) { - item2->DeleteCreators(); - item2->AddCreators( creators2 ); - changed = true; - } - } - } - } - } - } - return changed; -} - -} // namespace C3D - - -#endif // __MODEL_ITEM_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Объект геометрической модели. + \en A model geometric object. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MODEL_ITEM_H +#define __MODEL_ITEM_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbItem; +namespace c3d // namespace C3D +{ +typedef SPtr ItemSPtr; +typedef SPtr ConstItemSPtr; + +typedef std::vector ItemsVector; +typedef std::vector ConstItemsVector; + +typedef std::vector ItemsSPtrVector; +typedef std::vector ConstItemsSPtrVector; + +typedef std::set ItemsSet; +typedef ItemsSet::iterator ItemsSetIt; +typedef ItemsSet::const_iterator ItemsSetConstIt; +typedef std::pair ItemsSetRet; + +typedef std::set ConstItemsSet; +typedef ConstItemsSet::iterator ConstItemsSetIt; +typedef ConstItemsSet::const_iterator ConstItemsSetConstIt; +typedef std::pair ConstItemsSetRet; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Объект геометрической модели. + \en A model geometric object. \~ + \details \ru Родительский класс объектов геометрической модели. \n + Наследниками являются: \n + локальная система координат MbAssistingItem,\n + точечный каркас MbPointFrame,\n + проволочный каркас MbWireFrame,\n + твёрдое тело MbSolid,\n + полигональный объект MbMesh,\n + вставка объекта в локальной системе координат MbInstance,\n + сборка объектов в локальной системе координат MbAssembly,\n + вставка трехмерного объекта MbSpaceInstance,\n + вставка двумерного объекта MbPlaneInstance в плоскости XY локальной системы координат.\n + Объект содержит последовательность и способы своего построения MbTransactions.\n + Объект содержит не геометрические свойства в виде контейнера атрибутов MbAttributeContainer.\n + Имя объекта геометрической модели представляет собой контейнер простых имён. + В начале контейнера содержится простое имя SimpleName, присвоенное объекту геометрической моделью MbModel. \n + Если объект не держит в себе других объектов, то контейнер содержит одно простое имя SimpleName. + Ели объект держит в себе другие объекты (MbAssembly или MbInstance), + то имя внутренних объектов представляет собой контейнер, содержащий как минимум два простых имени. + Количество элементов имени объекта отражают количество уровней вложенности объект относительно модели. + \en Parent class of model geometric objects. \n + Inheritors are: \n + local coordinate system of MbAssistingItem,\n + MbPointFrame point-frame,\n + MbWireFrame wireframe,\n + MbSolid solid,\n + MbMesh polygonal planar object,\n + MbInstance instance of object in the local coordinate system,\n + MbAssembly assembly of objects in the local coordinate system,\n + MbSpaceInstance instance of three-dimensional object,\n + MbPlaneInstance instance of a two-dimensional object in the XY-plane of a local coordinate system.\n + Object contains MbTransactions sequence and ways to construct itself.\n + Object contains non-geometric properties as MbAttributeContainer attribute container.\n + The name of an object of a geometric model is represented as a container of simple names. + In the beginning of the container there is a SimpleName simple name assigned to object by MbModel geometric model. \n + If the object doesn't contain other objects, then the container contains one SimpleName simple name. + If the object contains other objects (MbAssembly or MbInstance), + then the internal objects name is represented as a container with at least two simple names. + Number of the elements of an object's name corresponds to the number of levels of objects inclusion relative to the model. \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbItem : public MbSpaceItem, + public MbTransactions, + public MbAttributeContainer, + public MbSyncItem { + +private: + SimpleName name; ///< \ru Имя объекта геометрической модели. \en Name of a geometric model object. + +protected: + /// \ru Конструктор копирования с регистратором дублирования. \en Copy-constructor with duplication registrator. + explicit MbItem( const MbItem &, MbRegDuplicate * ); +public: + /// \ru Конструктор. \en Constructor. + MbItem(); + /// \ru Деструктор. \en Destructor. + virtual ~MbItem(); + +public : + VISITING_CLASS( MbItem ); + + /** \ru \name Общие функции геометрического объекта. + \en \name Common functions of a geometric object. + \{ */ + virtual MbeSpaceType IsA() const = 0; // \ru Тип объекта. \en A type of an object. + virtual MbeSpaceType Type() const; // \ru Групповой тип объекта. \en Group type of object. + virtual MbeSpaceType Family() const; // \ru Семейство объекта. \en Family of object. + virtual MbeImplicationType ImplicationType() const; // \ru Тип контейнера атрибутов - классификатор наследников. \en Type of an attribute container is a classifier of inheritors. + virtual MbSpaceItem & Duplicate ( MbRegDuplicate * = c3d_null ) const = 0; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными? \en Are the objects equal? + virtual bool SetEqual ( const MbSpaceItem & init ) = 0; // \ru Сделать объекты равными. \en Make the objects equal. + virtual double DistanceToPoint ( const MbCartPoint3D & ) const = 0; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. + virtual void AddYourGabaritTo( MbCube & r ) const = 0; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. + virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const = 0; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. + + virtual MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create a custom property. + virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual void SetProperties( const MbProperties & properties ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + virtual void GetBasisPoints( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + /** + \brief \ru Получить систему координат объекта, если она есть. + \en Get the coordinate system of an item if it is exist. + \return \ru Функция вернет true, если объект имеет собственную подсистему координат, + иначе считается, что ЛСК объекта всегда "стандартная" (MbPlacement3D::global). + \en The function returns true, if the object have its own local coordinate system, + otherwise it is considered that the object LCS is always "standard" (MbPlacement3D :: global). + */ + virtual bool GetPlacement( MbPlacement3D & p ) const { p = MbPlacement3D::global; return false; } + /// \ru Установить систему координат объекта, если возможно. \en Set the coordinate system of an item if it is possible. + virtual bool SetPlacement( const MbPlacement3D & ) { return false; } + + /** \brief \ru Построить полигональную копию mesh. + \en Build polygonal copy mesh. \~ + \details \ru Построить полигональную копию данного объекта, представленную полигонами, или/и плоскими пластинами. + \en Build a polygonal copy of the object that is represented by polygons or/and fasets. \~ + \param[in] stepData - \ru Данные для вычисления шага при построении полигонального. + \en Data for еру step calculation for polygonal object. \~ + \param[in] note - \ru Способ построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \param[in, out] mesh - \ru Построенный полигональный объект. + \en The builded polygonal object. + */ + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const = 0; + /** \} */ + + /** \ru \name Общие функции объекта геометрической модели + \en \name Common functions of object of geometric model. + \{ */ + + /** \brief \ru Перестроить объект по журналу построения. + \en Reconstruct object according to the history tree. \~ + \details \ru Создать заново объект по журналу построения. + \en Create object by the history tree. \~ + \param[in] sameShell - \ru Полнота копирования элементов. + \en Whether to perform complete copying of elements while constructing. \~ + \param[out] items - \ru Контейнер для складывания элементов невыполненных построений (может быть c3d_null). + \en Container for the elements of not performed constructions (can be c3d_null). \~ + \return \ru Перестроен ли объект. + \en Whether an object is constructed. \~ + \ingroup Model_Items + */ + virtual bool RebuildItem( MbeCopyMode sameShell, RPArray * items, IProgressIndicator * progInd ); + + /** \brief \ru Создать полигональный объект. + \en Create polygonal object. \~ + \details \ru Создать полигональный объект - упрощенную копию данного объекта. + \en Create a polygonal object - a polygonal copy of the given object. \~ + \param[in] stepData - \ru Данные для вычисления шага при триангуляции. + \en Data for step calculation during triangulation. \~ + \param[in] note - \ru Способ построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \return \ru Построенный полигональный объект. + \en Created polygonal object. \~ + \ingroup Model_Items + */ + virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const = 0; + + /** \brief \ru Добавить полигональный объект. + \en Add polygonal object. \~ + \details \ru Добавить свою полигональную копию в присланный полигональный объект. + \en Add your own polygonal copy to the given polygonal object. \~ + \param[in] stepData - \ru Данные для вычисления шага при триангуляции. + \en Data for step calculation during triangulation. \~ + \param[in] note - \ru Способ построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \param[out] mesh - \ru Присланный полигональный объект. + \en Given polygonal object. \~ + \return \ru Добавлен ли объект. + \en Whether the object is added. \~ + \ingroup Model_Items + */ + virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; + + /** \brief \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. + \en Cut the polygonal object by one or two parallel planes. \~ + \details \ru Построить полигональный объект из части исходного полигонального объекта, + лежащей под плоскостью XY локальной системы координат на заданном расстоянии.\n + Функция "режет" только полигональный объект MbMesh. + Функция "режет" объект двумя плоскостями: + плоскостью XY локальной системы координат place и плоскостью, параллельной ей и + расположенной на расстоянии distance ниже неё. + Если distance<=0, то функция "режет" объект только одной плоскостью XY локальной системы.\n + Содержимое объекта, необходимое для построения разрезанного объекта и не затронутое режущими плоскостями, + добавляется в возвращаемый разрезанный объект без копирования.\n + \en Create polygonal object from a part of source polygonal object + which located under XY-plane of local coordinate system at given distance.\n + Function 'cuts' only MbMesh polygonal object. + Function 'cuts' the object by two planes: + XY plane of 'place' local coordinate system and plane parallel to it and + located at 'distance' distance below it. + If 'distance' is less than or equal to zero, then the function "cuts" an object only by one XY plane of local coordinate system.\n + Contents of an object that are necessary for creation of cut object and not affected by cutting planes + are added to returned cut object without copying.\n \~ + \param[in] cutPlace - \ru Локальная система координат, плоскость XY которой задаёт режущую плоскость. + \en A local coordinate system which XY plane defines a cutting plane. \~ + \param[in] distance - \ru Расстояние до параллельной режущей плоскости откладывается в отрицательную сторону оси Z локальной системы. + \en Distance to a parallel cutting plane is measured in negative direction of Z-axis of local coordinate system. \~ + \result \ru Возвращает новый полигональный объект, лежащий под плоскость XY локальной системы координат на заданном расстоянии. + \en Returns new polygonal object that located under XY-plane of local coordinate system at given distance. \~ + \ingroup Model_Items + */ + virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; + + /** \brief \ru Найти ближайший объект или имя ближайшего объекта. + \en Find the nearest object or name of the nearest object. \~ + \details \ru Найти ближайший трехмерный объект или его имя по типу объекта и + составляющий элемент искомого объекта или его имя по топологическому или двумерному типу элемента (по требованию) + на расстоянии от прямой, не превышающем заданной величины. + Функция предназначена для идентификации геометрического объекта, породившего полигональный объект. + Реальный поиск выполняется для элементов MbPrimitive полигонального объекта MbMesh, + у которых берётся информация о породившем примитив геометрическом объекте. + \en Find the nearest three-dimensional object or its name by type of object and + component of the required object or its name by topological or two-dimensional type of the element (on demand) + at distance from line less than or equal to the given value. + Function is intended for identification of a geometric object which is begetter of a polygonal object. + The real search is performed for MbMesh polygonal object's MbPrimitive elements + from which the information is taken about geometric object which is begetter of the primitive. \~ + \param[in] sType - \ru Тип искомого объекта. + \en Type of required object. \~ + \param[in] tType - \ru Топологический тип составляющего элемента искомого объекта. + \en Topological type of the required object's component. \~ + \param[in] pType - \ru Двумерный тип составляющего элемента искомого объекта. + \en Two-dimensional type of the required object's component. \~ + \param[in] axis - \ru Прямая поиска. + \en Line of search. \~ + \param[in] maxDistance - \ru Расстояние от прямой, на котором ищется объект. + \en Distance from the line on which the object is looked for. \~ + \param[in] gridPriority - \ru Повышенный приоритет триангуляционной сетки при поиске. + \en Increased priority triangulation grid when searching. \~ + \param[out] t - \ru Параметр прямой для найденной точки. + \en Parameter of found point on line. \~ + \param[out] dMin - \ru Найденное расстояние объекта от прямой. + \en Found distance from line to an object. \~ + \param[out] find - \ru Найденный объект. + \en Found object. \~ + \param[out] findName - \ru Имя найденного объекта. + \en Name of the found object. \~ + \param[out] element - \ru Найденный составляющий элемент объекта. + \en Found component of the object. \~ + \param[out] elementName - \ru Имя найденного составляющего элемента объекта. + \en Name of found component of the object. \~ + \param[out] path - \ru Путь положения объекта в модели. + \en Object's path in the model. \~ + \param[out] from - \ru Матрица преобразования найденного объекта в глобальную систему координат. + \en Transformation matrix of the found object to the global coordinate system. \~ + \return \ru Найден ли объект или его имя. + \en Whether the object or its name is found. \~ + \ingroup Model_Items + */ + virtual bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, + const MbAxis3D & axis, double maxDistance, bool gridPriority, double & t, double & dMin, + MbItem *& find, SimpleName & findName, + MbRefItem *& element, SimpleName & elementName, + MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Дать все объекты указанного типа. + \en Get all objects by type. \~ + \details \ru Дать все объекты указанного типа, + а также матрицы преобразования их в глобальную систему координат. \n + \en Get all objects by type + and get transformation matrix to the global coordinate system. \n \~ + \param[in] type - \ru Тип объекта. + \en Object's type. \~ + \param[in] from - \ru Исходная матрица преобразования в глобальную систему координат. + \en Initial transformation matrix to the global coordinate system. \~ + \param[out] items - \ru Множество найденных объектов. + \en Found objects. \~ + \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. + \en Transformation matrix of found objects to the global coordinate system. \~ + \return \ru Добавлен ли данный объект. + \en Whether add this object. \~ + \ingroup Model_Items + */ + virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + RPArray & items, SArray & matrs ); + /** \brief \ru Дать все уникальные объекты указанного типа. + \en Get all unique objects by type. \~ + \details \ru Дать все уникальные объекты указанного типа. \n + \en Get all unique objects by type. \n \~ + \param[in] type - \ru Тип объекта. + \en Object's type. \~ + \param[out] items - \ru Множество найденных объектов. + \en Found objects. \~ + \return \ru Добавлен ли данный объект. + \en Whether add this object. \~ + \ingroup Model_Items + */ + virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; + + /** \brief \ru Дать объект по его пути. + \en Get the object by its path. \~ + \details \ru Дать объект по его пути положения в модели и + дать матрицу преобразования объекта в глобальную систему координат. + Объект может содержаться в другом объекте (в сборке или вставке). + \en Get the object by path of its position in the model and + get transformation matrix of the object to the global coordinate system. + Object can be contained in other object (in assembly or in instance). \~ + \param[in] path - \ru Путь объекта. + \en Path of object. \~ + \param[in] ind - \ru Индекс требуемого объекта в path. + \en Index of the desired object in 'path'. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \param[in] currInd - \ru Индекс текущего объекта в path. + \en Index of current object in path. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; + + /** \brief \ru Найти объект по геометрическому объекту. + \en Find object by geometric object. \~ + \details \ru Найти объект по геометрическому объекту, + а также получить путь к объекту в модели + и матрицу преобразования в глобальную систему координат. \n + \en Find object by geometric object + and also get the path to the object in model + and get transformation matrix to the global coordinate system. \n \~ + \param[in] s - \ru Геометрический объект. + \en Geometric object. \~ + \param[out] path - \ru Путь к объекту в модели. + \en Path to object in the model. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Найти объект по геометрическому объекту. + \en Find object by geometric object. \~ + \details \ru Найти объект по геометрическому объекту, + а также получить путь к объекту в модели + и матрицу преобразования в глобальную систему координат. \n + \en Find object by geometric object + and also get the path to the object in model + and get transformation matrix to the global coordinate system. \n \~ + \param[in] s - \ru Геометрический объект. + \en Geometric object. \~ + \param[out] path - \ru Путь к объекту в модели. + \en Path to object in the model. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Найти объект по объекту геометрической модели. + \en Find object by object of geometric model \~ + \details \ru Найти объект по объекту геометрической модели. + а также получить путь к объекту в модели + и матрицу преобразования в глобальную систему координат. \n + \en Find object by object of geometric model + and also get the path to the object in model + and get transformation matrix to the global coordinate system. \n \~ + \param[in] s - \ru Геометрический объект. + \en Geometric object. \~ + \param[out] path - \ru Путь к объекту в модели. + \en Path to object in the model. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Найти объект по имени. + \en Find object by name. \~ + \details \ru Найти объект по имени, а также получить путь к объекту в модели + и матрицу преобразования в глобальную систему координат. \n + \en Find object by name and also get path to object in model + and get transformation matrix to the global coordinate system. \n \~ + \param[in] n - \ru Имя объекта. + \en A name of an object. \~ + \param[out] path - \ru Путь к объекту в модели. + \en Path to object in the model. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Преобразовать выбранный объект согласно матрице. + \en Transform selected object according to the matrix. \~ + \details \ru Преобразовать выбранный простой объект согласно матрице c использованием регистратора. + Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. + \en Transform selected simple object according to the matrix using the registrator. + If object contains other objects of geometric model then selected contents will be transformed. \~ + \param[in] matr - \ru Матрица преобразования. + \en A transformation matrix. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + \ingroup Model_Items + */ + virtual void TransformSelected( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + + /** \brief \ru Сдвинуть выбранный объект вдоль вектора. + \en Move selected object along a vector. \~ + \details \ru Сдвинуть вдоль вектора с использованием регистратора выбранный простой объект. + Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. + \en Move selected simple object along the vector using the registrator. + If object contains other objects of geometric model then selected contents will be transformed. \~ + \param[in] to - \ru Вектор сдвига. + \en Translation vector. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + \ingroup Model_Items + */ + virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + + /** \brief \ru Повернуть выбранный объект вокруг оси на заданный угол. + \en Rotate selected object by a given angle about an axis. \~ + \details \ru Повернуть вокруг оси на заданный угол с использованием регистратора выбранный простой объект. + Если объект содержит другие объекты геометрической модели, то преобразуется выбранное содержимое. + \en Rotate selected simple object about the axis by the given angle using the registrator. + If object contains other objects of geometric model then selected contents will be transformed. \~ + \param[in] axis - \ru Ось поворота. + \en The rotation axis. \~ + \param[in] angle - \ru Угол поворота. + \en The rotation angle. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + \ingroup Model_Items + */ + virtual void RotateSelected( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + + /// \ru Дать матрицу преобразования из локальной системы объекта. \en Get transform matrix from local coordinate system of object. + virtual bool GetMatrixFrom( MbMatrix3D & from ) const; + /// \ru Дать матрицу преобразования в локальную систему объекта. \en Get transform matrix into local coordinate system of object. + virtual bool GetMatrixInto( MbMatrix3D & into ) const; + + /// \ru Копировать строители и атрибуты. \en Copy creators and attributes. + void Assign( const MbItem & other ); + /// \ru Копировать имя объекта. \en Copy the name of an object. + void CopyItemName( const MbItem & other ) { name = other.GetItemName(); } + /// \ru Выдать имя объекта. \en Get name of object. + SimpleName GetItemName() const { return name; } + /// \ru Установить имя объекта. \en Set name of the object. + void SetItemName( SimpleName n ) { name = n; } + /// \ru Соответствует ли знаковый атрибут объекту? \en Whether a sign attribute matches an object? + bool IsAttributeEqual( int attribute ); + + /** \} */ + +protected: + /// \ru Захватить объект, если ядро работает в многопоточном режиме. \en Catch object if multithreading mode is on. + void LockItem() const; + /// \ru Освободить объект, если ядро работает в многопоточном режиме. \en Release object if multithreading mode is on. + void UnlockItem() const; + +private: + /** \brief \ru Построить путь положения объекта. + \en Create path of object's position. \~ + \details \ru Построить путь положения объекта в модели и + дать матрицу преобразования объекта в глобальную систему координат. + Объект может содержаться в другом объекте (в сборке или вставке). + \en Create path of object's position in the model and + get transformation matrix of the object to the global coordinate system. + Object can be contained in other object (in assembly or in instance). \~ + \param[in] obj - \ru Объект. + \en Object. \~ + \param[out] path - \ru Путь объекта. + \en Path of object. \~ + \param[out] from - \ru Матрица преобразования объекта в глобальную систему координат. + \en Transformation matrix of object to the global coordinate system. \~ + \return \ru Найден ли путь и матрица объекта. + \en Whether the path and the matrix of object are found. \~ + \ingroup Model_Items + */ + virtual bool MakePath( const MbItem & obj, MbPath & path, MbMatrix3D & from ) const; + +DECLARE_PERSISTENT_CLASS( MbItem ) +OBVIOUS_PRIVATE_COPY( MbItem ) +}; // MbItem + +IMPL_PERSISTENT_OPS( MbItem ) + + +//---------------------------------------------------------------------------------------- +// The functor implementing less operator of two model objects. +//--- +struct LessName +{ + bool operator()( const MbItem * _Left, const MbItem * _Right ) const + { + return (_Left->GetItemName() < _Right->GetItemName()); + } + bool operator()( const MbItem * _Left, SimpleName _Right ) const + { + return _Left->GetItemName() < _Right; + } + bool operator()( SimpleName _Left, const MbItem * _Right ) const + { + return _Left < _Right->GetItemName(); + } +}; + + +namespace c3d // namespace C3D +{ + +//------------------------------------------------------------------------------ +/// \ru Удалить копии построителей в объектах. \en Delete creators' copies. +// --- +template +bool DeleteCreatorsCopies( ItemsVector & items, double eps = LENGTH_EPSILON ) +{ + bool changed = false; + + size_t itemsCnt = items.size(); + c3d::CreatorsSPtrVector creators1, creators2; + + if ( itemsCnt > 1 ) { + for ( size_t i = 0; i < itemsCnt; ++i ) { + MbItem * item1 = items[i]; + if ( item1 == c3d_null ) + continue; + creators1.clear(); + item1->GetCreators( creators1 ); + size_t creatorsCnt1 = creators1.size(); + + if ( creatorsCnt1 > 0 ) { + for ( size_t j = i + 1; j < itemsCnt; ++j ) { + MbItem * item2 = items[j]; + if ( item2 == c3d_null ) + continue; + creators2.clear(); + item2->GetCreators( creators2 ); + size_t creatorsCnt2 = creators2.size(); + + if ( creatorsCnt2 > 0 ) { + bool replace = false; + for ( size_t k1 = 0; k1 < creatorsCnt1; ++k1 ) { + MbCreator * creator1 = creators1[k1]; + if ( creator1 == c3d_null ) + continue; + for ( size_t k2 = k1 + 1; k2 < creatorsCnt2; ++k2 ) { + MbCreator * creator2 = creators2[k2]; + if ( creator2 == c3d_null ) + continue; + if ( (creator1 != creator2) && creator1->IsSame( *creator2, eps ) ) { + creators2[k2] = creators1[k1]; + replace = true; + } + } + } + if ( replace ) { + item2->DeleteCreators(); + item2->AddCreators( creators2 ); + changed = true; + } + } + } + } + } + } + return changed; +} + +} // namespace C3D + + +#endif // __MODEL_ITEM_H diff --git a/C3d/Include/model_tree.h b/C3d/Include/model_tree.h index 51430ba..8eb3674 100644 --- a/C3d/Include/model_tree.h +++ b/C3d/Include/model_tree.h @@ -140,7 +140,7 @@ public: virtual const IModelTreeNode * GetModelTreeNode() const { return m_subtree; } // \ru Доступ к информации об исполнении. \en Access to the embodiment info. - virtual const MbItemData& GetEmbodimentData() const { C3D_ASSERT( m_subtree != NULL ); return m_subtree->GetData(); } + virtual const MbItemData& GetEmbodimentData() const { C3D_ASSERT( m_subtree != c3d_null ); return m_subtree->GetData(); } // \ru Построить дерево модели, которое содержится в данном исполнении. // \en Build a tree of a model which is contained in a given embodiment. @@ -197,13 +197,13 @@ public: // \en Build a tree with nodes, selected by filters. In case of embodiment tree, the function works with the first embodiment. virtual std_unique_ptr GetFilteredTree ( const std::vector& filters ) const; - // \ru Построить дерево по заданным узлам. Не применимо для дерева исполнений (в этом случае возвращает NULL). - // \en Build a tree for given nodes. Not applicable to embodiment tree (in this case, returns NULL). + // \ru Построить дерево по заданным узлам. Не применимо для дерева исполнений (в этом случае возвращает c3d_null). + // \en Build a tree for given nodes. Not applicable to embodiment tree (in this case, returns c3d_null). virtual std_unique_ptr GetFilteredTree ( std::vector& nodes ) const; - // \ru Выдать указатель на дерево исполнений. Выдает NULL, если не применимо (нет исполнений). - // \en Get pointer to embodiments tree. Return NULL if not applicable (no embodiments). - virtual const IEmbodimentTree* GetEmbodimentsTree() const { return GetType() == mtt_Embodiment ? &m_embTree : NULL; } + // \ru Выдать указатель на дерево исполнений. Выдает c3d_null, если не применимо (нет исполнений). + // \en Get pointer to embodiments tree. Return c3d_null if not applicable (no embodiments). + virtual const IEmbodimentTree* GetEmbodimentsTree() const { return GetType() == mtt_Embodiment ? &m_embTree : c3d_null; } /// \ru Версия дерева. \en Tree version. virtual VERSION GetVersion() { return m_currentVersion; } @@ -225,7 +225,7 @@ public: /// \param node - a node with data. /// \param added - filled if non-null (true - if a node added, false - a node already exists). /// \return - a pointer to the tree node. - MbTreeNode* AddNode ( const MbTreeNode& node, bool* added = NULL ); + MbTreeNode* AddNode ( const MbTreeNode& node, bool* added = c3d_null ); /// \ru Добавить узел с указанными данными, если узел с такими данными не существует. /// \param node - данные. @@ -235,7 +235,7 @@ public: /// \param node - a data. /// \param added - filled if non-null (true - if a node added, false - a node already exists). /// \return - a pointer to the tree node. - MbTreeNode* AddNode ( const MbItemData& data, bool* added = NULL ); + MbTreeNode* AddNode ( const MbItemData& data, bool* added = c3d_null ); /// \ru Доступ к узлам дерева, упорядоченным по данным. /// \en Access to nodes of the tree, ordered by data. diff --git a/C3d/Include/model_tree_data.h b/C3d/Include/model_tree_data.h index 5907391..94c3ec9 100644 --- a/C3d/Include/model_tree_data.h +++ b/C3d/Include/model_tree_data.h @@ -151,8 +151,8 @@ public: //---------------------------------------------------------------------------------------- -/// \ru Создать объект пользовательских данных для атрибута. Возвращает NULL, если данный атрибут не поддерживается деревом модели. -/// \en Create user data object for the attribute. Return NULL if this attribute is not supported in the model tree. +/// \ru Создать объект пользовательских данных для атрибута. Возвращает c3d_null, если данный атрибут не поддерживается деревом модели. +/// \en Create user data object for the attribute. Return c3d_null if this attribute is not supported in the model tree. //--- MATH_FUNC( ItemDataBase* ) CreateAttributeData( MbAttribute* attr ); @@ -800,8 +800,8 @@ inline writer& operator << ( writer & out, const UserDataMap& itemmap ) while ( !curIter.Empty() ) { MbeItemDataType type = curIter.Key(); ItemDataBase* item = curIter.Value(); - C3D_ASSERT( type < idtCount && item != NULL ); - if ( type < idtCount && item != NULL ) { + C3D_ASSERT( type < idtCount && item != c3d_null ); + if ( type < idtCount && item != c3d_null ) { out << (int)type; // \ru Тип данных. \en A data type. size_t dataSize = item->Size( out ); ::WriteCOUNT( out, dataSize );// \ru Размер данных. \en Data size. diff --git a/C3d/Include/mt_ref_item.h b/C3d/Include/mt_ref_item.h index d83e083..1ffedcb 100644 --- a/C3d/Include/mt_ref_item.h +++ b/C3d/Include/mt_ref_item.h @@ -1,63 +1,68 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Надкласс для объектов, время жизни которых автоматически регулируется счетчиком ссылок. - \en Superclass for objects their lifetime is automatically regulated by reference counter. -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __MT_REF_ITEM_H -#define __MT_REF_ITEM_H - -#include - - -////////////////////////////////////////////////////////////////////////////////////////// -/** - \brief \ru Базовый класс для объектов с подсчетом ссылок. - \en Base class for objects with reference counting. \~ - \ingroup Base_Items - \sa #MbRefItem, #SPtr -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -class MATH_CLASS MtRefItem -{ - mutable refcount_t useCount; - -protected: - MtRefItem() : useCount(0) {} - virtual ~MtRefItem() {} - -public: - /// \ru Добавить одну ссылку на объект. \en Adds a reference to this object. - refcount_t AddRef() const { return ++useCount; } - /// \ru Освободить одну ссылку на объект. \en Releases a reference to this object. - refcount_t Release() const; - -public: - /// \ru Вернуть количество объектов, ссылающихся на данный. \en Returns a number of objects referring to this. - refcount_t GetUseCount() const { return useCount; } - -private: - MtRefItem( const MtRefItem & ); - MtRefItem & operator = ( const MtRefItem & ); -}; - -//---------------------------------------------------------------------------------------- -// -//--- -inline refcount_t MtRefItem::Release() const -{ - if ( !useCount || (--useCount == 0) ) - { - delete this; // \ru Вызов виртуального деструктора \en Call of virtual destructor - return 0; - } - - return useCount; -} - -#endif // __MT_REF_ITEM_H - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Надкласс для объектов, время жизни которых автоматически регулируется счетчиком ссылок. + \en Superclass for objects their lifetime is automatically regulated by reference counter. +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __MT_REF_ITEM_H +#define __MT_REF_ITEM_H + +#include + + +#if defined (C3D_WINDOWS ) && !defined(ALL_WARNINGS) //_MSC_VER // Set warnings level +#pragma warning(disable: 4275) //AP non dll-interface class '1' used as base for dll-interface class '2' (deriving exported from non-exported) +#endif + + +////////////////////////////////////////////////////////////////////////////////////////// +/** + \brief \ru Базовый класс для объектов с подсчетом ссылок. + \en Base class for objects with reference counting. \~ + \ingroup Base_Items + \sa #MbRefItem, #SPtr +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +class MtRefItem +{ + mutable refcount_t useCount; + +protected: + MtRefItem() : useCount(0) {} + virtual ~MtRefItem() {} + +public: + /// \ru Добавить одну ссылку на объект. \en Adds a reference to this object. + refcount_t AddRef() const { return ++useCount; } + /// \ru Освободить одну ссылку на объект. \en Releases a reference to this object. + refcount_t Release() const; + +public: + /// \ru Вернуть количество объектов, ссылающихся на данный. \en Returns a number of objects referring to this. + refcount_t GetUseCount() const { return useCount; } + +private: + MtRefItem( const MtRefItem & ); + MtRefItem & operator = ( const MtRefItem & ); +}; + +//---------------------------------------------------------------------------------------- +// +//--- +inline refcount_t MtRefItem::Release() const +{ + if ( !useCount || (--useCount == 0) ) + { + delete this; // \ru Вызов виртуального деструктора \en Call of virtual destructor + return 0; + } + + return useCount; +} + +#endif // __MT_REF_ITEM_H + // eof \ No newline at end of file diff --git a/C3d/Include/multiline.h b/C3d/Include/multiline.h index cb8e0b8..d3f646e 100644 --- a/C3d/Include/multiline.h +++ b/C3d/Include/multiline.h @@ -441,7 +441,7 @@ public: // --- class MATH_CLASS MbMultiline : public MbPlaneItem { private: - MbContour * basisCurve; ///< \ru Базовая кривая (БК) (всегда не NULL). \en Base curve (BC) (always not NULL). + MbContour * basisCurve; ///< \ru Базовая кривая (БК) (всегда не c3d_null). \en Base curve (BC) (always not c3d_null). SArray vertices; ///< \ru Массив вершин мультилинии (согласован с вершинами БК). \en Array of vertices of a multiline (agreed with the vertices of the base curve). CSSArray equidRadii; ///< \ru Сортированный массив радиусов эквидистантных кривых. \en Sorted array of radii of equidistant curves. StMLTipParams begTipParams; ///< \ru Параметры законцовки в начале мультилинии (начале БК). \en Parameters of a tip at the beginning of a multiline ( the beginning of base curve). @@ -450,7 +450,7 @@ private: bool isTransparent; ///< \ru "Прозрачная" ли мультилиния. \en Whether the multiline is "transparent". // \ru Объекты, которые составляют мультилинию (рекомендовали не делать их mutable, а писать и читать) \en Objects which constitute a multiline (recommended to read and write and not to make them mutable) // \ru ЭТИ ОБЪЕКТЫ НЕЛЬЗЯ МЕНЯТЬ СНАРУЖИ!!! \en THESE OBJECTS CAN'T BE CHANGED OUTSIDE!!! - PArray curves; ///< \ru Кривые мультилинии (согласован с equidRadii) (всегда не NULL). \en Curves of a multiline (agreed with the 'equidRadii') (always not NULL). + PArray curves; ///< \ru Кривые мультилинии (согласован с equidRadii) (всегда не c3d_null). \en Curves of a multiline (agreed with the 'equidRadii') (always not c3d_null). PArray tipCurves; ///< \ru Законцовки в вершинах мультилинии (согласован с vertices). \en Tips at vertices of a multiline (agreed with 'vertices'). MbContour * begTipCurve; ///< \ru Законцовка в начале мультилинии (начале БК). \en Tip at the beginning of a multiline (beginning of the base curve). MbContour * endTipCurve; ///< \ru Законцовка в конце мультилинии (конце БК). \en Tip at the end of a multiline (end of the base curve). @@ -513,10 +513,10 @@ public: virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool IsSimilar ( const MbPlaneItem & item ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. virtual bool SetEqual ( const MbPlaneItem & item ); // \ru Сделать объекты равными. \en Make the objects equal. - virtual void Transform ( const MbMatrix & matr, MbRegTransform * = NULL, const MbSurface * newSurface = NULL );// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Move ( const MbVector & to, MbRegTransform * = NULL, const MbSurface * newSurface = NULL );// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Повернуть вокруг точки на угол. \en Rotate at angle around a point. - virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = NULL ) const; // \ru Сделать копию объекта. \en Create a copy of the object. + virtual void Transform ( const MbMatrix & matr, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null );// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. + virtual void Move ( const MbVector & to, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null );// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + virtual void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Повернуть вокруг точки на угол. \en Rotate at angle around a point. + virtual MbPlaneItem & Duplicate ( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию объекта. \en Create a copy of the object. virtual void AddYourGabaritTo( MbRect & r ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the given bounding box. virtual bool IsVisibleInRect ( const MbRect & r, bool exact = false ) const; // \ru Виден ли объект в заданном прям-ке. \en Whether the object is visible in the given rectangle. @@ -1319,7 +1319,7 @@ private: /// \ru Насчитать все кривые и все законцовки в вершинах. \en Calculate all curves and all tips at vertices. void CalculateCurvesAndTipCurves(); /// \ru Насчитать законцовку в начале. \en Calculate tip at the beginning. - void CalculateBegTipCurve ( SArray * changeCurvesNumbers = NULL ); + void CalculateBegTipCurve ( SArray * changeCurvesNumbers = c3d_null ); /// \ru Насчитать законцовку в конце. \en Calculate tip at the end. void CalculateEndTipCurve (); @@ -1576,7 +1576,7 @@ MATH_FUNC (bool) BreakMultilineNParts( const MbMultiline & multiline, size_t par // --- inline bool MbMultiline::IsDegenerate( double lenEps ) const { return ( (minNotDegInd == SYS_MAX_T) || // \ru Значит, и maxNotDegInd == SYS_MAX_T \en So maxNotDegInd == SYS_MAX_T - (basisCurve != NULL && basisCurve->IsDegenerate(lenEps)) ); + (basisCurve != c3d_null && basisCurve->IsDegenerate(lenEps)) ); } diff --git a/C3d/Include/name_check.h b/C3d/Include/name_check.h index 28212ab..c270156 100644 --- a/C3d/Include/name_check.h +++ b/C3d/Include/name_check.h @@ -155,7 +155,7 @@ struct NameIntersectionInfo { const MbName * name; ///< \ru Имя объектов. \en A name of objects. size_t intersections; ///< \ru Количество совпадений. \en The count of coincidences. - NameIntersectionInfo() : name( NULL ), intersections( 0 ) {} + NameIntersectionInfo() : name( c3d_null ), intersections( 0 ) {} }; @@ -188,14 +188,14 @@ MATH_FUNC (bool) CheckShellNames( const RPArray & shells, \en The first edge. \~ \param[in] edge2 - \ru Второе ребро. \en The second edge. \~ - \param[in] version - \ru Версия исполнения. - \en The version. \~ + \param[in] snMaker - \ru Именователь с версией исполнения. + \en Names maker with a version. \~ \ingroup Names */ //--- -MATH_FUNC (void) CombineNames( MbCurveEdge & edge1, - const MbCurveEdge & edge2, - VERSION version ); +MATH_FUNC (void) CombineNames( MbCurveEdge & edge1, + const MbCurveEdge & edge2, + const MbSNameMaker & snMaker ); #endif // __NAME_CHECK_H diff --git a/C3d/Include/name_contour_tree.h b/C3d/Include/name_contour_tree.h index d1d835f..ffcad24 100644 --- a/C3d/Include/name_contour_tree.h +++ b/C3d/Include/name_contour_tree.h @@ -31,7 +31,7 @@ private: bool intersectChildren; // \ru Пересекаются ли внутренние контуры \en Are inner contours intersect public: /// \ru Конструктор. \en Constructor. - MbNamedContoursTree( const MbContour * con = NULL, bool o = true ); + MbNamedContoursTree( const MbContour * con = c3d_null, bool o = true ); /// \ru Деструктор. \en Destructor. ~MbNamedContoursTree(); public: @@ -40,7 +40,7 @@ public: /// \ru Получить количество деревьев. \en Get count of trees. size_t GetChildrenCount() const { return children.Count(); } /// \ru Получить дерево контуров по индексу. \en Get contour tree by an index. - const MbNamedContoursTree * GetTreeContour( size_t index ) const { return (GetChildrenCount() >= index) ? children[index] : NULL; } + const MbNamedContoursTree * GetTreeContour( size_t index ) const { return (GetChildrenCount() >= index) ? children[index] : c3d_null; } /// \ru Проверить группы контуров на не пересечение. \en Check groups of contours for absence of intersection. MbResultType CheckProfiles( bool base ) const; /// \ru Получить указатель на внешний контур. \en Get the pointer to the external contour. @@ -64,8 +64,8 @@ private: \en Get the biggest contour. \~ \details \ru Выдать самый большой контур по длине диагонали габарита. \en Get the biggest contour by bounding box diagonal length. \~ - \return \ru Возвращает указатель на найденный контур или NULL. - \en Returns pointer to the found contour or NULL. \~ + \return \ru Возвращает указатель на найденный контур или c3d_null. + \en Returns pointer to the found contour or c3d_null. \~ \ingroup Names */ // --- diff --git a/C3d/Include/name_item.h b/C3d/Include/name_item.h index 924d8c6..f3ab337 100644 --- a/C3d/Include/name_item.h +++ b/C3d/Include/name_item.h @@ -789,7 +789,7 @@ public: \param[in] copy - \ru Имя копии. \en The name of the copy. \~ */ - MbNamePair( const MbName * copy ) : gageName( C3D_NULL_PTR ), copyName( copy ), copyHash( c3d::SIMPLENAME_MAX ) {} + MbNamePair( const MbName * copy ) : gageName( c3d_null ), copyName( copy ), copyHash( c3d::SIMPLENAME_MAX ) {} /// \ru . \en . /** \brief \ru Конструктор. \en Constructor. \~ @@ -798,13 +798,13 @@ public: \param[in] copy - \ru Хэш имени копии. \en The hash of the name of the copy. \~ */ - MbNamePair( SimpleName copy ) : gageName( C3D_NULL_PTR ), copyName( C3D_NULL_PTR ), copyHash( copy ) {} + MbNamePair( SimpleName copy ) : gageName( c3d_null ), copyName( c3d_null ), copyHash( copy ) {} /// \ru Деструктор. \en Destructor. ~MbNamePair() {} public: /// \ru Обнулить имя оригинала и имя копии. \en Set name of original and of its duplicate to null. - void SetNull() { gageName = C3D_NULL_PTR; copyName = C3D_NULL_PTR; copyHash = c3d::SIMPLENAME_MAX; } + void SetNull() { gageName = c3d_null; copyName = c3d_null; copyHash = c3d::SIMPLENAME_MAX; } /// \ru Оператор сравнения. \en Comparison operator. bool operator == ( const MbNamePair & other ) const; /// \ru Оператор меньше. \en "Less than" operator. @@ -871,8 +871,8 @@ public: */ void AddNameData( const MbName * orig, const MbName * copy ) { - C3D_ASSERT( (orig != C3D_NULL_PTR) && (copy != C3D_NULL_PTR) ); - if ( (orig != C3D_NULL_PTR) && (copy != C3D_NULL_PTR) ) { + C3D_ASSERT( (orig != c3d_null) && (copy != c3d_null) ); + if ( (orig != c3d_null) && (copy != c3d_null) ) { checkList.Add( MbNamePair( orig, copy ) ); } } @@ -973,7 +973,7 @@ public: , version() #ifdef ORIGINAL_MAIN_NAME , original( c3d::SIMPLENAME_MAX ) - , nameList( C3D_NULL_PTR ) + , nameList( c3d_null ) #endif // ORIGINAL_MAIN_NAME { defName.SetMainName( mn ); @@ -992,7 +992,7 @@ public: , version() #ifdef ORIGINAL_MAIN_NAME , original( c3d::SIMPLENAME_MAX ) - , nameList( C3D_NULL_PTR ) + , nameList( c3d_null ) #endif // ORIGINAL_MAIN_NAME { defName.MakeTemplate(); @@ -1076,6 +1076,28 @@ public: */ virtual void SetItemName( const MbName & name, MbTopologyItem & item ) const; + /** \brief \ru Установить главное имя топологическому объекту. + \en Set main name of topology item name. \~ + \details \ru Установить главное имя в имени топологического объекта. \n + \en Set main name of topology item name. \n \~ + \param[in,out] item - \ru Топологический элемент. + \en Topology item. \~ + \param[in] addOldMainName - \ru При true запомнить заменяемое главное имя в индексе копирования. + \en When it is true remember replaced main name in the copying index. \~ + */ + virtual bool SetItemMainName( MbTopologyItem & item, bool addOldMainName ) const; + + /** \brief \ru Установить индекс копирования топологическому объекту. + \en Set copy index into topology item name. \~ + \details \ru Установить (вставить) индекс копирования в имя топологического объекта. \n + \en Set (insert) copy index into topology item name. \n \~ + \param[in,out] item - \ru Топологический элемент. + \en Topology item. \~ + \param[in] copyIndex - \ru Индекс копирования. + \en Copy index. \~ + */ + virtual bool SetItemCopyIndex( MbTopologyItem & item, SimpleName copyIndex ) const; + /// \ru Является ли именователь родительским для данного топологического элемента? \en Is the name maker a parent for a given topological element?. virtual bool IsChild( const MbTopologyItem & ) const; @@ -1155,11 +1177,11 @@ public: MbNameMaker GetOriginalNameMaker() const; /// \ru Удалить ненужные элементы по именам копий. \en Clean up unnecessary pairs by name copies. bool CleanNameList( c3d::ConstNamesVector & delNamesCopies ) const { - return ((nameList != C3D_NULL_PTR) ? nameList->Clean( delNamesCopies ) : false); + return ((nameList != c3d_null) ? nameList->Clean( delNamesCopies ) : false); } /// \ru Заменить имена копий. \en Replace names copies. bool ReplaceNameList( const MbName & newNameCopies, const c3d::ConstNamesVector & oldNamesCopies ) const { - return ((nameList != C3D_NULL_PTR) ? nameList->Replace( newNameCopies, oldNamesCopies ) : false); + return ((nameList != c3d_null) ? nameList->Replace( newNameCopies, oldNamesCopies ) : false); } #endif // ORIGINAL_MAIN_NAME @@ -1498,7 +1520,7 @@ reader & operator >> ( reader & in, MbPath & ref ) if ( in.good() && count ) { ref.SetSize( count, true/*clear*/ ); - if ( (ref.GetAddr() == NULL) && (count >= SYS_MAX_UINT32) ) // We could not allocate the required amount of memory + if ( (ref.GetAddr() == c3d_null) && (count >= SYS_MAX_UINT32) ) // We could not allocate the required amount of memory in.setState( io::outOfMemory ); else { for ( size_t i = 0; i < count && in.good(); ++i ) { diff --git a/C3d/Include/op_curve_parameter.h b/C3d/Include/op_curve_parameter.h new file mode 100644 index 0000000..a005069 --- /dev/null +++ b/C3d/Include/op_curve_parameter.h @@ -0,0 +1,111 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Параметры операций над кривыми. + \en Parameters of operations on the curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __OP_CURVE_PARAMETERS_H +#define __OP_CURVE_PARAMETERS_H + +#include +#include +#include +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры эквидистантной кривой в пространстве. + \en Parameters of an offset curve in space. \~ + \details \ru Параметры эквидистантной кривой в пространстве по трехмерной кривой и вектору направления. \n + \en Parameters of an offset curve in space from a three-dimensional curve and a direction vector. \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbSpatialOffsetCurveParams { +public: + MbVector3D offsetVect; ///< \ru Вектор, задающий смещение в точке кривой. \en The displacement vector at a point of the curve. + bool useFillet; ///< \ru Если true, то разрывы заполнять скруглением, иначе продолженными кривыми. \en If 'true', the gaps are to be filled with fillet, otherwise with the extended curves. + bool keepRadius; ///< \ru Если true, то в существующих скруглениях сохранять радиусы. \en If 'true', the existent fillet radii are to be kept. + bool bluntAngle; ///< \ru Если true, то в притуплять острые углы. \en If 'true', sharp corners are to be blunt. + bool fromBeg; ///< \ru Вектор смещения привязан к началу (если true). \en The translation vector is associated with the beginning (if true). +protected: + bool useSurfaceNormal; ///< \ru Эквидистанта согласована с нормалью к поверхности. \en Offset point is moved according to surface normal. + c3d::ConstSurfaceSPtr surface; ///< \ru Поверхность кривой или подобная ей. \en Curve's surface or similar to such surface. + const MbSNameMaker & snMaker; ///< \ru Именователь кривых каркаса. \en An object defining the frame curves names. + +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbSpatialOffsetCurveParams( const MbVector3D & v, const MbSNameMaker & nm ) + : offsetVect ( v ) + , useFillet ( false ) + , keepRadius ( false ) + , bluntAngle ( false ) + , fromBeg ( true ) + , useSurfaceNormal( false ) + , surface ( c3d_null ) + , snMaker ( nm ) + {} +public: + /// \ru Установка режима по поверхности, переносится ли эквидистантная точка согласованно с нормалью к поверхности. \en Setting the mode whether offset point is moved according to surface normal or not. + void SetBySurfaceNormal( bool set, c3d::ConstSurfaceSPtr * s = c3d_null ) + { + if ( set ) { + useSurfaceNormal = set; + if ( s != c3d_null ) + surface = *s; + } + else { + useSurfaceNormal = false; + surface = c3d_null; + } + } + /// \ru Получить поверхность. \en Get surface. + bool BySurfaceNormal() const { return useSurfaceNormal; } + /// \ru Получить поверхность. \en Get surface. + const c3d::ConstSurfaceSPtr & GetSurface() const { return surface; } + /// \ru Получить ссылку на именователь. \en Get names maker reference. + const MbSNameMaker & GetNameMaker() const { return snMaker; } + +OBVIOUS_PRIVATE_COPY( MbSpatialOffsetCurveParams ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры эквидистантной кривой на поверхности. + \en Parameters of an offset curve on a surface. \~ + \details \ru Параметры эквидистантной кривой на поверхности по поверхностной кривой и значению смещения. \n + \en Parameters of an offset curve on surface from a curve on the surface and a shift value. \n \~ +\ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbSurfaceOffsetCurveParams { +public: + c3d::ConstFaceSPtr face; ///< \ru Грань, на которой строится эквидистанта. \en The face on which to build the offset curve. + MbAxis3D dirAxis; ///< \ru Направление смещения с точкой приложения. \en The offset direction with a reference point. + double dist; ///< \ru Величина смещения. \en The offset distance. +protected: + const MbSNameMaker & snMaker; ///< \ru Именователь кривых каркаса. \en An object defining the frame curves names. + +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbSurfaceOffsetCurveParams( const MbFace & f, const MbAxis3D & a, double d, const MbSNameMaker & nm ) + : face ( &f ) + , dirAxis( a ) + , dist ( d ) + , snMaker( nm ) + {} +public: + /// \ru Получить ссылку на именователь. \en Get names maker reference. + const MbSNameMaker & GetNameMaker() const { return snMaker; } + +OBVIOUS_PRIVATE_COPY( MbSurfaceOffsetCurveParams ) +}; + +#endif // __OP_CURVE_PARAMETERS_H diff --git a/C3d/Include/op_duplication_parameter.h b/C3d/Include/op_duplication_parameter.h index 440a802..4604831 100644 --- a/C3d/Include/op_duplication_parameter.h +++ b/C3d/Include/op_duplication_parameter.h @@ -110,21 +110,21 @@ public: /** \brief \ru Преобразовать параметры согласно матрице. \en Transform parameters according to the matrix. \~ */ - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; /** \brief \ru Сдвинуть параметры вдоль вектора. \en Move parameters along a vector. \~ \details \ru Сдвинуть параметры вдоль вектора. \en Move parameters along a vector. \n \~ */ - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; /** \brief \ru Повернуть параметры вокруг оси на заданный угол. \en Rotate parameters at a given angle around an axis. \~ \details \ru Повернуть параметры вокруг оси на заданный угол. \en Rotate parameters at a given angle around an axis. \n \~ */ - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = NULL ) = 0; + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = c3d_null ) = 0; /** \brief \ru Выдать свойства объекта. \en Get properties of the object. \~ @@ -152,7 +152,7 @@ public: \details \ru Построить копию объекта. \n \en Create a copy of the object. \n \~ */ - virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const = 0; + virtual DuplicationValues & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; /** \brief \ru Сгенерировать матрицы трансформаций. \en Generate matrices of transformations. \~ @@ -236,7 +236,7 @@ public: */ DuplicationMeshValues( bool isPolar, const MbVector3D & dir1, const double step1, const uint num1, const MbVector3D & dir2, const double step2, const uint num2, - const MbCartPoint3D * center = NULL, bool isAlongAxis = false ); + const MbCartPoint3D * center = c3d_null, bool isAlongAxis = false ); /// \ru Деструктор. \en Destructor. virtual ~DuplicationMeshValues(); @@ -248,11 +248,11 @@ public: /// \ru Тип параметров. \en Type of parameters. virtual MbeDuplicatesType Type() const; /// \ru Преобразовать сетку согласно матрице. \en Transform grid according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть сетку вдоль вектора. \en Move grid along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть сетку вокруг оси на заданный угол. \en Rotate grid at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = NULL ); + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = c3d_null ); /// \ru Выдать свойства объекта \en Get properties of the object virtual void GetProperties( MbProperties & ); @@ -263,7 +263,7 @@ public: virtual bool IsSame( const DuplicationValues &, double accuracy ) const; /// \ru Построить копию объекта. \en Create a copy of the object. - virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const; + virtual DuplicationValues & Duplicate( MbRegDuplicate * = c3d_null ) const; /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation by. virtual void GenerateTransformMatrices( std::vector & ) const; @@ -385,11 +385,11 @@ public: /// \ru Тип параметров. \en Type of parameters. virtual MbeDuplicatesType Type() const; /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = NULL ); + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = c3d_null ); /// \ru Выдать свойства объекта \en Get properties of the object virtual void GetProperties( MbProperties & ); @@ -400,7 +400,7 @@ public: virtual bool IsSame( const DuplicationValues &, double accuracy ) const; /// \ru Построить копию объекта. \en Create a copy of the object. - virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const; + virtual DuplicationValues & Duplicate( MbRegDuplicate * = c3d_null ) const; /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation. virtual void GenerateTransformMatrices( std::vector & ) const; diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index 4e9bbed..52768f6 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -138,7 +138,7 @@ public: } /// \ru Конструктор копирования. \en Copy-constructor. - SmoothValues( const SmoothValues & other, MbRegDuplicate * iReg = NULL ); + SmoothValues( const SmoothValues & other, MbRegDuplicate * iReg = c3d_null ); /// \ru Деструктор. \en Destructor. virtual ~SmoothValues(){} @@ -146,11 +146,11 @@ public: void Init( const SmoothValues & other ); public: /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ); /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = NULL ){} + virtual void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = c3d_null ){} /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL ); + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = c3d_null ); /// \ru Установить плоскость, параллельно которой будет выполнена остановка скругления в начале цепочки. \en Set the plane by which parallel will be carry out stop of the fillet at the begin. bool SetStopObjectAtBeg( const MbSurface * object, bool byObject = true ); @@ -202,7 +202,7 @@ public: {} /// \ru Конструктор копирования. \en Copy-constructor. - FullFilletValues( const FullFilletValues & other, MbRegDuplicate * iReg = NULL ); + FullFilletValues( const FullFilletValues & other, MbRegDuplicate * iReg = c3d_null ); /// \ru Деструктор. \en Destructor. ~FullFilletValues(){} @@ -210,11 +210,11 @@ public: /// \ru Функция инициализации. \en Initialization function. void Init( const FullFilletValues & other ); /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); + void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ); /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = NULL ){} + void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = c3d_null ){} /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL ); + void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = c3d_null ); /// \ru Оператор присваивания. \en Assignment operator. FullFilletValues & operator = ( const FullFilletValues & other ) { @@ -341,7 +341,7 @@ public: double placeAngle; ///< \ru Угол между осью и нормалью к поверхности (0 <= placeAngle <= M_PI_2). \en Angle between axis and normal to the surface (0 <= placeAngle <= M_PI_2). double azimuthAngle; ///< \ru Угол поворота оси вокруг нормали поверхности (-M_PI2 <= azimuthAngle <= M_PI2). \en Angle of rotation around the surface normal (-M_PI2 <= azimuthAngle <= M_PI2). protected: - MbSurface * surface; ///< \ru Обрабатываемая поверхность (если NULL, то считается плоской). \en Processing surface (if NULL, then is considered planar). + MbSurface * surface; ///< \ru Обрабатываемая поверхность (если c3d_null, то считается плоской). \en Processing surface (if c3d_null, then is considered planar). bool doPhantom; ///< \ru Создавать фантом результата операции. \en Create the phantom of the operation. protected: @@ -365,13 +365,13 @@ public: /// \ru Тип выемки. \en Type of notch. virtual MbeHoleType Type() const = 0; /// \ru Построить копию объекта. \en Create a copy of the object. - virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const = 0; + virtual HoleValues & Duplicate( MbRegDuplicate * ireg = c3d_null ) const = 0; /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ) = 0; + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = c3d_null ) = 0; /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL ); + virtual void Move ( const MbVector3D &, MbRegTransform * ireg = c3d_null ); /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL ); + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = c3d_null ); /// \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual bool IsSame( const HoleValues &, double accuracy ) const; @@ -451,7 +451,7 @@ public: // ____________/|| // /| | || // +-+----------+-++ - bt_DoubleCylinder = 6, ///< \ru Двойное цилиндрическое отверстие со скруглением. \en Double cylindrical hole with a fillet. + bt_DoubleCylinder = 6, ///< \ru Двойное цилиндрическое отверстие со скруглением. \en Double cylindrical hole with a fillet. }; public: @@ -498,8 +498,8 @@ public: public: virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch. - virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual HoleValues & Duplicate( MbRegDuplicate * ireg = c3d_null ) const; // \ru Построить копию. \en Create a copy. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator. private: @@ -565,8 +565,8 @@ public: public: virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch. - virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual HoleValues & Duplicate( MbRegDuplicate * ireg = c3d_null ) const; // \ru Построить копию. \en Create a copy. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator. private: @@ -676,8 +676,8 @@ public: public: virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch. - virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual HoleValues & Duplicate( MbRegDuplicate * ireg = c3d_null ) const; // \ru Построить копию. \en Create a copy. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal? virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator. private: @@ -1313,7 +1313,7 @@ private: bool vclosed; ///< \ru Признак замкнутости по V. \en Attribute of closedness along V. Array2 points; ///< \ru Множество точек. \en Set of points. double weight; ///< \ru Вес точек в случае одинаковости весов. \en Points weight in the case of equal weights. - Array2 * weights; ///< \ru Веса точек (может быть NULL). \en Weights of points (can be NULL). + Array2 * weights; ///< \ru Веса точек (может быть c3d_null). \en Weights of points (can be c3d_null). bool throughPoints; ///< \ru Строить поверхность, проходящую через точки. \en Build surface passing through points. bool pointsCloud; ///< \ru Облако точек (массив не упорядочен). \en Point cloud (disordered array). MbPlane * cloudPlane; ///< \ru Опорная плоскость облака точек. \en Support plane of point cloud. @@ -1486,11 +1486,11 @@ public: /// \ru Получить массив точек. \en Get array of points. bool GetPoints ( Array2 & pnts ) const { return pnts.Init( points ); } /// \ru Если ли веса? \en Is there weights? - bool IsWeighted() const { return (weights != NULL); } + bool IsWeighted() const { return (weights != c3d_null); } /// \ru Получить массив весов. \en Get array of weights. bool GetWeights( Array2 & wts ) const; /// \ru Получить плоскость проецирования. \en Get the plane of projection. - const MbPlane * GetCloudPlane() const { return (pointsCloud ? cloudPlane : NULL);} + const MbPlane * GetCloudPlane() const { return (pointsCloud ? cloudPlane : c3d_null);} /** \brief \ru Минимально возможный порядок сплайнов в случае облака точек. \en The smallest possible order of splines in the case of point cloud. \~ @@ -1528,7 +1528,7 @@ public: // --- inline bool NurbsSurfaceValues::GetWeights( Array2 & wts ) const { - if ( weights != NULL ) { + if ( weights != c3d_null ) { if ( wts.Init( *weights ) ) return true; } @@ -1602,7 +1602,7 @@ inline bool NurbsSurfaceValues::SetUVPoint( size_t ui, size_t vi, const MbCartPo // --- inline bool NurbsSurfaceValues::GetUVWeight( size_t ui, size_t vi, double & wt ) const { - if ( weights != NULL && ui < GetUCount() && vi < GetVCount() ) { + if ( weights != c3d_null && ui < GetUCount() && vi < GetVCount() ) { wt = (*weights)( vi, ui ); return (wt != UNDEFINED_DBL); //-V550 } @@ -1616,7 +1616,7 @@ inline bool NurbsSurfaceValues::GetUVWeight( size_t ui, size_t vi, double & wt ) // --- inline bool NurbsSurfaceValues::GetCommonWeight( double & wt ) const { - if ( weights == NULL && weight != UNDEFINED_DBL ) { //-V550 + if ( weights == c3d_null && weight != UNDEFINED_DBL ) { //-V550 wt = weight; return true; } @@ -1635,7 +1635,7 @@ inline void NurbsSurfaceValues::SetThroughPoints( bool tp ) DeleteWeights(); weight = 1.0; } - if ( weights == NULL && weight == UNDEFINED_DBL ) //-V550 + if ( weights == c3d_null && weight == UNDEFINED_DBL ) //-V550 weight = 1.0; } @@ -1718,15 +1718,15 @@ public: const RPArray & curvesV, bool vClosed, bool checkSelfInt, bool tess = false, - const RPArray * chainsU = NULL, - const RPArray * chainsV = NULL, + const RPArray * chainsU = c3d_null, + const RPArray * chainsV = c3d_null, MbeMatingType type0 = trt_Position, MbeMatingType type1 = trt_Position, MbeMatingType type2 = trt_Position, MbeMatingType type3 = trt_Position, - const c3d::ConstSurfacesVector * surf0 = NULL, // \ru Сопрягаемые поверхности через curvesU[0] \en Mating surfaces through curvesU[0] - const c3d::ConstSurfacesVector * surf1 = NULL, // \ru Сопрягаемые поверхности через curvesV[0] \en Mating surfaces through curvesV[0] - const c3d::ConstSurfacesVector * surf2 = NULL, // \ru Сопрягаемые поверхности через curvesU[maxU] \en Mating surfaces through curvesU[maxU] - const c3d::ConstSurfacesVector * surf3 = NULL, // \ru Сопрягаемые поверхности через curvesV[maxV] \en Mating surfaces through curvesV[maxV] - const MbPoint3D * pnt = NULL, + const c3d::ConstSurfacesVector * surf0 = c3d_null, // \ru Сопрягаемые поверхности через curvesU[0] \en Mating surfaces through curvesU[0] + const c3d::ConstSurfacesVector * surf1 = c3d_null, // \ru Сопрягаемые поверхности через curvesV[0] \en Mating surfaces through curvesV[0] + const c3d::ConstSurfacesVector * surf2 = c3d_null, // \ru Сопрягаемые поверхности через curvesU[maxU] \en Mating surfaces through curvesU[maxU] + const c3d::ConstSurfacesVector * surf3 = c3d_null, // \ru Сопрягаемые поверхности через curvesV[maxV] \en Mating surfaces through curvesV[maxV] + const MbPoint3D * pnt = c3d_null, bool modify = true, bool direct0 = true, bool direct1 = true, bool direct2 = true, bool direct3 = true ); @@ -1822,9 +1822,9 @@ public: /// \ru Максимальный индекс в массиве кривых по U. \en The maximum index in the array of curves along U. ptrdiff_t GetCurvesUMaxIndex() const { return curvesU.MaxIndex(); } /// \ru Получить кривую по индексу. \en Get the curve by the index. - const MbCurve3D * GetCurveU( size_t k ) const { return ((k < curvesU.Count()) ? curvesU[k] : NULL); } + const MbCurve3D * GetCurveU( size_t k ) const { return ((k < curvesU.Count()) ? curvesU[k] : c3d_null); } /// \ru Получить кривую по индексу. \en Get the curve by the index. - MbCurve3D * SetCurveU( size_t k ) { return ((k < curvesU.Count()) ? curvesU[k] : NULL); } + MbCurve3D * SetCurveU( size_t k ) { return ((k < curvesU.Count()) ? curvesU[k] : c3d_null); } /// \ru Получить кривые по U. \en Get curves along U. void GetCurvesU( RPArray & curves ) const { curves.AddArray(curvesU); } /// \ru Установить кривые по U. \en Set curves along U. @@ -1839,9 +1839,9 @@ public: /// \ru Максимальный индекс в массиве кривых по V. \en The maximum index in the array of curves along V. ptrdiff_t GetCurvesVMaxIndex() const { return curvesV.MaxIndex(); } /// \ru Получить кривую по индексу. \en Get the curve by the index. - const MbCurve3D * GetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : NULL); } + const MbCurve3D * GetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : c3d_null); } /// \ru Получить кривую по индексу. \en Get the curve by the index. - MbCurve3D * SetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : NULL); } + MbCurve3D * SetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : c3d_null); } /// \ru Получить кривые по V. \en Get curves along V. void GetCurvesV( RPArray & curves ) const { curves.AddArray(curvesV); } /// \ru Установить кривые по V. \en Set curves along V. @@ -1856,9 +1856,9 @@ public: /// \ru Максимальный индекс в массиве цепочек по U. \en The maximum index in the array of chains along U. ptrdiff_t GetChainsUMaxIndex() const { return chainsU.MaxIndex(); } /// \ru Получить цепочку по индексу. \en Get the chain by the index. - const MbPolyline3D * GetChainU( size_t k ) const { return ( ( k < chainsU.Count() ) ? chainsU[k] : NULL ); } + const MbPolyline3D * GetChainU( size_t k ) const { return ( ( k < chainsU.Count() ) ? chainsU[k] : c3d_null ); } /// \ru Получить цепочку по индексу. \en Get the chain by the index. - MbPolyline3D * SetChainU( size_t k ) { return ( ( k < chainsU.Count() ) ? chainsU[k] : NULL ); } + MbPolyline3D * SetChainU( size_t k ) { return ( ( k < chainsU.Count() ) ? chainsU[k] : c3d_null ); } /// \ru Получить цепочки по U. \en Get chains along U. void GetChainsU( RPArray & chains ) const { chains.AddArray( chainsU ); } /// \ru Установить цепочки по U. \en Set chains along U. @@ -1873,9 +1873,9 @@ public: /// \ru Максимальный индекс в массиве цепочек по V. \en The maximum index in the array of chains along V. ptrdiff_t GetChainsVMaxIndex() const { return chainsV.MaxIndex(); } /// \ru Получить цепочку по индексу. \en Get the chain by the index. - const MbPolyline3D * GetChainV( size_t k ) const { return ( ( k < chainsV.Count() ) ? chainsV[k] : NULL ); } + const MbPolyline3D * GetChainV( size_t k ) const { return ( ( k < chainsV.Count() ) ? chainsV[k] : c3d_null ); } /// \ru Получить цепочку по индексу. \en Get the chain by the index. - MbPolyline3D * SetChainV( size_t k ) { return ( ( k < chainsV.Count() ) ? chainsV[k] : NULL ); } + MbPolyline3D * SetChainV( size_t k ) { return ( ( k < chainsV.Count() ) ? chainsV[k] : c3d_null ); } /// \ru Получить цепочки по V. \en Get chains along V. void GetChainsV( RPArray & chains ) const { chains.AddArray( chainsV ); } /// \ru Установить цепочки по V. \en Set chains along V. @@ -2214,11 +2214,11 @@ public: void InitByShell ( ExtensionType t, LateralKind k, const MbFace * f, const MbSolid * s ); /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); + void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = c3d_null ); /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - void Move ( const MbVector3D & to, MbRegTransform * ireg = NULL ); + void Move ( const MbVector3D & to, MbRegTransform * ireg = c3d_null ); /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - void Rotate ( const MbAxis3D & axis, double ang, MbRegTransform * ireg = NULL ); + void Rotate ( const MbAxis3D & axis, double ang, MbRegTransform * ireg = c3d_null ); /// \ru Получить оболочку. \en Get the shell. const MbFaceShell * GetShell() const { return shell; } @@ -2287,10 +2287,10 @@ public: , checkSelfInt ( false ) , edgeConnType1 ( false ) , edgeConnType2 ( false ) - , boundDirection11 ( NULL ) - , boundDirection12 ( NULL ) - , boundDirection21 ( NULL ) - , boundDirection22 ( NULL ) + , boundDirection11 ( c3d_null ) + , boundDirection12 ( c3d_null ) + , boundDirection21 ( c3d_null ) + , boundDirection22 ( c3d_null ) {} /// \ru Конструктор по параметрам. \en Constructor by parameters. JoinSurfaceValues( JoinConnType t1, JoinConnType t2, double tens1, double tens2, bool selfInt = false ) @@ -2303,10 +2303,10 @@ public: , checkSelfInt ( selfInt ) , edgeConnType1 ( false ) , edgeConnType2 ( false ) - , boundDirection11 ( NULL ) - , boundDirection12 ( NULL ) - , boundDirection21 ( NULL ) - , boundDirection22 ( NULL ) + , boundDirection11 ( c3d_null ) + , boundDirection12 ( c3d_null ) + , boundDirection21 ( c3d_null ) + , boundDirection22 ( c3d_null ) {} /// \ru Конструктор копирования. \en Copy-constructor. JoinSurfaceValues( const JoinSurfaceValues & other ); @@ -2426,10 +2426,10 @@ public: } } if ( isSame ) { - bool isBoundDir11 = ((other.boundDirection11 != NULL) && (boundDirection11 != NULL)); - bool isBoundDir12 = ((other.boundDirection12 != NULL) && (boundDirection12 != NULL)); - bool isBoundDir21 = ((other.boundDirection21 != NULL) && (boundDirection21 != NULL)); - bool isBoundDir22 = ((other.boundDirection22 != NULL) && (boundDirection22 != NULL)); + bool isBoundDir11 = ((other.boundDirection11 != c3d_null) && (boundDirection11 != c3d_null)); + bool isBoundDir12 = ((other.boundDirection12 != c3d_null) && (boundDirection12 != c3d_null)); + bool isBoundDir21 = ((other.boundDirection21 != c3d_null) && (boundDirection21 != c3d_null)); + bool isBoundDir22 = ((other.boundDirection22 != c3d_null) && (boundDirection22 != c3d_null)); if ( isSame && isBoundDir11 ) isSame = c3d::EqualVectors( *other.boundDirection11, *boundDirection11, accuracy ); @@ -2523,31 +2523,35 @@ struct MATH_CLASS MedianShellValues { public: FilletType filletType; - double position; ///< \ru Параметр смещения срединной оболочки относительно первой грани из пары. По умолчанию равен 50% расстояния между гранями. \en Parameter of shift the median surface from first face in faces pair. By default is 50% from distance between faces in pair. - double dmin; ///< \ru Минимальный параметр эквидистантности. \en Minimal equidistation value. - double dmax; ///< \ru Максимальный параметр эквидистантности. \en Maximal equidistation value. + double position; ///< \ru Параметр смещения срединной оболочки относительно первой грани из пары. По умолчанию равен 50% расстояния между гранями. \en Parameter of shift the median surface from first face in faces pair. By default is 50% from distance between faces in pair. + double dmin; ///< \ru Минимальный параметр эквидистантности. \en Minimal equidistation value. + double dmax; ///< \ru Максимальный параметр эквидистантности. \en Maximal equidistation value. + bool cutByBordes; ///< \ru Флаг подрезки срединной оболочки границами родительской оболочки. \en Flag indicates is need to truncate median shell by parent shell faces. public: /// \ru Конструктор по умолчанию. \en Default constructor. MedianShellValues() - : filletType ( tf_average ) - , position ( 0.5 ) - , dmin ( 0.0 ) - , dmax ( 0.0 ) + : filletType ( tf_average ) + , position ( 0.5 ) + , dmin ( 0.0 ) + , dmax ( 0.0 ) + , cutByBordes ( false ) {} /// \ru Конструктор копирования. \en Copy-constructor. MedianShellValues( const MedianShellValues & other ) - : filletType ( other.filletType ) - , position ( other.position ) - , dmin ( other.dmin ) - , dmax ( other.dmax ) + : filletType ( other.filletType ) + , position ( other.position ) + , dmin ( other.dmin ) + , dmax ( other.dmax ) + , cutByBordes ( other.cutByBordes ) {} /// \ru Конструктор по параметрам. \en Constructor by parameters. - MedianShellValues( double pos, double d1, double d2 ) - : filletType( tf_average ) - , position ( pos ) - , dmin ( d1 ) - , dmax ( d2 ) + MedianShellValues( double pos, double d1, double d2, bool cut ) + : filletType ( tf_average ) + , position ( pos ) + , dmin ( d1 ) + , dmax ( d2 ) + , cutByBordes ( cut ) {} public: @@ -2557,7 +2561,8 @@ public: if ( filletType == obj.filletType && (::fabs(dmin - obj.dmin) < accuracy) && (::fabs(dmax - obj.dmax) < accuracy) && - (::fabs(position - obj.position) < accuracy) ) + (::fabs(position - obj.position) < accuracy) && + cutByBordes == obj.cutByBordes ) return true; return false; } @@ -2575,6 +2580,7 @@ public: position = other.position; dmin = other.dmin; dmax = other.dmax; + cutByBordes = other.cutByBordes; return *this; } @@ -2635,6 +2641,8 @@ public: } /// \ru Получить пару граней по индексу. \en Get pair of faces by index. const c3d::ItemIndexPair & _GetFacePair( size_t index ) const { return facePairs[index]; } + /// \ru Установить пару граней по индексу. \en Set pair of faces by index. + c3d::ItemIndexPair & SetFacePair( size_t index ) { return facePairs[index]; } /// \ru Удалить пару граней из набора. \en Remove pair of faces from set. void RemovePairByIndex( size_t index ) { @@ -3161,11 +3169,11 @@ public: } public: /// \ru Это резка плоским контуром? \en Is cutting by planar contour? - bool IsCuttingByPlanarContour() const { return (cutterData.GetSketchCurvesCount() > 0 && cutterData.GetSketchCurve(0) != NULL); } + bool IsCuttingByPlanarContour() const { return (cutterData.GetSketchCurvesCount() > 0 && cutterData.GetSketchCurve(0) != c3d_null); } /// \ru Это резка поверхностью? \en Is cutting by surface? - bool IsCuttingBySurface() const { return (cutterData.GetSurfacesCount() > 0 && cutterData.GetSurface(0) != NULL); } + bool IsCuttingBySurface() const { return (cutterData.GetSurfacesCount() > 0 && cutterData.GetSurface(0) != c3d_null); } /// \ru Это резка оболочкой? \en Is cutting by shell? - bool IsCuttingBySolid() const { return (cutterData.GetCreatorsCount() > 0 && cutterData.GetCreator(0) != NULL) || (cutterData.GetSolidShell() != NULL); } + bool IsCuttingBySolid() const { return (cutterData.GetCreatorsCount() > 0 && cutterData.GetCreator(0) != c3d_null) || (cutterData.GetSolidShell() != c3d_null); } /// \ru Получить данные секущего объекта. \en Get cutter object(s) data. const MbSplitData & GetCutterData() const { return cutterData; } diff --git a/C3d/Include/op_swept_parameter.h b/C3d/Include/op_swept_parameter.h index 06c1173..46e9c20 100644 --- a/C3d/Include/op_swept_parameter.h +++ b/C3d/Include/op_swept_parameter.h @@ -1,1998 +1,2087 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Параметры операций над телами. - \en Parameters of operations on the solids. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __OP_SWEPT_PARAMETERS_H -#define __OP_SWEPT_PARAMETERS_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbMatrix3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbPolyCurve; -class MbRegTransform; -class MbRegDuplicate; - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные об образующей. - \en The generating data. \~ - \details \ru Данные об образующей операции движения. \n - Образующая операции выдавливания, вращения или кинематической операции - может включать в себя набор двумерных контуров, набор трехмерных контуров, тело. \n - Для набора двумерных контуров на поверхности существуют следующие ограничения:\n - – может быть один или несколько контуров;\n - – если контуров несколько, они должны быть либо все замкнуты, либо все разомкнуты;\n - - если контуры замкнуты, они могут быть вложенными друг в друга, уровень вложенности не ограничивается;\n - – контуры не должны пересекаться между собой или самопересекаться.\n - Для двумерных контуров на не плоской поверхности есть дополнительное ограничение: - все контуры должны быть замкнуты.\n - Построение операции по двумерным контурам на не плоской поверхности рассчитано на указание пользователем - грани тела в качестве образующей. В этом случае данные для образующей можно получить - с помощью метода грани MbFace::GetSurfaceCurvesData.\n - Ограничения для трехмерных контуров:\n - – контуры не должны пересекаться между собой или самопересекаться.\n - \en Data about generating of movement operation. \n - При указании тела и поверхности одновременно предполагается, что выполняется кинематическая операция над - телом вдоль кривой на этой поверхности, причем движение согласовано с нормалью. \n - Generating of extrusion operation, rotation or sweeping operation - can include a set of two-dimensional contours, a set of three-dimensional contours, solid. \n - For a set of two-dimensional contours on the surface, the following restrictions:\n - - can be one or multiple contours;\n - - If there are multiple contours, all of them must be either closed or open;\n - - if contours are closed, then they can be nested into each other, the level of nesting is not limited;\n - - contours can't overlap each other or self-intersect.\n - For two-dimensional contour on the non-planar surface is additional constraint: - all the contours must be closed.\n - Constructing operation by two-dimensional contours on non-planar surface it is necessary to specify the by the user - face of solid as generating. In this case, the generating data can be obtained - by the method of face MbFace::GetSurfaceCurvesData.\n - Constraints for three-dimensional contour:\n - - contours can't overlap each other or self-intersect.\n - When set a solid and a surface at the same time, we suppose that sweeping operation over solid along curve on surface - is done, and moving is according to surface normal. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS MbSweptData { - -private: - // \ru Данные о двумерных контурах на поверхности. \en Data about two-dimensional contours on the surface. - c3d::SurfaceSPtr surface; ///< \ru Поверхность. \en The surface. - c3d::PlaneContoursSPtrVector contours; ///< \ru Множество двумерных контуров. \en Set of two-dimensional contours. - // \ru Трехмерные контуры. \en Three-dimensional contours. - c3d::SpaceContoursSPtrVector contours3D; ///< \ru Множество трёхмерных контуров. \en Set of three-dimensional contours. - // \ru Тело. \en Solid. - c3d::SolidSPtr solid; ///< \ru Тело. \en A solid. - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - MbSweptData(); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSweptData( const MbSweptData &, MbRegDuplicate * ireg = NULL ); - -public: - - /** \brief \ru Конструктор плоской образующей. - \en Constructor of planar swept. \~ - \details \ru Конструктор плоской образующей из одного контура. - \en Constructor of planar swept from one contour. \~ - \param[in] place - \ru Локальная система координат. - \en A local coordinate system. \~ - \param[in] contour - \ru Контур в параметрах заданной системы координат. Используется оригинал. - \en Contour in parameters of the given coordinate system. Used original. \~ - */ - MbSweptData( const MbPlacement3D & place, MbContour & contour ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по набору контуров на поверхности. - \en Constructor by a set of contours on a surface. \~ - \param[in] _surface - \ru Поверхность. Используется оригинал. - \en The surface. Used original. \~ - \param[in] _contours - \ru Набор контуров. Используются оригиналы. - \en A set of contours. Used originals. \~ - */ - MbSweptData( MbSurface & _surface, RPArray & _contours ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по набору контуров на поверхности. - \en Constructor by a set of contours on a surface. \~ - \param[in] _surface - \ru Поверхность. Используется оригинал. - \en The surface. Used original. \~ - \param[in] _contours - \ru Набор контуров. Используются оригиналы. - \en A set of contours. Used originals. \~ - */ - MbSweptData( MbSurface & _surface, c3d::PlaneContoursSPtrVector & _contours ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по кривой. - \en Constructor by a contour. \~ - \param[in] _contour3d - \ru Кривая. Используются оригиналы. - \en A curve. Used originals. \~ - */ - MbSweptData( MbCurve3D & _curve3d ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по контуру. - \en Constructor by a contour. \~ - \param[in] _contour3d - \ru Контур. Используются оригиналы. - \en A contour. Used originals. \~ - */ - MbSweptData( MbContour3D & _contour3d ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по набору пространственных контуров. - \en Constructor by a set of spatial contours. \~ - \param[in] _contours3d - \ru Набор контуров. Используются оригиналы. - \en A set of contours. Used originals. \~ - */ - MbSweptData( RPArray & _contours3d ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по набору пространственных контуров. - \en Constructor by a set of spatial contours. \~ - \param[in] _contours3d - \ru Набор контуров. Используются оригиналы. - \en A set of contours. Used originals. \~ - */ - MbSweptData( c3d::SpaceContoursSPtrVector & _contours3d ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по телу. - \en Constructor by a solid. \~ - \param[in] _solid - \ru Тело. Используется оригинал объекта. - \en A solid. Used original of object. \~ - \param[in] _newMainName - \ru Новое главное имя для топологических элементов тела. - \en New main name for names of solid's topological elements. \~ - */ - MbSweptData( MbSolid & _solid, SimpleName newMainName = c3d::SIMPLENAME_MAX ); - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор смешанной образующей. - \en Constructor of mixed swept. \~ - \param[in] _surface - \ru Поверхность. Используется оригинал. - \en The surface. Used original. \~ - \param[in] _contours - \ru Набор двумерных контуров в параметрах заданной поверхности. Используются оригиналы. - \en Set of two-dimensional contours in the parameters of the given surface. Used originals. \~ - \param[in] _contours3d - \ru Набор трехмерных контуров. Используются оригиналы. - \en A set of three-dimensional contours. Used originals. \~ - \param[in] _solid - \ru Тело. Используется оригинал объекта. - \en A solid. Used original of object. \~ - */ - MbSweptData( MbSurface * _surface, RPArray & _contours, - RPArray & _contours3d, MbSolid * _solid ); - - /// \ru Деструктор. \en Destructor. - ~MbSweptData(); - -public: - /** \brief \ru Добавить данные. - \en Add data. \~ - \details \ru Добавить данные о контурах на поверхности. - \en Add data about contours to the surface. \~ - \param[in] _surface - \ru Поверхность. Добавляется оригинал объекта. - \en The surface. Added original of the object. \~ - \param[in] _contours - \ru Набор контуров. Добавляются оригиналы. - \en A set of contours. Originals are added. \~ - */ - bool AddData( MbSurface & _surface, const RPArray & _contours ); - - /** \brief \ru Добавить данные. - \en Add data. \~ - \details \ru Добавить данные о контурах на поверхности. - \en Add data about contours to the surface. \~ - \param[in] _surface - \ru Поверхность. Добавляется оригинал объекта. - \en The surface. Added original of the object. \~ - \param[in] _contours - \ru Набор контуров. Добавляются оригиналы. - \en A set of contours. Originals are added. \~ - */ - bool AddData( MbSurface & _surface, c3d::PlaneContoursSPtrVector & _contours ); - - /** \brief \ru Количество всех кривых. - \en The count of all the curves. \~ - \details \ru Общее количество двумерных и трехмерных кривых. - \en The total count of two and three-dimensional curves. \~ - */ - size_t CurvesCount() const; - - /** \brief \ru Получить кривую по индексу. - \en Get the curve by the index. \~ - \details \ru Получить кривую из множества кривых на поверхности и трехмерных кривых. - \en Get the curve from set of curves on the surface and three-dimensional curves. \~ - \param[in] i - \ru Номер кривой в пределах от 0 до CurvesCount(). - \en The index of curve from 0 to CurvesCount(). \~ - \return \ru Кривую на поверхности или трехмерную кривую. - \en Curve on the surface or three-dimensional curve. \~ - */ - SPtr GetCurve3D( size_t i ) const; - - /// \ru Есть данные о двумерных кривых на поверхности? \en Is there data of two-dimensional curves on the surface? - bool IsSurfaceCurvesData() const { return ((surface != NULL) && !contours.empty()); } - /// \ru Есть данные о пространственных кривых? \en Is there data of spatial curves? - bool IsSpaceCurvesData() const { return !contours3D.empty(); } - /// \ru Есть данные о теле? \en Is there data about the solid? - bool IsSolidData() const { return (solid != NULL); } - - /// \ru Выдать поверхность. \en Get the surface. - const MbSurface * GetSurface() const { return surface; } - /// \ru Выдать поверхность для изменения. \en Get the surface for editing. - MbSurface * SetSurface() { return surface; } - - /// \ru Положить поверхность. \en Set a surface. - - /** \brief \ru Установить поверхность. - \en Set a surface. \~ - \details \ru Установить новую поверхность как носитель двумерных контуров или как целевую поверхность для направляющей. - \en Set surface carrier of two-dimensional contours or desired surface-carrier of guide curve. \~ - \param[in] surf - \ru Новая поверхность как носитель для двумерных контуров или целевая поверхность для направляющей. - \en Surface carrier of two-dimensional contours or desired surface-carrier of guide curve. \~ - */ - void SetSurface( const MbSurface & surf ) { surface = const_cast( &surf ); } - - /// \ru Выдать набор двумерных контуров. \en Get the set of two-dimensional contours. - const c3d::PlaneContoursSPtrVector & GetContours() const { return contours; } - /// \ru Выдать набор трехмерных контуров. \en Get the set of three-dimensional contours. - const c3d::SpaceContoursSPtrVector & GetContours3D() const { return contours3D; } - /// \ru Выдать тело. \en Get the solid. - const MbSolid * GetSolid() const { return solid; } - /// \ru Выдать тело для изменения. \en Get the solid for editing. - MbSolid * SetSolid() const { return solid; } - - /** \brief \ru Преобразовать объект. - \en Transform the object. \~ - \details \ru Преобразовать исходный объект согласно матрице c использованием регистратора. - \en Transform the initial object according to the matrix using the registrator. \~ - \param[in] matr - \ru Матрица преобразования. - \en A transformation matrix. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - /** \brief \ru Сдвинуть объект. - \en Move the object. \~ - \details \ru Сдвинуть геометрический объект вдоль вектора с использованием регистратора. - \en Move a geometric object along the vector using the registrator. \~ - \param[in] to - \ru Вектор сдвига. - \en Translation vector. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ); - /** \brief \ru Повернуть объект. - \en Rotate the object. \~ - \details \ru Повернуть объект вокруг оси на заданный угол с использованием регистратора. - \en Rotate an object about the axis by the given angle using the registrator. \~ - \param[in] axis - \ru Ось поворота. - \en The rotation axis. \~ - \param[in] angle - \ru Угол поворота. - \en The rotation angle. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - /** \brief \ru Определить, являются ли объекты равными. - \en Determine whether the objects are equal. \~ - \details \ru Определить, являются ли объекты равными с заданной точностью. - \en Determine whether the objects are equal with defined accuracy. \~ - \param[in] other - \ru Объект для сравнения. - \en Object for comparison. \~ - \return \ru Подобны ли объекты. - \en Whether the objects are similar. \~ - */ - bool IsSame( const MbSweptData & other, double accuracy ) const; - /** \brief \ru Определить, являются ли объекты подобными. - \en Determine whether the objects are similar. \~ - \details \ru Подобный объект можно инициализировать по данным подобного ему объекта. - \en Similar object can be initialized by data of object which is similar to it. \~ - \param[in] other - \ru Объект для сравнения. - \en Object for comparison. \~ - \return \ru Подобны ли объекты. - \en Whether the objects are similar. \~ - */ - bool IsSimilar( const MbSweptData & other ) const; - /** \brief \ru Сделать объекты равным. - \en Make objects equal. \~ - \details \ru Равными можно сделать только подобные объекты. - \en It is possible to make equal only similar objects. \~ - \param[in] init - \ru Объект для инициализации. - \en Object for initialization. \~ - \return \ru Сделан ли объект равным присланному. - \en Whether the object is made equal to the given one. \~ - */ - bool SetEqual ( const MbSweptData & other ); - - /** \brief \ru Замкнуты ли все контуры. - \en Whether all contours are closed. \~ - \details \ru Замкнуты ли все контуры. \n - \en Whether all contours are closed. \n \~ - \return \ru Возвращает true, если все контуры замкнуты. - \en Returns true if all contours are closed. \~ - */ - bool IsContoursClosed() const; - - /// \ru Проверить, что нет разрывов между сегментами поверхностных контуров. \en Check that there are no gaps between the segments of the surface contours. - bool CheckSurfaceContourConnection( double eps ) const; - /// \ru Проверить, что нет разрывов между сегментами пространственных контуров. \en Check that there are no gaps between the segments of the spatial contours. - bool CheckSpaceContourConnection( double eps ) const; - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSweptData & operator = ( const MbSweptData & ); - -KNOWN_OBJECTS_RW_REF_OPERATORS( MbSweptData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Cпособ выдавливания/вращения. - \en Method of extrusion/rotation. \~ - \details \ru Cпособ построения выдавливания/вращения. \n - \en Method of extrusion/rotation constructing. \n \~ - \ingroup Build_Parameters -*/ -// --- -enum MbSweptWay { - sw_scalarValue = -2, ///< \ru Выдавить на заданную глубину / вращать на заданный угол. \en Extrude to a given depth / rotate by a given angle. - sw_shell = -1, ///< \ru До ближайшего объекта (тела). \en To the nearest object (solid). - sw_surface = 0, ///< \ru До поверхности. \en To the surface. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры вращения и выдавливания. - \en Parameters of rotation and extrusion. \~ - \details \ru Данные о построении операции вращения или выдавливания - в одном из направлений: прямом или обратном. - \en Data about construction of rotation and extrusion - in one of directions: forward or backward. \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS MbSweptSide { -public: - MbSweptWay way; ///< \ru Способ выдавливания/вращения. \en Method of extrusion/rotation. - double scalarValue; ///< \ru Угол вращения/глубина выдавливания. \en Angle of rotation/depth of extrusion. - - /** \brief \ru Расстояние от поверхности. - \en Distance from the surface. \~ - \details \ru Расстояние от поверхности, до которой строим операцию. - Задавать при построении операции до поверхности (way = sw_surface). - distance < 0.0 при построении операции за поверхность, - distance > 0.0 при построении операции до поверхности. - \en Distance from the surface to construct up to. - Set when constructing operation to the surface (way = sw_surface). - distance < 0.0 when constructing operation back of surface, - distance > 0.0 when constructing operation front of surface. \~ - */ - double distance; - - /** \brief \ru Угол уклона. - \en Draft angle. \~ - \details \ru Угол уклона при выдавливании.\n - Операцию выдавливания с уклоном можно построить только в случае плоской образующей. - \en Draft angle when extruding.\n - Extrusion operation with draft can be constructed in the case of planar swept. \~ - */ - double rake; - -protected: - /** \brief \ru Поверхность, до которой строим операцию. - \en The surface to construct up to. \~ - \details \ru Поверхность, до которой строим операцию.\n - Задавать при построении операции до поверхности (way = sw_surface). - \en The surface to construct up to.\n - Set when constructing operation to the surface (way = sw_surface). \~ - */ - MbSurface * surface; - - /** \brief \ru Признак совпадения нормали поверхности с нормалью грани. - \en An attribute of coincidence between the surface normal and the face normal. \~ - \details \ru Признак совпадения нормали поверхности, до которой строим операцию, с нормалью грани.\n - Задавать при построении операции до поверхности (way = sw_surface).\n - Указывает положение оболочки-результата относительно поверхности. - Используется при построении массива операций до поверхности. - Если у всех элементов массива признак должен быть одинаковым, - то при построении исходной операции нужно задать признак равным orient_BOTH (направление не определено). - При построении признак будет определен, и его значение нужно использовать для построения остальных элементов массива. - \en An attribute of coincidence between the face normal and the normal of surface to which to create operation.\n - Set when constructing operation to the surface (way = sw_surface).\n - Specifies the position of shell-result relative to the surface. - Used when constructing the array of operations to the surface. - If attributes of all the elements of array must be the same, - then when constructing of the original operation need to set attribute which is equal to orient_BOTH (the direction is not determined). - When constructing the attribute is determined and its value should be used for the construction of other elements of the array. \~ - */ - MbeSenseValue sameSense; - - -public: - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Задает параметры операции со способом "на заданную глубину". - Для построения операции параметры нужно изменить, - например, указать глубину выдавливания (угол вращения). - \en Sets parameters of the operation with the method "to a given depth". - For construction of operation the parameters need to change, - for example: specify the depth of extrusion (angle of rotation). \~ - */ - MbSweptSide() - : way ( sw_scalarValue ) - , scalarValue( 0.0 ) - , distance ( 0.0 ) - , rake ( 0.0 ) - , surface ( NULL ) - , sameSense ( orient_BOTH ) - {} - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор на угол вращения\глубину выдавливания. - \en Constructor by angle of rotation\depth of extrusion. \~ - \param[in] sVal - \ru Угол вращения\глубина выдавливания. - \en Angle of rotation\depth of extrusion. \~ - */ - MbSweptSide( double sVal ) - : way ( sw_scalarValue ) - , scalarValue( sVal ) - , distance ( 0.0 ) - , rake ( 0.0 ) - , surface ( NULL ) - , sameSense ( orient_BOTH ) - {} - - /** \brief \ru Конструктор до поверхности. - \en Constructor to the surface. \~ - \details \ru Конструктор до поверхности. Расстояние от поверхности задается равным 0.0. - \en Constructor to the surface. Distance from the surface is set to 0.0. \~ - \param[in] surf - \ru Поверхность, до которой строится операция. - \en The surface to construct up to. \~ - */ - MbSweptSide( MbSurface * surf ); - - /** \brief \ru Конструктор до поверхности. - \en Constructor to the surface. \~ - \details \ru Конструктор до поверхности. Для элемента массива. - \en Constructor to the surface. For array element. \~ - \param[in] surf - \ru Поверхность, до которой строится операция. - \en The surface to construct up to. \~ - \param[in] sense - \ru Признак совпадения нормали заданной поверхности с нормалью грани. - Указывает, по какую сторону от поверхности должна находиться построенная оболочка. - \en An attribute of coincidence between the normal of given surface and the face normal. - Indicates at which side of the surface the must be located constructed shell. \~ - */ - MbSweptSide( MbSurface * surf, MbeSenseValue sense ); - - /** \brief \ru Конструктор копирования. - \en Copy-constructor. \~ - \details \ru Конструктор копирования данных с использованием той же поверхности. - \en Copy-constructor of data with using of the same surface. \~ - \param[in] other - \ru Исходные параметры. - \en Initial parameters. \~ - */ - MbSweptSide( const MbSweptSide & other ); - - /** \brief \ru Конструктор копирования с регистратором. - \en Copy-constructor with the registrator. \~ - \details \ru Конструктор копирования с регистратором. Поверхность копируется. - \en Copy-constructor with the registrator. Surface is copying. \~ - \param[in] other - \ru Исходные параметры. - \en Initial parameters. \~ - */ - MbSweptSide( const MbSweptSide & other, MbRegDuplicate * ireg ); - - /// \ru Деструктор. \en Destructor. - virtual ~MbSweptSide(); - - /// \ru Оператор присваивания данных с использованием той же поверхности. \en Assignment operator of data with using of the same surface. - MbSweptSide & operator = ( const MbSweptSide & other ); - - /// \ru Получить поверхность. \en Get the surface. - MbSurface * GetSurface() const { return surface; } - /// \ru Заменить поверхность. \en Replace surface. - void SetSurface( MbSurface * s ); - - /// \ru Получить признак совпадения нормали поверхности с нормалью грани. \en Get the attribute of coincidence between the surface normal and the face normal. - MbeSenseValue GetSameSense() const { return sameSense; } - /// \ru Установить признак совпадения нормали поверхности с нормалью грани. \en Set the attribute of coincidence between the surface normal and the face normal. - void SetSameSense( MbeSenseValue sense ) { sameSense = sense; } - /// \ru Доступ к признаку совпадения нормали поверхности с нормалью грани. \en Access to the attribute of coincidence between the surface normal and the face normal. - MbeSenseValue & SetSameSense() { return sameSense; } - - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSweptSide & other, double accuracy ) const - { - if ( (other.way == way) && (other.sameSense == sameSense) ) { - if ( (::fabs(other.scalarValue - scalarValue) < accuracy) && - (::fabs(other.distance - distance) < accuracy) && - (::fabs(other.rake - rake) < accuracy) ) - { - bool isSurf1 = (surface != NULL); - bool isSurf2 = (other.surface != NULL); - - if ( isSurf1 == isSurf2 ) { - if ( isSurf1 && isSurf2 ) { - if ( !other.surface->IsSame( *surface, accuracy ) ) - return false; - } - return true; - } - } - } - - return false; - } -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры формообразующей операции. - \en The parameters of form-generating operation. \~ - \details \ru Параметры построения формообразующей операции - (например, выдавливания, вращения, кинематической, по сечениям). \n - \en The construction parameters of form-generating operation. - (for example: extrusion, rotation, sweeping, loft). \n \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS SweptValues { -public: - - /** \brief \ru Толщина стенки (величина эквидистанты) в прямом направлении. - \en Wall thickness (offset distance) along the forward direction. \~ - \details \ru Толщина стенки (величина эквидистанты) в положительном направлении нормали объекта - (грани, поверхности, плоскости кривой). - \en Wall thickness (offset distance) along the positive direction of the normal of an object - (face, surface, plane of the curve). \~ - */ - double thickness1; - - /** \brief \ru Толщина стенки (величина эквидистанты) в обратном направлении. - \en Wall thickness (offset distance) along the backward direction. \~ - \details \ru Толщина стенки (величина эквидистанты) в отрицательном направлении нормали объекта - (грани, поверхности, плоскости кривой). - \en Wall thickness (offset distance) along the negative direction of the normal of an object - (face, surface, plane of the curve). \~ - */ - double thickness2; - - bool shellClosed; ///< \ru Замкнутость оболочки. \en Closedness of shell. - -private: - bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods). - bool mergeFaces; ///< \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - SweptValues() - : thickness1 ( 0.0 ) - , thickness2 ( 0.0 ) - , shellClosed ( true ) - , checkSelfInt( true ) - , mergeFaces ( true ) - {} - /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. - SweptValues( double t1, double t2, bool c = true ) - : thickness1 ( t1 ) - , thickness2 ( t2 ) - , shellClosed ( c ) - , checkSelfInt( true ) - , mergeFaces ( true ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - SweptValues( const SweptValues & other ) - : thickness1 ( other.thickness1 ) - , thickness2 ( other.thickness2 ) - , shellClosed ( other.shellClosed ) - , checkSelfInt( other.checkSelfInt ) - , mergeFaces ( other.mergeFaces ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~SweptValues() {} - -public: - /// \ru Это параметры выдавливания? \en This is extrusion parameters? - virtual bool IsExtrusionValues() const { return false; } - /// \ru Это параметры вращения? \en This is rotation parameters? - virtual bool IsRevolutionValues() const { return false; } - /// \ru Это параметры кинематики? \en This is "evolution" parameters? - virtual bool IsEvolutionValues() const { return false; } - /// \ru Это параметры операции по сечениям? \en This is "lofted" parameters? - virtual bool IsLoftedValues() const { return false; } - /// \ru Это параметры операции ребра жесткости? \en This is "rib" parameters? - virtual bool IsRibValues() const { return false; } - - /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const; - /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ - virtual bool IsSimilar( const MbSweptData & other ) const; - /// \ru Сделать объекты равным. \en Make objects equal. \~ - virtual bool SetEqual ( const MbSweptData & other ); - -public: - /// \ru Функция копирования данных. \en Function of copying data. - void Init( const SweptValues & other ) { - thickness1 = other.thickness1; - thickness2 = other.thickness2; - shellClosed = other.shellClosed; - checkSelfInt = other.checkSelfInt; - mergeFaces = other.mergeFaces; - } - - /// \ru Получить состояние замкнутости. \en Get the closedness state. - bool IsShellClosed() const { return shellClosed; } - /// \ru Установит состояние замкнутости. \en Set the closedness state. - void SetShellClosed( bool cl ) { shellClosed = cl; } - /// \ru Получить состояние флага проверки самопересечений. \en Get the state of flag of checking self-intersection. - bool CheckSelfInt() const { return checkSelfInt; } - /// \ru Установить состояние флага проверки самопересечений. \en Set the state of flag of checking self-intersection. - void SetCheckSelfInt( bool c ) { checkSelfInt = c; } - /// \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). - bool MergeFaces() const { return mergeFaces; } - /// \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). - void SetMergeFaces( bool mf ) { mergeFaces = mf; } - - /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const SweptValues & other ) { Init( other ); } - - KNOWN_OBJECTS_RW_REF_OPERATORS( SweptValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры выдавливания или вращения. - \en The parameters of extrusion or rotation. \~ - \details \ru Параметры выдавливания или вращения кривых с опциями по направлениям. \n - В операции выдавливания прямым направлением считается направление, сонаправленное - с вектором выдавливания, а обратным - противоположное направление. - В операции вращения прямое направлением определяется по оси вращения с помощью правила правой руки. - \en The parameters of extrusion or rotation of curves with options along the directions. \n - In the extrusion operations the forward direction is the direction collinear - with the vector of extrusion and back - the opposite direction. - In the rotation operation the forward direction is determined by the axis of rotation using the right hand rule. \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS SweptValuesAndSides: public SweptValues { -public: - MbSweptSide side1; ///< \ru Параметры выдавливания/вращения в прямом направлении. \en The parameters of extrusion/rotation along the forward direction. - MbSweptSide side2; ///< \ru Параметры выдавливания/вращения в обратном направлении. \en The parameters of extrusion/rotation along the backward direction. - -public: - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Конструктор параметров для построения замкнутой оболочки без тонкой стенки. - Способ построение в обоих направлениях - на заданную глубину, равную 0.0. - \en Constructor of parameters for construction of closed shell without the thin wall. - Method of construction in both directions - to a given depth equal to 0.0. \~ - */ - SweptValuesAndSides() - : SweptValues() - , side1 () - , side2 () - {} - /** \brief \ru Конструктор по углам вращения или глубинам выдавливания. - \en Constructor by rotation angles and extrusion depths. \~ - \details \ru Конструктор параметров для построения замкнутой оболочки без тонкой стенки. - Способ построение в обоих направлениях - на заданную глубину. - \en Constructor of parameters for construction of closed shell without the thin wall. - Method of construction in both directions - to a given depth. \~ - \param[in] scalarValue1 - \ru Угол вращения\глубина выдавливания в прямом направлении. - \en Angle of rotation\depth of extrusion along the forward direction. \~ - \param[in] scalarValue2 - \ru Угол вращения\глубина выдавливания в обратном направлении. - \en Angle of rotation\depth of extrusion along the backward direction. \~ - */ - SweptValuesAndSides( double scalarValue1, double scalarValue2 ) - : SweptValues( ) - , side1 ( scalarValue1 ) - , side2 ( scalarValue2 ) - {} - /// \ru Конструктор копирования данных на тех же поверхностях. \en Copy-constructor of data on the same surfaces. - SweptValuesAndSides( const SweptValuesAndSides & other ) - : SweptValues( other ) - , side1 ( other.side1 ) - , side2 ( other.side2 ) - {} - /// \ru Конструктор полного копирования данных. \en Constructor of complete copying of data. - SweptValuesAndSides( const SweptValuesAndSides & other, MbRegDuplicate * ireg ) - : SweptValues( other ) - , side1 ( other.side1, ireg ) - , side2 ( other.side2, ireg ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~SweptValuesAndSides(); - -public: - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const SweptValuesAndSides * obj = dynamic_cast( &other ); - if ( obj != NULL ) { - if ( side1.IsSame( obj->side1, accuracy ) && side2.IsSame( obj->side2, accuracy ) ) { - if ( obj->SweptValues::IsSame( *this, accuracy ) ) { - return true; - } - } - } - return false; - } - -public: - /// \ru Оператор присваивания данных на тех же поверхностях. \en Assignment operator of data copying on the same surfaces. - void operator = ( const SweptValuesAndSides & other ) { - SweptValues::Init( other ); - side1 = other.side1; - side2 = other.side2; - } - - /** \brief \ru Преобразовать согласно матрице. - \en Transform according to the matrix. \~ - \details \ru Преобразовать согласно матрице поверхности в прямом и обратном направлении. - \en Transform according to the matrix of surface in the forward and backward direction. \~ - \param[in] matr - \ru Матрица преобразования. - \en A transformation matrix. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - /** \brief \ru Сдвинуть вдоль вектора. - \en Move along a vector. \~ - \details \ru Сдвинуть вдоль вектора поверхности в прямом и обратном направлении. - \en Move along the vector of the surface along the forward and backward direction. \~ - \param[in] to - \ru Вектор сдвига. - \en Translation vector. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ); - /** \brief \ru Повернуть вокруг оси. - \en Rotate around an axis. \~ - \details \ru Повернуть вокруг оси поверхности в прямом и обратном направлении. - \en Rotate around the axis of the surface along the forward and backward direction. \~ - \param[in] axis - \ru Ось поворота. - \en The rotation axis. \~ - \param[in] angle - \ru Угол поворота. - \en The rotation angle. \~ - \param[in] iReg - \ru Регистратор. - \en Registrator. \~ - */ - void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - - /** \brief \ru Сделать копии поверхностей. - \en Make copies of surfaces. \~ - \details \ru Если в каком-либо направлении задана поверхность, заменить эту поверхность на ее копию. - \en If the surface is given in any direction, then replace the surface with its copy. \~ - \param[in] ireg - \ru Регистратор копий. - \en Registrator of copies. \~ - \return \ru true, если хотя бы одна поверхность имелась и сдублирована. - \en True if at least one surface is had and copied. \~ - */ - bool DuplicateSurfaces( MbRegDuplicate * ireg = NULL ); - - /// \ru Получить поверхность в положительном направлении. \en Get the surface along the positive direction. - MbSurface * GetSurface1() const { return side1.GetSurface(); } - /// \ru Получить поверхность в отрицательном направлении. \en Get the surface along the negative direction. - MbSurface * GetSurface2() const { return side2.GetSurface(); } - /// \ru Установить поверхность в положительном направлении. \en Set the surface along the positive direction. - void SetSurface1( MbSurface * s ) { side1.SetSurface( s ); } - /// \ru Установить поверхность в отрицательном направлении. \en Set the surface along the negative direction. - void SetSurface2( MbSurface * s ) { side2.SetSurface( s ); } - /// \ru Поменять поверхности местами. \en Swap surfaces. - void ExchangeSurfaces(); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры операции выдавливания. - \en The parameters of extrusion operation. \~ - \details \ru Параметры операции выдавливания кривых с опциями по направлениям. \n - \en The parameters of extrusion operation of curves with options along directions. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS ExtrusionValues : public SweptValuesAndSides { -public: - - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Конструктор параметров выдавливания для построения замкнутой оболочки без тонкой стенки - в прямом направлении на величину, равную 10.0. - \en Constructor of extrusion parameters for construction of closed shell without the thin wall. - along the forward direction by value 10.0. \~ - */ - ExtrusionValues() - : SweptValuesAndSides( 10., 0. ) {} - /** \brief \ru Конструктор по глубинам выдавливания. - \en Constructor by extrusion depths. \~ - \details \ru Конструктор параметров выдавливания для построения замкнутой оболочки без тонкой стенки. - Способ построение в обоих направлениях - на заданную глубину. - \en Constructor of extrusion parameters for construction of closed shell without the thin wall. - Method of construction in both directions - to a given depth. \~ - \param[in] scalarValue1 - \ru Глубина выдавливания в прямом направлении. - \en Depth of extrusion along the forward direction. \~ - \param[in] scalarValue2 - \ru Глубина выдавливания в обратном направлении. - \en Depth of extrusion along the backward direction. \~ - */ - ExtrusionValues( double scalarValue1, double scalarValue2 ) - : SweptValuesAndSides( scalarValue1, scalarValue2 ) {} - /// \ru Конструктор копирования, на тех же поверхностях. \en Copy-constructor on the same surfaces. - ExtrusionValues( const ExtrusionValues & other ) - : SweptValuesAndSides( other ) {} - /// \ru Конструктор копирования. \en Copy-constructor. - ExtrusionValues( const ExtrusionValues & other, MbRegDuplicate * ireg ) - : SweptValuesAndSides( other, ireg ) {} - /// \ru Деструктор. \en Destructor. - virtual ~ExtrusionValues(); - -public: - // \ru Это параметры выдавливания? \en This is extrusion parameters? - virtual bool IsExtrusionValues() const { return true; } - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const ExtrusionValues * obj = dynamic_cast( &other ); - if ( obj != NULL ) { - if ( obj->SweptValuesAndSides::IsSame( *this, accuracy ) ) - return true; - } - return false; - } - -public: - /// \ru Оператор присваивания, на тех же поверхностях. \en Assignment operator on the same surfaces. - ExtrusionValues & operator = ( const ExtrusionValues & other ) { - *static_cast(this) = *static_cast(&other); - return *this; - } - - KNOWN_OBJECTS_RW_REF_OPERATORS( ExtrusionValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры операции вращения. - \en The parameters of revolution operation. \~ - \details \ru Параметры операции вращения кривых с опциями по направлениям. \n - \en The parameters of revolution operation of curves with options along directions. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS RevolutionValues : public SweptValuesAndSides { -public: - /** \brief \ru Форма топологии. - \en Topology shape. \~ - \details \ru Форма топологии: 0 - тело типа сферы, 1 - тело типа тора.\n - Если образующая - не замкнутая плоская кривая, и ось вращения лежит в плоскости кривой, - то возможно построение тела вращения с топологией типа сферы. В этом случае образующая достраивается до оси вращения. - \en Topology shape: 0 - sphere, 1 - torus.\n - If swept is non-closed planar curve and axis of rotation lies on the curve plane, - then is possible to construct revolution solids with the topology of sphere type. In this case the swept is being updated to the rotation axis. -I \~ */ - int shape; - -public: - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Конструктор параметров вращения для построения замкнутой оболочки типа тора - без тонкой стенки в прямом направлении на полный оборот. - \en Constructor of revolution parameters for construction of closed shell of torus type - without thin wall along the forward direction at full turn. \~ - */ - RevolutionValues() - : SweptValuesAndSides( M_PI, 0. ) - , shape( 1 ) - {} - /** \brief \ru Конструктор по углам вращения. - \en Constructor by revolution angles. \~ - \details \ru Конструктор параметров вращения для построения замкнутой оболочки без тонкой стенки. - Способ построение в обоих направлениях - на заданную глубину (заданный угол). - \en Constructor of revolution parameters for construction of closed shell without the thin wall. - Method of construction in both directions - to a given depth (given angle). \~ - \param[in] scalarValue1 - \ru Угол вращение в прямом направлении. - \en Revolution angle along the forward direction. \~ - \param[in] scalarValue2 - \ru Угол вращения в обратном направлении. - \en Revolution angle along the backward direction. \~ - \param[in] s - \ru Форма топологии. - \en Topology shape. \~ - */ - RevolutionValues( double scalarValue1, double scalarValue2, int s ) - : SweptValuesAndSides( scalarValue1, scalarValue2 ) - , shape( s ) - {} - /// \ru Конструктор копирования, на тех же поверхностях. \en Copy-constructor on the same surfaces. - RevolutionValues( const RevolutionValues & other ) - : SweptValuesAndSides( other ) - , shape( other.shape ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - RevolutionValues( const RevolutionValues & other, MbRegDuplicate * ireg ) - : SweptValuesAndSides( other, ireg ) - , shape( other.shape ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~RevolutionValues(); - -public: - // \ru Это параметры вращения? \en This is rotation parameters? - virtual bool IsRevolutionValues() const { return true; } - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const RevolutionValues * obj = dynamic_cast( &other ); - if ( obj != NULL ) { - if ( obj->shape == shape ) { - if ( obj->SweptValuesAndSides::IsSame( *this, accuracy ) ) - return true; - } - } - return false; - } - -public: - /// \ru Оператор присваивания, на тех же поверхностях. \en Assignment operator on the same surfaces. - RevolutionValues & operator = ( const RevolutionValues & other ) { - *static_cast(this) = *static_cast(&other); - shape = other.shape; - return *this; - } - - KNOWN_OBJECTS_RW_REF_OPERATORS( RevolutionValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры кинематической операции. - \en Parameters of the sweeping operation. \~ - \details \ru Параметры операции движения образующей по направляющей кривой. \n - \en The operation parameters of moving the generating curve along the spine curve. \n \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS EvolutionValues : public SweptValues { - - /// \ru Способы переноса образующего объекта вдоль направляющей. \en Moving method of generating object along the spine curve. - enum ModesList { - eom_Parallel = 0x00, // 00000 ///< \ru Образующая переносится параллельно самой себе. \en Generating curve is moved parallel to itself. - eom_KeepingAngle = 0x01, // 00001 ///< \ru Образующая при переносе сохраняет исходный угол с направляющей. \en Generating curve when moving preserves initial angle with spine. - eom_Orthogonal = 0x02, // 00010 ///< \ru Плоскость образующей выставляется и сохраняется ортогональной направляющей. \en Plane of generating curve is set and saved as orthogonal to spine. - eom_BySurfaceNormal = 0x04, // 00100 ///< \ru Образующая переносится согласованно с нормалью к поверхности. \en Generating object is moved according to surface normal. - }; - -protected: - /** \brief \ru Способ переноса образующего контура вдоль направляющей. - \en Moving method of generating contour along the spine curve. \~ - \details \ru Способ переноса образующего контура вдоль направляющей: \n - parallel <= 0 - Образующая переносится параллельно самой себе; \n - parallel == 1 - Образующая при переносе сохраняет исходный угол с направляющей; \n - parallel == 2 - Плоскость образующей выставляется и сохраняется ортогональной направляющей. \n - parallel > 3 - Образующая переносится согласованно с нормалью к поверхности. \n - \en Moving method of generating contour along the spine curve: \n - parallel <= 0 - Generating curve is moved parallel to itself; \n - parallel == 1 - Generating curve when moving preserves initial angle with spine; \n - parallel == 2 - Plane of generating curve is set and saved as orthogonal to spine. \n - parallel > 3 - Generating object is moved according to surface normal. \n \~ - */ - int mode; -public: - // \ru Данные о функциях изменения образующих кривых вдоль направляющей кривой (могут быть NULL). \en Data about changes of generating curves along the guide curve (can be NULL). - double range; ///< \ru Эквидистантное смещение точек образующей кривой в конце траектории. \en The offset range of generating curve on the end of spine curve. - SPtr scaling; ///< \ru Функция масштабирования образующей кривой. \en The function of curve scale. - SPtr winding; ///< \ru Функция вращения образующей кривой. \en The function of curve rotation. - c3d::ConstSurfaceSPtr surface; ///< \ru Поверхность для управления направляющей кривой MbSpine. \en The surface for guide curve control (for MbSpine). - -public: - - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Конструктор параметров кинематической операции для построения замкнутой оболочки - без тонкой стенки с сохранением угла наклона. - \en Constructor of sweeping operation parameters for construction of closed shell - without the thin wall with keeping the angle inclination. \~ - */ - EvolutionValues() - : SweptValues( ) - , mode ( eom_KeepingAngle ) - , range ( 0.0 ) - , scaling ( NULL ) - , winding ( NULL ) - , surface ( NULL ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - EvolutionValues( const EvolutionValues & other ); - /// \ru Деструктор. \en Destructor. - virtual ~EvolutionValues(); - -public: - // \ru Это параметры кинематики? \en This is "evolution" parameters? - virtual bool IsEvolutionValues() const { return true; } - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const; - // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ - virtual bool IsSimilar( const SweptValues & other ) const; - // \ru Сделать объекты равным. \en Make objects equal. \~ - virtual bool SetEqual ( const SweptValues & other ); - - /// \ru Копировать значение режима операции. \en Copy operation mode. - void CopyMode( const EvolutionValues & ev ) { mode = ev.mode; } - /// \ru Получить значение режима операции. \en Get operation mode. - int GetMode() const { return mode; } - /// \ru Переносится ли образующая параллельно самой себе. \en Whether generating curve is moved parallel to itself. - bool IsParallel() const { return (mode < 1); } - /// \ru Сохраняет ли образующая при переносе исходный угол с направляющей. \en Whether generating curve when moving preserves initial angle with spine. - bool IsKeepingAngle() const { return !!(mode & eom_KeepingAngle); } - /// \ru Выставляется ли плоскость образующей ортогонально направляющей. \en Whether plane of generating curve is set and saved as orthogonal to spine. - bool IsOrthogonal() const { return !!(mode & eom_Orthogonal); } - /// \ru Переносится ли образующая согласованно с нормалью к поверхности. \en Whether generating object is moved according to surface normal. - bool BySurfaceNormal() const { return !!(mode & eom_BySurfaceNormal); } - - /// \ru Переносить образующая параллельно самой себе. \en Move generating curve parallel to itself. - void SetParallel() { mode = eom_Parallel; } - /// \ru Сохранять при переносе исходный угол между образующей и направляющей. \en Preserve initial angle between generatrix and spine when moving. - void SetKeepingAngle() { mode = eom_KeepingAngle; } - /// \ru Выставлять плоскость образующей ортогонально направляющей. \en Set and keep plane of generating curve as orthogonal to spine. - void SetOrthogonal() { mode = eom_Orthogonal; } - /// \ru Переносить образующую согласованно с нормалью к поверхности. \en Move generating object according to surface normal. - bool SetBySurfaceNormal( bool s ) - { - if ( !IsParallel() ) { - if ( s ) mode |= eom_BySurfaceNormal; - else mode ^= eom_BySurfaceNormal; - return true; - } - return false; - } - /// \ru Выдать функцию масштабирования образующей кривой. \en Get the function of curve scale. - double GetRange() const { return range; } - double & SetRange() { return range; } - void SetRange( double r ) { range = r; } - - /** \brief \ru Добавить данные. - \en Add data. \~ - \details \ru Добавить данные об изменении образующих контурах на поверхности вдоль образующей кривой. - \en Add data about changes of generating contours on the surface along the guide curve. \~ - \param[in] _scaling - \ru Масштабирование. - \en The scaling. \~ - \param[in] _winding - \ru Поворот. - \en The winding. \~ - */ - bool AddData( MbFunction & _scaling, MbFunction & _winding ); - - /// \ru Выдать функцию масштабирования образующей кривой. \en Get the function of curve scale. - const MbFunction * GetScaling() const { return scaling; } - MbFunction * SetScaling() { return scaling; } - - /// \ru Выдать функцию вращения образующей кривой. \en Get the function of curve rotation. - const MbFunction * GetWinding() const { return winding; } - MbFunction * SetWinding() { return winding; } - - ///< \ru Выдать поверхность для направляющей кривой MbSpine. \en Get the surface for guide curve MbSpine. - const MbSurface * GetSurface() const { return surface; } - void SetSurface( const MbSurface & surf ); - -public: - /// \ru Оператор присваивания. \en Assignment operator. - EvolutionValues & operator = ( const EvolutionValues & other ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( EvolutionValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры операции построения тела по плоским сечениям. - \en The operation parameters of constructing solid by lofted. \~ - \details \ru Параметры операции построения тела по плоским сечениям, заданных контурами. \n - \en The parameters of constructing operation by lofted which are given by contours. \n \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS LoftedValues : public SweptValues { -public: - bool closed; ///< \ru Замкнутость трубки сечений. \en Closedness of tube. - MbVector3D vector1; ///< \ru Производная в начале. \en The derivative at the start. - MbVector3D vector2; ///< \ru Производная в конце. \en The derivative at the end. - bool setNormal1; ///< \ru Установлена нормаль в начале, если начальное сечение точечное. \en The normal is set at the start, if first section is point curve. - bool setNormal2; ///< \ru Установлена нормаль в конце, если начальное сечение точечное. \en The normal is set at the end, if last section is point curve. - double derFactor1; ///< \ru Множитель величины производной при установке нормали в начале. По умолчанию 1.0. \en The modifier of the derivative when setting the normal at the beginning. The default is 1.0. - double derFactor2; ///< \ru Множитель величины производной при установке нормали в конце. По умолчанию 1.0. \en The modifier of the derivative when setting the normal at the end. The default is 1.0. - MbVector3D directSurf1; ///< \ru Ось направления движения поверхности в начале при установке нормали. \en Direction axis of the surface progress near the starting curve when setting the normal. - MbVector3D directSurf2; ///< \ru Ось направления движения поверхности в конце при установке нормали. \en Direction axis of the surface progress near the ending curve when setting the normal. - -public: - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - \details \ru Конструктор параметров операции по сечениям для построения замкнутой оболочки без тонкой стенки. - \en Constructor of lofted operation parameters for construction of closed shell without the thin wall. \~ - */ - LoftedValues() - : SweptValues ( ) - , closed ( false ) - , vector1 ( 0.0, 0.0, 0.0 ) - , vector2 ( 0.0, 0.0, 0.0 ) - , setNormal1 ( false ) - , setNormal2 ( false ) - , derFactor1 ( 1.0 ) - , derFactor2 ( 1.0 ) - , directSurf1 ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL ) - , directSurf2 ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - LoftedValues( const LoftedValues & other ) - : SweptValues ( other ) - , closed ( other.closed ) - , vector1 ( other.vector1 ) - , vector2 ( other.vector2 ) - , setNormal1 ( other.setNormal1 ) - , setNormal2 ( other.setNormal2 ) - , derFactor1 ( other.derFactor1 ) - , derFactor2 ( other.derFactor2 ) - , directSurf1 ( other.directSurf1 ) - , directSurf2 ( other.directSurf2 ) - {} - /// \ru Оператор присваивания. \en Assignment operator. - LoftedValues & operator = ( const LoftedValues & other ) - { - SweptValues::Init( other ); - closed = other.closed; - vector1 = other.vector1; - vector2 = other.vector2; - setNormal1 = other.setNormal1; - setNormal2 = other.setNormal2; - directSurf1 = other.directSurf1; - directSurf2 = other.directSurf2; - return *this; - } - /// \ru Деструктор. \en Destructor. - virtual ~LoftedValues(); - -public: - // \ru Это параметры операции по сечениям? \en This is "lofted" parameters? - virtual bool IsLoftedValues() const { return true; } - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const LoftedValues * obj = dynamic_cast( &other ); - if ( obj != NULL ) { - if ( obj->closed == closed ) { - if ( c3d::EqualVectors(vector1, obj->vector1, accuracy) && c3d::EqualVectors(vector2, obj->vector2, accuracy) ) { - if ( obj->setNormal1 == setNormal1 && obj->setNormal2 == setNormal2 ) { - if ( (setNormal1 == false || obj->derFactor1 == derFactor1 || c3d::EqualVectors(directSurf1, obj->directSurf1, accuracy)) && // Фактор может различаться, если нормаль не установлена. - (setNormal2 == false || obj->derFactor2 == derFactor2 || c3d::EqualVectors(directSurf2, obj->directSurf2, accuracy)) ) { - if ( obj->SweptValues::IsSame(*this, accuracy) ) { - return true; - } - } - } - } - } - } - return false; - } - -public: - /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - void Transform( const MbMatrix3D & matr ); - /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - void Move ( const MbVector3D & to ); - /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - void Rotate ( const MbAxis3D & axis, double ang ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( LoftedValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры ребра жёсткости. - \en Parameters of a rib. \~ - \details \ru Параметры построения ребра жёсткости по кривой, задающей его форму. \n - \en The construction parameters of rib by curve gives its shape. \n \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS RibValues : public SweptValues { -public: - /** \brief \ru Сторона заполнения пространства телом ребра. - \en The side to place the rib on. \~ - \details \ru С какой стороны от кривой располагается ребро. \n - \en With which side of the curve is rib. \n \~ - \ingroup Build_Parameters - */ - enum ExtrudeSide { - es_Left = 0, ///< \ru Ребро выдавливается в левую сторону от кривой вдоль плоскости. \en Rib is extruded to the left side of the curve along the plane. - es_Right, ///< \ru Ребро выдавливается в правую сторону от кривой вдоль плоскости. \en Rib is extruded to the right side of the curve along the plane. - es_Up, ///< \ru Ребро выдавливается в сторону нормали плоскости. \en Rib is extruded to the side of the surface normal. - es_Down, ///< \ru Ребро выдавливается в сторону против нормали плоскости. \en Rib is extruded to the side opposite to the surface normal. - }; - -public: - double angle1; ///< \ru Угол уклона плоскости в прямом направлении. \en Draft angle of the plane along the forward direction. - double angle2; ///< \ru Угол уклона плоскости в обратном направлении. \en Draft angle of the plane along the backward direction. - ExtrudeSide side; ///< \ru Сторона заполнения пространства телом ребра. \en The side to place the rib on. - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - RibValues() - : SweptValues( ) - , angle1 ( 0.0 ) - , angle2 ( 0.0 ) - , side ( es_Right ) - {} - /// \ru Конструктор по толщинам, углам и стороне заполнения пространства. \en Constructor by thickness, angles and filling space. - RibValues( double t1, double t2, double a1, double a2, int s ) - : SweptValues( t1, t2 ) - , angle1 ( a1 ) - , angle2 ( a2 ) - , side ( (ExtrudeSide)s ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - RibValues( const RibValues & other ) - : SweptValues( other ) - , angle1 ( other.angle1 ) - , angle2 ( other.angle2 ) - , side ( other.side ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~RibValues(); - -public: - // \ru Это параметры операции ребра жесткости? \en This is "rib" parameters? - virtual bool IsRibValues() const { return true; } - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const RibValues * obj = dynamic_cast( &other ); - - if ( obj != NULL ) { - if ( obj->side == side ) { - if ( ::fabs(obj->angle1 - angle1) < accuracy && ::fabs(obj->angle2 - angle2) < accuracy ) - return SweptValues::IsSame( *obj, accuracy ); - } - } - return false; - } - -public: - /// \ru Функция копирования. \en Copy function. - void Init( const RibValues & other ) - { - SweptValues::Init( other ); - angle1 = other.angle1; - angle2 = other.angle2; - side = other.side; - } - /// \ru Оператор присваивания. \en Assignment operator. - RibValues & operator = ( const RibValues & other ) - { - Init( other ); - return *this; - } - - KNOWN_OBJECTS_RW_REF_OPERATORS( RibValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры ребра жёсткости листового тела. - \en Parameters of a sheet metal rib. \~ - \details \ru Параметры построения ребра жёсткости листового тела по кривой, задающей его форму. \n - \en The construction parameters of a sheet metal rib by curve gives its shape. \n \~ -\ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS SheetRibValues: public RibValues { -public: - double radRibConvex; ///< \ru Радиус скругления выпуклой части ребра жесткости. \en Fillet radius of convex part of rib. - double radSideConcave; ///< \ru Радиус скругления примыкания вогнутой части ребра жесткости к листовому телу. \en Fillet radius of connection of concave part of rib and metal sheet. - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - SheetRibValues() - : RibValues ( ) - , radRibConvex ( 0.0 ) - , radSideConcave( 0.0 ) - {} - /// \ru Конструктор по параметрам. \en Constructor by parameters. - SheetRibValues( double t1, double t2, double a1, double a2, int s, double rFilletRib, const double & rFilletSide ) - : RibValues ( t1, t2, a1, a2, s ) - , radRibConvex ( ::fabs(rFilletRib) ) - , radSideConcave( ::fabs(rFilletSide) ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - SheetRibValues( const SheetRibValues & other ) - : RibValues ( other ) - , radRibConvex ( other.radRibConvex ) - , radSideConcave( other.radSideConcave ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~SheetRibValues(); - -public: - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const SweptValues & other, double accuracy ) const - { - const SheetRibValues * obj = dynamic_cast( &other ); - - if ( obj != NULL ) { - if ( (::fabs(radRibConvex - obj->radRibConvex) < accuracy) && (::fabs(radSideConcave - obj->radSideConcave) < accuracy) ) - return RibValues::IsSame( *obj, accuracy ); - } - return false; - } - -public: - /// \ru Функция копирования. \en Copy function. - void Init( const SheetRibValues & other ) - { - RibValues::Init( other ); - radRibConvex = other.radRibConvex; - radSideConcave = other.radSideConcave; - } - - /// \ru Оператор присваивания. \en Assignment operator. - SheetRibValues & operator = ( const SheetRibValues & other ) { - Init( other ); - return *this; - } - - /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - void Transform( const MbMatrix3D & matr ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( SheetRibValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры булевой операции выдавливания или вращения до объекта. - \en The parameters of Boolean operation of extrusion or revolution to object. \~ - \details \ru Параметры булевой операции выдавливания или вращения до объекта. \n - Используется при булевой операции исходного тела - и построенной операции выдавливания или вращения двумерных контуров на поверхности. - \en The parameters of Boolean operation of extrusion or revolution to object. \n - Used in Boolean operation of initial solid - and constructed operation of extrusion or revolution of two-dimensional contours on the surface. \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS MbSweptLayout { - /** \brief \ru Направление выдавливания (вращения). - \en A direction of extrusion (revolution). \~ - \details \ru Направление выдавливания (вращения) по отношению к вектору выдавливания (оси вращения). - \en The direction of extrusion relative to the extrusion vector. \~ - */ - enum Direction { - ed_minus_minus = -2, ///< \ru В обратном направлении, для обеих строн. \en Along the backward direction, for both sides. - ed_minus = -1, ///< \ru В обратном направлении, для одной стороны. \en Along the backward direction, for one sides. - ed_both = 0, ///< \ru В обоих направлениях. \en Along both directions. - ed_plus = 1, ///< \ru В прямом направлении, для одной стороны. \en Along the forward direction, for one sides. - ed_plus_plus = 2, ///< \ru В прямом направлении, для обеих сторон. \en Along the forward direction, for both sides. - }; - Direction direction; ///< \ru Направление выдавливания относительно вектора. \en The direction of extrusion relative to the vector. - bool skipUnion; ///< \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. - -protected: - SPtr surface; ///< \ru Поверхность, на которой размещена образующая. \en The surface, which contains the generating curve. - -protected: - /// \ru Конструктор. \en Constructor. - MbSweptLayout( const MbSurface & surf, Direction dir ) : surface( &surf ), direction( dir ), skipUnion( false ) {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbSweptLayout( const MbSweptLayout & other ) : surface( other.surface ), direction( other.direction ), skipUnion( other.skipUnion ) {} - /// \ru Деструктор. \en Destructor. - virtual ~MbSweptLayout(); -public: - /// \ru Получить поверхность. \en Get the surface. - const MbSurface & GetSurface() const { return *surface; } - - /// \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. - bool SkipUnion() const { return skipUnion; } - /// \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. - void SkipUnion( bool su ) { skipUnion = su; } -public: - /// \ru Это параметры выдавливания? \en This is extrusion parameters? - virtual bool IsExtrusionLayout() const { return false; } - /// \ru Это параметры вращения? \en This is rotation parameters? - virtual bool IsRevolutionLayout() const { return false; } -public: - /// \ru Классификация точки относительно несущей поверхности. \en Classification point relative to the surface. - MbeItemLocation PointRelative( const MbCartPoint3D & p ) const; -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSweptLayout & operator = ( const MbSweptLayout & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры булевой операции выдавливания до объекта. - \en The parameters of Boolean operation of extrusion to object. \~ - \details \ru Параметры булевой операции выдавливания до объекта. \n - Используется при булевой операции исходного тела - и построенной операции выдавливания двумерных контуров на поверхности. - \en The parameters of Boolean operation of extrusion to object. \n - Used in Boolean operation of initial solid - and constructed operation of extrusion of two-dimensional contours on the surface. \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS MbExtrusionLayout : public MbSweptLayout { - MbVector3D dirVector; ///< \ru Вектор выдавливания. \en An extrusion vector. -public: - /// \ru Конструктор. \en Constructor. - MbExtrusionLayout( const MbSurface & surf, Direction dir, const MbVector3D & dirVec ) : MbSweptLayout( surf, dir ), dirVector( dirVec ) {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbExtrusionLayout( const MbExtrusionLayout & other ) : MbSweptLayout( other ), dirVector( other.dirVector ) {} - /// \ru Деструктор. \en Destructor. - virtual ~MbExtrusionLayout(); -public: - /// \ru Это параметры выдавливания? \en This is extrusion parameters? - virtual bool IsExtrusionLayout() const { return true; } -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbExtrusionLayout & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры булевой операции вращения до объекта. - \en The parameters of Boolean operation of revolution to object. \~ - \details \ru Параметры булевой операции вращения до объекта. \n - Используется при булевой операции исходного тела - и построенной операции вращения двумерных контуров на поверхности. - \en The parameters of Boolean operation of revolution to object. \n - Used in Boolean operation of initial solid - and constructed operation of revolution of two-dimensional contours on the surface. \~ - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS MbRevolutionLayout : public MbSweptLayout { - MbAxis3D revAxis; ///< \ru Ось вращения. \en An revolution axis. -public: - /// \ru Конструктор. \en Constructor. - MbRevolutionLayout( const MbSurface & surf, Direction dir, const MbAxis3D & rotAxis ) : MbSweptLayout( surf, dir ), revAxis( rotAxis ) {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbRevolutionLayout( const MbRevolutionLayout & other ) : MbSweptLayout( other ), revAxis( other.revAxis ) {} - /// \ru Деструктор. \en Destructor. - virtual ~MbRevolutionLayout(); -public: - /// \ru Это параметры вращения? \en This is rotation parameters? - virtual bool IsRevolutionLayout() const { return true; } -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbRevolutionLayout & ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные края сечения поверхности. - \en The surface section control function. \~ - \details \ru Точку края сечения определяют: или рёбра, или кривые. Направление сечения на краю определяют: илди поверхности смежных граней рёбер, или поверхности граней, или функция угла наклона. - \en The end of the section is determined as point either edges, or curves. The direction on the end of the section is determined as either the surfaces of edges, or the surfaces of faces, or a function of the angle. - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS MbSectionRail { - -private: - std::vector edges; ///< \ru Направляющие рёбра (могут отсутствовать). \en The guide edges (may be empty). - std::vector edgeSide; ///< \ru С какой гранью ребра гладко стыковать поверхность (синхронно с edges). \en What face of edge should the surface join smoothly to (synchronously with edges). - std::vector faces; ///< \ru Опорные грани (могут отсутствовать). \en The reference faces (may be empty). - std::vector faceSide; ///< \ru С каких сторон касаться поверхностей при form==cs_Linea (синхронно с faces). \en On which sides to touch surfaces when form==cs_Linea (synchronously with faces). - std::vector curves; ///< \ru Направляющие кривые (могут отсутствовать). \en The guide curves (may be empty). - MbFunction * angle; ///< \ru Функция угла наклона (может отсутствовать). \en The function of the angle of inclination (may be NULL). - ThreeStates state; ///< \ru Как использовать angle: угол к хорде (ts_neutral), отклонение от касательной поверхности (ts_positive), отклонение от нормали к поверхности (ts_negative). - ///< \en How to use angle: angle to chord (ts_neutral), deviation from tangent surface (ts_positive), deviation from normal to surface (ts_negative). -public: - - /// \ru Конструктор по умолчанию. \en Empty constructor. - MbSectionRail() - : edges () - , edgeSide() - , faces () - , faceSide() - , curves () - , angle ( NULL ) - , state( ts_neutral ) - {} - - /** \brief \ru Конструктор по параметрам. - \en Constructor by parameters. \~ - \param[in] eds - \ru Направляющие рёбра. - \en The guide edges. \~ - \param[in] eSide - \ru Какую сторону кривой гладко стыковать с поверхностью (синхронно с edges). - \en Which side should the surface join smoothly to (synchronously with edges). \~ - \param[in] fcs - \ru Направляющие грани (могут отсутствовать). - \en The guide faces (may be empty). \~ - \param[in] fSide - \ru С каких сторон касаться поверхностей (синхронно с faces). - \en On which sides to touch surfaces (synchronously with faces). \~ - \param[in] cs - \ru Направляющие кривые (могут отсутствовать). - \en The guide curves (may be empty). \~ - \param[in] ang - \ru Функция угла наклона (может быть NULL). - \en The function of the angle of inclination (may be NULL). \~ - \param[in] st - \ru Как использовать ang. - \en How to use ang. \~ - */ - MbSectionRail( std::vector & edges_, std::vector & eSides, - std::vector & faces_, std::vector & fSides, - std::vector & cs, - MbFunction * ang, ThreeStates st ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionRail( const MbSectionRail & other ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionRail( const MbSectionRail & other, MbRegDuplicate * ireg ); - /// \ru Деструктор. \en Destructor. - ~MbSectionRail(); - -public: - - /// \ru Добавить в данные направляющую кривую. \en Add guiding to data. \~ - void AddEdge( MbCurveEdge & _edge, bool side ); - /// \ru Выдать направляющие рёбра. \en Get guide edges. - void GetEdges( std::vector & eds ) const; - void GetEdges( RPArray & eds ) const; - /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? - void GetEdgeSide( std::vector & eSide ) const; - /// \ru Выдать количество направляющих ребер. \en Get guide edges count. - size_t GetEdgesCount() const { return edges.size(); } - size_t GetEdgeSideCount() const { return edgeSide.size(); } - /// \ru Выдать направляющее ребро. \en Get guide edge. - MbCurveEdge * SetEdge( size_t i ) { return ( i < edges.size() ) ? edges[i] : NULL; } - - /// \ru Добавить в данные поверхность. \en Add surface to data. \~ - void AddFace( MbFace & _face, bool side ); - /// \ru Выдать грани. \en Get faces. - void GetFaces( std::vector & fas ) const; - void GetFaces( RPArray & fas ) const; - /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? - void GetFaceSide( std::vector & fSide ) const; - /// \ru Выдать количество направляющих граней. \en Get guide faces count. - size_t GetFacesCount() const { return faces.size(); } - size_t GetFaceSideCount() const { return faceSide.size(); } - /// \ru Выдать направляющую грань. \en Get guide face. - MbFace * SetFace( size_t i ) { return ( i < faces.size() ) ? faces[i] : NULL; } - - /// \ru Добавить в данные кривую. \en Add curve to data. \~ - void AddCurve( MbCurve3D & _curve ); - /// \ru Добавить в данные кривые. \en Add curves to data. \~ - void AddCurves( std::vector & _curves ); - /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. - void GetCurves( std::vector & crs ) const; - /// \ru Выдать количество дополнительных направляющих кривых. \en Get additional guide curves count. - size_t GetCurvesCount() const { return curves.size(); } - MbCurve3D * SetCurve( size_t i ) { return ( i < curves.size() ) ? curves[i] : NULL; } - - /// \ru Установить функцию управления сечением. \en Set section control function. - void SetAngle( MbFunction & an ); - /// \ru Выдать функцию управления сечением (радиус или дискриминант). \en Get section control function (radius or discriminant). - const MbFunction * GetAngle() const { return angle; } - MbFunction * SetAngle() { return angle; } - - /// \ru Выдать образующую кривую. \en Get forming curve. - const ThreeStates GetState() const { return state; } - void SetState( ThreeStates st ) { state = st; } - - /// \ru Преобразовать объект. \en Transform the object. \~ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - /// \ru Сдвинуть объект. \en Move the object. \~ - void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ); - /// \ru Повернуть объект. \en Rotate the object. \~ - void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSectionRail & other, double accuracy ) const; - /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ - bool IsSimilar( const MbSectionRail & other ) const; - /// \ru Сделать объекты равным. \en Make objects equal. \~ - bool SetEqual ( const MbSectionRail & other ); - - // Дать любую точку и ориентировочную длину. - double GetAnyPopint( MbCartPoint3D & p0 ); - - /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. - void operator = ( const MbSectionRail & other ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionRail ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. - -}; // MbSectionRail - - -//------------------------------------------------------------------------------ -/** \brief \ru Функция управления сечением поверхности. - \en The surface section control function. \~ - \details \ru Форму сечения поверхности заметания определяет функция управления сечением (радиус или дискриминант). - Если функция управления сечением не определена, то она рассчитывается покривой, через которую должно пройти сечение, или поверхности, которой должно касаться сечение. \n - \en The surface section form is determined by the section control function (radius or discriminant). - If the section control function is not determined, it is calculated with curve that the section should pass through or surface that the section should touch. \n - \ingroup Build_Parameters -*/ -// --- -struct MATH_CLASS MbSectionRule { - -public: - MbFunction * function; ///< \ru Функция управления сечением (радиус или дискриминант, может быть NULL). \en Section control function (radius or discriminant). - MbCurve3D * curve; ///< \ru Кривая, через которую должно пройти сечение. \en The curve that the section should pass through. - MbSurface * surface; ///< \ru Поверхность, которой должно касаться сечение. \en The surface that the section should touch. - -public: - /// \ru Конструктор по умолчанию. \en Empty constructor. - MbSectionRule(); - /// \ru Конструктор по функции. \en The constructor by function. - MbSectionRule( MbFunction * fun ); - /// \ru Конструктор по кривой. \en The constructor by function. - MbSectionRule( MbCurve3D * cur ); - /// \ru Конструктор по поверхности. \en The constructor by surface. - MbSectionRule( MbSurface * sur ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionRule( const MbSectionRule & other ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionRule( const MbSectionRule & other, MbRegDuplicate * ireg ); - /// \ru Деструктор. \en Destructor. - ~MbSectionRule(); - -public: - - /// \ru Выдать функцию управления сечением. \en Get section control function. - const MbFunction * GetFunction() const { return function; } - /// \ru Установить функцию управления сечением. \en Set section control function. - void SetFunction( MbFunction & f ); - void SetFunction( double f ); - /// \ru Выдать кривую управления сечением. \en Get section control curve. - const MbCurve3D * GetCurve() const { return curve; } - /// \ru Установить кривую управления сечением. \en Set section control curve. - void SetCurve( MbCurve3D & c ); - /// \ru Выдать поверхность управления сечением. \en Get section control surface. - const MbSurface * GetSurface() const { return surface; } - /// \ru Установить поверхность управления сечением. \en Set section control surface. - void SetSurface( MbSurface & s ); - - /// \ru Преобразовать объект. \en Transform the object. \~ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - /// \ru Сдвинуть объект. \en Move the object. \~ - void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ); - /// \ru Повернуть объект. \en Rotate the object. \~ - void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSectionRule & other, double accuracy ) const; - /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ - bool IsSimilar( const MbSectionRule & other ) const; - /// \ru Сделать объекты равным. \en Make objects equal. \~ - bool SetEqual ( const MbSectionRule & other ); - - /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. - void operator = ( const MbSectionRule & other ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionRule ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. - -}; // MbSectionRule - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры операции построения поверхности заметания переменного сечения. - \en The parameters for buyilding the swept mutable section surface. \~ - \details \ru Поверхность заметания строится путем движения плоского сечения вдоль опорной кривой. - Плоское сечение может начинаться на направляющей кривой и заканчиваться на другой направляющей кривой. - Направляющих кривых может быть две, одна или ни одной. Кроме того, в построении могут использоваться управляющие кривые. \n - Сечение поверхности плоскостью, перпендикулярной опорной кривой, может иметь одну из пяти форм и некоторые из них могут меняться по заданному закону. - Сечение может иметь форму окружности (или её дуги), отрезка прямой, кривой второго порядка, кривой третьего порядка или заданной сплайновой кривой. \n - При наличие направляющих кривых и их несущих поверхностей построенная поверхность заметания гладко стыкуется с несущими поверхностями. \n - \en The swept mutable section surface is form-generating by moving the flat section along the reference curve. \n - The flat section can start on a guide curve and end on another guide curve. - There can be two guide curves, one or none. In addition, control curves can be used in the construction. \n - The cross section of a surface with a plane perpendicular to the reference curve can have one of five shapes, and some of them can change according to a given law. - The cross section can take the form of a circle (or its arc), a straight line segment, a second-order curve, a third-order curve, or a given spline curve. \n - If there are guide curves and their bearing surfaces, the constructed sweep surface is smoothly joined to the bearing surfaces. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS MbSectionData { - -private: - MbCurve3D * spine; ///< \ru Опорная кривая. \en The reference curve. - MbeSectionShape form; ///< \ru Форма сечения поверхности. \en The surface cross-section shape. - MbSectionRail rail1; ///< \ru Данные начального края сечения. \en The data of the begining of section. - MbSectionRail rail2; ///< \ru Данные конечного края сечения. \en The data of the end of section. - MbCurve3D * curve; ///< \ru Кривая вершин (может отсутствовать). \en The apex curve (may be NULL). - MbSectionRule descript; ///< \ru Функция управления сечением поверхности (радиус или дискриминант, может быть NULL). \en The section control function (radius or discriminant). - MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм NULL). \en Forming curve for form==cs_Shape (NULL on other case). - double uMin; ///< \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. - double uMax; ///< \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. - double buildSag; ///< \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. - double accuracy; ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. - -public: - /// \ru Конструктор по умолчанию. \en Empty constructor. - MbSectionData() - : spine ( NULL ) - , form ( cs_Round ) - , rail1 () - , rail2 () - , curve ( NULL ) - , descript() - , pattern ( NULL ) - , uMin ( 0.0 ) - , uMax ( 1.0 ) - , buildSag( Math::deviateSag ) - , accuracy( Math::metricPrecision ) - {} - - /** \brief \ru Конструктор по параметрам. - \en Constructor by parameters. \~ - \param[in] sp - \ru Опорная кривая. - \en The reference curve. \~ - \param[in] f - \ru Форма сечения поверхности. - \en The surface cross-section shape. \~ - \param[in] r1 - \ru Данные начального края сечения. - \en The data of the begining of section. \~ - \param[in] r2 - \ru Данные конечного края сечения. - \en The data of the end of section. \~ - \param[in] ap - \ru Кривая вершин (может быть NULL). - \en The apex curve (may be empty). \~ - \param[in] desc - \ru Функция управления сечением (может быть NULL). - \en Section control function (may be NULL). \~ - \param[in] patt - \ru Образующая кривая (может быть NULL). - \en Forming curve (may be NULL). \~ - */ - MbSectionData( MbCurve3D & sp, - MbeSectionShape f, - MbSectionRail & r1, - MbSectionRail & r2, - MbCurve3D * ap, - MbSectionRule & desc, - MbPolyCurve * patt ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionData( const MbSectionData & other ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionData( const MbSectionData & other, MbRegDuplicate * ireg ); - /// \ru Деструктор. \en Destructor. - ~MbSectionData(); - -public: - - /// \ru Установить опорную кривую. \en Set reference curve. - void SetSpine( MbCurve3D & s ); - //< \ru Установить вектор направления опорной кривой (если spine==NULL). \en Set the direction vector of the reference curve (if spine= = NULL). - void SetSpine( const MbVector3D & a ); - /// \ru Выдать опорную кривую. \en Get reference curve. - const MbCurve3D * GetSpine() const { return spine; } - MbCurve3D * SetSpine() { return spine; } - - /// \ru Выдать форму сечения поверхности. \en Get cross-section shape. - MbeSectionShape GetForm() const { return form; } - /// \ru Установить форму сечения поверхности. \en Set cross-section shape. - void SetForm( MbeSectionShape f ) { form = f; } - - ///< \ru Данные начального края сечения. \en The data of the begining of section. - MbSectionRail & GetRrail1() { return rail1; } - ///< \ru Данные конечного края сечения. \en The data of the end of section. - MbSectionRail & GetRrail2() { return rail2; } - - /// \ru Добавить в данные направляющее ребро. \en Add guiding to data. \~ - void AddEdge1( MbCurveEdge & _edge, bool side ) { rail1.AddEdge( _edge, side ); } - void AddEdge2( MbCurveEdge & _edge, bool side ) { rail2.AddEdge( _edge, side ); } - /// \ru Выдать направляющие рёбра. \en Get guide edges. - void GetEdges1( std::vector & eds ) const { rail1.GetEdges( eds ); } - void GetEdges1( RPArray & eds ) const { rail1.GetEdges( eds ); } - /// \ru Выдать направляющие рёбра. \en Get guide edges. - void GetEdges2( std::vector & eds ) const { rail2.GetEdges( eds ); } - void GetEdges2( RPArray & eds ) const { rail2.GetEdges( eds ); } - /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? - void GetEdgeSide1( std::vector & eSide ) const { rail1.GetEdgeSide( eSide ); } - /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? - void GetEdgeSide2( std::vector & eSide ) const { rail2.GetEdgeSide( eSide ); } - /// \ru Выдать количество направляющих ребер. \en Get guide edges count. - size_t GetEdgesCount1() const { return rail1.GetEdgesCount(); } - size_t GetEdgesCount2() const { return rail2.GetEdgesCount(); } - size_t GetEdgeSideCount1() const { return rail1.GetEdgeSideCount(); } - size_t GetEdgeSideCount2() const { return rail2.GetEdgeSideCount(); } - /// \ru Выдать направляющее ребро. \en Get guide edge. - MbCurveEdge * SetEdge1( size_t i ) { return rail1.SetEdge( i ); } - /// \ru Выдать направляющее ребро. \en Get guide edge. - MbCurveEdge * SetEdge2( size_t i ) { return rail2.SetEdge( i ); } - - /// \ru Добавить направляющую грань. \en Add guide face. - void AddFace1( MbFace & _face, bool side ) { rail1.AddFace( _face, side ); } - void AddFace2( MbFace & _face, bool side ) { rail2.AddFace( _face, side ); } - /// \ru Выдать поверхности. \en Get surfaces. - void GetFaces1( std::vector & fas ) const { rail1.GetFaces( fas ); } - void GetFaces1( RPArray & fas ) const { rail1.GetFaces( fas ); } - /// \ru Выдать поверхности. \en Get surfaces. - void GetFaces2( std::vector & fas ) const { rail2.GetFaces( fas ); } - void GetFaces2( RPArray & fas ) const { rail2.GetFaces( fas ); } - /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? - void GetFaceSide1( std::vector & fSide ) const { rail1.GetFaceSide( fSide ); } - /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? - void GetFaceSide2( std::vector & fSide ) const { rail2.GetFaceSide( fSide ); } - /// \ru Выдать количество направляющих граней. \en Get guide faces count. - size_t GetFacesCount1() const { return rail1.GetFacesCount(); } - size_t GetFacesCount2() const { return rail2.GetFacesCount(); } - size_t GetFaceSideCount1() const { return rail1.GetFaceSideCount(); } - size_t GetFaceSideCount2() const { return rail2.GetFaceSideCount(); } - /// \ru Выдать направляющую грань. \en Get guide face. - MbFace * SetFace1( size_t i ) { return rail1.SetFace( i ); } - /// \ru Выдать направляющую грань. \en Get guide face. - MbFace * SetFace2( size_t i ) { return rail2.SetFace( i ); } - - /// \ru Добавить в данные направляющую кривую. \en Add guiding to data. \~ - void AddCurve1( MbCurve3D & crv ) { rail1.AddCurve( crv ); } - void AddCurve2( MbCurve3D & crv ) { rail2.AddCurve( crv ); } - /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. - void GetCurves1( std::vector & crs ) const { rail1.GetCurves( crs ); } - /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. - void GetCurves2( std::vector & crs ) const { rail2.GetCurves( crs ); } - /// \ru Выдать количество дополнительных направляющих кривых. \en Get additional guide curves count. - size_t GetCurvesCount1() const { return rail1.GetCurvesCount(); } - size_t GetCurvesCount2() const { return rail2.GetCurvesCount(); } - /// \ru Выдать направляющую кривую. \en Get guide curve. - MbCurve3D * SetCurve1( size_t i ) { return rail1.SetCurve( i ); } - /// \ru Выдать направляющую кривую. \en Get guide curve. - MbCurve3D * SetCurve2( size_t i ) { return rail2.SetCurve( i ); } - - /// \ru Добавить в данные функции. \en Add functions to data. \~ - void SetAngle1( MbFunction & ang ) { rail1.SetAngle( ang ); } - /// \ru Добавить в данные функции. \en Add functions to data. \~ - void SetAngle2( MbFunction & ang ) { rail2.SetAngle( ang ); } - /// \ru Выдать функции углов наклона. \en Get angle functions. - const MbFunction * GetAngle1() const { return rail1.GetAngle(); } - /// \ru Выдать функции углов наклона. \en Get angle functions. - const MbFunction * GetAngle2() const { return rail2.GetAngle(); } - /// \ru Выдать функцию угла наклона. \en Get angle function. - MbFunction * SetAngle1() { return rail1.SetAngle(); } - /// \ru Выдать функцию угла наклона. \en Get angle function. - MbFunction * SetAngle2() { return rail2.SetAngle(); } - - /// \ru Добавить в данные кривую. \en Set curve. \~ - void SetCurve( MbCurve3D & curv ); - /// \ru Выдать направляющую кривую. \en Get guide curve. - MbCurve3D * SetCurve() { return curve; } - /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. - const MbCurve3D * GetCurve() const { return curve; } - - /// \ru Выдать данные управления сечением. \en Get section control data. - const MbSectionRule & GetSectionRule() const { return descript; } - MbSectionRule & SetSectionRule() { return descript; } - /// \ru Выдать функцию управления сечением (радиус или дискриминант). \en Get section control function (radius or discriminant). - const MbFunction * GetFunction() const { return descript.function; } - MbFunction * SetFunction() { return descript.function; } - /// \ru Установить функцию управления сечением. \en Set section control function. - void SetFunction( MbFunction & f ) { descript.SetFunction( f ); } - void SetFunction( double f ) { descript.SetFunction( f ); } - - /// \ru Выдать образующую кривую. \en Get forming curve. - const MbPolyCurve * GetPattern() const { return pattern; } - MbPolyCurve * SetPattern() { return pattern; } - /// \ru Установить образующую кривую. \en Set forming curve. - void SetPattern( MbPolyCurve & p ); - - /// \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. - double GetUMin() const { return uMin; } - /// \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. - double GetUMax() const { return uMax; } - /// \ru Установить область определения первого параметра поверхностей. \en Set the first parameter region of the surface. - void SetUParams( double u1, double u2 ); - /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. - double GetBuildSag() const { return buildSag; } - ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. - double GetAccuracy() const { return accuracy; } - void SetAccuracy( double acc ); - - /// \ru Преобразовать объект. \en Transform the object. \~ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - /// \ru Сдвинуть объект. \en Move the object. \~ - void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ); - /// \ru Повернуть объект. \en Rotate the object. \~ - void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSectionData & other, double acc ) const; - /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ - bool IsSimilar( const MbSectionData & other ) const; - /// \ru Сделать объекты равным. \en Make objects equal. \~ - bool SetEqual ( const MbSectionData & other ); - - /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. - void operator = ( const MbSectionData & other ); - - KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. - -}; // MbSectionData - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные о поверхности переменного сечения. - \en Data about swept mutable section surface. \~ - \details \ru Данные содержат номера рёбер и граней исходной оболочки, на которых строится поверхность. - \en The data contains the numbers of edges and faces of the original shell on which the surface is built. - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbSectionCode { - -private: - SArray edgeIndex1; ///< \ru Номера рёбер первой направляющей кривой. \en The edge numbers of the first guide curve. - SArray faceIndex1; ///< \ru Номера граней первой направляющей поверхности. \en The face numbers of the first guide surface. - SArray edgeIndex2; ///< \ru Номера рёбер второй направляющей кривой. \en The edge numbers of the second guide curve. - SArray faceIndex2; ///< \ru Номера граней второй направляющей поверхности. \en The face numbers of the second guide surface. - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - MbSectionCode() - : edgeIndex1( 0, 1 ) - , faceIndex1( 0, 1 ) - , edgeIndex2( 0, 1 ) - , faceIndex2( 0, 1 ) - {} - /// \ru Конструктор. \en Constructor. - MbSectionCode( SArray & edI1, SArray & faI1, - SArray & edI2, SArray & faI2 ) - : edgeIndex1( edI1 ) - , faceIndex1( faI1 ) - , edgeIndex2( edI2 ) - , faceIndex2( faI2 ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbSectionCode( const MbSectionCode & other ) - : edgeIndex1( other.edgeIndex1 ) - , faceIndex1( other.faceIndex1 ) - , edgeIndex2( other.edgeIndex2 ) - , faceIndex2( other.faceIndex2 ) - {} - /// \ru Деструктор. \en Destructor. - ~MbSectionCode() {} - -public: - - SArray & SetEdgeIndex1() { return edgeIndex1; } - SArray & SetFaceIndex1() { return faceIndex1; } - SArray & SetEdgeIndex2() { return edgeIndex2; } - SArray & SetFaceIndex2() { return faceIndex2; } - - /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - void Transform( const MbMatrix3D & matr ); - /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - void Move ( const MbVector3D & to ); - /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - void Rotate ( const MbAxis3D & axis, double ang ); - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSectionCode & other, double accuracy ) const; - - // \ru Оператор присваивания. \en The assignment operator. - void operator = ( const MbSectionCode & other ) { - edgeIndex1 = other.edgeIndex1; - faceIndex1 = other.faceIndex1; - edgeIndex2 = other.edgeIndex2; - faceIndex2 = other.faceIndex2; - } - - KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionCode ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. - //DECLARE_NEW_DELETE_CLASS( MbSectionCode ) - //DECLARE_NEW_DELETE_CLASS_EX( MbSectionCode ) -}; // MbSectionCode - - -#endif // __OP_SWEPT_PARAMETERS_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Параметры операций над телами. + \en Parameters of operations on the solids. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __OP_SWEPT_PARAMETERS_H +#define __OP_SWEPT_PARAMETERS_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbMatrix3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbPolyCurve; +class MATH_CLASS MbSNameMaker; +class MbRegTransform; +class MbRegDuplicate; + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные об образующей. + \en The generating data. \~ + \details \ru Данные об образующей операции движения. \n + Образующая операции выдавливания, вращения или кинематической операции + может включать в себя набор двумерных контуров, набор трехмерных контуров, тело. \n + Для набора двумерных контуров на поверхности существуют следующие ограничения:\n + – может быть один или несколько контуров;\n + – если контуров несколько, они должны быть либо все замкнуты, либо все разомкнуты;\n + - если контуры замкнуты, они могут быть вложенными друг в друга, уровень вложенности не ограничивается;\n + – контуры не должны пересекаться между собой или самопересекаться.\n + Для двумерных контуров на не плоской поверхности есть дополнительное ограничение: + все контуры должны быть замкнуты.\n + Построение операции по двумерным контурам на не плоской поверхности рассчитано на указание пользователем + грани тела в качестве образующей. В этом случае данные для образующей можно получить + с помощью метода грани MbFace::GetSurfaceCurvesData.\n + Ограничения для трехмерных контуров:\n + – контуры не должны пересекаться между собой или самопересекаться.\n + \en Data about generating of movement operation. \n + При указании тела и поверхности одновременно предполагается, что выполняется кинематическая операция над + телом вдоль кривой на этой поверхности, причем движение согласовано с нормалью. \n + Generating of extrusion operation, rotation or sweeping operation + can include a set of two-dimensional contours, a set of three-dimensional contours, solid. \n + For a set of two-dimensional contours on the surface, the following restrictions:\n + - can be one or multiple contours;\n + - If there are multiple contours, all of them must be either closed or open;\n + - if contours are closed, then they can be nested into each other, the level of nesting is not limited;\n + - contours can't overlap each other or self-intersect.\n + For two-dimensional contour on the non-planar surface is additional constraint: + all the contours must be closed.\n + Constructing operation by two-dimensional contours on non-planar surface it is necessary to specify the by the user + face of solid as generating. In this case, the generating data can be obtained + by the method of face MbFace::GetSurfaceCurvesData.\n + Constraints for three-dimensional contour:\n + - contours can't overlap each other or self-intersect.\n + When set a solid and a surface at the same time, we suppose that sweeping operation over solid along curve on surface + is done, and moving is according to surface normal. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbSweptData { + +private: + // \ru Данные о двумерных контурах на поверхности. \en Data about two-dimensional contours on the surface. + c3d::SurfaceSPtr surface; ///< \ru Поверхность. \en The surface. + c3d::PlaneContoursSPtrVector contours; ///< \ru Множество двумерных контуров. \en Set of two-dimensional contours. + // \ru Трехмерные контуры. \en Three-dimensional contours. + c3d::SpaceContoursSPtrVector contours3D; ///< \ru Множество трёхмерных контуров. \en Set of three-dimensional contours. + // \ru Тело. \en Solid. + c3d::SolidSPtr solid; ///< \ru Тело. \en A solid. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbSweptData(); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSweptData( const MbSweptData &, MbRegDuplicate * ireg = c3d_null ); + +public: + + /** \brief \ru Конструктор плоской образующей. + \en Constructor of planar swept. \~ + \details \ru Конструктор плоской образующей из одного контура. + \en Constructor of planar swept from one contour. \~ + \param[in] place - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] contour - \ru Контур в параметрах заданной системы координат. Используется оригинал. + \en Contour in parameters of the given coordinate system. Used original. \~ + */ + MbSweptData( const MbPlacement3D & place, MbContour & contour ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по набору контуров на поверхности. + \en Constructor by a set of contours on a surface. \~ + \param[in] _surface - \ru Поверхность. Используется оригинал. + \en The surface. Used original. \~ + \param[in] _contours - \ru Набор контуров. Используются оригиналы. + \en A set of contours. Used originals. \~ + */ + MbSweptData( MbSurface & _surface, RPArray & _contours ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по набору контуров на поверхности. + \en Constructor by a set of contours on a surface. \~ + \param[in] _surface - \ru Поверхность. Используется оригинал. + \en The surface. Used original. \~ + \param[in] _contours - \ru Набор контуров. Используются оригиналы. + \en A set of contours. Used originals. \~ + */ + MbSweptData( MbSurface & _surface, c3d::PlaneContoursSPtrVector & _contours ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по кривой. + \en Constructor by a contour. \~ + \param[in] _contour3d - \ru Кривая. Используются оригиналы. + \en A curve. Used originals. \~ + */ + MbSweptData( MbCurve3D & _curve3d ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по контуру. + \en Constructor by a contour. \~ + \param[in] _contour3d - \ru Контур. Используются оригиналы. + \en A contour. Used originals. \~ + */ + MbSweptData( MbContour3D & _contour3d ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по набору пространственных контуров. + \en Constructor by a set of spatial contours. \~ + \param[in] _contours3d - \ru Набор контуров. Используются оригиналы. + \en A set of contours. Used originals. \~ + */ + MbSweptData( RPArray & _contours3d ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по набору пространственных контуров. + \en Constructor by a set of spatial contours. \~ + \param[in] _contours3d - \ru Набор контуров. Используются оригиналы. + \en A set of contours. Used originals. \~ + */ + MbSweptData( c3d::SpaceContoursSPtrVector & _contours3d ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по телу. + \en Constructor by a solid. \~ + \param[in] _solid - \ru Тело. Используется оригинал объекта. + \en A solid. Used original of object. \~ + \param[in] _newMainName - \ru Новое главное имя для топологических элементов тела. + \en New main name for names of solid's topological elements. \~ + */ + MbSweptData( MbSolid & _solid, const MbSNameMaker * newNameMaker = c3d_null ); + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор смешанной образующей. + \en Constructor of mixed swept. \~ + \param[in] _surface - \ru Поверхность. Используется оригинал. + \en The surface. Used original. \~ + \param[in] _contours - \ru Набор двумерных контуров в параметрах заданной поверхности. Используются оригиналы. + \en Set of two-dimensional contours in the parameters of the given surface. Used originals. \~ + \param[in] _contours3d - \ru Набор трехмерных контуров. Используются оригиналы. + \en A set of three-dimensional contours. Used originals. \~ + \param[in] _solid - \ru Тело. Используется оригинал объекта. + \en A solid. Used original of object. \~ + */ + MbSweptData( MbSurface * _surface, RPArray & _contours, + RPArray & _contours3d, MbSolid * _solid ); + + /// \ru Деструктор. \en Destructor. + ~MbSweptData(); + +public: + /** \brief \ru Добавить данные. + \en Add data. \~ + \details \ru Добавить данные о контурах на поверхности. + \en Add data about contours to the surface. \~ + \param[in] _surface - \ru Поверхность. Добавляется оригинал объекта. + \en The surface. Added original of the object. \~ + \param[in] _contours - \ru Набор контуров. Добавляются оригиналы. + \en A set of contours. Originals are added. \~ + */ + bool AddData( MbSurface & _surface, const RPArray & _contours ); + + /** \brief \ru Добавить данные. + \en Add data. \~ + \details \ru Добавить данные о контурах на поверхности. + \en Add data about contours to the surface. \~ + \param[in] _surface - \ru Поверхность. Добавляется оригинал объекта. + \en The surface. Added original of the object. \~ + \param[in] _contours - \ru Набор контуров. Добавляются оригиналы. + \en A set of contours. Originals are added. \~ + */ + bool AddData( MbSurface & _surface, c3d::PlaneContoursSPtrVector & _contours ); + + /** \brief \ru Количество всех кривых. + \en The count of all the curves. \~ + \details \ru Общее количество двумерных и трехмерных кривых. + \en The total count of two and three-dimensional curves. \~ + */ + size_t CurvesCount() const; + + /** \brief \ru Получить кривую по индексу. + \en Get the curve by the index. \~ + \details \ru Получить кривую из множества кривых на поверхности и трехмерных кривых. + \en Get the curve from set of curves on the surface and three-dimensional curves. \~ + \param[in] i - \ru Номер кривой в пределах от 0 до CurvesCount(). + \en The index of curve from 0 to CurvesCount(). \~ + \return \ru Кривую на поверхности или трехмерную кривую. + \en Curve on the surface or three-dimensional curve. \~ + */ + SPtr GetCurve3D( size_t i ) const; + + /// \ru Есть данные о двумерных кривых на поверхности? \en Is there data of two-dimensional curves on the surface? + bool IsSurfaceCurvesData() const { return ((surface != c3d_null) && !contours.empty()); } + /// \ru Есть данные о пространственных кривых? \en Is there data of spatial curves? + bool IsSpaceCurvesData() const { return !contours3D.empty(); } + /// \ru Есть данные о теле? \en Is there data about the solid? + bool IsSolidData() const { return (solid != c3d_null); } + + /// \ru Выдать поверхность. \en Get the surface. + const MbSurface * GetSurface() const { return surface; } + /// \ru Выдать поверхность для изменения. \en Get the surface for editing. + MbSurface * SetSurface() { return surface; } + + /// \ru Положить поверхность. \en Set a surface. + + /** \brief \ru Установить поверхность. + \en Set a surface. \~ + \details \ru Установить новую поверхность как носитель двумерных контуров или как целевую поверхность для направляющей. + \en Set surface carrier of two-dimensional contours or desired surface-carrier of guide curve. \~ + \param[in] surf - \ru Новая поверхность как носитель для двумерных контуров или целевая поверхность для направляющей. + \en Surface carrier of two-dimensional contours or desired surface-carrier of guide curve. \~ + */ + void SetSurface( const MbSurface & surf ) { surface = const_cast( &surf ); } + + /// \ru Выдать набор двумерных контуров. \en Get the set of two-dimensional contours. + const c3d::PlaneContoursSPtrVector & GetContours() const { return contours; } + /// \ru Выдать набор трехмерных контуров. \en Get the set of three-dimensional contours. + const c3d::SpaceContoursSPtrVector & GetContours3D() const { return contours3D; } + /// \ru Выдать тело. \en Get the solid. + const MbSolid * GetSolid() const { return solid; } + /// \ru Выдать тело для изменения. \en Get the solid for editing. + MbSolid * SetSolid() const { return solid; } + + /** \brief \ru Преобразовать объект. + \en Transform the object. \~ + \details \ru Преобразовать исходный объект согласно матрице c использованием регистратора. + \en Transform the initial object according to the matrix using the registrator. \~ + \param[in] matr - \ru Матрица преобразования. + \en A transformation matrix. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + /** \brief \ru Сдвинуть объект. + \en Move the object. \~ + \details \ru Сдвинуть геометрический объект вдоль вектора с использованием регистратора. + \en Move a geometric object along the vector using the registrator. \~ + \param[in] to - \ru Вектор сдвига. + \en Translation vector. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + /** \brief \ru Повернуть объект. + \en Rotate the object. \~ + \details \ru Повернуть объект вокруг оси на заданный угол с использованием регистратора. + \en Rotate an object about the axis by the given angle using the registrator. \~ + \param[in] axis - \ru Ось поворота. + \en The rotation axis. \~ + \param[in] angle - \ru Угол поворота. + \en The rotation angle. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + /** \brief \ru Определить, являются ли объекты равными. + \en Determine whether the objects are equal. \~ + \details \ru Определить, являются ли объекты равными с заданной точностью. + \en Determine whether the objects are equal with defined accuracy. \~ + \param[in] other - \ru Объект для сравнения. + \en Object for comparison. \~ + \return \ru Подобны ли объекты. + \en Whether the objects are similar. \~ + */ + bool IsSame( const MbSweptData & other, double accuracy ) const; + /** \brief \ru Определить, являются ли объекты подобными. + \en Determine whether the objects are similar. \~ + \details \ru Подобный объект можно инициализировать по данным подобного ему объекта. + \en Similar object can be initialized by data of object which is similar to it. \~ + \param[in] other - \ru Объект для сравнения. + \en Object for comparison. \~ + \return \ru Подобны ли объекты. + \en Whether the objects are similar. \~ + */ + bool IsSimilar( const MbSweptData & other ) const; + /** \brief \ru Сделать объекты равным. + \en Make objects equal. \~ + \details \ru Равными можно сделать только подобные объекты. + \en It is possible to make equal only similar objects. \~ + \param[in] init - \ru Объект для инициализации. + \en Object for initialization. \~ + \return \ru Сделан ли объект равным присланному. + \en Whether the object is made equal to the given one. \~ + */ + bool SetEqual ( const MbSweptData & other ); + + /** \brief \ru Замкнуты ли все контуры. + \en Whether all contours are closed. \~ + \details \ru Замкнуты ли все контуры. \n + \en Whether all contours are closed. \n \~ + \return \ru Возвращает true, если все контуры замкнуты. + \en Returns true if all contours are closed. \~ + */ + bool IsContoursClosed() const; + + /// \ru Проверить, что нет разрывов между сегментами поверхностных контуров. \en Check that there are no gaps between the segments of the surface contours. + bool CheckSurfaceContourConnection( double eps ) const; + /// \ru Проверить, что нет разрывов между сегментами пространственных контуров. \en Check that there are no gaps between the segments of the spatial contours. + bool CheckSpaceContourConnection( double eps ) const; + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSweptData & operator = ( const MbSweptData & ); + +KNOWN_OBJECTS_RW_REF_OPERATORS( MbSweptData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Cпособ выдавливания/вращения. + \en Method of extrusion/rotation. \~ + \details \ru Cпособ построения выдавливания/вращения. \n + \en Method of extrusion/rotation constructing. \n \~ + \ingroup Build_Parameters +*/ +// --- +enum MbSweptWay { + sw_scalarValue = -2, ///< \ru Выдавить на заданную глубину / вращать на заданный угол. \en Extrude to a given depth / rotate by a given angle. + sw_shell = -1, ///< \ru До ближайшего объекта (тела). \en To the nearest object (solid). + sw_surface = 0, ///< \ru До поверхности. \en To the surface. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры вращения и выдавливания. + \en Parameters of rotation and extrusion. \~ + \details \ru Данные о построении операции вращения или выдавливания + в одном из направлений: прямом или обратном. + \en Data about construction of rotation and extrusion + in one of directions: forward or backward. \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbSweptSide { +public: + MbSweptWay way; ///< \ru Способ выдавливания/вращения. \en Method of extrusion/rotation. + double scalarValue; ///< \ru Угол вращения/глубина выдавливания. \en Angle of rotation/depth of extrusion. + + /** \brief \ru Расстояние от поверхности. + \en Distance from the surface. \~ + \details \ru Расстояние от поверхности, до которой строим операцию. + Задавать при построении операции до поверхности (way = sw_surface). + distance < 0.0 при построении операции за поверхность, + distance > 0.0 при построении операции до поверхности. + \en Distance from the surface to construct up to. + Set when constructing operation to the surface (way = sw_surface). + distance < 0.0 when constructing operation back of surface, + distance > 0.0 when constructing operation front of surface. \~ + */ + double distance; + + /** \brief \ru Угол уклона. + \en Draft angle. \~ + \details \ru Угол уклона при выдавливании.\n + Операцию выдавливания с уклоном можно построить только в случае плоской образующей. + \en Draft angle when extruding.\n + Extrusion operation with draft can be constructed in the case of planar swept. \~ + */ + double rake; + +protected: + /** \brief \ru Поверхность, до которой строим операцию. + \en The surface to construct up to. \~ + \details \ru Поверхность, до которой строим операцию.\n + Задавать при построении операции до поверхности (way = sw_surface). + \en The surface to construct up to.\n + Set when constructing operation to the surface (way = sw_surface). \~ + */ + c3d::SurfaceSPtr surface; + + /** \brief \ru Признак совпадения нормали поверхности с нормалью грани. + \en An attribute of coincidence between the surface normal and the face normal. \~ + \details \ru Признак совпадения нормали поверхности, до которой строим операцию, с нормалью грани.\n + Задавать при построении операции до поверхности (way = sw_surface).\n + Указывает положение оболочки-результата относительно поверхности. + Используется при построении массива операций до поверхности. + Если у всех элементов массива признак должен быть одинаковым, + то при построении исходной операции нужно задать признак равным orient_BOTH (направление не определено). + При построении признак будет определен, и его значение нужно использовать для построения остальных элементов массива. + \en An attribute of coincidence between the face normal and the normal of surface to which to create operation.\n + Set when constructing operation to the surface (way = sw_surface).\n + Specifies the position of shell-result relative to the surface. + Used when constructing the array of operations to the surface. + If attributes of all the elements of array must be the same, + then when constructing of the original operation need to set attribute which is equal to orient_BOTH (the direction is not determined). + When constructing the attribute is determined and its value should be used for the construction of other elements of the array. \~ + */ + MbeSenseValue sameSense; + + +public: + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Задает параметры операции со способом "на заданную глубину". + Для построения операции параметры нужно изменить, + например, указать глубину выдавливания (угол вращения). + \en Sets parameters of the operation with the method "to a given depth". + For construction of operation the parameters need to change, + for example: specify the depth of extrusion (angle of rotation). \~ + */ + MbSweptSide() + : way ( sw_scalarValue ) + , scalarValue( 0.0 ) + , distance ( 0.0 ) + , rake ( 0.0 ) + , surface ( c3d_null ) + , sameSense ( orient_BOTH ) + {} + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор на угол вращения\глубину выдавливания. + \en Constructor by angle of rotation\depth of extrusion. \~ + \param[in] sVal - \ru Угол вращения\глубина выдавливания. + \en Angle of rotation\depth of extrusion. \~ + */ + MbSweptSide( double sVal ) + : way ( sw_scalarValue ) + , scalarValue( sVal ) + , distance ( 0.0 ) + , rake ( 0.0 ) + , surface ( c3d_null ) + , sameSense ( orient_BOTH ) + {} + + /** \brief \ru Конструктор до поверхности. + \en Constructor to the surface. \~ + \details \ru Конструктор до поверхности. Расстояние от поверхности задается равным 0.0. + \en Constructor to the surface. Distance from the surface is set to 0.0. \~ + \param[in] surf - \ru Поверхность, до которой строится операция. + \en The surface to construct up to. \~ + */ + MbSweptSide( const MbSurface * surf ); + + /** \brief \ru Конструктор до поверхности. + \en Constructor to the surface. \~ + \details \ru Конструктор до поверхности. Для элемента массива. + \en Constructor to the surface. For array element. \~ + \param[in] surf - \ru Поверхность, до которой строится операция. + \en The surface to construct up to. \~ + \param[in] sense - \ru Признак совпадения нормали заданной поверхности с нормалью грани. + Указывает, по какую сторону от поверхности должна находиться построенная оболочка. + \en An attribute of coincidence between the normal of given surface and the face normal. + Indicates at which side of the surface the must be located constructed shell. \~ + */ + MbSweptSide( const MbSurface * surf, MbeSenseValue sense ); + + /** \brief \ru Конструктор копирования. + \en Copy-constructor. \~ + \details \ru Конструктор копирования данных с использованием той же поверхности. + \en Copy-constructor of data with using of the same surface. \~ + \param[in] other - \ru Исходные параметры. + \en Initial parameters. \~ + */ + MbSweptSide( const MbSweptSide & other ); + + /** \brief \ru Конструктор копирования с регистратором. + \en Copy-constructor with the registrator. \~ + \details \ru Конструктор копирования с регистратором. Поверхность копируется. + \en Copy-constructor with the registrator. Surface is copying. \~ + \param[in] other - \ru Исходные параметры. + \en Initial parameters. \~ + */ + MbSweptSide( const MbSweptSide & other, MbRegDuplicate * ireg ); + + /// \ru Деструктор. \en Destructor. + virtual ~MbSweptSide(); + +public: + /// \ru Оператор присваивания данных с использованием той же поверхности. \en Assignment operator of data with using of the same surface. + MbSweptSide & operator = ( const MbSweptSide & other ); + + /// \ru Получить поверхность. \en Get the surface. + const MbSurface * GetSurface() const { return surface; } + /// \ru Получить поверхность. \en Get the surface. + MbSurface * SetSurface() { return surface; } + /// \ru Заменить поверхность. \en Replace surface. + void SetSurface( const MbSurface * s ); + + /// \ru Получить признак совпадения нормали поверхности с нормалью грани. \en Get the attribute of coincidence between the surface normal and the face normal. + MbeSenseValue GetSameSense() const { return sameSense; } + /// \ru Установить признак совпадения нормали поверхности с нормалью грани. \en Set the attribute of coincidence between the surface normal and the face normal. + void SetSameSense( MbeSenseValue sense ) { sameSense = sense; } + /// \ru Доступ к признаку совпадения нормали поверхности с нормалью грани. \en Access to the attribute of coincidence between the surface normal and the face normal. + MbeSenseValue & SetSameSense() { return sameSense; } + + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSweptSide & other, double accuracy ) const + { + if ( (other.way == way) && (other.sameSense == sameSense) ) { + if ( (::fabs(other.scalarValue - scalarValue) < accuracy) && + (::fabs(other.distance - distance) < accuracy) && + (::fabs(other.rake - rake) < accuracy) ) + { + bool isSurf1 = (surface != c3d_null); + bool isSurf2 = (other.surface != c3d_null); + + if ( isSurf1 == isSurf2 ) { + if ( isSurf1 && isSurf2 ) { + if ( !other.surface->IsSame( *surface, accuracy ) ) + return false; + } + return true; + } + } + } + + return false; + } +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры формообразующей операции. + \en The parameters of form-generating operation. \~ + \details \ru Параметры построения формообразующей операции + (например, выдавливания, вращения, кинематической, по сечениям). \n + \en The construction parameters of form-generating operation. + (for example: extrusion, rotation, sweeping, loft). \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS SweptValues { +public: + + /** \brief \ru Толщина стенки (величина эквидистанты) в прямом направлении. + \en Wall thickness (offset distance) along the forward direction. \~ + \details \ru Толщина стенки (величина эквидистанты) в положительном направлении нормали объекта + (грани, поверхности, плоскости кривой). + \en Wall thickness (offset distance) along the positive direction of the normal of an object + (face, surface, plane of the curve). \~ + */ + double thickness1; + + /** \brief \ru Толщина стенки (величина эквидистанты) в обратном направлении. + \en Wall thickness (offset distance) along the backward direction. \~ + \details \ru Толщина стенки (величина эквидистанты) в отрицательном направлении нормали объекта + (грани, поверхности, плоскости кривой). + \en Wall thickness (offset distance) along the negative direction of the normal of an object + (face, surface, plane of the curve). \~ + */ + double thickness2; + + bool shellClosed; ///< \ru Замкнутость создаваемой оболочки. \en Closedness of created shell. + +private: + bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods). + MbMergingFlags mergeFlags; ///< \ru Управляющие флаги слияния элементов оболочки. \en Control flags of shell items merging. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + SweptValues() + : thickness1 ( 0.0 ) + , thickness2 ( 0.0 ) + , shellClosed ( true ) + , checkSelfInt( true ) + , mergeFlags ( ) + {} + /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. + SweptValues( double t1, double t2, bool c = true ) + : thickness1 ( t1 ) + , thickness2 ( t2 ) + , shellClosed ( c ) + , checkSelfInt( true ) + , mergeFlags ( ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + SweptValues( const SweptValues & other ) + : thickness1 ( other.thickness1 ) + , thickness2 ( other.thickness2 ) + , shellClosed ( other.shellClosed ) + , checkSelfInt( other.checkSelfInt ) + , mergeFlags ( other.mergeFlags ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~SweptValues() {} + +public: + /// \ru Это параметры выдавливания? \en This is extrusion parameters? + virtual bool IsExtrusionValues() const { return false; } + /// \ru Это параметры вращения? \en This is rotation parameters? + virtual bool IsRevolutionValues() const { return false; } + /// \ru Это параметры кинематики? \en This is "evolution" parameters? + virtual bool IsEvolutionValues() const { return false; } + /// \ru Это параметры операции по сечениям? \en This is "lofted" parameters? + virtual bool IsLoftedValues() const { return false; } + /// \ru Это параметры операции ребра жесткости? \en This is "rib" parameters? + virtual bool IsRibValues() const { return false; } + + /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const; + /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ + virtual bool IsSimilar( const MbSweptData & other ) const; + /// \ru Сделать объекты равным. \en Make objects equal. \~ + virtual bool SetEqual ( const MbSweptData & other ); + +public: + /// \ru Функция копирования данных. \en Function of copying data. + void Init( const SweptValues & other ) { + thickness1 = other.thickness1; + thickness2 = other.thickness2; + shellClosed = other.shellClosed; + checkSelfInt = other.checkSelfInt; + mergeFlags = other.mergeFlags; + } + + /// \ru Получить состояние замкнутости. \en Get the closedness state. + bool IsShellClosed() const { return shellClosed; } + /// \ru Установит состояние замкнутости. \en Set the closedness state. + void SetShellClosed( bool cl ) { shellClosed = cl; } + + /// \ru Получить состояние флага проверки самопересечений. \en Get the state of flag of checking self-intersection. + bool CheckSelfInt() const { return checkSelfInt; } + /// \ru Установить состояние флага проверки самопересечений. \en Set the state of flag of checking self-intersection. + void SetCheckSelfInt( bool c ) { checkSelfInt = c; } + + /// \ru Сливать ли подобные грани. \en Whether to merge similar faces. + bool MergeFaces() const { return mergeFlags.MergeFaces(); } + /// \ru Сливать подобные грани. \en Whether to merge similar faces. + void SetMergingFaces( bool mf ) { mergeFlags.SetMergingFaces( mf ); } + + /// \ru Сливать ли подобные ребра. \en Whether to merge similar edges. + bool MergeEdges() const { return mergeFlags.MergeEdges(); } + /// \ru Сливать подобные ребра. \en Whether to merge similar edges. + void SetMergingEdges( bool me ) { mergeFlags.SetMergingEdges( me ); } + + /// \ru Получить управляющие флаги слияния элементов оболочки. \en Get control flags of shell items merging. + const MbMergingFlags & MergingFlags() const { return mergeFlags; } + /// \ru Установить управляющие флаги слияния элементов оболочки. \en Set control flags of shell items merging. + void SetMergingFlags( const MbMergingFlags & f ) { mergeFlags = f; } + + /// \ru Оператор присваивания. \en Assignment operator. + void operator = ( const SweptValues & other ) { Init( other ); } + + KNOWN_OBJECTS_RW_REF_OPERATORS( SweptValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры выдавливания или вращения. + \en The parameters of extrusion or rotation. \~ + \details \ru Параметры выдавливания или вращения кривых с опциями по направлениям. \n + В операции выдавливания прямым направлением считается направление, сонаправленное + с вектором выдавливания, а обратным - противоположное направление. + В операции вращения прямое направлением определяется по оси вращения с помощью правила правой руки. + \en The parameters of extrusion or rotation of curves with options along the directions. \n + In the extrusion operations the forward direction is the direction collinear + with the vector of extrusion and back - the opposite direction. + In the rotation operation the forward direction is determined by the axis of rotation using the right hand rule. \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS SweptValuesAndSides: public SweptValues { +public: + MbSweptSide side1; ///< \ru Параметры выдавливания/вращения в прямом направлении. \en The parameters of extrusion/rotation along the forward direction. + MbSweptSide side2; ///< \ru Параметры выдавливания/вращения в обратном направлении. \en The parameters of extrusion/rotation along the backward direction. + +public: + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Конструктор параметров для построения замкнутой оболочки без тонкой стенки. + Способ построение в обоих направлениях - на заданную глубину, равную 0.0. + \en Constructor of parameters for construction of closed shell without the thin wall. + Method of construction in both directions - to a given depth equal to 0.0. \~ + */ + SweptValuesAndSides() + : SweptValues() + , side1 () + , side2 () + {} + /** \brief \ru Конструктор по углам вращения или глубинам выдавливания. + \en Constructor by rotation angles and extrusion depths. \~ + \details \ru Конструктор параметров для построения замкнутой оболочки без тонкой стенки. + Способ построение в обоих направлениях - на заданную глубину. + \en Constructor of parameters for construction of closed shell without the thin wall. + Method of construction in both directions - to a given depth. \~ + \param[in] scalarValue1 - \ru Угол вращения\глубина выдавливания в прямом направлении. + \en Angle of rotation\depth of extrusion along the forward direction. \~ + \param[in] scalarValue2 - \ru Угол вращения\глубина выдавливания в обратном направлении. + \en Angle of rotation\depth of extrusion along the backward direction. \~ + */ + SweptValuesAndSides( double scalarValue1, double scalarValue2 ) + : SweptValues( ) + , side1 ( scalarValue1 ) + , side2 ( scalarValue2 ) + {} + /// \ru Конструктор копирования данных на тех же поверхностях. \en Copy-constructor of data on the same surfaces. + SweptValuesAndSides( const SweptValuesAndSides & other ) + : SweptValues( other ) + , side1 ( other.side1 ) + , side2 ( other.side2 ) + {} + /// \ru Конструктор полного копирования данных. \en Constructor of complete copying of data. + SweptValuesAndSides( const SweptValuesAndSides & other, MbRegDuplicate * ireg ) + : SweptValues( other ) + , side1 ( other.side1, ireg ) + , side2 ( other.side2, ireg ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~SweptValuesAndSides(); + +public: + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const SweptValuesAndSides * obj = dynamic_cast( &other ); + if ( obj != c3d_null ) { + if ( side1.IsSame( obj->side1, accuracy ) && side2.IsSame( obj->side2, accuracy ) ) { + if ( obj->SweptValues::IsSame( *this, accuracy ) ) { + return true; + } + } + } + return false; + } + +public: + /// \ru Оператор присваивания данных на тех же поверхностях. \en Assignment operator of data copying on the same surfaces. + void operator = ( const SweptValuesAndSides & other ) { + SweptValues::Init( other ); + side1 = other.side1; + side2 = other.side2; + } + + /** \brief \ru Преобразовать согласно матрице. + \en Transform according to the matrix. \~ + \details \ru Преобразовать согласно матрице поверхности в прямом и обратном направлении. + \en Transform according to the matrix of surface in the forward and backward direction. \~ + \param[in] matr - \ru Матрица преобразования. + \en A transformation matrix. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + /** \brief \ru Сдвинуть вдоль вектора. + \en Move along a vector. \~ + \details \ru Сдвинуть вдоль вектора поверхности в прямом и обратном направлении. + \en Move along the vector of the surface along the forward and backward direction. \~ + \param[in] to - \ru Вектор сдвига. + \en Translation vector. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + /** \brief \ru Повернуть вокруг оси. + \en Rotate around an axis. \~ + \details \ru Повернуть вокруг оси поверхности в прямом и обратном направлении. + \en Rotate around the axis of the surface along the forward and backward direction. \~ + \param[in] axis - \ru Ось поворота. + \en The rotation axis. \~ + \param[in] angle - \ru Угол поворота. + \en The rotation angle. \~ + \param[in] iReg - \ru Регистратор. + \en Registrator. \~ + */ + void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + + /** \brief \ru Сделать копии поверхностей. + \en Make copies of surfaces. \~ + \details \ru Если в каком-либо направлении задана поверхность, заменить эту поверхность на ее копию. + \en If the surface is given in any direction, then replace the surface with its copy. \~ + \param[in] ireg - \ru Регистратор копий. + \en Registrator of copies. \~ + \return \ru true, если хотя бы одна поверхность имелась и сдублирована. + \en True if at least one surface is had and copied. \~ + */ + bool DuplicateSurfaces( MbRegDuplicate * ireg = c3d_null ); + +public: + /// \ru Получить поверхность в положительном направлении. \en Get the surface along the positive direction. + const MbSurface * GetSurface1() const { return side1.GetSurface(); } + /// \ru Получить поверхность в отрицательном направлении. \en Get the surface along the negative direction. + const MbSurface * GetSurface2() const { return side2.GetSurface(); } + /// \ru Получить поверхность в положительном направлении. \en Get the surface along the positive direction. + MbSurface * SetSurface1() { return side1.SetSurface(); } + /// \ru Получить поверхность в отрицательном направлении. \en Get the surface along the negative direction. + MbSurface * SetSurface2() { return side2.SetSurface(); } + /// \ru Установить поверхность в положительном направлении. \en Set the surface along the positive direction. + void SetSurface1( const MbSurface * s ) { side1.SetSurface( s ); } + /// \ru Установить поверхность в отрицательном направлении. \en Set the surface along the negative direction. + void SetSurface2( const MbSurface * s ) { side2.SetSurface( s ); } + /// \ru Поменять поверхности местами. \en Swap surfaces. + void ExchangeSurfaces(); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры операции выдавливания. + \en The parameters of extrusion operation. \~ + \details \ru Параметры операции выдавливания кривых с опциями по направлениям. \n + \en The parameters of extrusion operation of curves with options along directions. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS ExtrusionValues : public SweptValuesAndSides { +public: + + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Конструктор параметров выдавливания для построения замкнутой оболочки без тонкой стенки + в прямом направлении на величину, равную 10.0. + \en Constructor of extrusion parameters for construction of closed shell without the thin wall. + along the forward direction by value 10.0. \~ + */ + ExtrusionValues() + : SweptValuesAndSides( 10., 0. ) {} + /** \brief \ru Конструктор по глубинам выдавливания. + \en Constructor by extrusion depths. \~ + \details \ru Конструктор параметров выдавливания для построения замкнутой оболочки без тонкой стенки. + Способ построение в обоих направлениях - на заданную глубину. + \en Constructor of extrusion parameters for construction of closed shell without the thin wall. + Method of construction in both directions - to a given depth. \~ + \param[in] scalarValue1 - \ru Глубина выдавливания в прямом направлении. + \en Depth of extrusion along the forward direction. \~ + \param[in] scalarValue2 - \ru Глубина выдавливания в обратном направлении. + \en Depth of extrusion along the backward direction. \~ + */ + ExtrusionValues( double scalarValue1, double scalarValue2 ) + : SweptValuesAndSides( scalarValue1, scalarValue2 ) {} + /// \ru Конструктор копирования, на тех же поверхностях. \en Copy-constructor on the same surfaces. + ExtrusionValues( const ExtrusionValues & other ) + : SweptValuesAndSides( other ) {} + /// \ru Конструктор копирования. \en Copy-constructor. + ExtrusionValues( const ExtrusionValues & other, MbRegDuplicate * ireg ) + : SweptValuesAndSides( other, ireg ) {} + /// \ru Деструктор. \en Destructor. + virtual ~ExtrusionValues(); + +public: + // \ru Это параметры выдавливания? \en This is extrusion parameters? + virtual bool IsExtrusionValues() const { return true; } + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const ExtrusionValues * obj = dynamic_cast( &other ); + if ( obj != c3d_null ) { + if ( obj->SweptValuesAndSides::IsSame( *this, accuracy ) ) + return true; + } + return false; + } + +public: + /// \ru Оператор присваивания, на тех же поверхностях. \en Assignment operator on the same surfaces. + ExtrusionValues & operator = ( const ExtrusionValues & other ) { + *static_cast(this) = *static_cast(&other); + return *this; + } + + KNOWN_OBJECTS_RW_REF_OPERATORS( ExtrusionValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры операции вращения. + \en The parameters of revolution operation. \~ + \details \ru Параметры операции вращения кривых с опциями по направлениям. \n + \en The parameters of revolution operation of curves with options along directions. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS RevolutionValues : public SweptValuesAndSides { +public: + /** \brief \ru Форма топологии. + \en Topology shape. \~ + \details \ru Форма топологии: 0 - тело типа сферы, 1 - тело типа тора.\n + Если образующая - не замкнутая плоская кривая, и ось вращения лежит в плоскости кривой, + то возможно построение тела вращения с топологией типа сферы. В этом случае образующая достраивается до оси вращения. + \en Topology shape: 0 - sphere, 1 - torus.\n + If swept is non-closed planar curve and axis of rotation lies on the curve plane, + then is possible to construct revolution solids with the topology of sphere type. In this case the swept is being updated to the rotation axis. +I \~ */ + int shape; + +public: + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Конструктор параметров вращения для построения замкнутой оболочки типа тора + без тонкой стенки в прямом направлении на полный оборот. + \en Constructor of revolution parameters for construction of closed shell of torus type + without thin wall along the forward direction at full turn. \~ + */ + RevolutionValues() + : SweptValuesAndSides( M_PI, 0. ) + , shape( 1 ) + {} + /** \brief \ru Конструктор по углам вращения. + \en Constructor by revolution angles. \~ + \details \ru Конструктор параметров вращения для построения замкнутой оболочки без тонкой стенки. + Способ построение в обоих направлениях - на заданную глубину (заданный угол). + \en Constructor of revolution parameters for construction of closed shell without the thin wall. + Method of construction in both directions - to a given depth (given angle). \~ + \param[in] scalarValue1 - \ru Угол вращение в прямом направлении. + \en Revolution angle along the forward direction. \~ + \param[in] scalarValue2 - \ru Угол вращения в обратном направлении. + \en Revolution angle along the backward direction. \~ + \param[in] s - \ru Форма топологии. + \en Topology shape. \~ + */ + RevolutionValues( double scalarValue1, double scalarValue2, int s ) + : SweptValuesAndSides( scalarValue1, scalarValue2 ) + , shape( s ) + {} + /// \ru Конструктор копирования, на тех же поверхностях. \en Copy-constructor on the same surfaces. + RevolutionValues( const RevolutionValues & other ) + : SweptValuesAndSides( other ) + , shape( other.shape ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + RevolutionValues( const RevolutionValues & other, MbRegDuplicate * ireg ) + : SweptValuesAndSides( other, ireg ) + , shape( other.shape ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~RevolutionValues(); + +public: + // \ru Это параметры вращения? \en This is rotation parameters? + virtual bool IsRevolutionValues() const { return true; } + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const RevolutionValues * obj = dynamic_cast( &other ); + if ( obj != c3d_null ) { + if ( obj->shape == shape ) { + if ( obj->SweptValuesAndSides::IsSame( *this, accuracy ) ) + return true; + } + } + return false; + } + +public: + /// \ru Оператор присваивания, на тех же поверхностях. \en Assignment operator on the same surfaces. + RevolutionValues & operator = ( const RevolutionValues & other ) { + *static_cast(this) = *static_cast(&other); + shape = other.shape; + return *this; + } + + KNOWN_OBJECTS_RW_REF_OPERATORS( RevolutionValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры кинематической операции. + \en Parameters of the sweeping operation. \~ + \details \ru Параметры операции движения образующей по направляющей кривой. \n + \en The operation parameters of moving the generating curve along the spine curve. \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS EvolutionValues : public SweptValues { + + /// \ru Способы переноса образующего объекта вдоль направляющей. \en Moving method of generating object along the spine curve. + enum ModesList { + eom_Parallel = 0x00, // 00000 ///< \ru Образующая переносится параллельно самой себе. \en Generating curve is moved parallel to itself. + eom_KeepingAngle = 0x01, // 00001 ///< \ru Образующая при переносе сохраняет исходный угол с направляющей. \en Generating curve when moving preserves initial angle with spine. + eom_Orthogonal = 0x02, // 00010 ///< \ru Плоскость образующей выставляется и сохраняется ортогональной направляющей. \en Plane of generating curve is set and saved as orthogonal to spine. + eom_BySurfaceNormal = 0x04, // 00100 ///< \ru Образующая переносится согласованно с нормалью к поверхности. \en Generating object is moved according to surface normal. + }; + +protected: + /** \brief \ru Способ переноса образующего контура вдоль направляющей. + \en Moving method of generating contour along the spine curve. \~ + \details \ru Способ переноса образующего контура вдоль направляющей: \n + parallel <= 0 - Образующая переносится параллельно самой себе; \n + parallel == 1 - Образующая при переносе сохраняет исходный угол с направляющей; \n + parallel == 2 - Плоскость образующей выставляется и сохраняется ортогональной направляющей. \n + parallel > 3 - Образующая переносится согласованно с нормалью к поверхности. \n + \en Moving method of generating contour along the spine curve: \n + parallel <= 0 - Generating curve is moved parallel to itself; \n + parallel == 1 - Generating curve when moving preserves initial angle with spine; \n + parallel == 2 - Plane of generating curve is set and saved as orthogonal to spine. \n + parallel > 3 - Generating object is moved according to surface normal. \n \~ + */ + int mode; +public: + // \ru Данные о функциях изменения образующих кривых вдоль направляющей кривой (могут быть c3d_null). \en Data about changes of generating curves along the guide curve (can be c3d_null). + double range; ///< \ru Эквидистантное смещение точек образующей кривой в конце траектории. \en The offset range of generating curve on the end of spine curve. + SPtr scaling; ///< \ru Функция масштабирования образующей кривой. \en The function of curve scale. + SPtr winding; ///< \ru Функция вращения образующей кривой. \en The function of curve rotation. + c3d::ConstSurfaceSPtr surface; ///< \ru Поверхность для управления направляющей кривой MbSpine. \en The surface for guide curve control (for MbSpine). + +public: + + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Конструктор параметров кинематической операции для построения замкнутой оболочки + без тонкой стенки с сохранением угла наклона. + \en Constructor of sweeping operation parameters for construction of closed shell + without the thin wall with keeping the angle inclination. \~ + */ + EvolutionValues() + : SweptValues( ) + , mode ( eom_KeepingAngle ) + , range ( 0.0 ) + , scaling ( c3d_null ) + , winding ( c3d_null ) + , surface ( c3d_null ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + EvolutionValues( const EvolutionValues & other ); + /// \ru Деструктор. \en Destructor. + virtual ~EvolutionValues(); + +public: + // \ru Это параметры кинематики? \en This is "evolution" parameters? + virtual bool IsEvolutionValues() const { return true; } + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const; + // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ + virtual bool IsSimilar( const SweptValues & other ) const; + // \ru Сделать объекты равным. \en Make objects equal. \~ + virtual bool SetEqual ( const SweptValues & other ); + + /// \ru Копировать значение режима операции. \en Copy operation mode. + void CopyMode( const EvolutionValues & ev ) { mode = ev.mode; } + /// \ru Получить значение режима операции. \en Get operation mode. + int GetMode() const { return mode; } + /// \ru Переносится ли образующая параллельно самой себе. \en Whether generating curve is moved parallel to itself. + bool IsParallel() const { return (mode < 1); } + /// \ru Сохраняет ли образующая при переносе исходный угол с направляющей. \en Whether generating curve when moving preserves initial angle with spine. + bool IsKeepingAngle() const { return !!(mode & eom_KeepingAngle); } + /// \ru Выставляется ли плоскость образующей ортогонально направляющей. \en Whether plane of generating curve is set and saved as orthogonal to spine. + bool IsOrthogonal() const { return !!(mode & eom_Orthogonal); } + /// \ru Переносится ли образующая согласованно с нормалью к поверхности. \en Whether generating object is moved according to surface normal. + bool BySurfaceNormal() const { return !!(mode & eom_BySurfaceNormal); } + + /// \ru Переносить образующая параллельно самой себе. \en Move generating curve parallel to itself. + void SetParallel() { mode = eom_Parallel; } + /// \ru Сохранять при переносе исходный угол между образующей и направляющей. \en Preserve initial angle between generatrix and spine when moving. + void SetKeepingAngle() { mode = eom_KeepingAngle; } + /// \ru Выставлять плоскость образующей ортогонально направляющей. \en Set and keep plane of generating curve as orthogonal to spine. + void SetOrthogonal() { mode = eom_Orthogonal; } + /// \ru Переносить образующую согласованно с нормалью к поверхности. \en Move generating object according to surface normal. + bool SetBySurfaceNormal( bool s ) + { + if ( !IsParallel() ) { + if ( s ) mode |= eom_BySurfaceNormal; + else mode ^= eom_BySurfaceNormal; + return true; + } + return false; + } + /// \ru Выдать функцию масштабирования образующей кривой. \en Get the function of curve scale. + double GetRange() const { return range; } + double & SetRange() { return range; } + void SetRange( double r ) { range = r; } + + /** \brief \ru Добавить данные. + \en Add data. \~ + \details \ru Добавить данные об изменении образующих контурах на поверхности вдоль образующей кривой. + \en Add data about changes of generating contours on the surface along the guide curve. \~ + \param[in] _scaling - \ru Масштабирование. + \en The scaling. \~ + \param[in] _winding - \ru Поворот. + \en The winding. \~ + */ + bool AddData( MbFunction & _scaling, MbFunction & _winding ); + + /// \ru Выдать функцию масштабирования образующей кривой. \en Get the function of curve scale. + const MbFunction * GetScaling() const { return scaling; } + MbFunction * SetScaling() { return scaling; } + + /// \ru Выдать функцию вращения образующей кривой. \en Get the function of curve rotation. + const MbFunction * GetWinding() const { return winding; } + MbFunction * SetWinding() { return winding; } + + ///< \ru Выдать поверхность для направляющей кривой MbSpine. \en Get the surface for guide curve MbSpine. + const MbSurface * GetSurface() const { return surface; } + void SetSurface( const MbSurface & surf ); + +public: + /// \ru Оператор присваивания. \en Assignment operator. + EvolutionValues & operator = ( const EvolutionValues & other ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( EvolutionValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры операции построения тела по плоским сечениям. + \en The operation parameters of constructing solid by lofted. \~ + \details \ru Параметры операции построения тела по плоским сечениям, заданных контурами. \n + \en The parameters of constructing operation by lofted which are given by contours. \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS LoftedValues : public SweptValues { +public: + bool closed; ///< \ru Замкнутость трубки сечений. \en Closedness of tube. + MbVector3D vector1; ///< \ru Производная в начале. \en The derivative at the start. + MbVector3D vector2; ///< \ru Производная в конце. \en The derivative at the end. + bool setNormal1; ///< \ru Установлена нормаль в начале, если начальное сечение точечное. \en The normal is set at the start, if first section is point curve. + bool setNormal2; ///< \ru Установлена нормаль в конце, если начальное сечение точечное. \en The normal is set at the end, if last section is point curve. + double derFactor1; ///< \ru Множитель величины производной при установке нормали в начале. По умолчанию 1.0. \en The modifier of the derivative when setting the normal at the beginning. The default is 1.0. + double derFactor2; ///< \ru Множитель величины производной при установке нормали в конце. По умолчанию 1.0. \en The modifier of the derivative when setting the normal at the end. The default is 1.0. + MbVector3D directSurf1; ///< \ru Ось направления движения поверхности в начале при установке нормали. \en Direction axis of the surface progress near the starting curve when setting the normal. + MbVector3D directSurf2; ///< \ru Ось направления движения поверхности в конце при установке нормали. \en Direction axis of the surface progress near the ending curve when setting the normal. + +public: + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + \details \ru Конструктор параметров операции по сечениям для построения замкнутой оболочки без тонкой стенки. + \en Constructor of lofted operation parameters for construction of closed shell without the thin wall. \~ + */ + LoftedValues() + : SweptValues ( ) + , closed ( false ) + , vector1 ( 0.0, 0.0, 0.0 ) + , vector2 ( 0.0, 0.0, 0.0 ) + , setNormal1 ( false ) + , setNormal2 ( false ) + , derFactor1 ( 1.0 ) + , derFactor2 ( 1.0 ) + , directSurf1 ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL ) + , directSurf2 ( UNDEFINED_DBL, UNDEFINED_DBL, UNDEFINED_DBL ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + LoftedValues( const LoftedValues & other ) + : SweptValues ( other ) + , closed ( other.closed ) + , vector1 ( other.vector1 ) + , vector2 ( other.vector2 ) + , setNormal1 ( other.setNormal1 ) + , setNormal2 ( other.setNormal2 ) + , derFactor1 ( other.derFactor1 ) + , derFactor2 ( other.derFactor2 ) + , directSurf1 ( other.directSurf1 ) + , directSurf2 ( other.directSurf2 ) + {} + /// \ru Оператор присваивания. \en Assignment operator. + LoftedValues & operator = ( const LoftedValues & other ) + { + SweptValues::Init( other ); + closed = other.closed; + vector1 = other.vector1; + vector2 = other.vector2; + setNormal1 = other.setNormal1; + setNormal2 = other.setNormal2; + directSurf1 = other.directSurf1; + directSurf2 = other.directSurf2; + return *this; + } + /// \ru Деструктор. \en Destructor. + virtual ~LoftedValues(); + +public: + // \ru Это параметры операции по сечениям? \en This is "lofted" parameters? + virtual bool IsLoftedValues() const { return true; } + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const LoftedValues * obj = dynamic_cast( &other ); + if ( obj != c3d_null ) { + if ( obj->closed == closed ) { + if ( c3d::EqualVectors(vector1, obj->vector1, accuracy) && c3d::EqualVectors(vector2, obj->vector2, accuracy) ) { + if ( obj->setNormal1 == setNormal1 && obj->setNormal2 == setNormal2 ) { + if ( (setNormal1 == false || obj->derFactor1 == derFactor1 || c3d::EqualVectors(directSurf1, obj->directSurf1, accuracy)) && // Фактор может различаться, если нормаль не установлена. + (setNormal2 == false || obj->derFactor2 == derFactor2 || c3d::EqualVectors(directSurf2, obj->directSurf2, accuracy)) ) { + if ( obj->SweptValues::IsSame(*this, accuracy) ) { + return true; + } + } + } + } + } + } + return false; + } + +public: + /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. + void Transform( const MbMatrix3D & matr ); + /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + void Move ( const MbVector3D & to ); + /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. + void Rotate ( const MbAxis3D & axis, double ang ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( LoftedValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры ребра жёсткости. + \en Parameters of a rib. \~ + \details \ru Параметры построения ребра жёсткости по кривой, задающей его форму. \n + \en The construction parameters of rib by curve gives its shape. \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS RibValues : public SweptValues { +public: + /** \brief \ru Сторона заполнения пространства телом ребра. + \en The side to place the rib on. \~ + \details \ru С какой стороны от кривой располагается ребро. \n + \en With which side of the curve is rib. \n \~ + \ingroup Build_Parameters + */ + enum ExtrudeSide { + es_Left = 0, ///< \ru Ребро выдавливается в левую сторону от кривой вдоль плоскости. \en Rib is extruded to the left side of the curve along the plane. + es_Right, ///< \ru Ребро выдавливается в правую сторону от кривой вдоль плоскости. \en Rib is extruded to the right side of the curve along the plane. + es_Up, ///< \ru Ребро выдавливается в сторону нормали плоскости. \en Rib is extruded to the side of the surface normal. + es_Down, ///< \ru Ребро выдавливается в сторону против нормали плоскости. \en Rib is extruded to the side opposite to the surface normal. + }; + +public: + double angle1; ///< \ru Угол уклона плоскости в прямом направлении. \en Draft angle of the plane along the forward direction. + double angle2; ///< \ru Угол уклона плоскости в обратном направлении. \en Draft angle of the plane along the backward direction. + ExtrudeSide side; ///< \ru Сторона заполнения пространства телом ребра. \en The side to place the rib on. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + RibValues() + : SweptValues( ) + , angle1 ( 0.0 ) + , angle2 ( 0.0 ) + , side ( es_Right ) + {} + /// \ru Конструктор по толщинам, углам и стороне заполнения пространства. \en Constructor by thickness, angles and filling space. + RibValues( double t1, double t2, double a1, double a2, int s ) + : SweptValues( t1, t2 ) + , angle1 ( a1 ) + , angle2 ( a2 ) + , side ( (ExtrudeSide)s ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + RibValues( const RibValues & other ) + : SweptValues( other ) + , angle1 ( other.angle1 ) + , angle2 ( other.angle2 ) + , side ( other.side ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~RibValues(); + +public: + // \ru Это параметры операции ребра жесткости? \en This is "rib" parameters? + virtual bool IsRibValues() const { return true; } + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const RibValues * obj = dynamic_cast( &other ); + + if ( obj != c3d_null ) { + if ( obj->side == side ) { + if ( ::fabs(obj->angle1 - angle1) < accuracy && ::fabs(obj->angle2 - angle2) < accuracy ) + return SweptValues::IsSame( *obj, accuracy ); + } + } + return false; + } + +public: + /// \ru Функция копирования. \en Copy function. + void Init( const RibValues & other ) + { + SweptValues::Init( other ); + angle1 = other.angle1; + angle2 = other.angle2; + side = other.side; + } + /// \ru Оператор присваивания. \en Assignment operator. + RibValues & operator = ( const RibValues & other ) + { + Init( other ); + return *this; + } + + KNOWN_OBJECTS_RW_REF_OPERATORS( RibValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры ребра жёсткости листового тела. + \en Parameters of a sheet metal rib. \~ + \details \ru Параметры построения ребра жёсткости листового тела по кривой, задающей его форму. \n + \en The construction parameters of a sheet metal rib by curve gives its shape. \n \~ +\ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS SheetRibValues: public RibValues { +public: + double radRibConvex; ///< \ru Радиус скругления выпуклой части ребра жесткости. \en Fillet radius of convex part of rib. + double radSideConcave; ///< \ru Радиус скругления примыкания вогнутой части ребра жесткости к листовому телу. \en Fillet radius of connection of concave part of rib and metal sheet. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + SheetRibValues() + : RibValues ( ) + , radRibConvex ( 0.0 ) + , radSideConcave( 0.0 ) + {} + /// \ru Конструктор по параметрам. \en Constructor by parameters. + SheetRibValues( double t1, double t2, double a1, double a2, int s, double rFilletRib, const double & rFilletSide ) + : RibValues ( t1, t2, a1, a2, s ) + , radRibConvex ( ::fabs(rFilletRib) ) + , radSideConcave( ::fabs(rFilletSide) ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + SheetRibValues( const SheetRibValues & other ) + : RibValues ( other ) + , radRibConvex ( other.radRibConvex ) + , radSideConcave( other.radSideConcave ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~SheetRibValues(); + +public: + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const SweptValues & other, double accuracy ) const + { + const SheetRibValues * obj = dynamic_cast( &other ); + + if ( obj != c3d_null ) { + if ( (::fabs(radRibConvex - obj->radRibConvex) < accuracy) && (::fabs(radSideConcave - obj->radSideConcave) < accuracy) ) + return RibValues::IsSame( *obj, accuracy ); + } + return false; + } + +public: + /// \ru Функция копирования. \en Copy function. + void Init( const SheetRibValues & other ) + { + RibValues::Init( other ); + radRibConvex = other.radRibConvex; + radSideConcave = other.radSideConcave; + } + + /// \ru Оператор присваивания. \en Assignment operator. + SheetRibValues & operator = ( const SheetRibValues & other ) { + Init( other ); + return *this; + } + + /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. + void Transform( const MbMatrix3D & matr ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( SheetRibValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры булевой операции выдавливания или вращения до объекта. + \en The parameters of Boolean operation of extrusion or revolution to object. \~ + \details \ru Параметры булевой операции выдавливания или вращения до объекта. \n + Используется при булевой операции исходного тела + и построенной операции выдавливания или вращения двумерных контуров на поверхности. + \en The parameters of Boolean operation of extrusion or revolution to object. \n + Used in Boolean operation of initial solid + and constructed operation of extrusion or revolution of two-dimensional contours on the surface. \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbSweptLayout { + /** \brief \ru Направление выдавливания (вращения). + \en A direction of extrusion (revolution). \~ + \details \ru Направление выдавливания (вращения) по отношению к вектору выдавливания (оси вращения). + \en The direction of extrusion relative to the extrusion vector. \~ + */ + enum Direction { + ed_minus_minus = -2, ///< \ru В обратном направлении, для обеих строн. \en Along the backward direction, for both sides. + ed_minus = -1, ///< \ru В обратном направлении, для одной стороны. \en Along the backward direction, for one sides. + ed_both = 0, ///< \ru В обоих направлениях. \en Along both directions. + ed_plus = 1, ///< \ru В прямом направлении, для одной стороны. \en Along the forward direction, for one sides. + ed_plus_plus = 2, ///< \ru В прямом направлении, для обеих сторон. \en Along the forward direction, for both sides. + }; + Direction direction; ///< \ru Направление выдавливания относительно вектора. \en The direction of extrusion relative to the vector. + bool skipUnion; ///< \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. + +protected: + SPtr surface; ///< \ru Поверхность, на которой размещена образующая. \en The surface, which contains the generating curve. + +protected: + /// \ru Конструктор. \en Constructor. + MbSweptLayout( const MbSurface & surf, Direction dir ) : surface( &surf ), direction( dir ), skipUnion( false ) {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbSweptLayout( const MbSweptLayout & other ) : surface( other.surface ), direction( other.direction ), skipUnion( other.skipUnion ) {} + /// \ru Деструктор. \en Destructor. + virtual ~MbSweptLayout(); +public: + /// \ru Получить поверхность. \en Get the surface. + const MbSurface & GetSurface() const { return *surface; } + + /// \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. + bool SkipUnion() const { return skipUnion; } + /// \ru Создавать новое тело (Не приклеивать к телу). \en Create a new solid. + void SkipUnion( bool su ) { skipUnion = su; } +public: + /// \ru Это параметры выдавливания? \en This is extrusion parameters? + virtual bool IsExtrusionLayout() const { return false; } + /// \ru Это параметры вращения? \en This is rotation parameters? + virtual bool IsRevolutionLayout() const { return false; } +public: + /// \ru Классификация точки относительно несущей поверхности. \en Classification point relative to the surface. + MbeItemLocation PointRelative( const MbCartPoint3D & p ) const; +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSweptLayout & operator = ( const MbSweptLayout & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры булевой операции выдавливания до объекта. + \en The parameters of Boolean operation of extrusion to object. \~ + \details \ru Параметры булевой операции выдавливания до объекта. \n + Используется при булевой операции исходного тела + и построенной операции выдавливания двумерных контуров на поверхности. + \en The parameters of Boolean operation of extrusion to object. \n + Used in Boolean operation of initial solid + and constructed operation of extrusion of two-dimensional contours on the surface. \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbExtrusionLayout : public MbSweptLayout { + MbVector3D dirVector; ///< \ru Вектор выдавливания. \en An extrusion vector. +public: + /// \ru Конструктор. \en Constructor. + MbExtrusionLayout( const MbSurface & surf, Direction dir, const MbVector3D & dirVec ) : MbSweptLayout( surf, dir ), dirVector( dirVec ) {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbExtrusionLayout( const MbExtrusionLayout & other ) : MbSweptLayout( other ), dirVector( other.dirVector ) {} + /// \ru Деструктор. \en Destructor. + virtual ~MbExtrusionLayout(); +public: + /// \ru Это параметры выдавливания? \en This is extrusion parameters? + virtual bool IsExtrusionLayout() const { return true; } +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbExtrusionLayout & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры булевой операции вращения до объекта. + \en The parameters of Boolean operation of revolution to object. \~ + \details \ru Параметры булевой операции вращения до объекта. \n + Используется при булевой операции исходного тела + и построенной операции вращения двумерных контуров на поверхности. + \en The parameters of Boolean operation of revolution to object. \n + Used in Boolean operation of initial solid + and constructed operation of revolution of two-dimensional contours on the surface. \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbRevolutionLayout : public MbSweptLayout { + MbAxis3D revAxis; ///< \ru Ось вращения. \en An revolution axis. +public: + /// \ru Конструктор. \en Constructor. + MbRevolutionLayout( const MbSurface & surf, Direction dir, const MbAxis3D & rotAxis ) : MbSweptLayout( surf, dir ), revAxis( rotAxis ) {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbRevolutionLayout( const MbRevolutionLayout & other ) : MbSweptLayout( other ), revAxis( other.revAxis ) {} + /// \ru Деструктор. \en Destructor. + virtual ~MbRevolutionLayout(); +public: + /// \ru Это параметры вращения? \en This is rotation parameters? + virtual bool IsRevolutionLayout() const { return true; } +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbRevolutionLayout & ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные края сечения поверхности. + \en The surface section control function. \~ + \details \ru Точку края сечения определяют: или рёбра, или кривые. Направление сечения на краю определяют: или поверхности смежных граней рёбер, или поверхности граней, или функция угла наклона. + \en The end of the section is determined as point either edges, or curves. The direction on the end of the section is determined as either the surfaces of edges, or the surfaces of faces, or a function of the angle. + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbSectionRail { + +private: + std::vector edges; ///< \ru Направляющие рёбра (могут отсутствовать). \en The guide edges (may be empty). + std::vector edgeSide; ///< \ru С какой гранью ребра гладко стыковать поверхность (синхронно с edges). \en What face of edge should the surface join smoothly to (synchronously with edges). + std::vector faces; ///< \ru Опорные грани (могут отсутствовать). \en The reference faces (may be empty). + std::vector faceSide; ///< \ru С каких сторон касаться поверхностей при form==cs_Linea (синхронно с faces). \en On which sides to touch surfaces when form==cs_Linea (synchronously with faces). + std::vector curves; ///< \ru Направляющие кривые (могут отсутствовать). \en The guide curves (may be empty). + MbCurve3D * track; ///< \ru Кривая, через которую должно пройти сечение (может отсутствовать). \en The curve that the section should pass through (may be c3d_null). + MbFunction * angle; ///< \ru Функция угла наклона (может отсутствовать). \en The function of the angle of inclination (may be c3d_null). + ThreeStates state; ///< \ru Как использовать angle: угол к хорде (ts_neutral), отклонение от касательной поверхности (ts_positive), отклонение от нормали к поверхности (ts_negative). + ///< \en How to use angle: angle to chord (ts_neutral), deviation from tangent surface (ts_positive), deviation from normal to surface (ts_negative). +public: + + /// \ru Конструктор по умолчанию. \en Empty constructor. + MbSectionRail() + : edges () + , edgeSide() + , faces () + , faceSide() + , curves () + , track ( c3d_null ) + , angle ( c3d_null ) + , state( ts_neutral ) + {} + + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] eds - \ru Направляющие рёбра. + \en The guide edges. \~ + \param[in] eSide - \ru Какую сторону кривой гладко стыковать с поверхностью (синхронно с edges). + \en Which side should the surface join smoothly to (synchronously with edges). \~ + \param[in] fcs - \ru Направляющие грани (могут отсутствовать). + \en The guide faces (may be empty). \~ + \param[in] fSide - \ru С каких сторон касаться поверхностей (синхронно с faces). + \en On which sides to touch surfaces (synchronously with faces). \~ + \param[in] cs - \ru Направляющие кривые (могут отсутствовать). + \en The guide curves (may be empty). \~ + \param[in] trk - \ru Кривая, через которую должно пройти сечение (может отсутствовать). + \en The curve that the section should pass through (may be c3d_null). \~ + \param[in] ang - \ru Функция угла наклона (может быть c3d_null). + \en The function of the angle of inclination (may be c3d_null). \~ + \param[in] st - \ru Как использовать ang. + \en How to use ang. \~ + */ + MbSectionRail( std::vector & edges_, std::vector & eSides, + std::vector & faces_, std::vector & fSides, + std::vector & cs, MbCurve3D * trk, + MbFunction * ang, ThreeStates st ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionRail( const MbSectionRail & other ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionRail( const MbSectionRail & other, MbRegDuplicate * ireg ); + /// \ru Деструктор. \en Destructor. + ~MbSectionRail(); + +public: + + /// \ru Добавить в данные направляющую кривую. \en Add guiding to data. \~ + void AddEdge( MbCurveEdge & _edge, bool side ); + /// \ru Выдать направляющие рёбра. \en Get guide edges. + void GetEdges( std::vector & eds ) const; + void GetEdges( RPArray & eds ) const; + /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? + void GetEdgeSide( std::vector & eSide ) const; + /// \ru Выдать количество направляющих ребер. \en Get guide edges count. + size_t GetEdgesCount() const { return edges.size(); } + size_t GetEdgeSideCount() const { return edgeSide.size(); } + /// \ru Выдать направляющее ребро. \en Get guide edge. + MbCurveEdge * SetEdge( size_t i ) { return ( i < edges.size() ) ? edges[i] : c3d_null; } + + /// \ru Добавить в данные поверхность. \en Add surface to data. \~ + void AddFace( MbFace & _face, bool side ); + /// \ru Выдать грани. \en Get faces. + void GetFaces( std::vector & fas ) const; + void GetFaces( RPArray & fas ) const; + /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? + void GetFaceSide( std::vector & fSide ) const; + /// \ru Выдать количество направляющих граней. \en Get guide faces count. + size_t GetFacesCount() const { return faces.size(); } + size_t GetFaceSideCount() const { return faceSide.size(); } + /// \ru Выдать направляющую грань. \en Get guide face. + MbFace * SetFace( size_t i ) { return ( i < faces.size() ) ? faces[i] : c3d_null; } + + /// \ru Добавить в данные кривую. \en Add curve to data. \~ + void AddCurve( MbCurve3D & _curve ); + /// \ru Добавить в данные кривые. \en Add curves to data. \~ + void AddCurves( std::vector & _curves ); + /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. + void GetCurves( std::vector & crs ) const; + /// \ru Выдать количество дополнительных направляющих кривых. \en Get additional guide curves count. + size_t GetCurvesCount() const { return curves.size(); } + /// \ru Выдать дополнительную направляющую кривую. \en Get additional guide curve. + MbCurve3D * SetCurve( size_t i ) { return ( i < curves.size() ) ? curves[i] : c3d_null; } + + /// \ru Добавить в данные кривую. \en Add curve to data. \~ + void SetTrack( MbCurve3D & trk ); + /// \ru Выдать кривую, через которую должно пройти сечение. \en Get the curve that the section should pass through. + const MbCurve3D * GetTrack() const { return track; } + MbCurve3D * SetTrack() { return track; } + + /// \ru Установить функцию управления сечением. \en Set section control function. + void SetAngle( MbFunction & an, ThreeStates ts ); + /// \ru Выдать функцию управления сечением (радиус или дискриминант). \en Get section control function (radius or discriminant). + const MbFunction * GetAngle() const { return angle; } + MbFunction * SetAngle() { return angle; } + /// \ru К чему задан угол функции: к хорде, к поверхности, к нормали поверхности. \en What is the angle of the function set to: to the chord, to the surface, to the surface normal. + ThreeStates GetState() const { return state; } + void SetState( ThreeStates st ) { state = st; } + + /// \ru Преобразовать объект. \en Transform the object. \~ + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + /// \ru Сдвинуть объект. \en Move the object. \~ + void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + /// \ru Повернуть объект. \en Rotate the object. \~ + void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSectionRail & other, double accuracy ) const; + /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ + bool IsSimilar( const MbSectionRail & other ) const; + /// \ru Сделать объекты равным. \en Make objects equal. \~ + bool SetEqual ( const MbSectionRail & other ); + + // Дать любую точку и ориентировочную длину. + double GetAnyPopint( MbCartPoint3D & p0 ); + + /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. + void operator = ( const MbSectionRail & other ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionRail ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. + +}; // MbSectionRail + + +//------------------------------------------------------------------------------ +/** \brief \ru Функция управления сечением поверхности. + \en The surface section control function. \~ + \details \ru Форму сечения поверхности заметания определяет функция управления сечением (радиус или дискриминант). + Если функция управления сечением не определена, то она рассчитывается покривой, через которую должно пройти сечение, или поверхности, которой должно касаться сечение. \n + \en The surface section form is determined by the section control function (radius or discriminant). + If the section control function is not determined, it is calculated with curve that the section should pass through or surface that the section should touch. \n + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbSectionRule { + +public: + MbFunction * discr; ///< \ru Функция управления сечением (дискриминант или радиус, может быть c3d_null). \en Section control function (discriminant or radius). + MbCurve3D * track; ///< \ru Кривая, через которую должно пройти сечение. \en The curve that the section should pass through. + MbSurface * touch; ///< \ru Поверхность, которой должно касаться сечение. \en The surface that the section should touch. + MbFaceShell * shell; ///< \ru Оболочка, которой должно касаться сечение. \en The shell that the section should touch. + +public: + /// \ru Конструктор по умолчанию. \en Empty constructor. + MbSectionRule(); + /// \ru Конструктор по функции. \en The constructor by function. + MbSectionRule( MbFunction * fun ); + /// \ru Конструктор по кривой. \en The constructor by function. + MbSectionRule( MbCurve3D * cur ); + /// \ru Конструктор по поверхности. \en The constructor by surface. + MbSectionRule( MbSurface * sur ); + /// \ru Конструктор по оболочке. \en The constructor by shell. + MbSectionRule( MbFaceShell * sur ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionRule( const MbSectionRule & other ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionRule( const MbSectionRule & other, MbRegDuplicate * ireg ); + /// \ru Деструктор. \en Destructor. + ~MbSectionRule(); + +public: + + /// \ru Выдать функцию управления сечением. \en Get section control function. + const MbFunction * GetFunction() const { return discr; } + /// \ru Установить функцию управления сечением. \en Set section control function. + void SetFunction( MbFunction & f ); + void SetFunction( double f ); + /// \ru Выдать кривую управления сечением. \en Get section control curve. + const MbCurve3D * GetCurve() const { return track; } + /// \ru Установить кривую управления сечением. \en Set section control curve. + void SetCurve( MbCurve3D & c ); + /// \ru Выдать поверхность управления сечением. \en Get section control surface. + const MbSurface * GetSurface() const { return touch; } + /// \ru Установить поверхность управления сечением. \en Set section control surface. + void SetSurface( MbSurface & s ); + /// \ru Выдать оболочку управления сечением. \en Get section control shell. + const MbFaceShell * GetShell() const { return shell; } + /// \ru Установить оболочку управления сечением. \en Set section control shell. + void SetShell( MbFaceShell & s ); + + /// \ru Преобразовать объект. \en Transform the object. \~ + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + /// \ru Сдвинуть объект. \en Move the object. \~ + void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + /// \ru Повернуть объект. \en Rotate the object. \~ + void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSectionRule & other, double accuracy ) const; + /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ + bool IsSimilar( const MbSectionRule & other ) const; + /// \ru Сделать объекты равным. \en Make objects equal. \~ + bool SetEqual ( const MbSectionRule & other ); + + /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. + void operator = ( const MbSectionRule & other ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionRule ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. + +}; // MbSectionRule + + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры операции построения поверхности заметания переменного сечения. + \en The parameters for buyilding the swept mutable section surface. \~ + \details \ru Поверхность заметания строится путем движения плоского сечения вдоль опорной кривой. + Плоское сечение может начинаться на направляющей кривой и заканчиваться на другой направляющей кривой. + Направляющих кривых может быть две, одна или ни одной. Кроме того, в построении могут использоваться управляющие кривые. \n + Сечение поверхности плоскостью, перпендикулярной опорной кривой, может иметь одну из пяти форм и некоторые из них могут меняться по заданному закону. + Сечение может иметь форму окружности (или её дуги), отрезка прямой, кривой второго порядка, кривой третьего порядка или заданной сплайновой кривой. \n + В качестве примера рассмотрим сечение в форме участка кривой второго порядка. + В этом случае должны быть заданы две напраляющие в виде рёбер MbSectionRail::edges или в виде кривых MbSectionRail::curves. + Кривая второго порядка начинается в точке пересечения первой направляющей с плоскостью сечения и + оканчивается в точке пересечения второй направляющей с плоскостью сечения. + Направление кривой второго порядка на краю может быть задано одним из способов: + - поверхностью грани ребра (рёбер) MbSectionRail::edges, где MbSectionRail::edgeSide указывает на грань слева или справа; + - поверхностью кривой (кривых) MbSectionRail::curves, если кривая имеют поверхность в своих данных; + - функцией угла наклона касательной MbSectionRail::angle, параметр MbSectionRail::state указывает, от чего отсчитывается угол; + - дополнительной контрольной кривой MbSectionRail::track, через точку пересечения которой с плоскостью сечения должна проходить кривая второго порядка; + - вершинной кривой MbSectionData::apexCurve, точка пересечения которой с плоскостью сечения определяет точку пересечения касательных кривой второго порядка на краях; + Дискриминант кривой второго порядка может быть задан одним из способов: + - функцией изменения дискриминанта MbSectionRule::discr; + - дополнительной контрольной кривой MbSectionRule::track, через точку пересечения которой с плоскостью сечения должна проходить кривая второго порядка; + - дополнительной поверхностью MbSectionRule::touch, которой должна касаться кривая второго порядка сечения; + При наличие направляющих кривых и их несущих поверхностей построенная поверхность заметания гладко стыкуется с несущими поверхностями. \n + \en The swept mutable section surface is form-generating by moving the flat section along the reference curve. \n + The flat section can start on a guide curve and end on another guide curve. + There can be two guide curves, one or none. In addition, control curves can be used in the construction. \n + The cross section of a surface with a plane perpendicular to the reference curve can have one of five shapes, and some of them can change according to a given law. + The cross section can take the form of a circle (or its arc), a straight line segment, a second-order curve, a third-order curve, or a given spline curve. \n + As an example, consider a section in the form of a second-order curve. + In this case, you must specify two edges as MbSectionRail::edges or as MbSectionRail::curves. + The second-order curve starts at the intersection of the first guide with the cross-section plane and + ends at the intersection of the second guide with the cross-section plane. + The direction of the second-order curve on the begining or on the end can be set in one of the following ways: + - the face surface of the edge (s) MbSectionRail::edges, where MbSectionRail::edgeSide specifies the face on the left or on the right; + - surface of the curve (s) MbSectionRail::curves, if the curve has a surface in its data; + - function of the tangent angle MbSectionRail:: angle, the parameter MbSectionRail::state specifies from what the angle is calculated; + - an additional control curve MbSectionRail::track, the second-order curve should pass through the point of intersection of the control curve with the cross-section plane; + - vertex curve MbSectionData::apexCurve, whose intersection point with the section plane determines the intersection point of the tangents of second-order curve at the begining and at the end; + The second-order curve discriminant can be set in one of the following ways: + - the function for changing the discriminant MbSectionRule:: discr; + - an additional control curve MbSectionRule::track, the second-order curve should pass through the point of intersection of the control curve with the cross-section plane; + - an additional surface MbSsectionRule::touch that the second-order curve of the section should touch; + If there are guide curves and their bearing surfaces, the constructed sweep surface is smoothly joined to the bearing surfaces. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbSectionData { + +private: + MbCurve3D * spine; ///< \ru Опорная кривая. \en The reference curve. + MbeSectionShape form; ///< \ru Форма сечения поверхности. \en The surface cross-section shape. + MbSectionRail rail1; ///< \ru Данные начального края сечения. \en The data of the begining of section. + MbSectionRail rail2; ///< \ru Данные конечного края сечения. \en The data of the end of section. + MbCurve3D * apexCurve; ///< \ru Кривая вершин (может отсутствовать). \en The apex curve (may be c3d_null). + MbSectionRule descript; ///< \ru Функция управления сечением поверхности (радиус или дискриминант, может быть c3d_null). \en The section control function (radius or discriminant). + MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм c3d_null). \en Forming curve for form==cs_Shape (c3d_null on other case). + double uMin; ///< \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. + double uMax; ///< \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. + double buildSag; ///< \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. + double accuracy; ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. + uint32 count; ///< \ru Минимальное количество шагов по опорной кривой. \en Minimum number of steps along the reference curve. + bool check; ///< \ru Проверять самопересечение построенной поверхности. \en Check the self-intersection of the constructed surface (default false). + +public: + /// \ru Конструктор по умолчанию. \en Empty constructor. + MbSectionData(); + + /** \brief \ru Конструктор по параметрам. + \en Constructor by parameters. \~ + \param[in] sp - \ru Опорная кривая. + \en The reference curve. \~ + \param[in] f - \ru Форма сечения поверхности. + \en The surface cross-section shape. \~ + \param[in] r1 - \ru Данные начального края сечения. + \en The data of the begining of section. \~ + \param[in] r2 - \ru Данные конечного края сечения. + \en The data of the end of section. \~ + \param[in] ap - \ru Кривая вершин (может быть c3d_null). + \en The apex curve (may be empty). \~ + \param[in] desc - \ru Функция управления сечением (может быть c3d_null). + \en Section control function (may be c3d_null). \~ + \param[in] patt - \ru Образующая кривая (может быть c3d_null). + \en Forming curve (may be c3d_null). \~ + */ + MbSectionData( MbCurve3D & sp, + MbeSectionShape f, + MbSectionRail & r1, + MbSectionRail & r2, + MbCurve3D * ap, + MbSectionRule & desc, + MbPolyCurve * patt ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionData( const MbSectionData & other ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionData( const MbSectionData & other, MbRegDuplicate * ireg ); + /// \ru Деструктор. \en Destructor. + ~MbSectionData(); + +public: + + /// \ru Установить опорную кривую. \en Set reference curve. + void SetSpine( MbCurve3D & s ); + //< \ru Установить вектор направления опорной кривой (если spine==c3d_null). \en Set the direction vector of the reference curve (if spine= = c3d_null). + void SetSpine( const MbVector3D & a ); + /// \ru Выдать опорную кривую. \en Get reference curve. + const MbCurve3D * GetSpine() const { return spine; } + MbCurve3D * SetSpine() { return spine; } + + /// \ru Выдать форму сечения поверхности. \en Get cross-section shape. + MbeSectionShape GetForm() const { return form; } + /// \ru Установить форму сечения поверхности. \en Set cross-section shape. + void SetForm( MbeSectionShape f ) { form = f; } + + ///< \ru Данные начального края сечения. \en The data of the begining of section. + MbSectionRail & GetRrail1() { return rail1; } + ///< \ru Данные конечного края сечения. \en The data of the end of section. + MbSectionRail & GetRrail2() { return rail2; } + + /// \ru Добавить в данные направляющее ребро. \en Add guiding to data. \~ + void AddEdge1( MbCurveEdge & _edge, bool side ) { rail1.AddEdge( _edge, side ); } + void AddEdge2( MbCurveEdge & _edge, bool side ) { rail2.AddEdge( _edge, side ); } + /// \ru Выдать направляющие рёбра. \en Get guide edges. + void GetEdges1( std::vector & eds ) const { rail1.GetEdges( eds ); } + void GetEdges1( RPArray & eds ) const { rail1.GetEdges( eds ); } + /// \ru Выдать направляющие рёбра. \en Get guide edges. + void GetEdges2( std::vector & eds ) const { rail2.GetEdges( eds ); } + void GetEdges2( RPArray & eds ) const { rail2.GetEdges( eds ); } + /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? + void GetEdgeSide1( std::vector & eSide ) const { rail1.GetEdgeSide( eSide ); } + /// \ru Какую сторону кривой гладко стыковать с поверхностью? \en Which side should the surface join smoothly to? + void GetEdgeSide2( std::vector & eSide ) const { rail2.GetEdgeSide( eSide ); } + /// \ru Выдать количество направляющих ребер. \en Get guide edges count. + size_t GetEdgesCount1() const { return rail1.GetEdgesCount(); } + size_t GetEdgesCount2() const { return rail2.GetEdgesCount(); } + size_t GetEdgeSideCount1() const { return rail1.GetEdgeSideCount(); } + size_t GetEdgeSideCount2() const { return rail2.GetEdgeSideCount(); } + /// \ru Выдать направляющее ребро. \en Get guide edge. + MbCurveEdge * SetEdge1( size_t i ) { return rail1.SetEdge( i ); } + /// \ru Выдать направляющее ребро. \en Get guide edge. + MbCurveEdge * SetEdge2( size_t i ) { return rail2.SetEdge( i ); } + + /// \ru Добавить направляющую грань. \en Add guide face. + void AddFace1( MbFace & _face, bool side ) { rail1.AddFace( _face, side ); } + void AddFace2( MbFace & _face, bool side ) { rail2.AddFace( _face, side ); } + /// \ru Выдать поверхности. \en Get surfaces. + void GetFaces1( std::vector & fas ) const { rail1.GetFaces( fas ); } + void GetFaces1( RPArray & fas ) const { rail1.GetFaces( fas ); } + /// \ru Выдать поверхности. \en Get surfaces. + void GetFaces2( std::vector & fas ) const { rail2.GetFaces( fas ); } + void GetFaces2( RPArray & fas ) const { rail2.GetFaces( fas ); } + /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? + void GetFaceSide1( std::vector & fSide ) const { rail1.GetFaceSide( fSide ); } + /// \ru С каких сторон касаться поверхностей? \en On which sides to touch surfaces? + void GetFaceSide2( std::vector & fSide ) const { rail2.GetFaceSide( fSide ); } + /// \ru Выдать количество направляющих граней. \en Get guide faces count. + size_t GetFacesCount1() const { return rail1.GetFacesCount(); } + size_t GetFacesCount2() const { return rail2.GetFacesCount(); } + size_t GetFaceSideCount1() const { return rail1.GetFaceSideCount(); } + size_t GetFaceSideCount2() const { return rail2.GetFaceSideCount(); } + /// \ru Выдать направляющую грань. \en Get guide face. + MbFace * SetFace1( size_t i ) { return rail1.SetFace( i ); } + /// \ru Выдать направляющую грань. \en Get guide face. + MbFace * SetFace2( size_t i ) { return rail2.SetFace( i ); } + + /// \ru Добавить в данные направляющую кривую. \en Add guiding to data. \~ + void AddCurve1( MbCurve3D & crv ) { rail1.AddCurve( crv ); } + void AddCurve2( MbCurve3D & crv ) { rail2.AddCurve( crv ); } + /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. + void GetCurves1( std::vector & crs ) const { rail1.GetCurves( crs ); } + /// \ru Выдать дополнительные направляющие кривые. \en Get additional guide curves. + void GetCurves2( std::vector & crs ) const { rail2.GetCurves( crs ); } + /// \ru Выдать количество дополнительных направляющих кривых. \en Get additional guide curves count. + size_t GetCurvesCount1() const { return rail1.GetCurvesCount(); } + size_t GetCurvesCount2() const { return rail2.GetCurvesCount(); } + /// \ru Выдать направляющую кривую. \en Get guide curve. + MbCurve3D * SetCurve1( size_t i ) { return rail1.SetCurve( i ); } + /// \ru Выдать направляющую кривую. \en Get guide curve. + MbCurve3D * SetCurve2( size_t i ) { return rail2.SetCurve( i ); } + + /// \ru Добавить в данные кривую, через которую должно пройти сечение. \en Add curve that the section should pass through. \~ + void SetTrack1( MbCurve3D & tr ) { rail1.SetTrack( tr ); } + /// \ru Добавить в данные кривую, через которую должно пройти сечение. \en Add curve that the section should pass through. \~ + void SetTrack2( MbCurve3D & tr ) { rail2.SetTrack( tr ); } + /// \ru Выдать кривую, через которую должно пройти сечение. \en Get the curve that the section should pass through. \~ + const MbCurve3D * GetTrack1() const { return rail1.GetTrack(); } + /// \ru Выдать кривую, через которую должно пройти сечение. \en Get the curve that the section should pass through. \~ + const MbCurve3D * GetTrack2() const { return rail2.GetTrack(); } + /// \ru Выдать кривую, через которую должно пройти сечение. \en Get the curve that the section should pass through. \~ + MbCurve3D * SetTrack1() { return rail1.SetTrack(); } + /// \ru Выдать кривую, через которую должно пройти сечение. \en Get the curve that the section should pass through. \~ + MbCurve3D * SetTrack2() { return rail2.SetTrack(); } + + /// \ru Добавить в данные функцию. \en Add functions to data. \~ + void SetAngle1( MbFunction & ang, ThreeStates ts ) { rail1.SetAngle( ang, ts ); } + /// \ru Добавить в данные функцию. \en Add functions to data. \~ + void SetAngle2( MbFunction & ang, ThreeStates ts ) { rail2.SetAngle( ang, ts ); } + /// \ru Выдать функции углов наклона. \en Get angle functions. + const MbFunction * GetAngle1() const { return rail1.GetAngle(); } + /// \ru Выдать функции углов наклона. \en Get angle functions. + const MbFunction * GetAngle2() const { return rail2.GetAngle(); } + /// \ru Выдать функцию угла наклона. \en Get angle function. + MbFunction * SetAngle1() { return rail1.SetAngle(); } + /// \ru Выдать функцию угла наклона. \en Get angle function. + MbFunction * SetAngle2() { return rail2.SetAngle(); } + + /// \ru К чему задан угол функции: к хорде, к поверхности, к нормали поверхности. \en What is the angle of the function set to: to the chord, to the surface, to the surface normal. + ThreeStates GetState1() const { return rail1.GetState(); } + ThreeStates GetState2() const { return rail2.GetState(); } + /// \ru Как отсчитывать угол функции: от хорде, от поверхности, от нормали поверхности. \en How to count the angle of the function: from the chord, from the surface, from the surface normal. + void SetState1( ThreeStates st ) { rail1.SetState( st ); } + void SetState2( ThreeStates st ) { rail2.SetState( st ); } + + /// \ru Добавить в данные кривую вершин. \en Set apex curve. \~ + void SetApexCurve( MbCurve3D & curv ); + /// \ru Выдать кривую вершин. \en Get apex curve. + MbCurve3D * SetApexCurve() { return apexCurve; } + /// \ru Выдать кривую вершин. \en Get apex curve. + const MbCurve3D * GetApexCurve() const { return apexCurve; } + + /// \ru Выдать данные управления сечением. \en Get section control data. + const MbSectionRule & GetSectionRule() const { return descript; } + MbSectionRule & SetSectionRule() { return descript; } + /// \ru Выдать функцию управления сечением (радиус или дискриминант). \en Get section control function (radius or discriminant). + const MbFunction * GetFunction() const { return descript.discr; } + MbFunction * SetFunction() { return descript.discr; } + /// \ru Установить функцию управления сечением. \en Set section control function. + void SetFunction( MbFunction & f ) { descript.SetFunction( f ); } + void SetFunction( double f ) { descript.SetFunction( f ); } + /// \ru Выдать кривую управления сечением. \en Get section control curve. + const MbCurve3D * GetDescriptCurve() const { return descript.GetCurve(); } + /// \ru Выдать поверхность управления сечением. \en Get section control surface. + const MbSurface * GetDescriptSurface() const { return descript.GetSurface(); } + /// \ru Выдать оболочку управления сечением. \en Get section control shell. + const MbFaceShell * GetDescriptShell() const { return descript.GetShell(); } + + /// \ru Выдать образующую кривую. \en Get forming curve. + const MbPolyCurve * GetPattern() const { return pattern; } + MbPolyCurve * SetPattern() { return pattern; } + /// \ru Установить образующую кривую. \en Set forming curve. + void SetPattern( MbPolyCurve & p ); + + /// \ru Минимальное значение первого параметра. \en Minimal value of the first parameter. + double GetUMin() const { return uMin; } + /// \ru Максимальное значение первого параметра. \en Maximal value of the first parameter. + double GetUMax() const { return uMax; } + /// \ru Установить область определения первого параметра поверхностей. \en Set the first parameter region of the surface. + void SetUParams( double u1, double u2 ); + /// \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. + double GetBuildSag() const { return buildSag; } + ///< \ru Точность построения толерантных объектов. \en An accuracy of building tolerant objects. + double GetAccuracy() const { return accuracy; } + void SetAccuracy( double acc ); + ///< \ru Минимальное количество шагов по опорной кривой. \en Minimum number of steps along the reference curve. + uint32 GetCount() const { return count; } + void SetCount( uint32 c ); + ///< \ru Проверять самопересечение построенной поверхности. \en Check the self-intersection of the constructed surface. + bool GetCheck() const { return check; } + void SetCheck( bool c ); + + /// \ru Преобразовать объект. \en Transform the object. \~ + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); + /// \ru Сдвинуть объект. \en Move the object. \~ + void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); + /// \ru Повернуть объект. \en Rotate the object. \~ + void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); + /// \ru Определить, являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSectionData & other, double acc ) const; + /// \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. \~ + bool IsSimilar( const MbSectionData & other ) const; + /// \ru Сделать объекты равным. \en Make objects equal. \~ + bool SetEqual ( const MbSectionData & other ); + + /// \ru Оператор присваивания без копирования данных. \en Assignment operator without copying. + void operator = ( const MbSectionData & other ); + + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionData ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. + +}; // MbSectionData + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные о поверхности переменного сечения. + \en Data about swept mutable section surface. \~ + \details \ru Данные содержат номера рёбер и граней исходной оболочки, на которых строится поверхность. + \en The data contains the numbers of edges and faces of the original shell on which the surface is built. + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbSectionCode { + +private: + SArray edgeIndex1; ///< \ru Номера рёбер первой направляющей кривой. \en The edge numbers of the first guide curve. + SArray faceIndex1; ///< \ru Номера граней первой направляющей поверхности. \en The face numbers of the first guide surface. + SArray edgeIndex2; ///< \ru Номера рёбер второй направляющей кривой. \en The edge numbers of the second guide curve. + SArray faceIndex2; ///< \ru Номера граней второй направляющей поверхности. \en The face numbers of the second guide surface. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbSectionCode() + : edgeIndex1( 0, 1 ) + , faceIndex1( 0, 1 ) + , edgeIndex2( 0, 1 ) + , faceIndex2( 0, 1 ) + {} + /// \ru Конструктор. \en Constructor. + MbSectionCode( SArray & edI1, SArray & faI1, + SArray & edI2, SArray & faI2 ) + : edgeIndex1( edI1 ) + , faceIndex1( faI1 ) + , edgeIndex2( edI2 ) + , faceIndex2( faI2 ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbSectionCode( const MbSectionCode & other ) + : edgeIndex1( other.edgeIndex1 ) + , faceIndex1( other.faceIndex1 ) + , edgeIndex2( other.edgeIndex2 ) + , faceIndex2( other.faceIndex2 ) + {} + /// \ru Деструктор. \en Destructor. + ~MbSectionCode() {} + +public: + + SArray & SetEdgeIndex1() { return edgeIndex1; } + SArray & SetFaceIndex1() { return faceIndex1; } + SArray & SetEdgeIndex2() { return edgeIndex2; } + SArray & SetFaceIndex2() { return faceIndex2; } + + /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + void Transform( const MbMatrix3D & matr ); + /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + void Move ( const MbVector3D & to ); + /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. + void Rotate ( const MbAxis3D & axis, double ang ); + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSectionCode & other, double accuracy ) const; + + // \ru Оператор присваивания. \en The assignment operator. + void operator = ( const MbSectionCode & other ) { + edgeIndex1 = other.edgeIndex1; + faceIndex1 = other.faceIndex1; + edgeIndex2 = other.edgeIndex2; + faceIndex2 = other.faceIndex2; + } + + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSectionCode ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. + //DECLARE_NEW_DELETE_CLASS( MbSectionCode ) + //DECLARE_NEW_DELETE_CLASS_EX( MbSectionCode ) +}; // MbSectionCode + + +#endif // __OP_SWEPT_PARAMETERS_H diff --git a/C3d/Include/pars_equation_tree.h b/C3d/Include/pars_equation_tree.h index a3aab3a..7287fdd 100644 --- a/C3d/Include/pars_equation_tree.h +++ b/C3d/Include/pars_equation_tree.h @@ -75,7 +75,7 @@ struct CharacterPointInfo equPoint_DerBreak1 ///< \ru Разрыв производной. \en Derivative discontinuity. }; - const BTreeNode * m_tree; ///< \ru Узел дерева. Не равен NULL. \en Node of a tree. Not equal to NULL. + const BTreeNode * m_tree; ///< \ru Узел дерева. Не равен c3d_null. \en Node of a tree. Not equal to c3d_null. EquCharacterPointType m_type; ///< \ru Тип характерной точки. \en Type of a characteristic point. double m_ph; ///< \ru Значение параметра функции. \en The value of the function parameter. double m_period; ///< \ru Период функции. \en A period of a function. @@ -653,8 +653,8 @@ IMPL_PERSISTENT_OPS( TreeIntervalNode ) // --- class MATH_CLASS IntervalConstNode : public TreeIntervalNode { - BTreeNode * m_firstValue; ///< \ru Первое значение (всегда не NULL). \en First value (always not NULL). - BTreeNode * m_secondValue; ///< \ru Второе значение (всегда не NULL). \en Second value (always not NULL). + BTreeNode * m_firstValue; ///< \ru Первое значение (всегда не c3d_null). \en First value (always not c3d_null). + BTreeNode * m_secondValue; ///< \ru Второе значение (всегда не c3d_null). \en Second value (always not c3d_null). public: @@ -752,7 +752,7 @@ IMPL_PERSISTENT_OPS( IntervalConstNode ) // --- class MATH_CLASS IntervalIdentNode : public TreeIntervalNode { - ItIntervalTreeVariable * m_ident; ///< \ru Всегда не NULL. \en Always not NULL. + ItIntervalTreeVariable * m_ident; ///< \ru Всегда не c3d_null. \en Always not c3d_null. public: /** \brief \ru Конструктор. @@ -867,7 +867,7 @@ public: \details \ru Получить вложенный узел по индексу.\n \en Get a child node by an index.\n \~ */ - virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } + virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return c3d_null; } virtual bool GetDefRange(DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const { return true; } @@ -981,7 +981,7 @@ public : \{ */ /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. - virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } + virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return c3d_null; } virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const{ return true; } diff --git a/C3d/Include/pars_user_function.h b/C3d/Include/pars_user_function.h index 1f7e73a..4c82ef1 100644 --- a/C3d/Include/pars_user_function.h +++ b/C3d/Include/pars_user_function.h @@ -96,7 +96,7 @@ public: /// \ru Получить массив параметров. \en Get array of parameters. void GetPars ( RPArray & pars ) const; /// \ru Получить аргумент по индексу. \en Get argument by index. - ItTreeVariable * GetPar( size_t i ) const { return i < m_vars.Count() ? m_vars[i] : NULL; } + ItTreeVariable * GetPar( size_t i ) const { return i < m_vars.Count() ? m_vars[i] : c3d_null; } /// \ru Подготовить объект к записи. \en Prepare an object for writing. void WritingBeginEnd( bool begin ) { RegisterVars( begin ? registrable : noRegistrable ); } /// \ru Оператор присваивания. \en Assignment operator. diff --git a/C3d/Include/part_solid.h b/C3d/Include/part_solid.h index b8e0251..4613b43 100644 --- a/C3d/Include/part_solid.h +++ b/C3d/Include/part_solid.h @@ -431,7 +431,7 @@ public: {} public: /// \ru Проверить данные на корректность. \en Check data for correctness. - bool IsValid() const { return (part != NULL && ind > -1 && id != SYS_MAX_UINT32); } + bool IsValid() const { return (part != c3d_null && ind > -1 && id != SYS_MAX_UINT32); } private: /// \ru Конструктор без параметров. \en Constructor without parameters. MbPartSolidData(); diff --git a/C3d/Include/plane_instance.h b/C3d/Include/plane_instance.h index b385b7d..83a55a8 100644 --- a/C3d/Include/plane_instance.h +++ b/C3d/Include/plane_instance.h @@ -66,10 +66,10 @@ public : // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равными. \en Make the objects equal. @@ -104,7 +104,7 @@ public : MbPlaneItem * SetPlaneItem( size_t ind = 0 ); /// \ru Заменить двумерный геометрический объект. \en Replace two-dimensional geometric object. bool SetPlaneItem( MbPlaneItem * init, size_t ind = 0 ); - /// \ru Добавить двумерный геометрический объект. \en Add two-dimensional geometric object. The method returns the index of added or existing object in MbPlaneInstance (the method returns SYS_MAX_T if the object is NULL). + /// \ru Добавить двумерный геометрический объект. \en Add two-dimensional geometric object. The method returns the index of added or existing object in MbPlaneInstance (the method returns SYS_MAX_T if the object is c3d_null). size_t AddPlaneItem( MbPlaneItem * init ); /// \ru Метод возвращает индекс двумерного геометрического объекта. \en The method returns the index of two-dimensional geometric object in MbPlaneInstance (the method returns SYS_MAX_T if the object was not finded). size_t GetIndex( MbPlaneItem * init ); @@ -114,13 +114,13 @@ public : MbPlacement3D & SetPlacement() { return place; } /// \ru Преобразовать двумерный объект согласно матрице. \en Transform two-dimensional object according to the matrix. - void Transform( const MbMatrix &, MbRegTransform * iReg = NULL ); + void Transform( const MbMatrix &, MbRegTransform * iReg = c3d_null ); /// \ru Сдвинуть двумерный объект вдоль вектора. \en Translate two-dimensional object along a vector. - void Move ( const MbVector &, MbRegTransform * iReg = NULL ); + void Move ( const MbVector &, MbRegTransform * iReg = c3d_null ); /// \ru Повернуть двумерный объект вокруг точки на заданный угол. \en Rotate two-dimensional object at a given angle around an axis. - void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * iReg = NULL ); + void Rotate ( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * iReg = c3d_null ); /// \ru Повернуть двумерный объект вокруг точки на заданный угол. \en Rotate two-dimensional object at a given angle around an axis. - void Rotate ( const MbCartPoint & pnt, double angle, MbRegTransform * iReg = NULL ); + void Rotate ( const MbCartPoint & pnt, double angle, MbRegTransform * iReg = c3d_null ); /// \ru Удалить все объекты эскиза. \en Delete all the sketch items. void DeleteItems(); @@ -168,7 +168,7 @@ inline MbPlaneInstance::MbPlaneInstance( const MbPlacement3D & p, const PlaneIte planeItems.reserve( addCnt ); for ( size_t k = 0; k < addCnt; ++k ) { const MbPlaneItem * planeItem = inits[k]; - if ( planeItem != NULL ) { + if ( planeItem != c3d_null ) { planeItem->AddRef(); planeItems.push_back( const_cast( planeItem ) ); } @@ -187,7 +187,7 @@ void MbPlaneInstance::GetItems( PlaneItems & items ) const items.reserve( items.size() + addCnt ); SPtr item_i; for ( size_t i = 0; i < addCnt; ++i ) { - if ( planeItems[i] != NULL ) { + if ( planeItems[i] != c3d_null ) { item_i = planeItems[i]; items.push_back( item_i ); } diff --git a/C3d/Include/plane_item.h b/C3d/Include/plane_item.h index a4e3fb7..8447db5 100644 --- a/C3d/Include/plane_item.h +++ b/C3d/Include/plane_item.h @@ -143,7 +143,7 @@ public : \return \ru Копия объекта. \en Copy of the object. \~ */ - virtual MbPlaneItem & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; + virtual MbPlaneItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; /** \brief \ru Преобразовать согласно матрице. \en Transform according to the matrix. \~ @@ -174,7 +174,7 @@ public : For transformation of projection curve. It isn't considered if the surface is planar. \~ */ - virtual void Transform( const MbMatrix & matr, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ) = 0; + virtual void Transform( const MbMatrix & matr, MbRegTransform * iReg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; /** \brief \ru Сдвинуть вдоль вектора. \en Translate along a vector. \~ @@ -205,7 +205,7 @@ public : For transformation of projection curve. It isn't considered if the surface is planar. \~ */ - virtual void Move ( const MbVector & to, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ) = 0; + virtual void Move ( const MbVector & to, MbRegTransform * iReg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; /** \brief \ru Повернуть вокруг точки. \en Rotate about a point. \~ @@ -239,7 +239,7 @@ public : It isn't considered if the surface is planar. \~ */ virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, - MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ) = 0; + MbRegTransform * iReg = c3d_null, const MbSurface * newSurface = c3d_null ) = 0; /** \brief \ru Повернуть вокруг точки. \en Rotate about a point. \~ @@ -261,7 +261,7 @@ public : It isn't considered if the surface is planar. \~ */ void Rotate( const MbCartPoint & pnt, double angle, - MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ); + MbRegTransform * iReg = c3d_null, const MbSurface * newSurface = c3d_null ); /** \brief \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. \~ diff --git a/C3d/Include/point3d.h b/C3d/Include/point3d.h index 0f0479a..7bb9d1b 100644 --- a/C3d/Include/point3d.h +++ b/C3d/Include/point3d.h @@ -49,10 +49,10 @@ public: virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. virtual MbeSpaceType Type() const; // \ru Групповой тип объекта. \en Group type of object. virtual MbeSpaceType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равным. \en Make the objects equal. virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. diff --git a/C3d/Include/point_frame.h b/C3d/Include/point_frame.h index e930442..f1c18ff 100644 --- a/C3d/Include/point_frame.h +++ b/C3d/Include/point_frame.h @@ -72,7 +72,7 @@ public: size_t vertsCnt = verts.size(); vertices.reserve( vertsCnt ); for ( size_t k = 0; k < vertsCnt; ++k ) { - if ( verts[k] != NULL ) + if ( verts[k] != c3d_null ) AddVertex( const_cast( *verts[k] ), same ); } } @@ -96,10 +96,10 @@ public: // \ru Общие функции геометрического объекта \en Common functions of a geometric object virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. virtual MbeSpaceType Type() const; // \ru Групповой тип объекта. \en Group type of object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равным. \en Make the objects equal. @@ -128,9 +128,9 @@ public: /// \ru Выдать количество вершин. \en Get count of vertices. size_t GetVerticesCount() const { return vertices.size(); } /// \ru Получить вершину по индексу. \en Get vertex by an index. - const MbVertex * GetVertex( size_t k ) const { return ((k < vertices.size()) ? vertices[k] : NULL ); } + const MbVertex * GetVertex( size_t k ) const { return ((k < vertices.size()) ? vertices[k] : c3d_null ); } /// \ru Получить вершину по индексу для возможного редактирования. \en Get vertex by an index for the possible editing. - MbVertex * SetVertex( size_t k ) { return ((k < vertices.size()) ? vertices[k] : NULL ); } + MbVertex * SetVertex( size_t k ) { return ((k < vertices.size()) ? vertices[k] : c3d_null ); } /// \ru Получить вершины. \en Get vertices. template diff --git a/C3d/Include/position_data.h b/C3d/Include/position_data.h index 9e729a0..180873b 100644 --- a/C3d/Include/position_data.h +++ b/C3d/Include/position_data.h @@ -170,7 +170,7 @@ public: /// \ru Установить замкнутость. \en Set closedness. void SetClosed( bool c ) { closed = c; } - const MbCurveEdge * Edge ( size_t i ) const { return ( i < edges.Count() ) ? edges[i] : NULL; } + const MbCurveEdge * Edge ( size_t i ) const { return ( i < edges.Count() ) ? edges[i] : c3d_null; } const bool Sense( size_t i ) const { return ( i < sense.Count() ) ? sense[i] : false; } size_t Count() const { return edges.Count(); } /// \ru Оператор присваивания. \en Assignment operator. diff --git a/C3d/Include/reference_item.h b/C3d/Include/reference_item.h index f8f459c..a6c4401 100644 --- a/C3d/Include/reference_item.h +++ b/C3d/Include/reference_item.h @@ -191,9 +191,9 @@ template MbSerialItem::~MbSerialItem() template inline void DeleteMatItem( Type *& item ) { - if ( item != NULL ) { + if ( item != c3d_null ) { delete item; - item = NULL; + item = c3d_null; } } @@ -244,8 +244,8 @@ Type & DuplicateIfUsed( Type & item, RegType * iReg ) template Type * DuplicateIfUsed( SPtr & item ) { - if ( item == NULL ) - return NULL; + if ( item == c3d_null ) + return c3d_null; Type * resItem = item.get(); if ( item->GetUseCount() > 1 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. resItem = static_cast( &item->Duplicate() ); @@ -260,8 +260,8 @@ Type * DuplicateIfUsed( SPtr & item ) template Type * DuplicateIfUsed( SPtr & item, RegType * iReg ) { - if ( item == NULL ) - return NULL; + if ( item == c3d_null ) + return c3d_null; Type * resItem = item.get(); if ( item->GetUseCount() > 1 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. resItem = static_cast( &item->Duplicate( iReg ) ); @@ -275,10 +275,10 @@ Type * DuplicateIfUsed( SPtr & item, RegType * iReg ) template void DeleteItem( Type *& item ) { - if ( item != NULL ) { + if ( item != c3d_null ) { if ( item->GetUseCount() < 1 ) delete item; - item = NULL; + item = c3d_null; } } @@ -288,9 +288,9 @@ void DeleteItem( Type *& item ) template void ReleaseItem( Type *& item ) { - if ( item != NULL ) { + if ( item != c3d_null ) { item->Release(); - item = NULL; + item = c3d_null; } } @@ -300,7 +300,7 @@ void ReleaseItem( Type *& item ) template void AddRefItem( const Type * item ) { - if ( item != NULL ) + if ( item != c3d_null ) item->AddRef(); } @@ -310,7 +310,7 @@ void AddRefItem( const Type * item ) template void DecRefItem( const Type * item ) { - if ( item != NULL ) + if ( item != c3d_null ) item->DecRef(); } @@ -318,11 +318,11 @@ void DecRefItem( const Type * item ) //------------------------------------------------------------------------------ /// \ru Захватить объекты. \en Catch objects. // --- -template -void AddRefItems( const Vector & items ) +template +void AddRefItems( const ItemsVector & items ) { for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { - if ( items[k] != NULL ) + if ( items[k] != c3d_null ) items[k]->AddRef(); } } @@ -331,11 +331,11 @@ void AddRefItems( const Vector & items ) //------------------------------------------------------------------------------ /// \ru Отпустить объекты без удаления. \en Detach objects without removing. // --- -template -void DecRefItems( const Vector & items ) +template +void DecRefItems( const ItemsVector & items ) { for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { - if ( items[k] != NULL ) + if ( items[k] != c3d_null ) items[k]->DecRef(); } } @@ -344,8 +344,8 @@ void DecRefItems( const Vector & items ) //------------------------------------------------------------------------------ /// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. // --- -template -void DeleteItems( Vector & items ) +template +void DeleteItems( ItemsVector & items ) { for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) ::DeleteItem( items[k] ); @@ -356,8 +356,8 @@ void DeleteItems( Vector & items ) //------------------------------------------------------------------------------ /// \ru Отпустить объекты с возможным удалением. \en Detach objects with possible removing. // --- -template -void ReleaseItems( Vector & items ) +template +void ReleaseItems( ItemsVector & items ) { for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) ::ReleaseItem( items[k] ); @@ -368,8 +368,24 @@ void ReleaseItems( Vector & items ) //------------------------------------------------------------------------------ /// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. // --- -template -void DeleteItems( Vector & items, SArray & coItems ) +template +void DeleteItems( ItemsVector & items, SArray & coItems ) +{ + size_t itemsCnt = items.size(); + if ( itemsCnt > 0 ) { + for ( size_t k = 0; k < itemsCnt; ++k ) + ::DeleteItem( items[k] ); + items.clear(); + coItems.clear(); + } +} + + +//------------------------------------------------------------------------------ +/// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. +// --- +template +void DeleteItems( ItemsVector & items, std::vector & coItems ) { size_t itemsCnt = items.size(); if ( itemsCnt > 0 ) { @@ -384,8 +400,24 @@ void DeleteItems( Vector & items, SArray & coItems ) //------------------------------------------------------------------------------ /// \ru Отпустить объекты с возможным удалением. \en Detach objects with possible removing. // --- -template -void ReleaseItems( Vector & items, SArray & coItems ) +template +void ReleaseItems( ItemsVector & items, SArray & coItems ) +{ + size_t itemsCnt = items.size(); + if ( itemsCnt > 0 ) { + for ( size_t k = 0; k < itemsCnt; ++k ) + ::ReleaseItem( items[k] ); + items.clear(); + coItems.clear(); + } +} + + +//------------------------------------------------------------------------------ +/// \ru Отпустить объекты с возможным удалением. \en Detach objects with possible removing. +// --- +template +void ReleaseItems( ItemsVector & items, std::vector & coItems ) { size_t itemsCnt = items.size(); if ( itemsCnt > 0 ) { @@ -406,7 +438,7 @@ void AddRefItems( const TypeVector & srcItems, bool same, RPArray & dstIte if ( (srcItems.size() > 0) && reinterpret_cast( &srcItems ) != reinterpret_cast( &dstItems ) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); dstItem->AddRef(); @@ -426,7 +458,7 @@ void AddRefItems( const TypeVector & srcItems, bool same, std::vector< SPtr 0) && reinterpret_cast(&srcItems) != reinterpret_cast(&dstItems) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; k++ ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); SPtr dstItem; dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); @@ -446,7 +478,7 @@ void AddRefItems( const TypeVector & srcItems, bool same, std::vector & if ( (srcItems.size() > 0) && reinterpret_cast( &srcItems ) != reinterpret_cast( &dstItems ) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); dstItem->AddRef(); @@ -466,7 +498,7 @@ void AddRefRegItems( const TypeVector & srcItems, bool same, RPArray & dst if ( (srcItems.size() > 0) && reinterpret_cast(&srcItems) != reinterpret_cast(&dstItems) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); dstItem->AddRef(); @@ -486,7 +518,7 @@ void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector< SPtr 0) && reinterpret_cast(&srcItems) != reinterpret_cast(&dstItems) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); SPtr dstItem; dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); @@ -506,7 +538,7 @@ void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector if ( (srcItems.size() > 0) && reinterpret_cast(&srcItems) != reinterpret_cast(&dstItems) ) { dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - if ( srcItems[k] != NULL ) { + if ( srcItems[k] != c3d_null ) { Type * srcItem = &const_cast(*srcItems[k]); Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); dstItem->AddRef(); @@ -523,9 +555,9 @@ void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector template bool IsItemSame( const Item * item1, const Item * item2, double accuracy ) { - if ( (item1 == NULL) && (item2 == NULL) ) + if ( (item1 == c3d_null) && (item2 == c3d_null) ) return true; - else if ( (item1 != NULL) && (item2 != NULL) && item1->IsSame( *item2, accuracy ) ) + else if ( (item1 != c3d_null) && (item2 != c3d_null) && item1->IsSame( *item2, accuracy ) ) return true; return false; } @@ -543,7 +575,7 @@ bool AreItemsSame( const Vector & items1, const Vector & items2, double accuracy if ( cnt == items2.size() ) { areEqual = true; for ( size_t k = 0; k < cnt; ++k ) { - if ( (items1[k] == NULL) || (items2[k] == NULL) || !items1[k]->IsSame( *items2[k], accuracy ) ) { + if ( (items1[k] == c3d_null) || (items2[k] == c3d_null) || !items1[k]->IsSame( *items2[k], accuracy ) ) { areEqual = false; break; } @@ -589,7 +621,7 @@ bool AreItemsSimilar( const Vector & items1, const Vector & items2 ) if ( cnt == items2.size() ) { areEqual = true; for ( size_t k = 0; k < cnt; ++k ) { - if ( (items1[k] == NULL) || (items2[k] == NULL) || !items1[k]->IsSimilar( *items2[k] ) ) { + if ( (items1[k] == c3d_null) || (items2[k] == c3d_null) || !items1[k]->IsSimilar( *items2[k] ) ) { areEqual = false; break; } @@ -614,7 +646,7 @@ bool SetItemsEqual( const Vector & srcItems, Vector & dstItems ) if ( setEqual ) { for ( size_t k = 0; k < cnt; ++k ) { - if ( srcItems[k] == NULL || dstItems[k] == NULL || !dstItems[k]->SetEqual( *srcItems[k] ) ) { + if ( srcItems[k] == c3d_null || dstItems[k] == c3d_null || !dstItems[k]->SetEqual( *srcItems[k] ) ) { setEqual = false; break; } @@ -636,7 +668,7 @@ void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, RPA dstItems.Reserve( srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { + if ( srcItem != c3d_null ) { Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); dstItems.push_back( dstItem ); } @@ -654,7 +686,7 @@ void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { + if ( srcItem != c3d_null ) { SPtr dstItem; dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); dstItems.push_back( dstItem ); @@ -673,7 +705,7 @@ void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std dstItems.reserve( dstItems.size() + srcItems.size() ); for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { + if ( srcItem != c3d_null ) { Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); dstItems.push_back( dstItem ); } @@ -688,7 +720,7 @@ template void TransformItems( Array & items, const Matrix & matr, RegType * iReg ) { for ( size_t k = 0, cnt = items.size(); k < cnt; ++k ) { - if ( items[k] != NULL ) + if ( items[k] != c3d_null ) items[k]->Transform( matr, iReg ); } } @@ -711,7 +743,7 @@ template void MoveItems( Array & items, const Vector & to, RegType * iReg ) { for ( size_t k = 0, cnt = items.size(); k < cnt; ++k ) { - if ( items[k] != NULL ) + if ( items[k] != c3d_null ) items[k]->Move( to, iReg ); } } @@ -734,7 +766,7 @@ template void RotateItems( Array & items, const Axis & axis, double angle, RegType * iReg ) { for ( size_t k = 0, cnt = items.size(); k < cnt; ++k ) { - if ( items[k] != NULL ) + if ( items[k] != c3d_null ) items[k]->Rotate( axis, angle, iReg ); } } @@ -759,7 +791,7 @@ void WriteRefItems( const Vector & items, Writer & out ) size_t k, cnt = items.size(); for ( k = 0; k < cnt; ++k ) { - if ( items[k] == NULL ) + if ( items[k] == c3d_null ) cnt--; } @@ -767,7 +799,7 @@ void WriteRefItems( const Vector & items, Writer & out ) if ( out.good() ) { for ( k = 0; k < cnt; ++k ) { - if ( items[k] != NULL ) { + if ( items[k] != c3d_null ) { items[k]->PrepareWrite(); out << &(*items[k]); } @@ -785,7 +817,7 @@ void WriteRefItems( const std::vector< SPtr > & items, Writer & out ) size_t k, cnt = items.size(); for ( k = 0; k < cnt; ++k ) { - if ( items[k] == NULL ) + if ( items[k] == c3d_null ) cnt--; } @@ -793,7 +825,7 @@ void WriteRefItems( const std::vector< SPtr > & items, Writer & out ) if ( out.good() ) { for ( k = 0; k < cnt; ++k ) { - if ( items[k] != NULL ) { + if ( items[k] != c3d_null ) { items[k]->PrepareWrite(); out << items[k].get(); } @@ -814,9 +846,9 @@ void ReadRefItems( Reader & in, RPArray & items ) items.reserve( items.size() + cnt ); for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; + Type * item = c3d_null; in >> item; - if ( item != NULL ) { + if ( item != c3d_null ) { items.push_back( item ); item->AddRef(); } @@ -835,9 +867,9 @@ void ReadRefItems( Reader & in, std::vector & items ) if ( in.good() && cnt > 0 ) { for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; + Type * item = c3d_null; in >> item; - if ( item != NULL ) { + if ( item != c3d_null ) { items.push_back( item ); item->AddRef(); } @@ -856,9 +888,9 @@ void ReadRefItems( Reader & in, std::vector< SPtr > & items ) if ( in.good() && cnt > 0 ) { for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; + Type * item = c3d_null; in >> item; - if ( item != NULL ) + if ( item != c3d_null ) items.push_back( SPtr(item) ); } } @@ -997,7 +1029,7 @@ inline Type * DetachItem( SPtr & itemOwner ) template void ReplaceByCopy( Type *& item ) { - if ( item != NULL ) { + if ( item != c3d_null ) { Type * temp = (Type *)&item->Duplicate(); ::DeleteItem( item ); item = temp; diff --git a/C3d/Include/region.h b/C3d/Include/region.h index cc0c05c..995dc57 100644 --- a/C3d/Include/region.h +++ b/C3d/Include/region.h @@ -51,7 +51,7 @@ public: MbRegion( const SPtr &, bool same ); ///< \ru Регион с одним внешним контуром. \en Region with one external contour. MbRegion( const RPArray &, bool same ); ///< \ru Регион с несколькими контурами. \en Region with several contours. MbRegion( const std::vector< SPtr > &, bool same ); ///< \ru Регион с несколькими контурами. \en Region with several contours. - MbRegion( const MbRegion &, bool same, MbRegDuplicate * iReg = NULL ); ///< \ru Конструктор копии. \en Copy-constructor. + MbRegion( const MbRegion &, bool same, MbRegDuplicate * iReg = c3d_null ); ///< \ru Конструктор копии. \en Copy-constructor. public: virtual ~MbRegion(); @@ -63,10 +63,10 @@ public: virtual MbePlaneType IsA() const; // \ru Тип объекта. \en A type of an object. virtual MbePlaneType Type() const; // \ru Групповой тип объекта. \en Group type of object. virtual MbePlaneType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию. \en Create a copy - virtual void Transform( const MbMatrix &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbCartPoint &, const MbDirection & angle, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ); + virtual MbPlaneItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию. \en Create a copy + virtual void Transform( const MbMatrix &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector &, MbRegTransform * = c3d_null, const MbSurface * newSurface = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbCartPoint &, const MbDirection & angle, MbRegTransform * iReg = c3d_null, const MbSurface * newSurface = c3d_null ); virtual bool IsSame ( const MbPlaneItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. virtual bool SetEqual ( const MbPlaneItem & ); // \ru Сделать объекты равным. \en Make objects equal. virtual void AddYourGabaritTo( MbRect & ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. @@ -276,7 +276,7 @@ private: // --- MATH_FUNC (bool) CreateBooleanResultRegions( RPArray & contours1, RPArray & contours2, const MbRegionBooleanParams & operParams, RPArray & regions, - MbResultType * resInfo = NULL ); + MbResultType * resInfo = c3d_null ); //------------------------------------------------------------------------------- @@ -301,7 +301,7 @@ MATH_FUNC (bool) CreateBooleanResultRegions( RPArray & contours1, RPA // --- MATH_FUNC (bool) CreateBooleanResultRegions( MbRegion & region1, MbRegion & region2, const MbRegionBooleanParams & operParams, RPArray & regions, - MbResultType * resInfo = NULL ); + MbResultType * resInfo = c3d_null ); //------------------------------------------------------------------------------- diff --git a/C3d/Include/sheet_metal_param.h b/C3d/Include/sheet_metal_param.h index a62a2bd..8475292 100644 --- a/C3d/Include/sheet_metal_param.h +++ b/C3d/Include/sheet_metal_param.h @@ -18,6 +18,7 @@ #include #include #include +#include class MATH_CLASS MbFace; @@ -36,6 +37,19 @@ enum MbeReleaseType { }; +//------------------------------------------------------------------------------ +/** \brief \ru Тип создаваемой части штамповки. + \en The type of stamping part being created. \~ + \ingroup Sheet_Metal_Modeling +*/ +// --- +enum MbeStampingCreatedType { + sct_add, ///< \ru Добавляемая часть штамповки. \en Added part of the stamping. + sct_substact, ///< \ru Вычитаемая часть штамповки. \en Substracted part of the stamping. + sct_all ///< \ru Вcя штамповка вместе с телом. \en All stamping with the body. +}; + + //------------------------------------------------------------------------------ /** \brief \ru Параметры сгиба. \en The bend parameters. \~ @@ -142,11 +156,11 @@ public: // --- struct MATH_CLASS MbSheetMetalValues { public: - double thickness; ///< \ru Толщина. \en The thickness. - double k; ///< \ru Коэффициент, определяющий положение нейтрального слоя. \en Coefficient determining the position of the neutral layer. - double radius; ///< \ru Внутренний радиус сгиба. \en The internal radius of the bend. - MbSweptSide side1; ///< \ru Параметры для стороны, лежащей в направлении нормали к эскизу. \en Parameters for side lying along the direction of normal to the sketch. - MbSweptSide side2; ///< \ru Параметры для противоположной стороны. \en Parameters for the opposite side. + double thickness; ///< \ru Толщина. \en The thickness. + double k; ///< \ru Коэффициент, определяющий положение нейтрального слоя. \en Coefficient determining the position of the neutral layer. + double radius; ///< \ru Внутренний радиус сгиба. \en The internal radius of the bend. + MbSweptSide side1; ///< \ru Параметры для стороны, лежащей в направлении нормали к эскизу. \en Parameters for side lying along the direction of normal to the sketch. + MbSweptSide side2; ///< \ru Параметры для противоположной стороны. \en Parameters for the opposite side. public: /// \ru Конструктор по умолчанию. \en Default constructor. @@ -183,29 +197,29 @@ public: \en \name Functions for working with surfaces to which extrude. \{ */ /// \ru Получить ограничивающую поверхность в направлении нормали. \en Get bounding surface in direction of normal. - MbSurface * GetSurface1() const { return side1.GetSurface(); } + const MbSurface * GetSurface1() const { return side1.GetSurface(); } /// \ru Получить ограничивающую поверхность в противоположном направлении. \en Get bounding surface along the opposite direction. - MbSurface * GetSurface2() const { return side2.GetSurface(); } + const MbSurface * GetSurface2() const { return side2.GetSurface(); } + + /// \ru Получить ограничивающую поверхность в направлении нормали. \en Get bounding surface in direction of normal. + MbSurface * SetSurface1() { return side1.SetSurface(); } + /// \ru Получить ограничивающую поверхность в противоположном направлении. \en Get bounding surface along the opposite direction. + MbSurface * SetSurface2() { return side2.SetSurface(); } /// \ru Установить ограничивающую поверхность в направлении нормали. \en Set bounding surface along the direction of normal. - void SetSurface1( MbSurface *s ) { side1.SetSurface( s ); } + void SetSurface1( const MbSurface * s ) { side1.SetSurface( s ); } /// \ru Установить ограничивающую поверхность в противоположном направлении. \en Set bounding surface along the opposite direction. - void SetSurface2( MbSurface *s ) { side2.SetSurface( s ); } + void SetSurface2( const MbSurface * s ) { side2.SetSurface( s ); } + /// \ru Поменять местами ограничивающие выдавливание поверхности. \en Swap bounding extrusions of surfaces. - void ExchangeSurfaces() { - MbSurface *s = side1.GetSurface(); - MbSweptWay w = side1.way; - double d = side1.distance; - if (s!=NULL) - s->AddRef(); + void ExchangeSurfaces() + { + std::swap( side1.way, side2.way ); + std::swap( side1.distance, side2.distance ); + + c3d::ConstSurfaceSPtr surf1( side1.GetSurface() ); side1.SetSurface( side2.GetSurface() ); - side1.way = side2.way; - side1.distance = side2.distance; - side2.SetSurface( s ); - side2.way = w; - side2.distance = d; - if (s!=NULL) - s->DecRef(); + side2.SetSurface( surf1 ); } /** \} */ @@ -1345,10 +1359,10 @@ struct MATH_CLASS MbRuledSolidValues { MbRuledSolidValues() : placement1 ( ), contour1 ( ), - breaks1 ( NULL ), - placement2 ( NULL ), - contour2 ( NULL ), - breaks2 ( NULL ), + breaks1 ( c3d_null ), + placement2 ( c3d_null ), + contour2 ( c3d_null ), + breaks2 ( c3d_null ), thickness ( 0.0 ), radius ( 0.0 ), slopeAngle ( 0.0 ), @@ -1362,16 +1376,16 @@ struct MATH_CLASS MbRuledSolidValues { cylindricBends ( false ), joinByVertices ( true ), surfDistance ( 0.0 ), - surface ( NULL ) { + surface ( c3d_null ) { } /// \ru Конструктор копирования. \en Copy-constructor. MbRuledSolidValues( const MbRuledSolidValues & other ) : placement1 ( other.placement1 ), contour1 (), - breaks1 ( (other.breaks1 != NULL) ? new SArray(*other.breaks1) : NULL ), - placement2 ( (other.placement2 != NULL) ? new MbPlacement3D(*other.placement2) : NULL ), - contour2 ( (other.contour2 != NULL) ? new MbContour() : NULL ), - breaks2 ( (other.breaks2 != NULL) ? new SArray(*other.breaks2) : NULL ), + breaks1 ( (other.breaks1 != c3d_null) ? new SArray(*other.breaks1) : c3d_null ), + placement2 ( (other.placement2 != c3d_null) ? new MbPlacement3D(*other.placement2) : c3d_null ), + contour2 ( (other.contour2 != c3d_null) ? new MbContour() : c3d_null ), + breaks2 ( (other.breaks2 != c3d_null) ? new SArray(*other.breaks2) : c3d_null ), thickness ( other.thickness ), radius ( other.radius ), slopeAngle ( other.slopeAngle ), @@ -1385,9 +1399,9 @@ struct MATH_CLASS MbRuledSolidValues { cylindricBends ( other.cylindricBends ), joinByVertices ( other.joinByVertices ), surfDistance ( other.surfDistance ), - surface ( (other.surface != NULL) ? static_cast(&other.surface->Duplicate()) : NULL ) { + surface ( (other.surface != c3d_null) ? static_cast(&other.surface->Duplicate()) : c3d_null ) { contour1.Init( other.contour1 ); - if ( contour2 != NULL && other.contour2 != NULL ) + if ( contour2 != c3d_null && other.contour2 != c3d_null ) contour2->Init( *other.contour2 ); } /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. @@ -1399,10 +1413,10 @@ struct MATH_CLASS MbRuledSolidValues { const double surfDist, const MbSurface * surf ) : placement1( place1 ), contour1(), - breaks1( (brks1 != NULL) ? new SArray(*brks1) : NULL ), - placement2( (place2 != NULL) ? new MbPlacement3D(*place2) : NULL ), - contour2( (cntr2 != NULL) ? new MbContour() : NULL ), - breaks2( (brks2 != NULL) ? new SArray(*brks2) : NULL ), + breaks1( (brks1 != c3d_null) ? new SArray(*brks1) : c3d_null ), + placement2( (place2 != c3d_null) ? new MbPlacement3D(*place2) : c3d_null ), + contour2( (cntr2 != c3d_null) ? new MbContour() : c3d_null ), + breaks2( (brks2 != c3d_null) ? new SArray(*brks2) : c3d_null ), thickness( thick ), radius( rad ), slopeAngle( sAngle ), @@ -1416,9 +1430,9 @@ struct MATH_CLASS MbRuledSolidValues { cylindricBends( cylBends ), joinByVertices( joinByVert ), surfDistance( surfDist ), - surface( (surf != NULL) ? static_cast(&surf->Duplicate()) : NULL ) { + surface( (surf != c3d_null) ? static_cast(&surf->Duplicate()) : c3d_null ) { contour1.Init( cntr1 ); - if ( (contour2 != NULL) && (cntr2 != NULL) ) + if ( (contour2 != c3d_null) && (cntr2 != c3d_null) ) contour2->Init( *cntr2 ); } @@ -1427,40 +1441,40 @@ struct MATH_CLASS MbRuledSolidValues { placement1.Init( other.placement1 ); contour1.Init( other.contour1 ); - if ( other.breaks1 != NULL ) { - if ( breaks1 != NULL ) + if ( other.breaks1 != c3d_null ) { + if ( breaks1 != c3d_null ) ((SArray &)*breaks1) = *other.breaks1; else breaks1 = new SArray( *other.breaks1 ); } else - breaks1 = NULL; + breaks1 = c3d_null; - if ( other.placement2 != NULL ) { - if ( placement2 != NULL ) + if ( other.placement2 != c3d_null ) { + if ( placement2 != c3d_null ) placement2->Init( *other.placement2 ); else placement2 = new MbPlacement3D( *other.placement2 ); } else - placement2 = NULL; + placement2 = c3d_null; - if ( other.contour2 != NULL ) { - if ( contour2 == NULL ) + if ( other.contour2 != c3d_null ) { + if ( contour2 == c3d_null ) contour2 = new MbContour(); contour2->Init( *other.contour2 ); } else - contour2 = NULL; + contour2 = c3d_null; - if ( other.breaks2 != NULL ) { - if ( breaks2 != NULL ) + if ( other.breaks2 != c3d_null ) { + if ( breaks2 != c3d_null ) ((SArray &)*breaks2) = *other.breaks2; else breaks2 = new SArray( *other.breaks2 ); } else - breaks1 = NULL; + breaks1 = c3d_null; thickness = other.thickness; radius = other.radius; @@ -1476,10 +1490,10 @@ struct MATH_CLASS MbRuledSolidValues { joinByVertices = other.joinByVertices; surfDistance = other.surfDistance; - if ( other.surface != NULL ) + if ( other.surface != c3d_null ) surface = static_cast( &other.surface->Duplicate() ); else - surface = NULL; + surface = c3d_null; } /// \ru Инициализировать контуры. \en Initialize contours. @@ -1488,40 +1502,40 @@ struct MATH_CLASS MbRuledSolidValues { placement1.Init( place1 ); contour1.Init( cntr1 ); - if ( brks1 != NULL ) { - if ( breaks1 != NULL ) + if ( brks1 != c3d_null ) { + if ( breaks1 != c3d_null ) ((SArray &)*breaks1) = *brks1; else breaks1 = new SArray( *brks1 ); } else - breaks1 = NULL; + breaks1 = c3d_null; - if ( place2 != NULL ) { - if ( placement2 != NULL ) + if ( place2 != c3d_null ) { + if ( placement2 != c3d_null ) placement2->Init( *place2 ); else placement2 = new MbPlacement3D( *place2 ); } else - placement2 = NULL; + placement2 = c3d_null; - if ( cntr2 != NULL ) { - if ( contour2 == NULL ) + if ( cntr2 != c3d_null ) { + if ( contour2 == c3d_null ) contour2 = new MbContour(); contour2->Init( *cntr2 ); } else - contour2 = NULL; + contour2 = c3d_null; - if ( brks2 != NULL ) { - if ( breaks2 != NULL ) + if ( brks2 != c3d_null ) { + if ( breaks2 != c3d_null ) ((SArray &)*breaks2) = *brks2; else breaks2 = new SArray( *brks2 ); } else - breaks1 = NULL; + breaks1 = c3d_null; } /// \ru Оператор присваивания. \en Assignment operator. @@ -1551,16 +1565,16 @@ struct MATH_CLASS MbRuledSolidValues { ::fabs( gapShift - other.gapShift ) < accuracy && ::fabs( surfDistance - other.surfDistance ) < accuracy ) { - bool isBreaks1 = breaks1 != NULL; - bool isOtherBreaks1 = other.breaks1 != NULL; - bool isPlacement2 = placement2 != NULL; - bool isOtherPlacement2 = other.placement2 != NULL; - bool isContour2 = contour2 != NULL; - bool isOtherContour2 = other.contour2 != NULL; - bool isBreaks2 = breaks2 != NULL; - bool isOtherBreaks2 = other.breaks2 != NULL; - bool isSurf = surface != NULL; - bool isOtherSurf = other.surface != NULL; + bool isBreaks1 = breaks1 != c3d_null; + bool isOtherBreaks1 = other.breaks1 != c3d_null; + bool isPlacement2 = placement2 != c3d_null; + bool isOtherPlacement2 = other.placement2 != c3d_null; + bool isContour2 = contour2 != c3d_null; + bool isOtherContour2 = other.contour2 != c3d_null; + bool isBreaks2 = breaks2 != c3d_null; + bool isOtherBreaks2 = other.breaks2 != c3d_null; + bool isSurf = surface != c3d_null; + bool isOtherSurf = other.surface != c3d_null; if ( isBreaks1 == isOtherBreaks1 && isPlacement2 == isOtherPlacement2 && @@ -1766,13 +1780,13 @@ public: size_t i, cnt; for ( i = 0, cnt = innerFaces.Count(); i < cnt && isSame; i++ ) - if ( innerFaces[i] == NULL || other.innerFaces[i] == NULL || !innerFaces[i]->IsSame( *other.innerFaces[i], accuracy ) ) { + if ( innerFaces[i] == c3d_null || other.innerFaces[i] == c3d_null || !innerFaces[i]->IsSame( *other.innerFaces[i], accuracy ) ) { isSame = false; break; } for ( i = 0, cnt = outerFaces.Count(); i < cnt && isSame; i++ ) - if ( outerFaces[i] == NULL || other.outerFaces[i] == NULL || !outerFaces[i]->IsSame( *other.outerFaces[i], accuracy ) ) { + if ( outerFaces[i] == c3d_null || other.outerFaces[i] == c3d_null || !outerFaces[i]->IsSame( *other.outerFaces[i], accuracy ) ) { isSame = false; break; } @@ -1903,29 +1917,33 @@ private: struct MATH_CLASS MbToolStampingValues { double punchFilletRadius; ///< \ru Радиус скругления основания со стороны пуансона (отрицательное значение запрещает скругление). \en Punch fillet radius of base (negative value prohibits fillet). double dieFilletRadius; ///< \ru Радиус скругления основания со стороны матрицы (отрицательное значение запрещает скругление). \en Die fillet radius of base (negative value prohibits fillet). + double toolFilletRadius; ///< \ru Радиус скругления негладких ребер инструмента (отрицательное значение запрещает скругление). \en Fillet radius of sharp edges of tool (negative value prohibits fillet). double stampThickness; ///< \ru Толщина формованной части. \en Thickness of a stamped part. - bool constantThickness; ///< \ru Флаг постоянной толщины на штамповке. \en Constant thickness flag. + bool filletToolEdges; ///< \ru Флаг скругления острых ребер инструмента. \en Flag of fillet sharp edges of tool solid. /// \ru Конструктор по умолчанию. \en Default constructor. MbToolStampingValues() : punchFilletRadius( 0.0 ), dieFilletRadius ( 0.0 ), + toolFilletRadius ( 0.0 ), stampThickness ( 0.0 ), - constantThickness( true ) + filletToolEdges ( true ) {} /// \ru Конструктор копирования. \en Copy-constructor. MbToolStampingValues( const MbToolStampingValues & other ) : punchFilletRadius( other.punchFilletRadius ), dieFilletRadius ( other.dieFilletRadius ), + toolFilletRadius ( other.toolFilletRadius ), stampThickness ( other.stampThickness ), - constantThickness( other.constantThickness ) + filletToolEdges ( other.filletToolEdges ) {} /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. - MbToolStampingValues( double punchRad, double dieRad, double thick, bool constThick ) : + MbToolStampingValues( double punchRad, double dieRad, double toolRad, double thick, bool filletTool ) : punchFilletRadius( punchRad ), dieFilletRadius ( dieRad ), + toolFilletRadius ( toolRad ), stampThickness ( thick ), - constantThickness( constThick ) + filletToolEdges ( filletTool ) {} /// \ru Оператор присваивания. \en Assignment operator. @@ -1934,8 +1952,9 @@ struct MATH_CLASS MbToolStampingValues { void Init( const MbToolStampingValues & other ) { punchFilletRadius = other.punchFilletRadius; dieFilletRadius = other.dieFilletRadius; + toolFilletRadius = other.toolFilletRadius; stampThickness = other.stampThickness; - constantThickness = other.constantThickness; + filletToolEdges = other.filletToolEdges; } ///\ru Являются ли объекты равными? \en Determine whether an object is equal? @@ -1944,8 +1963,9 @@ struct MATH_CLASS MbToolStampingValues { if ( ::fabs(punchFilletRadius - other.punchFilletRadius) < accuracy && ::fabs(dieFilletRadius - other.dieFilletRadius) < accuracy && + ::fabs(toolFilletRadius - other.toolFilletRadius) < accuracy && ::fabs(stampThickness - other.stampThickness) < accuracy && - constantThickness == other.constantThickness ) + filletToolEdges == other.filletToolEdges ) isSame = true; return isSame; @@ -1968,42 +1988,53 @@ struct MATH_CLASS MbToolStampingValues { struct MATH_CLASS MbSolidToSheetMetalValues { public: /// \ru Ребро для построения сгиба и параметры сгиба. \en The bend edge and parameters of bending. \~ - struct MbBendEdgeValues { - double bendRadius; ///< \ru Внутренний радиус сгиба. \en The internal radius of the bend. + struct MATH_CLASS MbBendEdgeValues : public MbBendValues { MbEdgeFacesIndexes bendEdgeIndex; ///< \ru Индекс ребра сгиба. \en Index of bend edge. + MbName innerFaceName; ///< \ru Имя внутренней грани сгиба. \en Name of interior face of bend. + MbName outerFaceName; ///< \ru Имя внешней грани сгиба. \en Name of exterior face of bend. /// \ru Конструктор по умолчанию. \en Default constructor. MbBendEdgeValues() - : bendRadius () + : MbBendValues() , bendEdgeIndex() + , innerFaceName() + , outerFaceName() {} /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. - MbBendEdgeValues( double r, MbEdgeFacesIndexes index ) - : bendRadius ( r ) - , bendEdgeIndex( index ) + MbBendEdgeValues( double coef, double rad, MbEdgeFacesIndexes index ) + : MbBendValues( coef, rad, 0.0, 0.0/*coneAng*/ ) + , bendEdgeIndex( index ) + , innerFaceName( ) + , outerFaceName( ) {} /// \ru Конструктор копирования. \en Copy-constructor. MbBendEdgeValues( const MbBendEdgeValues & other ) - : bendRadius ( other.bendRadius ) + : MbBendValues ( other ) , bendEdgeIndex( other.bendEdgeIndex ) + , innerFaceName( other.innerFaceName ) + , outerFaceName( other.outerFaceName ) {} /// \ru Оператор присваивания. \en Assignment operator. MbBendEdgeValues & operator = ( const MbBendEdgeValues &other ) { Init( other ); return *this; } /// \ru Инициализация по другому объекту. \en Initialization by another object. void Init( const MbBendEdgeValues & other ) { - bendRadius = other.bendRadius; + MbBendValues::Init( other ); bendEdgeIndex = other.bendEdgeIndex; + innerFaceName = other.innerFaceName; + outerFaceName = other.outerFaceName; } ///\ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MbBendEdgeValues & other, double accuracy ) const { bool isSame = false; - if ( ::fabs(bendRadius - other.bendRadius) < accuracy && - bendEdgeIndex.IsSame(other.bendEdgeIndex,accuracy) ) + if ( MbBendValues::IsSame(other, accuracy) && + bendEdgeIndex.IsSame(other.bendEdgeIndex,accuracy) && + innerFaceName == other.innerFaceName && + outerFaceName == other.outerFaceName ) isSame = true; return isSame; } /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. void Transform( const MbMatrix3D & matr ) { - matr.TransformLength( bendRadius ); + matr.TransformLength( radius ); bendEdgeIndex.Transform( matr ); } /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. @@ -2018,60 +2049,67 @@ public: }; /// \ru Ребро разъема и параметры замыкания углов. \en The rip edge and closing corner parameters. \~ struct MbRipEdgeValues { - MbEdgeFacesIndexes ripEdgeIndex; ///< \ru Индекс ребра разъема. \en Index of rip edge. - MbClosedCornerValues cornerValues; + std::vector ripEdgeIndicies; ///< \ru Индекс ребра разъема. \en Index of rip edge. + MbClosedCornerValues cornerValues; /// \ru Конструктор по умолчанию. \en Default constructor. MbRipEdgeValues() - : ripEdgeIndex() + : ripEdgeIndicies() , cornerValues() {} /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. - MbRipEdgeValues( MbEdgeFacesIndexes index, const MbClosedCornerValues & cValues ) - : ripEdgeIndex( index ) - , cornerValues( cValues ) + MbRipEdgeValues( const std::vector & indicies, const MbClosedCornerValues & cValues ) + : ripEdgeIndicies( indicies ) + , cornerValues ( cValues ) {} /// \ru Конструктор копирования. \en Copy-constructor. MbRipEdgeValues( const MbRipEdgeValues & other ) - : ripEdgeIndex( other.ripEdgeIndex ) - , cornerValues( other.cornerValues ) + : ripEdgeIndicies( other.ripEdgeIndicies ) + , cornerValues ( other.cornerValues ) {} /// \ru Оператор присваивания. \en Assignment operator. MbRipEdgeValues & operator = ( const MbRipEdgeValues &other ) { Init( other ); return *this; } /// \ru Инициализация по другому объекту. \en Initialization by another object. void Init( const MbRipEdgeValues & other ) { - ripEdgeIndex = other.ripEdgeIndex; + ripEdgeIndicies = other.ripEdgeIndicies; cornerValues = other.cornerValues; } ///\ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MbRipEdgeValues & other, double accuracy ) const { bool isSame = false; - if ( ripEdgeIndex.IsSame(other.ripEdgeIndex, accuracy) && - cornerValues.IsSame(other.cornerValues, accuracy) ) + if ( cornerValues.IsSame( other.cornerValues, accuracy ) && + ripEdgeIndicies.size() == other.ripEdgeIndicies.size() ) { isSame = true; + for ( size_t i = 0, iCount = ripEdgeIndicies.size(); i < iCount && isSame; i++ ) + isSame = ripEdgeIndicies[i].IsSame( other.ripEdgeIndicies[i], accuracy ); + } return isSame; } /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. void Transform( const MbMatrix3D & matr ) { - ripEdgeIndex.Transform( matr ); + for ( size_t i = 0, iCount = ripEdgeIndicies.size(); i < iCount; i++ ) + ripEdgeIndicies[i].Transform( matr ); cornerValues.Transform( matr ); } /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. void Move( const MbVector3D & to ) { - ripEdgeIndex.Move( to ); + for ( size_t i = 0, iCount = ripEdgeIndicies.size(); i < iCount; i++ ) + ripEdgeIndicies[i].Move( to ); } /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. void Rotate( const MbAxis3D & axis, double ang ) { - ripEdgeIndex.Rotate( axis, ang ); + for ( size_t i = 0, iCount = ripEdgeIndicies.size(); i < iCount; i++ ) + ripEdgeIndicies[i].Rotate( axis, ang ); } KNOWN_OBJECTS_RW_REF_OPERATORS( MbRipEdgeValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; public: - double k; ///< \ru Коэффициент, определяющий положение нейтрального слоя. \en Coefficient determining the position of the neutral layer. - double sheetThickness; ///< \ru Толщина листового тела. \en Thickness of a sheet solid. - std::vector bendEdges; ///< \ru Набор ребер и параметров сгиба. \en Indicies of bend edges. - std::vector ripEdges; ///< \ru Набор ребер и параметров разъемов. \en Indicies of cut edges. - MbClosedCornerValues defaultCornerValues; + double k; ///< \ru Коэффициент, определяющий положение нейтрального слоя. \en Coefficient determining the position of the neutral layer. + double sheetThickness; ///< \ru Толщина листового тела. \en Thickness of a sheet solid. + std::vector bendEdges; ///< \ru Набор ребер и параметров сгиба. \en Indicies of bend edges. + std::vector ripEdges; ///< \ru Набор ребер и параметров разъемов. \en Indicies of cut edges. + MbClosedCornerValues defaultCornerValues; ///<\ru Параметры замыкания сгиба. \en The bend closure parameters. + /// \ru Конструктор по умолчанию. \en Default constructor. MbSolidToSheetMetalValues() : k ( 0.0 ) diff --git a/C3d/Include/solid.h b/C3d/Include/solid.h index 4461bdc..f27368a 100644 --- a/C3d/Include/solid.h +++ b/C3d/Include/solid.h @@ -143,10 +143,10 @@ public : // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Determine whether objects are similar. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равными. \en Make the objects equal. @@ -236,36 +236,40 @@ public : MbFaceShell * GetShell() const; /// \ru Имеется ли оболочка? \en Is there a shell? bool IsShellBuild() const; + /// \ru Переустановить в ребрах указатели на соединяемые ими грани. \en Reinstall pointers to mating faces in edges. void MakeRight(); /// \ru Верно ли установлены в ребра указатели на соединяемые ими грани? \en Are the pointers in edges to the faces connected by them set correctly? bool IsRight() const; + /// \ru Выдать количество граней. \en Get the count of faces. - size_t GetFacesCount() const; + size_t GetFacesCount() const { return outer ? outer->GetFacesCount() : 0; } /// \ru Заполнить контейнер вершинами тела. \en Fill container by solid vertices. template - void GetVertices( VerticesVector & vertices ) const { if ( outer != NULL ) { outer->GetVertices( vertices ); } } + void GetVertices( VerticesVector & vertices ) const { if ( outer != c3d_null ) { outer->GetVertices( vertices ); } } /// \ru Заполнить контейнер ориентированными ребрами тела. \en Fill container by oriented edges of the solid. template - void GetEdges( EdgesVector & edges ) const { if ( outer != NULL ) { outer->GetEdges( edges ); } } + void GetEdges( EdgesVector & edges ) const { if ( outer != c3d_null ) { outer->GetEdges( edges ); } } /// \ru Заполнить контейнеры вершинами и ребрами тела. \en Fill containers by vertices and edges of the solid. template - void GetItems( VerticesVector & vertices, EdgesVector & edges ) const { if ( outer != NULL ) { outer->GetItems( vertices, edges ); } } + void GetItems( VerticesVector & vertices, EdgesVector & edges ) const { if ( outer != c3d_null ) { outer->GetItems( vertices, edges ); } } /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. template - void GetFaces ( FacesVector & faces ) const { if ( outer != NULL ) { outer->GetFaces( faces ); } } + void GetFaces ( FacesVector & faces ) const { if ( outer != c3d_null ) { outer->GetFaces( faces ); } } /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. template - void GetFacesSet( FacesSet & faces ) const { if ( outer != NULL ) { outer->GetFacesSet( faces ); } } - + void GetFacesSet( FacesSet & faces ) const { if ( outer != c3d_null ) { outer->GetFacesSet( faces ); } } /// \ru Заполнить контейнер вершинами, ребрами и гранями тела. \en Fill container by vertices, edges and faces of the solid. - void GetItems ( RPArray & ) const; + template + void GetItems( TopologyItemsVector & items ) const { if ( outer != c3d_null ) { outer->GetItems( items ); } } + /// \ru Выдать вершину по её номеру. \en Get vertex by its index. MbVertex * GetVertex( size_t index ) const; /// \ru Выдать ребро по его номеру. \en Get edge by its index. MbCurveEdge * GetEdge ( size_t index ) const; /// \ru Выдать грань по её номеру. \en Get face by its index. MbFace * GetFace ( size_t index ) const; + /// \ru Выдать номер вершины. \en Get the vertex index. size_t GetVertexIndex( const MbVertex & ) const; /// \ru Выдать номер ребра. \en Get the edge index. @@ -274,6 +278,7 @@ public : size_t GetFaceIndex ( const MbFace & ) const; /// \ru Выдать количество связных оболочек тела. \en Get the count of connected shells of the solid. size_t GetShellCount() const; + /// \ru Вывернуть тело наизнанку - переориентировать все грани. \en Revert the solid - reorientation of the whole set of faces. bool Reverse(); diff --git a/C3d/Include/space_instance.h b/C3d/Include/space_instance.h index 63ba5d0..11d7d35 100644 --- a/C3d/Include/space_instance.h +++ b/C3d/Include/space_instance.h @@ -73,10 +73,10 @@ public : // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en A type of an object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * iReg = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * iReg = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать объекты равными. \en Make the objects equal. diff --git a/C3d/Include/space_item.h b/C3d/Include/space_item.h index 3b014ad..4b76de1 100644 --- a/C3d/Include/space_item.h +++ b/C3d/Include/space_item.h @@ -246,7 +246,7 @@ public : \return \ru Копия объекта. \en A copy of the object. */ - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const = 0; + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const = 0; /** \brief \ru Преобразовать объект согласно матрице. \en Convert the object according to the matrix. \~ @@ -269,7 +269,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. */ - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ) = 0; + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. \~ @@ -292,7 +292,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. */ - virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ) = 0; + virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object around an axis at a given angle. \~ @@ -317,7 +317,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. */ - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ) = 0; + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Определить, являются ли объекты равными. \en Determine whether an object is equal. \~ diff --git a/C3d/Include/surf_chamfer_surface.h b/C3d/Include/surf_chamfer_surface.h index 07fe82a..5d0d08f 100644 --- a/C3d/Include/surf_chamfer_surface.h +++ b/C3d/Include/surf_chamfer_surface.h @@ -110,13 +110,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента. \en Make a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента. \en Make a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Cделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties &properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -199,7 +199,7 @@ public: virtual double GetSmoothRadius() const; // \ru Дать радиус. \en Get radius. virtual void GetDistances( double u, double &d1, double &d2 ) const; // \ru Дать радиусы со знаком. \en Get radii with a sign. virtual double GetDistance( bool s ) const; // \ru Дать радиус со знаком. \en Get radius with a sign. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar. virtual bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional matrix of transformation from its parametric domain to the parametric domain of surf. diff --git a/C3d/Include/surf_channel_surface.h b/C3d/Include/surf_channel_surface.h index 1cc3bad..fb42c21 100644 --- a/C3d/Include/surf_channel_surface.h +++ b/C3d/Include/surf_channel_surface.h @@ -163,7 +163,7 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. diff --git a/C3d/Include/surf_cone_surface.h b/C3d/Include/surf_cone_surface.h index 6a982c8..197e6b0 100644 --- a/C3d/Include/surf_cone_surface.h +++ b/C3d/Include/surf_cone_surface.h @@ -174,10 +174,10 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA () const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & init ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -279,7 +279,7 @@ public: virtual MbCurve3D * CurveUV( const MbLineSegment &, bool bApprox = true ) const; // \ru Пространственная копия линии по параметрической линии. \en Spatial copy of line by parametric line. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Пересечение с кривой. \en Intersection with curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -333,7 +333,7 @@ public: /** \ru \name Функции элементарных поверхностей \en \name Functions of elementary surfaces \{ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \} */ /** \ru \name Функции конической поверхности \en \name Functions of conical surface diff --git a/C3d/Include/surf_coons_surface.h b/C3d/Include/surf_coons_surface.h index fe1a28d..eb30cc0 100644 --- a/C3d/Include/surf_coons_surface.h +++ b/C3d/Include/surf_coons_surface.h @@ -23,9 +23,9 @@ class MATH_CLASS MbCurve; //------------------------------------------------------------------------------ /** \brief \ru Способ расчёта поверхности Кунса. - \en Type of calculation of Coons surface. \~ + \en Type of calculation of Coons surface. \~ \details \ru Способ расчёта поверхности Кунса. \n - \en Type of calculation of Coons surface. \n \~ + \en Type of calculation of Coons surface. \n \~ \ingroup Surfaces */ // --- @@ -36,6 +36,35 @@ enum MbeCoonsSurfaceCalcType { }; +//------------------------------------------------------------------------------ +/** \brief \ru Производные по uv в вершинах. + \en Derivative by uv at vertices. \~ + \details \ru Производные по uv в вершинах. \n + \en Derivative by uv at vertices. \n \~ +*/ +// --- +struct CoonsDerivesUV { + MbVector3D firstUV0[COONS_COUNT]; ///< \ru Производные в началах кривых производных. \en Derivatives in the beginning curves of derivatives. + MbVector3D firstUV1[COONS_COUNT]; ///< \ru Производные в концая кривых производных. \en Derivatives at the ends of derivative curves. + + /// \ru Конструктор. \en Constructor. + CoonsDerivesUV() + { + SetZero(); + } + + /// \ru Обнулить координаты векторов. \en Set coordinates of vectors to zero. + void SetZero() { + for ( size_t i = 0; i < COONS_COUNT; ++i ) { + firstUV0[i].SetZero(); + firstUV1[i].SetZero(); + } + } + + OBVIOUS_PRIVATE_COPY( CoonsDerivesUV ) +}; + + //------------------------------------------------------------------------------ /** \brief \ru Поверхность Кунса на четырех кривых. \en Coons surface on four curves. \~ @@ -96,6 +125,7 @@ private: bool poleVMin; ///< \ru Полюс в начале. \en Pole at the beginning. bool poleVMax; ///< \ru Полюс в конце. \en Pole at the end. MbeCoonsSurfaceCalcType calcType; ///< \ru Версия реализации определяет способ расчёта поверхности. \en Version of implementation determines a type of calculation of surface. + DPtr derivesUV; ///< \ru Производные в началах и концах кривых производных. \en Derivatives in the beginning and ends curves of derivatives. //------------------------------------------------------------------------------ /** \brief \ru Вспомогательные данные. @@ -108,7 +138,9 @@ private: public: DPtr mp; ///< \ru Дополнительные временные данные для ускорения вычислений. \en Additional temporary data to speed up computations. MbCoonsSurfaceAuxiliaryData(); + MbCoonsSurfaceAuxiliaryData( const MbCoonsSurfaceAuxiliaryData & init ); virtual ~MbCoonsSurfaceAuxiliaryData(); + MbCoonsSurfaceAuxiliaryData & operator = ( const MbCoonsSurfaceAuxiliaryData & init ); }; mutable CacheManager cache; @@ -162,13 +194,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента \en Make a copy of element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента \en Make a copy of element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object @@ -284,9 +316,11 @@ public: const MbCurve3D & GetDerCurve3() const { return *curve3U; } /// \ru Получить кривую по индексу. \en Get curve by an index. const MbCurve3D * GetCurve( size_t ind ) const; + /// \ru Получить количество кривых. \en Get count of curves. size_t GetCurvesCount() const { return COONS_COUNT; } //-V112 const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. + MbeCoonsSurfaceCalcType GetCalcType() const { return calcType; } ///< \ru Выдать способ расчёта поверхности. \en Get surface calculation type. /** \} */ double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. @@ -305,8 +339,8 @@ public: \en Index of the curve. \~ \param[out] sense - \ru Флаг совпадения направленности кривой с рисунком, приведенным выше. \en Flag that indicates the coincidence of the curve with the picture shown above.\~ - \return - \ru Указатель на кривую или NULL. - \en Pointer to the curve or NULL. \~ + \return - \ru Указатель на кривую или c3d_null. + \en Pointer to the curve or c3d_null. \~ */ const MbCurve3D * GetExactCurve( size_t k, bool & sense ) const; @@ -322,7 +356,7 @@ public: private: void operator = ( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. void Setup(); - // void SetVertexUV( double u, double v ) const; + void SetupUVDerives(); void CheckParams( double & u, double & v, bool ext = false ) const; // \ru Проверить и изменить при необходимости параметры. \en Check and correct parameters. void CalculateTwist( double u, double v ) const; // \ru Определение местных координат. \en Determination of local coordinates. @@ -412,33 +446,6 @@ inline void MbCoonsPatchSurface::ParamThird ( double /*w*/, double * t ) const { } -//------------------------------------------------------------------------------ -// \ru Добавить матрицу поверхности. \en Add the matrix of the surface. -// --- -inline void MbCoonsPatchSurface::AddMatrix( double u, double v, double * uu, double * vv, MbVector3D & p ) const { - - MbCartPoint3D twist[COONS_COUNT]; - - if ( calcType == cst_GregoryPatchType ) { - // SetVertexUV( u, v ); - CalculateTwist( u, v ); - - MbCoonsSurfaceAuxiliaryData * loccache = cache(); - for ( size_t i = 0; i < COONS_COUNT; ++i ) - twist[i] = loccache->mp->twist[i]; - } - else { - for ( size_t i = 0; i < COONS_COUNT; ++i ) - twist[i] = vertexUV[i]; - } - - p.Add( vertex[0], -uu[0] * vv[0], vertex[1], -uu[1] * vv[0], vertex[2], -uu[1] * vv[1], vertex[3], -uu[0] * vv[1] ); - p.Add( vertexU[0], -uu[2] * vv[0], vertexU[1], -uu[3] * vv[0], vertexU[2], -uu[3] * vv[1], vertexU[3], -uu[2] * vv[1] ); - p.Add( vertexV[0], -uu[0] * vv[2], vertexV[1], -uu[1] * vv[2], vertexV[2], -uu[1] * vv[3], vertexV[3], -uu[0] * vv[3] ); - p.Add( twist[0], -uu[2] * vv[2], twist[1], -uu[3] * vv[2], twist[2], -uu[3] * vv[3], twist[3], -uu[2] * vv[3] ); -} - - //------------------------------------------------------------------------------ // \ru Получить кривую по индексу \en Get curve by an index // --- @@ -452,146 +459,8 @@ inline const MbCurve3D * MbCoonsPatchSurface::GetCurve( size_t ind ) const case 2 : { return curve2; } case 3 : { return curve3; } } - return NULL; + return c3d_null; } -//////////////////////////////////////////////////////////////////////////////// -// -// Вспомогательные объекты бикубической поверхности Кунса. -// Auxiliary objects for bicubic Coons surface. -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -// \ru Кривая производных, обслуживающая точную бикубическую поверхность Кунса, построенная кривой на поверхности. -// \en The curve of derivatives serving the exact bicubic Coons surface, constructed by a curve on the surface. \~ -// --- -class MATH_CLASS MbCoonsDerivative : public MbCurve3D { -protected : - MbSurfaceCurve * curve; ///< \ru Кривая на поверхности (всегда не NULL). \en Curve on surface (always not NULL). - double param1; ///< \ru Параметр первой точки кривой. \en The first point parameter of curve. - double param2; ///< \ru Параметр второй точки кривой. \en The second point parameter of curve. - MbVector rail1; ///< \ru Вектор для вычисления поперечной производной в первой точке кривой. \en The vector for calculation of the transverse derivative in first point of curve. - MbVector rail2; ///< \ru Вектор для вычисления поперечной производной во второй точке кривой. \en The vector for calculation of the transverse derivative in second point of curve. - double turner; ///< \ru Угол поворота векторов на единицу изменения параметра. \en The angle of rotation of vectors per unit of parameter change. - - //------------------------------------------------------------------------------ - /** \brief \ru Вспомогательные данные. - \en Auxiliary data. \~ - \details \ru Вспомогательные данные служат для ускорения работы объекта. - \en Auxiliary data are used for fast calculations. \n \~ - */ - // --- - class MbCoonsDerivativeAuxiliaryData: public AuxiliaryData { - public: - double t; ///< \ru Параметр. \en Parameter. - MbCartPoint3D point; ///< \ru Точка. \en Point. - MbVector3D first; ///< \ru Первая производная. \en First derivative. - MbVector3D second; ///< \ru Вторая производная. \en Second derivative. - MbVector3D third; ///< \ru Третья производная. \en Third derivative. - - MbCoonsDerivativeAuxiliaryData(); - MbCoonsDerivativeAuxiliaryData( const MbCoonsDerivativeAuxiliaryData & ); - virtual ~MbCoonsDerivativeAuxiliaryData(); - - void Init(); - void Init( const MbCoonsDerivativeAuxiliaryData & ); - void Move( const MbVector3D & ); - }; - - mutable CacheManager cache; - -public : - /// \ru Конструктор кривой на поверхности. \en Constructor of curve on surface. - MbCoonsDerivative( MbSurfaceCurve & c, double t1, const MbVector & r1, double t2, const MbVector & r2 ); -protected: - /// \ru Конструктор копирования. \en Copy-constructor. - MbCoonsDerivative( const MbCoonsDerivative &, MbRegDuplicate * ); -private: - MbCoonsDerivative( const MbCoonsDerivative & ); // \ru Не реализовано!!! \en Not implemented!!! - -public : - virtual ~MbCoonsDerivative(); - -public: - /// \ru Реализация функции, инициирующей посещение объекта. \en Implementation of a function initializing a visit of an object. - VISITING_CLASS( MbCoonsDerivative ); - - /** \ru \name Общие функции геометрического объекта. - \en \name Common functions of a geometric object. - \{ */ - - virtual MbeSpaceType IsA() const; // \ru Дать тип элемента. \en Get element type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, являются ли объекты одинаковыми. \en Determine whether objects are equal. - virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. - virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Определить, являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. - /// \ru Перевести все временные (mutable) данные объекта в неопределённое (исходное) состояние. \en Translate all the time (mutable) data objects in an inconsistent (initial) state. - virtual void Refresh(); - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. - - /** \} */ - /** \ru \name Общие функции кривой. - \en \name Common functions of curve. - \{ */ - - virtual double GetTMin() const; // \ru Вернуть минимальное значение параметра. \en Get the minimum value of parameter. - virtual double GetTMax() const; // \ru Вернуть максимальное значение параметра. \en Get the maximum value of parameter. - virtual bool IsClosed() const; // \ru Проверить замкнутость кривой. \en Check for curve closedness. - virtual double GetPeriod() const; // \ru Вернуть период периодической кривой. \en Get period of a periodic curve. - - // \ru Функции для работы в области определения. \en Functions for working in the definition domain. - virtual void PointOn ( double & t, MbCartPoint3D & ) const; // \ru Вычислить точку на кривой. \en Calculate a point on the curve. - virtual void FirstDer ( double & t, MbVector3D & ) const; // \ru Вычислить первую производную. \en Calculate the first derivative. - virtual void SecondDer( double & t, MbVector3D & ) const; // \ru Вычислить вторую производную. \en Calculate the second derivative. - virtual void ThirdDer ( double & t, MbVector3D & ) const; // \ru Вычислить третью производную по t. \en Calculate the third derivative by t. - // \ru Функции для работы вне области определения. \en Functions for working outside of definition domain. - virtual void _PointOn ( double t, MbCartPoint3D & ) const; // \ru Вычислить точку на расширенной кривой. \en Calculate a point on the extended curve. - virtual void _FirstDer ( double t, MbVector3D & ) const; // \ru Вычислить первую производную. \en Calculate the first derivative. - virtual void _SecondDer( double t, MbVector3D & ) const; // \ru Вычислить вторую производную. \en Calculate the second derivative. - virtual void _ThirdDer ( double t, MbVector3D & ) const; // \ru Вычислить третью производную по t. \en Calculate the third derivative by t. - // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ - virtual void Explore ( double & t, bool ext, - MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - - virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменить направление. \en Change the direction. - - virtual double Step ( double t, double sag ) const; // \ru Вычисление шага по стрелке прогиба. \en Calculation of parameter step by the sag. - virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага по углу отклонения нормали. \en Calculation of parameter step by the deviation angle. - - virtual void ChangeCarrier ( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменить носитель. \en Change the carrier. - virtual bool ChangeCarrierBorne( const MbSpaceItem &, MbSpaceItem &, const MbMatrix & matr ); // \ru Изменить носимые элементы. \en Change a carrier elements. - - /** \} */ - - /// \ru Вычислить нормаль к поверхности. \en Calculate surface normal. - void SurfaceNormal( double & t, MbVector3D & n ) const { curve->SurfaceNormal( t, n ); } - /// \ru Заменить кривую. \en Replace curve. - bool ChangeCurve( MbSurfaceCurve & ); - /// \ru Дать кривую. \en Get curve. - const MbSurfaceCurve * GetSurfaceCurve() const { return curve; } - /// \ru Дать кривую. \en Get curve. - MbSurfaceCurve * SetSurfaceCurve() { return curve; } - -protected: - void CheckParam ( double & t ) const; // \ru Проверить и изменить при необходимости параметр. \en Check and correct parameter. - -private: - // \ru Объявить оператор приравнивания по ссылке. \en Declare operator of assignment by reference. - void operator = ( const MbCoonsDerivative & ); // \ru Не реализовано!!! \en Not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoonsDerivative ) - -}; - -IMPL_PERSISTENT_OPS( MbCoonsDerivative ) - - #endif // __SURF_COONS_SURFACE_H diff --git a/C3d/Include/surf_coons_surface_.h b/C3d/Include/surf_coons_surface_.h index cc07336..ca90a6e 100644 --- a/C3d/Include/surf_coons_surface_.h +++ b/C3d/Include/surf_coons_surface_.h @@ -43,43 +43,99 @@ private: MbCartPoint3D twistVVV[COONS_COUNT]; // Производная по VVV. public: - // Конструктор. + /// \ru Конструктор. \en Constructor. MbCoonsWorkingData() : calcU ( UNDEFINED_DBL ) , calcV ( UNDEFINED_DBL ) { for ( size_t i = 0; i < COONS_COUNT; ++i ) { - twist[i] .SetZero(); - twistU[i] .SetZero(); - twistV[i] .SetZero(); - twistUU[i] .SetZero(); - twistUV[i] .SetZero(); - twistVV[i] .SetZero(); - twistUUU[i].SetZero(); - twistUUV[i].SetZero(); - twistUVV[i].SetZero(); + twist[i] .SetZero(); + twistU[i] .SetZero(); + twistV[i] .SetZero(); + twistUU[i] .SetZero(); + twistUV[i] .SetZero(); + twistVV[i] .SetZero(); + twistUUU[i].SetZero(); + twistUUV[i].SetZero(); + twistUVV[i].SetZero(); twistVVV[i].SetZero(); } } + + /// \ru Конструктор копирования. \en Copy-constructor. + MbCoonsWorkingData( const MbCoonsWorkingData & init ) + : calcU( init.calcU ) + , calcV( init.calcV ) + { + for ( size_t i = 0; i < COONS_COUNT; ++i ) { + twist[i] = init. twist[i] ; + twistU[i] = init. twistU[i] ; + twistV[i] = init. twistV[i] ; + twistUU[i] = init. twistUU[i] ; + twistUV[i] = init. twistUV[i] ; + twistVV[i] = init. twistVV[i] ; + twistUUU[i] = init. twistUUU[i]; + twistUUV[i] = init. twistUUV[i]; + twistUVV[i] = init. twistUVV[i]; + twistVVV[i] = init. twistVVV[i]; + } + } + // Деструктор. ~MbCoonsWorkingData() {} + /// \ru Обнулить координаты. \en Set coordinates to zero. void SetZeroVectors() { for ( size_t i = 0; i < COONS_COUNT; ++i ) { - twist[i] .SetZero(); - twistU[i] .SetZero(); - twistV[i] .SetZero(); - twistUU[i] .SetZero(); - twistUV[i] .SetZero(); - twistVV[i] .SetZero(); - twistUUU[i].SetZero(); - twistUUV[i].SetZero(); - twistUVV[i].SetZero(); + twist[i] .SetZero(); + twistU[i] .SetZero(); + twistV[i] .SetZero(); + twistUU[i] .SetZero(); + twistUV[i] .SetZero(); + twistVV[i] .SetZero(); + twistUUU[i].SetZero(); + twistUUV[i].SetZero(); + twistUVV[i].SetZero(); twistVVV[i].SetZero(); } } - OBVIOUS_PRIVATE_COPY( MbCoonsWorkingData ) + /// \ru Присвоить значение другого объекта. \en Assign a value of another object. + MbCoonsWorkingData & operator = ( const MbCoonsWorkingData & init ) { + calcU = init.calcU; + calcV = init.calcV; + for ( size_t i = 0; i < COONS_COUNT; ++i ) { + twist[i] = init.twist[i]; + twistU[i] = init.twistU[i]; + twistV[i] = init.twistV[i]; + twistUU[i] = init.twistUU[i]; + twistUV[i] = init.twistUV[i]; + twistVV[i] = init.twistVV[i]; + twistUUU[i] = init.twistUUU[i]; + twistUUV[i] = init.twistUUV[i]; + twistUVV[i] = init.twistUVV[i]; + twistVVV[i] = init.twistVVV[i]; + } + return *this; + } + + /// \ru Проверить объекты на равенство. \en Check objects for equality. + bool operator == ( const MbCoonsWorkingData & init ) { + bool res = calcU == init.calcU && calcV == init.calcV; + for ( size_t i = 0; i < COONS_COUNT && res; ++i ) { + res &= twist[i] == init.twist[i]; + res &= twistU[i] == init.twistU[i]; + res &= twistV[i] == init.twistV[i]; + res &= twistUU[i] == init.twistUU[i]; + res &= twistUV[i] == init.twistUV[i]; + res &= twistVV[i] == init.twistVV[i]; + res &= twistUUU[i] == init.twistUUU[i]; + res &= twistUUV[i] == init.twistUUV[i]; + res &= twistUVV[i] == init.twistUVV[i]; + res &= twistVVV[i] == init.twistVVV[i]; + } + return res; + } }; diff --git a/C3d/Include/surf_corner_surface.h b/C3d/Include/surf_corner_surface.h index 33b2518..002424e 100644 --- a/C3d/Include/surf_corner_surface.h +++ b/C3d/Include/surf_corner_surface.h @@ -90,13 +90,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента \en Make a copy of element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента \en Make a copy of element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const; @@ -307,7 +307,7 @@ inline const MbCurve3D * MbCornerSurface::GetCurve( size_t ind ) const case 1 : { return curve1; } case 2 : { return curve2; } } - return NULL; + return c3d_null; } diff --git a/C3d/Include/surf_cover_surface.h b/C3d/Include/surf_cover_surface.h index 94b3e23..bfe8d8e 100644 --- a/C3d/Include/surf_cover_surface.h +++ b/C3d/Include/surf_cover_surface.h @@ -1,370 +1,370 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Билинейная поверхность на четырех кривых. - \en Bilinear surface on four curves. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_COVER_SURFACE_H -#define __SURF_COVER_SURFACE_H - - -#include - - -#define COVER_COUNT 4 ///< \ru Число кривых, используемых для построения билинейной поверхности. \en Count of curves used to construct bilinear surface. - - -//------------------------------------------------------------------------------ -/** \brief \ru Четырёхугольная поверхность на кривых. - \en Quadrangular surface on curves. \~ - \details \ru Билинейная поверхность на четырех кривых. \n - Кривые должны попарно пересекаться или иметь точки скрещения. - Если кривые попарно пересекаются, то поверхность проходит через определяющиее её кривые. \n - \en Bilinear surface on four curves. \n - Curves have to be intersected pairwise or have crossing points. - If curves are intersected pairwise then surface passes through its determining curves. \n \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbCoverSurface : public MbSurface { - -// t2min curve2 t2max -// R(u,v) = P3 ______________________ P2 -// (curve0(t0) - P0*(1-u)) *(1-v)+ t3max | | t1max -// (curve1(t1) - P1*(1-v)) * u + | | -// (curve2(t2) - P2* u ) * v + | | -// (curve3(t3) - P3* v ) *(1-u) curve3 | R | curve1 -// t0=t0min*(1-u)+t0max*u | | -// t1=t1min*(1-v)+t1max*v | | -// t2=t2min*(1-u)+t2max*u t3min |______________________| t1min -// t3=t3min*(1-v)+t3max*v P0 P1 -// t0min curve0 t0max - -private: - MbCurve3D * curve0; ///< \ru Кривая 0. \en Curve 0. - MbCurve3D * curve1; ///< \ru Кривая 1. \en Curve 1. - MbCurve3D * curve2; ///< \ru Кривая 2. \en Curve 2. - MbCurve3D * curve3; ///< \ru Кривая 3. \en Curve 3. - - MbCartPoint3D vertex[COVER_COUNT]; ///< \ru Вершины \en Vertices - double t0min; ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. - double t0max; ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. - double t1min; ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. - double t1max; ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. - double t2min; ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. - double t2max; ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. - double t3min; ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. - double t3max; ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. - bool uclosed; ///< \ru Замкнутость поверхности по u. \en Closedness of surface by u. - bool vclosed; ///< \ru Замкнутость поверхности по v. \en Closedness of surface by v. - bool poleUMin; ///< \ru Полюс в начале. \en Pole at the beginning. - bool poleUMax; ///< \ru Полюс в конце. \en Pole at the end. - bool poleVMin; ///< \ru Полюс в начале. \en Pole at the beginning. - bool poleVMax; ///< \ru Полюс в конце. \en Pole at the end. - -public: - /** \brief \ru Конструктор билинейной поверхности. - \en Constructor of bilinear surface. \~ - \details \ru Конструктор билинейной поверхности по набору кривых. - \en Constructor of bilinear surface by set of curves. \~ - \param[in] initCurve0 - \ru Кривая 0. - \en Curve 0. \~ - \param[in] initCurve1 - \ru Кривая 1. - \en Curve 1. \~ - \param[in] initCurve2 - \ru Кривая 2. - \en Curve 2. \~ - \param[in] initCurve3 - \ru Кривая 3. - \en Curve 3. \~ - */ - MbCoverSurface ( const MbCurve3D & initCurve0, const MbCurve3D & initCurve1, - const MbCurve3D & initCurve2, const MbCurve3D & initCurve3 ); -private: - MbCoverSurface( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. - MbCoverSurface( const MbCoverSurface &, MbRegDuplicate * ); -public: - virtual ~MbCoverSurface( void ); - -public: - VISITING_CLASS( MbCoverSurface ); - - /// \ru Инициализация билинейной поверхности заданной билинейной поверхностью. \en Initialization of bilinear surface by given bilinear surface. - void Init( const MbCoverSurface & ); - - /** \ru \name Общие функции геометрического объекта - \en \name Common functions of a geometric object - \{ */ - virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента \en Make a copy of element - virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. - virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal - virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis - - virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object - virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты \en Get the base objects - virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - - /** \} */ - - /** \ru \name Функции описания области определения поверхности - \en \name Functions for surface domain description - \{ */ - virtual double GetUMin() const; - virtual double GetVMin() const; - virtual double GetUMax() const; - virtual double GetVMax() const; - virtual bool IsUClosed() const; // \ru Замкнута ли поверхность по параметру u. \en Whether the surface is closed by parameter u. - virtual bool IsVClosed() const; // \ru Замкнута ли поверхность по параметру v. \en Whether the surface is closed by parameter v. - // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - virtual bool GetPoleUMin() const; - virtual bool GetPoleUMax() const; - virtual bool GetPoleVMin() const; - virtual bool GetPoleVMax() const; - virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special - /** \} */ - - /** \ru \name Функции для работы в области определения поверхности - Функции PointOn, Derive... поверхностей корректируют параметры - при выходе их за пределы прямоугольной области определения параметров.\n - \en \name Functions for working at surface domain - Functions PointOn, Derive... of surfaces correct parameters - when they are out of bounds of rectangular domain of parameters.\n - \{ */ - virtual void PointOn ( double & u, double & v, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface - virtual void DeriveU ( double & u, double & v, MbVector3D & p ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void DeriveV ( double & u, double & v, MbVector3D & p ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void DeriveUU ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void DeriveVV ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void DeriveUV ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void DeriveUUU( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUUV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUVV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void DeriveVVV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void Normal ( double & u, double & v, MbVector3D & p ) const; // \ru Нормаль \en Normal - /** \} */ - - /** \ru \name Функции для работы внутри и вне области определения поверхности - функции _PointOn, _Derive... поверхностей не корректируют - параметры при выходе их за пределы прямоугольной области определения параметров. - \en \name Functions for working inside and outside the surface's domain - functions _PointOn, _Derive... of surfaces don't correct - parameters when they are out of bounds of rectangular domain of parameters. - \{ */ - virtual void _PointOn ( double u, double v, MbCartPoint3D & p ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface - virtual void _DeriveU ( double u, double v, MbVector3D & p ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void _DeriveV ( double u, double v, MbVector3D & p ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void _DeriveUU ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void _DeriveVV ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void _DeriveUV ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void _DeriveUUU( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveUUV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveUVV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveVVV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative - virtual void _Normal ( double u, double v, MbVector3D & p ) const; // \ru Нормаль \en Normal - /** \} */ - - /** \ru \name Функции доступа к группе данных для работы внутри и вне области определения параметров поверхности. - \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. - \{ */ - virtual void Explore( double & u, double & v, bool ext, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const; -/** \} */ - - /** \ru \name Функции движения по поверхности - \en \name Functions of moving along the surface - \{ */ - virtual double StepU( double u, double v, double sag ) const; // \ru Вычисление шага параметра u по по величине прогиба \en Calculation of parameter u step by the value of sag - virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага параметра v по по величине прогиба \en Calculation of parameter v step by the value of sag - virtual double DeviationStepU( double u, double v, double ang ) const; // \ru Вычисление шага параметра u по углу отклонения нормали \en Calculation of parameter u step by the angle of deviation of normal - virtual double DeviationStepV( double u, double v, double ang ) const; // \ru Вычисление шага параметра v по углу отклонения нормали \en Calculation of parameter v step by the angle of deviation of normal - virtual size_t GetUCount() const; - virtual size_t GetVCount() const; - /** \} */ - - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - virtual MbCurve3D * CurveU( double v, MbRect1D * pRgn, bool doApprox = true ) const; // \ru Пространственная копия линии v = const \en Spatial copy of 'v = const'-line - virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool doApprox = true ) const; // \ru Пространственная копия линии u = const \en Spatial copy of 'u = const'-line - - virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier - // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar. - virtual bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; - // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional transformation matrix from own parametric region to parametric region of 'surf'. - virtual bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const; - // \ru Подобные ли поверхности для объединения (слива) \en Whether the surfaces to union (joining) are similar - virtual bool IsSpecialSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; // \ru Специальный случай \en Special case - - virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u \en Get the count of polygons by u - virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v \en Get the count of polygons by v - - /// \ru Получить кривую 0. \en Get curve 0. - const MbCurve3D & GetCurve0() const { return *curve0; } - /// \ru Получить кривую 1. \en Get curve 1. - const MbCurve3D & GetCurve1() const { return *curve1; } - /// \ru Получить кривую 2. \en Get curve 2. - const MbCurve3D & GetCurve2() const { return *curve2; } - /// \ru Получить кривую 3. \en Get curve 3. - const MbCurve3D & GetCurve3() const { return *curve3; } - /// \ru Получить кривую по индексу. \en Get curve by an index. - const MbCurve3D * GetCurve( size_t ind ) const; - /// \ru Получить количество кривых. \en Get count of curves. - size_t GetCurvesCount() const { return 4; } //-V112 - const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. - double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. - double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. - double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. - double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. - double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. - double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. - double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. - double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. - double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. - double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. - - /** \brief \ru Получить образующую кривую по индексу, если она точно совпадает с соответствующим краем поверхности. - \en Get exact curve by index, if it coincides with the corresponding border of the surface. \~ - \details \ru Совпадение кривой с краем поверхности определяется по крайним точкам кривой. - \en Coincidence of the curve with the border of the surface is determined by the end points of the curve. \~ - \param[in] k - \ru Индекс кривой. - \en Index of the curve. \~ - \param[out] sense - \ru Флаг совпадения направленности кривой с рисунком, приведенным выше. - \en Flag that indicates the coincidence of the curve with the picture shown above.\~ - \return - \ru Указатель на кривую или NULL. - \en Pointer to the curve or NULL. \~ - */ - const MbCurve3D * GetExactCurve( size_t k, bool &sense ) const; - - /** \brief \ru Проверка полюсов на кривых. - \en Check poles on curves. \~ - \details \ru Определяет, есть ли полюс на границе области определения по длине кривой, определяющей границу.\n - Результат вычислений можно получить с помощью функций GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax. - \en Determines whether the pole at domain boundary by curve length determining boundary.\n - Result of calculations can be obtained with help of GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax functions. \~ - */ - void CheckPole(); - /** \brief \ru Корректировка параметров. - \en Correct parameters. \~ - \details \ru Загоняет параметры, выходящие за область определения в область определения,\n - если поверхность замкнута по соответствующему параметру или параметр лежит за полюсом. - \en Drives parameters leaving out of domain into domain\n - if the surface is closed by corresponding parameter or parameter lies behind a pole. \~ - */ - inline void CheckParam( double & u, double & v ) const; - -private: - void operator = ( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. - void Init(); - // \ru Определение местных координат. \en Determination of local coordinates. - void CalculateCoordinate( double & u, double & v, bool ext, - double & t0, double & t1, double & t2, double & t3 ) const; - void CalculatePoint ( double & u, double & v, bool ext, MbCartPoint3D * point ) const; - void CalculateFirst ( double & u, double & v, bool ext, MbCartPoint3D * point, MbVector3D * first ) const; - void CalculateSecond( double & u, double & v, bool ext, MbVector3D * second ) const; - void CalculateThird ( double & u, double & v, bool ext, MbVector3D * third ) const; - void CalculateExplore( double & u, double & v, bool ext, - MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoverSurface ) -}; // MbCoverSurface - - -IMPL_PERSISTENT_OPS( MbCoverSurface ) - - -//------------------------------------------------------------------------------ -// \ru Получить кривую по индексу \en Get curve by an index -// --- -inline const MbCurve3D * MbCoverSurface::GetCurve( size_t ind ) const -{ - if ( ind >= COVER_COUNT ) - ind = ind % COVER_COUNT; - switch ( ind ) { - case 0 : { return curve0; } - case 1 : { return curve1; } - case 2 : { return curve2; } - case 3 : { return curve3; } - } - return NULL; -} - - -//------------------------------------------------------------------------------ -// \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. -// --- -inline double MbCoverSurface::GetTMin( size_t ind ) const -{ - if ( ind >= COVER_COUNT ) - ind = ind % COVER_COUNT; - switch ( ind ) { - case 0 : { return t0min; } - case 1 : { return t1min; } - case 2 : { return t2min; } - case 3 : { return t3min; } - } - return UNDEFINED_DBL; -} - - -//------------------------------------------------------------------------------ -// \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. -// --- -inline double MbCoverSurface::GetTMax( size_t ind ) const -{ - if ( ind >= COVER_COUNT ) - ind = ind % COVER_COUNT; - switch ( ind ) { - case 0 : { return t0max; } - case 1 : { return t1max; } - case 2 : { return t2max; } - case 3 : { return t3max; } - } - return UNDEFINED_DBL; -} - - -//------------------------------------------------------------------------------ -// \ru Корректировка параметров \en Correct parameters -// --- -inline void MbCoverSurface::CheckParam( double &u, double &v ) const -{ - double umin = 0; - double umax = 1; - double vmin = 0; - double vmax = 1; - if ( uclosed ) { - if ( (u < umin) || (u > umax ) ) { - double tmp = umax - umin; - u -= ::floor((u - umin) / tmp) * tmp; - } - } - else { - if ( poleUMin && uumax ) - u = umax; - } - if ( vclosed ) { - if ( (v < vmin) || (v > vmax ) ) { - double tmp = vmax - vmin; - v -= ::floor((v - vmin) / tmp) * tmp; - } - } - else { - if ( poleVMin && vvmax ) - v = vmax; - } -} - - -#endif // __SURF_COVER_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Билинейная поверхность на четырех кривых. + \en Bilinear surface on four curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_COVER_SURFACE_H +#define __SURF_COVER_SURFACE_H + + +#include + + +#define COVER_COUNT 4 ///< \ru Число кривых, используемых для построения билинейной поверхности. \en Count of curves used to construct bilinear surface. + + +//------------------------------------------------------------------------------ +/** \brief \ru Четырёхугольная поверхность на кривых. + \en Quadrangular surface on curves. \~ + \details \ru Билинейная поверхность на четырех кривых. \n + Кривые должны попарно пересекаться или иметь точки скрещения. + Если кривые попарно пересекаются, то поверхность проходит через определяющиее её кривые. \n + \en Bilinear surface on four curves. \n + Curves have to be intersected pairwise or have crossing points. + If curves are intersected pairwise then surface passes through its determining curves. \n \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbCoverSurface : public MbSurface { + +// t2min curve2 t2max +// R(u,v) = P3 ______________________ P2 +// (curve0(t0) - P0*(1-u)) *(1-v)+ t3max | | t1max +// (curve1(t1) - P1*(1-v)) * u + | | +// (curve2(t2) - P2* u ) * v + | | +// (curve3(t3) - P3* v ) *(1-u) curve3 | R | curve1 +// t0=t0min*(1-u)+t0max*u | | +// t1=t1min*(1-v)+t1max*v | | +// t2=t2min*(1-u)+t2max*u t3min |______________________| t1min +// t3=t3min*(1-v)+t3max*v P0 P1 +// t0min curve0 t0max + +private: + MbCurve3D * curve0; ///< \ru Кривая 0. \en Curve 0. + MbCurve3D * curve1; ///< \ru Кривая 1. \en Curve 1. + MbCurve3D * curve2; ///< \ru Кривая 2. \en Curve 2. + MbCurve3D * curve3; ///< \ru Кривая 3. \en Curve 3. + + MbCartPoint3D vertex[COVER_COUNT]; ///< \ru Вершины \en Vertices + double t0min; ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. + double t0max; ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. + double t1min; ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. + double t1max; ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. + double t2min; ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. + double t2max; ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. + double t3min; ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. + double t3max; ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. + bool uclosed; ///< \ru Замкнутость поверхности по u. \en Closedness of surface by u. + bool vclosed; ///< \ru Замкнутость поверхности по v. \en Closedness of surface by v. + bool poleUMin; ///< \ru Полюс в начале. \en Pole at the beginning. + bool poleUMax; ///< \ru Полюс в конце. \en Pole at the end. + bool poleVMin; ///< \ru Полюс в начале. \en Pole at the beginning. + bool poleVMax; ///< \ru Полюс в конце. \en Pole at the end. + +public: + /** \brief \ru Конструктор билинейной поверхности. + \en Constructor of bilinear surface. \~ + \details \ru Конструктор билинейной поверхности по набору кривых. + \en Constructor of bilinear surface by set of curves. \~ + \param[in] initCurve0 - \ru Кривая 0. + \en Curve 0. \~ + \param[in] initCurve1 - \ru Кривая 1. + \en Curve 1. \~ + \param[in] initCurve2 - \ru Кривая 2. + \en Curve 2. \~ + \param[in] initCurve3 - \ru Кривая 3. + \en Curve 3. \~ + */ + MbCoverSurface ( const MbCurve3D & initCurve0, const MbCurve3D & initCurve1, + const MbCurve3D & initCurve2, const MbCurve3D & initCurve3 ); +private: + MbCoverSurface( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. + MbCoverSurface( const MbCoverSurface &, MbRegDuplicate * ); +public: + virtual ~MbCoverSurface( void ); + +public: + VISITING_CLASS( MbCoverSurface ); + + /// \ru Инициализация билинейной поверхности заданной билинейной поверхностью. \en Initialization of bilinear surface by given bilinear surface. + void Init( const MbCoverSurface & ); + + /** \ru \name Общие функции геометрического объекта + \en \name Common functions of a geometric object + \{ */ + virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента \en Make a copy of element + virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. + virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal + virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis + + virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object + virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты \en Get the base objects + virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + + /** \} */ + + /** \ru \name Функции описания области определения поверхности + \en \name Functions for surface domain description + \{ */ + virtual double GetUMin() const; + virtual double GetVMin() const; + virtual double GetUMax() const; + virtual double GetVMax() const; + virtual bool IsUClosed() const; // \ru Замкнута ли поверхность по параметру u. \en Whether the surface is closed by parameter u. + virtual bool IsVClosed() const; // \ru Замкнута ли поверхность по параметру v. \en Whether the surface is closed by parameter v. + // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + virtual bool GetPoleUMin() const; + virtual bool GetPoleUMax() const; + virtual bool GetPoleVMin() const; + virtual bool GetPoleVMax() const; + virtual bool IsPole( double u, double v ) const; // \ru Является ли точка особенной \en Whether the point is special + /** \} */ + + /** \ru \name Функции для работы в области определения поверхности + Функции PointOn, Derive... поверхностей корректируют параметры + при выходе их за пределы прямоугольной области определения параметров.\n + \en \name Functions for working at surface domain + Functions PointOn, Derive... of surfaces correct parameters + when they are out of bounds of rectangular domain of parameters.\n + \{ */ + virtual void PointOn ( double & u, double & v, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface + virtual void DeriveU ( double & u, double & v, MbVector3D & p ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void DeriveV ( double & u, double & v, MbVector3D & p ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void DeriveUU ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void DeriveVV ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void DeriveUV ( double & u, double & v, MbVector3D & p ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void DeriveUUU( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUUV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUVV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void DeriveVVV( double & u, double & v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void Normal ( double & u, double & v, MbVector3D & p ) const; // \ru Нормаль \en Normal + /** \} */ + + /** \ru \name Функции для работы внутри и вне области определения поверхности + функции _PointOn, _Derive... поверхностей не корректируют + параметры при выходе их за пределы прямоугольной области определения параметров. + \en \name Functions for working inside and outside the surface's domain + functions _PointOn, _Derive... of surfaces don't correct + parameters when they are out of bounds of rectangular domain of parameters. + \{ */ + virtual void _PointOn ( double u, double v, MbCartPoint3D & p ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface + virtual void _DeriveU ( double u, double v, MbVector3D & p ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void _DeriveV ( double u, double v, MbVector3D & p ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void _DeriveUU ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void _DeriveVV ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void _DeriveUV ( double u, double v, MbVector3D & p ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void _DeriveUUU( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveUUV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveUVV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveVVV( double u, double v, MbVector3D & p ) const; // \ru Третья производная \en Third derivative + virtual void _Normal ( double u, double v, MbVector3D & p ) const; // \ru Нормаль \en Normal + /** \} */ + + /** \ru \name Функции доступа к группе данных для работы внутри и вне области определения параметров поверхности. + \en \name Functions for get of the group of data inside and outside the surface's domain of parameters. + \{ */ + virtual void Explore( double & u, double & v, bool ext, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D * uuDer, MbVector3D * vvDer, MbVector3D * uvDer, MbVector3D * nor ) const; +/** \} */ + + /** \ru \name Функции движения по поверхности + \en \name Functions of moving along the surface + \{ */ + virtual double StepU( double u, double v, double sag ) const; // \ru Вычисление шага параметра u по по величине прогиба \en Calculation of parameter u step by the value of sag + virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага параметра v по по величине прогиба \en Calculation of parameter v step by the value of sag + virtual double DeviationStepU( double u, double v, double ang ) const; // \ru Вычисление шага параметра u по углу отклонения нормали \en Calculation of parameter u step by the angle of deviation of normal + virtual double DeviationStepV( double u, double v, double ang ) const; // \ru Вычисление шага параметра v по углу отклонения нормали \en Calculation of parameter v step by the angle of deviation of normal + virtual size_t GetUCount() const; + virtual size_t GetVCount() const; + /** \} */ + + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + virtual MbCurve3D * CurveU( double v, MbRect1D * pRgn, bool doApprox = true ) const; // \ru Пространственная копия линии v = const \en Spatial copy of 'v = const'-line + virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool doApprox = true ) const; // \ru Пространственная копия линии u = const \en Spatial copy of 'u = const'-line + + virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier + // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces to union (joining) are similar. + virtual bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; + // \ru Дать двумерную матрицу преобразования из своей параметрической области в параметрическую область surf. \en Get two-dimensional transformation matrix from own parametric region to parametric region of 'surf'. + virtual bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const; + // \ru Подобные ли поверхности для объединения (слива) \en Whether the surfaces to union (joining) are similar + virtual bool IsSpecialSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; // \ru Специальный случай \en Special case + + virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u \en Get the count of polygons by u + virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v \en Get the count of polygons by v + + /// \ru Получить кривую 0. \en Get curve 0. + const MbCurve3D & GetCurve0() const { return *curve0; } + /// \ru Получить кривую 1. \en Get curve 1. + const MbCurve3D & GetCurve1() const { return *curve1; } + /// \ru Получить кривую 2. \en Get curve 2. + const MbCurve3D & GetCurve2() const { return *curve2; } + /// \ru Получить кривую 3. \en Get curve 3. + const MbCurve3D & GetCurve3() const { return *curve3; } + /// \ru Получить кривую по индексу. \en Get curve by an index. + const MbCurve3D * GetCurve( size_t ind ) const; + /// \ru Получить количество кривых. \en Get count of curves. + size_t GetCurvesCount() const { return 4; } //-V112 + const MbCartPoint3D * GetVertex() const { return vertex; } ///< \ru Выдать вершины P0, P1, P2. \en Get vertices P0, P1, P2. + double GetT0Min() const { return t0min; } ///< \ru Минимальное значение параметра на кривой 0. \en Minimal value of parameter on curve 0. + double GetT0Max() const { return t0max; } ///< \ru Максимальное значение параметра на кривой 0. \en Maximal value of parameter on curve 0. + double GetT1Min() const { return t1min; } ///< \ru Минимальное значение параметра на кривой 1. \en Minimal value of parameter on curve 1. + double GetT1Max() const { return t1max; } ///< \ru Максимальное значение параметра на кривой 1. \en Maximal value of parameter on curve 1. + double GetT2Min() const { return t2min; } ///< \ru Минимальное значение параметра на кривой 2. \en Minimal value of parameter on curve 2. + double GetT2Max() const { return t2max; } ///< \ru Максимальное значение параметра на кривой 2. \en Maximal value of parameter on curve 2. + double GetT3Min() const { return t3min; } ///< \ru Минимальное значение параметра на кривой 3. \en Minimal value of parameter on curve 3. + double GetT3Max() const { return t3max; } ///< \ru Максимальное значение параметра на кривой 3. \en Maximal value of parameter on curve 3. + double GetTMin( size_t ind ) const; ///< \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. + double GetTMax( size_t ind ) const; ///< \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. + + /** \brief \ru Получить образующую кривую по индексу, если она точно совпадает с соответствующим краем поверхности. + \en Get exact curve by index, if it coincides with the corresponding border of the surface. \~ + \details \ru Совпадение кривой с краем поверхности определяется по крайним точкам кривой. + \en Coincidence of the curve with the border of the surface is determined by the end points of the curve. \~ + \param[in] k - \ru Индекс кривой. + \en Index of the curve. \~ + \param[out] sense - \ru Флаг совпадения направленности кривой с рисунком, приведенным выше. + \en Flag that indicates the coincidence of the curve with the picture shown above.\~ + \return - \ru Указатель на кривую или c3d_null. + \en Pointer to the curve or c3d_null. \~ + */ + const MbCurve3D * GetExactCurve( size_t k, bool &sense ) const; + + /** \brief \ru Проверка полюсов на кривых. + \en Check poles on curves. \~ + \details \ru Определяет, есть ли полюс на границе области определения по длине кривой, определяющей границу.\n + Результат вычислений можно получить с помощью функций GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax. + \en Determines whether the pole at domain boundary by curve length determining boundary.\n + Result of calculations can be obtained with help of GetPoleUMin, GetPoleUMax, GetPoleVMin, GetPoleVMax functions. \~ + */ + void CheckPole(); + /** \brief \ru Корректировка параметров. + \en Correct parameters. \~ + \details \ru Загоняет параметры, выходящие за область определения в область определения,\n + если поверхность замкнута по соответствующему параметру или параметр лежит за полюсом. + \en Drives parameters leaving out of domain into domain\n + if the surface is closed by corresponding parameter or parameter lies behind a pole. \~ + */ + inline void CheckParam( double & u, double & v ) const; + +private: + void operator = ( const MbCoverSurface & ); // \ru Не реализовано. \en Not implemented. + void Init(); + // \ru Определение местных координат. \en Determination of local coordinates. + void CalculateCoordinate( double & u, double & v, bool ext, + double & t0, double & t1, double & t2, double & t3 ) const; + void CalculatePoint ( double & u, double & v, bool ext, MbCartPoint3D * point ) const; + void CalculateFirst ( double & u, double & v, bool ext, MbCartPoint3D * point, MbVector3D * first ) const; + void CalculateSecond( double & u, double & v, bool ext, MbVector3D * second ) const; + void CalculateThird ( double & u, double & v, bool ext, MbVector3D * third ) const; + void CalculateExplore( double & u, double & v, bool ext, + MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoverSurface ) +}; // MbCoverSurface + + +IMPL_PERSISTENT_OPS( MbCoverSurface ) + + +//------------------------------------------------------------------------------ +// \ru Получить кривую по индексу \en Get curve by an index +// --- +inline const MbCurve3D * MbCoverSurface::GetCurve( size_t ind ) const +{ + if ( ind >= COVER_COUNT ) + ind = ind % COVER_COUNT; + switch ( ind ) { + case 0 : { return curve0; } + case 1 : { return curve1; } + case 2 : { return curve2; } + case 3 : { return curve3; } + } + return c3d_null; +} + + +//------------------------------------------------------------------------------ +// \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. +// --- +inline double MbCoverSurface::GetTMin( size_t ind ) const +{ + if ( ind >= COVER_COUNT ) + ind = ind % COVER_COUNT; + switch ( ind ) { + case 0 : { return t0min; } + case 1 : { return t1min; } + case 2 : { return t2min; } + case 3 : { return t3min; } + } + return UNDEFINED_DBL; +} + + +//------------------------------------------------------------------------------ +// \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. +// --- +inline double MbCoverSurface::GetTMax( size_t ind ) const +{ + if ( ind >= COVER_COUNT ) + ind = ind % COVER_COUNT; + switch ( ind ) { + case 0 : { return t0max; } + case 1 : { return t1max; } + case 2 : { return t2max; } + case 3 : { return t3max; } + } + return UNDEFINED_DBL; +} + + +//------------------------------------------------------------------------------ +// \ru Корректировка параметров \en Correct parameters +// --- +inline void MbCoverSurface::CheckParam( double &u, double &v ) const +{ + double umin = 0; + double umax = 1; + double vmin = 0; + double vmax = 1; + if ( uclosed ) { + if ( (u < umin) || (u > umax ) ) { + double tmp = umax - umin; + u -= ::floor((u - umin) / tmp) * tmp; + } + } + else { + if ( poleUMin && uumax ) + u = umax; + } + if ( vclosed ) { + if ( (v < vmin) || (v > vmax ) ) { + double tmp = vmax - vmin; + v -= ::floor((v - vmin) / tmp) * tmp; + } + } + else { + if ( poleVMin && vvmax ) + v = vmax; + } +} + + +#endif // __SURF_COVER_SURFACE_H diff --git a/C3d/Include/surf_curve_bounded_surface.h b/C3d/Include/surf_curve_bounded_surface.h index 2b7bb35..69bd3a8 100644 --- a/C3d/Include/surf_curve_bounded_surface.h +++ b/C3d/Include/surf_curve_bounded_surface.h @@ -120,7 +120,7 @@ public : /// \ru Конструктор для поверхности c габаритом при чтении грани. \en Constructor for surface with bounding box at face reading. MbCurveBoundedSurface( MbSurface & initSurface, c3d::PlaneContoursSPtrVector & initCurves, MbCube & gab ); /// \ru Конструктор по контурам, берет за базовую поверхность поверхность первого контура. \en Constructor by contours, uses the surface of first contour as base surface. - MbCurveBoundedSurface( MbContourOnSurface & init1, MbContourOnSurface * init2 = NULL ); + MbCurveBoundedSurface( MbContourOnSurface & init1, MbContourOnSurface * init2 = c3d_null ); /// \ru Конструктор-копия на новую базовую поверхность. \en Copy-constructor for new base surface. MbCurveBoundedSurface( const MbCurveBoundedSurface & init, MbSurface & newBaseSurface, bool calculateGabarit = true ); @@ -141,13 +141,13 @@ public : \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. @@ -269,7 +269,7 @@ public : virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии v. \en Curvature of v-line. virtual bool IsSameBase( const MbSurface & ) const; // \ru Является ли базовая поверхность копией базовой поверхности данного объекта. \en Whether the base surface is a duplicate of base surface of current object. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual double GetFilletRadius( const MbCartPoint3D & ) const; // \ru Является ли поверхность скруглением. \en Whether the surface is fillet. virtual MbeParamDir GetFilletDirection() const; // \ru Направление поверхности скругления. \en Direction of fillet surface. @@ -306,9 +306,9 @@ public : size_t SegmentIntersection( const MbCurve & pCurve, SArray & curveParams, double epsilon = Math::metricEpsilon ) const; // \ru Найти ближайшую проекцию точки на поверхность. \en Find the nearest projection of a point onto the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Вce точки пересечения поверхности и кривой. \en All the points of intersection of a surface and a curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -500,7 +500,7 @@ public : \details \ru Дать контур, ограничивающий поверхность, по его индексу. С проверкой индекса. \en Get contour bounding surface by its index. With index checking. \~ */ - const MbContourOnSurface * GetCurve ( size_t ind ) const { return ( ind < curves.Count() ) ? curves[ind] : NULL; } + const MbContourOnSurface * GetCurve ( size_t ind ) const { return ( ind < curves.Count() ) ? curves[ind] : c3d_null; } /** \brief \ru Дать контур, ограничивающий поверхность, по его индексу. \en Get contour bounding surface by its index. \~ \details \ru Дать контур, ограничивающий поверхность, по его индексу. Без проверки индекса. @@ -514,7 +514,7 @@ public : \details \ru Дать контур, ограничивающий поверхность, по его индексу. С проверкой индекса. \en Get contour bounding surface by its index. With index checking. \~ */ - MbContourOnSurface * SetCurve ( size_t ind ) { return ( ind < curves.Count() ) ? curves[ind] : NULL; } + MbContourOnSurface * SetCurve ( size_t ind ) { return ( ind < curves.Count() ) ? curves[ind] : c3d_null; } /** \brief \ru Дать контур, ограничивающий поверхность, по его индексу. \en Get contour bounding surface by its index. \~ \details \ru Дать контур, ограничивающий поверхность, по его индексу. Без проверки индекса. @@ -530,9 +530,9 @@ public : /// \ru Слить двумерные сегменты в контурах. \en Merge two-dimensional segments in contours. void MergeSegments( double eps = Math::LengthEps ); /// \ru Копия объекта со старой базовой поверхностью. \en Copy of object with old base surface. - MbCurveBoundedSurface & CurvesDuplicate() const; + MbCurveBoundedSurface & CurvesDuplicate() const { return *new MbCurveBoundedSurface( this ); } /// \ru Проверить на замкнутость по u или v по внешнему контуру. \en Check closeness by u or v using outer contour. - bool CheckTouchByContour( bool byU ) const; + bool CheckTouchByContour( bool byU ) const; /** \} */ protected: diff --git a/C3d/Include/surf_cylinder_surface.h b/C3d/Include/surf_cylinder_surface.h index a77edfb..af8a112 100644 --- a/C3d/Include/surf_cylinder_surface.h +++ b/C3d/Include/surf_cylinder_surface.h @@ -151,10 +151,10 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -254,7 +254,7 @@ public: virtual MbCurve3D * CurveUV( const MbLineSegment &, bool bApprox = true ) const; // \ru Пространственная копия линии по параметрической линии. \en Spatial copy of line by parametric line. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Пересечение с кривой. \en Intersection with curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -316,7 +316,7 @@ public: /** \ru \name Функции элементарных поверхностей \en \name Functions of elementary surfaces \{ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \} */ /** \ru \name Функции цилиндрической поверхности \en \name Functions of the cylindrical surface diff --git a/C3d/Include/surf_elementary_surface.h b/C3d/Include/surf_elementary_surface.h index a5fe3df..ba593e9 100644 --- a/C3d/Include/surf_elementary_surface.h +++ b/C3d/Include/surf_elementary_surface.h @@ -59,12 +59,12 @@ public: \{ */ virtual MbeSpaceType IsA () const = 0; // \ru Тип элемента. \en A type of element. virtual MbeSpaceType Type() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D & to, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D & to, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & to ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void GetProperties( MbProperties & properties ) = 0; // \ru Выдать свойства объекта. \en Get properties of the object. @@ -140,7 +140,7 @@ public: // \ru Ближайшая проекция точки на поверхность \en Nearest point projection onto the surface virtual MbeNewtonResult PointProjectionNewton( const MbCartPoint3D & p, size_t iterLimit, double & u, double & v, bool ext ) const; // \ru Функция для нахождения проекции точки на поверхность. \en Function for searching the point projection onto the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. virtual bool IsRectangular() const; // \ru Если true производные по u и v ортогональны. \en If true, then derivatives by u and v are orthogonal. virtual void SetLimit( double u1, double v1, double u2, double v2 ) = 0; @@ -168,7 +168,7 @@ public: \return \ru true в случае успеха операции \en True if the operation succeeded \~ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const = 0; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const = 0; // Дать приращение параметра u и параметра v, соответствующее единичной длине в пространстве. \en Get increment of parameters, corresponding to the unit length in space. virtual void GetParamsToUnit( double u, double v, double & uParam, double & vParam ) const; diff --git a/C3d/Include/surf_elevation_surface.h b/C3d/Include/surf_elevation_surface.h index 0f40d94..df975a1 100644 --- a/C3d/Include/surf_elevation_surface.h +++ b/C3d/Include/surf_elevation_surface.h @@ -38,7 +38,7 @@ const VERSION ELEVATION_SURFACE_VERSION1 = 0x0F001003L; ///< \ru Расчёт т // --- class MATH_CLASS MbElevationSurface : public MbLoftedSurface { private: - MbCurve3D * spine; ///< \ru Направляющая кривая (не NULL). \en Guide curve (not NULL). + MbCurve3D * spine; ///< \ru Направляющая кривая (не c3d_null). \en Guide curve (not c3d_null). RPArray mSpines; ///< \ru Множество указателей на направляющие кривые (на основе spine). \en Set of pointers to guide curves (based on 'spine'). bool isSimToEvol; ///< \ru Способ расчёта точек на поверхности. \en Way of calculating of points on the surface. @@ -102,13 +102,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты \en Whether the objects are equal virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void Refresh (); virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -193,7 +193,7 @@ public: virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v \en Get the count of polygons by v /// \ru Вернуть направляющую кривую. \en Return spine (guide) curve. - const MbCurve3D & GetSpineCurve() const { C3D_ASSERT( spine != NULL ); return *spine; } + const MbCurve3D & GetSpineCurve() const { C3D_ASSERT( spine != c3d_null ); return *spine; } /// \ru Вернуть направляющую кривую. \en Return spine (guide) curve. bool IsSimilarToEvolution() const { return isSimToEvol; } @@ -315,8 +315,8 @@ inline void MbElevationSurface::CheckParam( double & u, double & v, bool ext ) c \en Center of mass of profile curve. \~ \param[in,out] ct - \ru Искомый параметр. \en Required parameter. \~ - \param[in,out] tau - \ru Производная направляющей в точке с координатой ct. Если в функцию передать NULL, производная не вычисляется. - \en Derivative of guide curve at point with 'ct' coordinate. If giving NULL to function, then derivative isn't calculated. \~ + \param[in,out] tau - \ru Производная направляющей в точке с координатой ct. Если в функцию передать c3d_null, производная не вычисляется. + \en Derivative of guide curve at point with 'ct' coordinate. If giving c3d_null to function, then derivative isn't calculated. \~ \return \ru true - если направляющая пересекается с плоскостью профиля, false - если не пересекается. \en True - if guide curve intersects with plane of profile, false - if not intersects. \~ \ingroup Algorithms_3D @@ -341,8 +341,8 @@ bool CreateElevationParam( const MbCurve3D & crvThis, const MbCurve3D & spine, \en The spine (guide) curve. \~ \param[in,out] vParams - \ru Множество параметров. \en Set of parameters. \~ - \param[in,out] tiePnts - \ru Множество центров масс профильных кривых. Не заполняется, если в функцию передать NULL. - \en Set of centers of mass of profile curves. If giving NULL to function, then it isn't filled. \~ + \param[in,out] tiePnts - \ru Множество центров масс профильных кривых. Не заполняется, если в функцию передать c3d_null. + \en Set of centers of mass of profile curves. If giving c3d_null to function, then it isn't filled. \~ \return \ru true - если массив параметров успешно создан. \en True - if the array of parameters successfully created. \~ \ingroup Algorithms_3D diff --git a/C3d/Include/surf_evolution_surface.h b/C3d/Include/surf_evolution_surface.h index fdf1022..858c429 100644 --- a/C3d/Include/surf_evolution_surface.h +++ b/C3d/Include/surf_evolution_surface.h @@ -140,13 +140,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar ( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -216,7 +216,7 @@ public: \en \name Common functions of surface \{ */ virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line by u. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. diff --git a/C3d/Include/surf_exaction_surface.h b/C3d/Include/surf_exaction_surface.h index 484349c..257f5cb 100644 --- a/C3d/Include/surf_exaction_surface.h +++ b/C3d/Include/surf_exaction_surface.h @@ -96,13 +96,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равными. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -153,7 +153,7 @@ public: /** \ru \name Общие функции поверхности \en \name Common functions of surface \{ */ - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru NURBS копия поверхности. \en NURBS copy of a surface. virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Create an offset surface. diff --git a/C3d/Include/surf_expansion_surface.h b/C3d/Include/surf_expansion_surface.h index 199e813..35990db 100644 --- a/C3d/Include/surf_expansion_surface.h +++ b/C3d/Include/surf_expansion_surface.h @@ -38,7 +38,7 @@ class MATH_CLASS MbExpansionSurface : public MbSweptSurface { private: MbCurve3D * spine; ///< \ru Направляющая кривая. \en Spine (guide) curve. - MbCurve3D * brink; ///< \ru Вторая образующая кривая (первой является curve, может быть NULL). \en The second generating curve ('curve' is first one, may be NULL). + MbCurve3D * brink; ///< \ru Вторая образующая кривая (первой является curve, может быть c3d_null). \en The second generating curve ('curve' is first one, may be c3d_null). double tmin; ///< \ru Начальный параметр brink. \en Start parameter of 'brink'. double dt; ///< \ru Производная параметра кривой brink по параметру u (dt * (u - umin) = t_brink - tmin_brink). \en Derivative of parameter of 'brink' curve by u parameter (dt * (u - umin) = t_brink - tmin_brink). MbCartPoint3D origin; ///< \ru Начало образующей. \en Begin of gravity of generating curve. @@ -62,7 +62,7 @@ public: \en Second generating curve \~ */ MbExpansionSurface( const MbCurve3D & cr, const MbCurve3D & sp, bool sameCurve, bool sameSpine, - MbCurve3D * sl = NULL ); + MbCurve3D * sl = c3d_null ); /** \brief \ru Конструктор по точке, образующей и направляющей. \en Constructor by point, generating curve and guide curve. \~ @@ -101,13 +101,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -174,7 +174,7 @@ public: \{ */ virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line by u. virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии по v. \en Curvature of line by v. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. @@ -248,7 +248,7 @@ IMPL_PERSISTENT_OPS( MbExpansionSurface ) // --- inline double MbExpansionSurface::BrinkParameterFrom( const double & u ) const { double t = u; - if ( brink != NULL ) + if ( brink != c3d_null ) t = tmin + (u - umin) * dt; return t; } @@ -259,7 +259,7 @@ inline double MbExpansionSurface::BrinkParameterFrom( const double & u ) const { // --- inline double MbExpansionSurface::BrinkParameterInto( const double & t ) const { double u = t; - if ( brink != NULL ) { + if ( brink != c3d_null ) { double du = (::fabs(dt) > EXTENT_EQUAL) ? 1.0 / dt : 1.0; u = umin + (t - tmin) * du; } diff --git a/C3d/Include/surf_exploration_surface.h b/C3d/Include/surf_exploration_surface.h index a102f9e..404c8b1 100644 --- a/C3d/Include/surf_exploration_surface.h +++ b/C3d/Include/surf_exploration_surface.h @@ -75,13 +75,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar ( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -163,16 +163,16 @@ public: \en Create an evolution surface. \~ \details \ru Создать кинематическую поверхность. \en Create an evolution surface. \~ - \param[in] curve - \ru Образующая кривая - \en Generating curve \~ - \param[in] spine - \ru Направляющая кривая - \en Guide curve \~ - \param[in] samec - \ru Признак использования оригинала образующей кривой, а не копии - \en Attribute of usage of original of generating curve, not a copy \~ - \param[in] sFunc - \ru Функция масштабирования образующей кривой. - \en The function of curve scaling. \~ - \param[in] rFunc - \ru Функция вращения образующей кривой. - \en The function of curve rotation. \~ + \param[in] curve - \ru Образующая кривая. + \en Generating curve. \~ + \param[in] spine - \ru Направляющая кривая. + \en Guide curve. \~ + \param[in] samec - \ru Признак использования оригинала образующей кривой, а не копии. + \en Attribute of usage of original of generating curve, not a copy. \~ + \param[in] _scaling - \ru Функция масштабирования образующей кривой. + \en The function of curve scaling. \~ + \param[in] _winding - \ru Функция вращения образующей кривой. + \en The function of curve rotation. \~ \return \ru Возвращает созданную поверхность. \en Return the created surface. \~ \ingroup Surface_Modeling diff --git a/C3d/Include/surf_extrusion_surface.h b/C3d/Include/surf_extrusion_surface.h index 89f83fa..7030984 100644 --- a/C3d/Include/surf_extrusion_surface.h +++ b/C3d/Include/surf_extrusion_surface.h @@ -76,13 +76,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -150,7 +150,7 @@ public: virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line by u. virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии v. \en Curvature of v-line. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru NURBS копия поверхности. \en NURBS copy of a surface. @@ -163,7 +163,7 @@ public: virtual ThreeStates Salient() const; // \ru Выпуклая ли поверхность. \en Whether a surface is convex. // \ru Проекция точки на поверхность. \en The point projection onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. + virtual bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. // \ru Пересечение с кривой. \en Intersection with curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; diff --git a/C3d/Include/surf_fillet_surface.h b/C3d/Include/surf_fillet_surface.h index 9b0e375..444352b 100644 --- a/C3d/Include/surf_fillet_surface.h +++ b/C3d/Include/surf_fillet_surface.h @@ -46,7 +46,7 @@ class MATH_CLASS MbFunction; */// --- class MATH_CLASS MbFilletSurface : public MbSmoothSurface { protected: - MbCurve3D * curve0; ///< \ru Кривая пересечения касательных к поверхностям - всегда не NULL. \en Intersection curve of tangents to surfaces - always not NULL. + MbCurve3D * curve0; ///< \ru Кривая пересечения касательных к поверхностям - всегда не c3d_null. \en Intersection curve of tangents to surfaces - always not c3d_null. MbFunction * weights0; ///< \ru Функция веса точек средней кривой curve0. \en Function of weight of points of curve0 mid-curve. double conic; ///< \ru Коэффициент формы, изменяется от 0.05 до 0.95, определяет вес точек кривой curve0. \en Coefficient of shape is changed between 0.05 and 0.95 and determines weight of points of curve0 curve. bool even; ///< \ru Равномерная параметризация по дуге или нет. \en Whether arc length parameterization is uniform or not. @@ -181,13 +181,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties &properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -284,7 +284,7 @@ public: // \ru Проекции точки на поверхность. \en The point projections onto the surface. virtual MbeNewtonResult PointProjectionNewton( const MbCartPoint3D & p, size_t iterLimit, double & u, double & v, bool ext ) const; // \ru Функция для нахождения проекции точки на поверхность. \en Function for searching the point projection onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. + virtual bool NearPointProjection ( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. virtual double GetFilletRadius( const MbCartPoint3D & p ) const; // \ru Является ли поверхность скруглением. \en Whether the surface is fillet. virtual double GetFilletRadius( double u ) const; // \ru Дать радиус скругления по первому параметру. \en Get fillet radius if the surface is fillet. diff --git a/C3d/Include/surf_gregory_surface.h b/C3d/Include/surf_gregory_surface.h index c96e3d8..388eddb 100644 --- a/C3d/Include/surf_gregory_surface.h +++ b/C3d/Include/surf_gregory_surface.h @@ -52,7 +52,7 @@ public: \param[in] initContour - \ru Контур. \en The contour. \~ */ - MbGregorySurface( const MbContour3D & initContour, const SArray * conj = NULL ); + MbGregorySurface( const MbContour3D & initContour, const SArray * conj = c3d_null ); protected: /// \ru Конструктор-копия. \en Copy constructor. MbGregorySurface( const MbGregorySurface &, MbRegDuplicate * ); @@ -66,13 +66,13 @@ public: \en \name Common functions of a geometric object. \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Make a copy of element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Make a copy of element. virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными. \en Whether the objects are similar. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix + virtual void Move( const MbVector3D &to, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation + virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis virtual void Refresh(); // \ru Сбросить все временные данные. \en Flush all the temporary data. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. diff --git a/C3d/Include/surf_grid_surface.h b/C3d/Include/surf_grid_surface.h index c656a89..70146be 100644 --- a/C3d/Include/surf_grid_surface.h +++ b/C3d/Include/surf_grid_surface.h @@ -193,13 +193,13 @@ public: \{ */ // \ru Общие функции геометрического объекта \en Common functions of a geometric object virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента \en Make a copy of element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента \en Make a copy of element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; virtual bool SetEqual( const MbSpaceItem &init ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem &init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -280,9 +280,9 @@ public: virtual size_t CurveClassification( const MbCurve & curve, SArray & tcurv, SArray & dir ) const; // \ru Найти ближайшую проекцию точки на поверхность. \en Find the nearest projection of a point onto the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Вce точки пересечения поверхности и кривой. \en All the points of intersection of a surface and a curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -341,7 +341,7 @@ public: , const Triangles & _triangles , const Bounds & _bounds ) { - MbGridSurface * surface = NULL; + MbGridSurface * surface = c3d_null; const size_t itemsCnt = _params.size(); diff --git a/C3d/Include/surf_join_surface.h b/C3d/Include/surf_join_surface.h index f8cae00..6cec37f 100644 --- a/C3d/Include/surf_join_surface.h +++ b/C3d/Include/surf_join_surface.h @@ -219,12 +219,12 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными \en Determine whether objects are equal virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта \en Set properties of the object diff --git a/C3d/Include/surf_lofted_surface.h b/C3d/Include/surf_lofted_surface.h index c088578..9bbfa06 100644 --- a/C3d/Include/surf_lofted_surface.h +++ b/C3d/Include/surf_lofted_surface.h @@ -198,13 +198,13 @@ public: \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element virtual MbeSpaceType Type() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента \en Create a copy of the element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента \en Create a copy of the element virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты \en Whether the objects are equal virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void Refresh(); virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -291,7 +291,7 @@ public: /** \ru \name Общие функции поверхности \en \name Common functions of surface \{ */ - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской \en Whether the surface is planar + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской \en Whether the surface is planar virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier virtual void CalculateGabarit( MbCube & ) const; // \ru Рассчитать габарит поверхности \en Calculate bounding box of surface @@ -318,9 +318,9 @@ public: SArray & uu, SArray & vv ) const; // \ru Найти ближайшую проекцию точки на поверхность или ее продолжение по заданному начальному приближению. \en Find the neares projection of a point onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; virtual bool IsLineU() const; // \ru Если true все производные по U выше первой равны нулю \en If true, then all the derivatives by U higher the first one are equal to zero virtual bool IsLineV() const; // \ru Если true все производные по V выше первой равны нулю \en If true, then all the derivatives by V higher the first one are equal to zero @@ -346,7 +346,7 @@ public: \return \ru Константная кривая. \en The constant curve. \~ */ - const MbCurve3D * GetCurve( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } + const MbCurve3D * GetCurve( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : c3d_null; } /** \brief \ru Получить кривую для редактирования по номеру. \en Get curve for editing by an index. \~ \details \ru Получить кривую для редактирования по номеру. \n @@ -356,7 +356,7 @@ public: \return \ru Кривая. \en A curve. \~ */ - MbCurve3D * SetCurve( ptrdiff_t ind ) { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } + MbCurve3D * SetCurve( ptrdiff_t ind ) { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : c3d_null; } /** \brief \ru Получить параметр по номеру. \en Get parameter by an index. \~ \details \ru Получить параметр по номеру.\n @@ -687,8 +687,8 @@ inline void MbLoftedSurface::ParamThird( double t1, double t2, double * tLoft ) \en Whether the surface is closed by parameter v. \~ \param[in,out] vParams - \ru Множество параметров. \en Set of parameters. \~ - \param[in,out] tiePnts - \ru Множество центров масс профильных кривых. Не заполняется, если в функцию передать NULL. - \en Set of centers of mass of profile curves. If giving NULL to function, then it isn't filled. \~ + \param[in,out] tiePnts - \ru Множество центров масс профильных кривых. Не заполняется, если в функцию передать c3d_null. + \en Set of centers of mass of profile curves. If giving c3d_null to function, then it isn't filled. \~ \param[in] version - \ru Версия. \en Version. \~ \return \ru true - если массив параметров успешно создан. diff --git a/C3d/Include/surf_mesh_surface.h b/C3d/Include/surf_mesh_surface.h index 641434c..cf6701a 100644 --- a/C3d/Include/surf_mesh_surface.h +++ b/C3d/Include/surf_mesh_surface.h @@ -191,7 +191,7 @@ public: */ MbMeshSurface( RPArray & initU, RPArray & initV, bool uClosed, bool vClosed, - bool same, const SArray * types = NULL, + bool same, const SArray * types = c3d_null, MbeMeshSurfaceVersion vers = msv_Ver3 ); /** \brief \ru Конструктор поверхности. \en Constructor of surface. \~ @@ -225,7 +225,7 @@ public: MbMeshSurface( RPArray & initU, RPArray & initV, SArray & parsU, SArray & parsV, bool uClosed, bool vClosed, - bool same, const SArray * types = NULL, + bool same, const SArray * types = c3d_null, MbeMeshSurfaceVersion vers = msv_Ver3 ); private: @@ -279,13 +279,13 @@ public: \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element virtual MbeSpaceType Type() const; // \ru Групповой тип элемента. \en Group element type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента \en Make a copy of element + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента \en Make a copy of element virtual bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal virtual bool IsSimilar( const MbSpaceItem & init ) const; // \ru Являются ли объекты подобными \en Whether the objects are similar - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move( const MbVector3D &to, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate around an axis + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move( const MbVector3D &to, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate( const MbAxis3D &axis, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate around an axis virtual void Refresh(); // \ru Сбросить все временные данные \en Flush all the temporary data virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта \en Get properties of the object @@ -390,9 +390,9 @@ public: virtual bool IsLineV() const; // \ru Если true все производные по V выше первой равны нулю \en If true, then all the derivatives by V higher the first one are equal to zero // \ru Найти ближайшую проекцию точки на поверхность или ее продолжение по заданному начальному приближению. \en Find the neares projection of a point onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; virtual MbCurve3D * CurveU( double v, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии v = const. \en Spatial copy of 'v = const'-line. virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии u = const. \en Spatial copy of 'u = const'-line. @@ -420,20 +420,20 @@ public: \en Get curve with 'ind' index from first family. \n \~ \param[in] ind - \ru Номер запрашиваемой кривой в массиве. \en Index of required curve in array. \~ - \return \ru Кривая или NULL, если значение ind выходит за диапазон возможных индексов массиве кривых. - \en Curve or NULL if value of 'ind' is out of range of possible indices of array of curves. \~ + \return \ru Кривая или c3d_null, если значение ind выходит за диапазон возможных индексов массиве кривых. + \en Curve or c3d_null if value of 'ind' is out of range of possible indices of array of curves. \~ */ - const MbCurve3D * GetUCurve( size_t ind ) const { return ( ind < uCurves.Count()) ? uCurves[ind] : NULL; } + const MbCurve3D * GetUCurve( size_t ind ) const { return ( ind < uCurves.Count()) ? uCurves[ind] : c3d_null; } /** \brief \ru Получить кривую с индексом ind из второго семейства. \en Get curve with 'ind' index from second family. \~ \details \ru Получить кривую с индексом ind из второго семейства. \n \en Get curve with 'ind' index from second family. \n \~ \param[in] ind - \ru Номер запрашиваемой кривой в массиве. \en Index of required curve in array. \~ - \return \ru Кривая или NULL, если значение ind выходит за диапазон возможных индексов массиве кривых. - \en Curve or NULL if value of 'ind' is out of range of possible indices of array of curves. \~ + \return \ru Кривая или c3d_null, если значение ind выходит за диапазон возможных индексов массиве кривых. + \en Curve or c3d_null if value of 'ind' is out of range of possible indices of array of curves. \~ */ - const MbCurve3D * GetVCurve( size_t ind ) const { return ( ind < vCurves.Count()) ? vCurves[ind] : NULL; } + const MbCurve3D * GetVCurve( size_t ind ) const { return ( ind < vCurves.Count()) ? vCurves[ind] : c3d_null; } /** \brief \ru Получить значение параметра, соответствующего кривой с индексом ind из первого семейства. \en Get value of parameter corresponding to curve with 'ind' index from first family. \~ \details \ru Получить значение параметра, соответствующего кривой с индексом ind из первого семейства.\n @@ -522,7 +522,7 @@ private: void PointOn( double & u, double & v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface // \ru Определить местные координаты области поверхности. \en Determine local coordinates of surface region. - void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i0,size_t & j0,size_t & i1, size_t & j1, MbMeshSurfaceAuxiliaryData * ucache = NULL ) const; + void LocalCoordinate( double u, double v, double & ul, double & vl, size_t & i0,size_t & j0,size_t & i1, size_t & j1, MbMeshSurfaceAuxiliaryData * ucache = c3d_null ) const; void LocalCoordinate_v2( double u, double v, double & ul, double & vl, size_t & i0, size_t & j0, size_t & i1, size_t & j1, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Вычислить вспомогательные вектора производных вдоль U кривых патча. \en Calculate auxiliary vectors of derivatives along U curves of patch. void CalculateAlongU( const double & ul, const size_t & j0, const size_t & j1, MbMeshSurfaceAuxiliaryData * ucache ) const; @@ -675,7 +675,7 @@ private: void GeneratrixCurveExplore_v3( bool dirU, size_t ind, double t, MbCartPoint3D & p, MbVector3D & fir, MbVector3D & sec, MbVector3D & thir ) const; // \ru Инициализировать массивы расширения. \en Init expansion arrays. - void InitExtArrays( const bool (*adjPatch)[4] = NULL ); + void InitExtArrays( const bool (*adjPatch)[4] = c3d_null ); /** \} */ diff --git a/C3d/Include/surf_offset_surface.h b/C3d/Include/surf_offset_surface.h index b784f34..831f2de 100644 --- a/C3d/Include/surf_offset_surface.h +++ b/C3d/Include/surf_offset_surface.h @@ -44,7 +44,7 @@ class MATH_CLASS MbSurfaceContiguousData; // --- class MATH_CLASS MbOffsetSurface : public MbSurface { private: - MbSurface * basisSurface; ///< \ru Базовая поверхность (всегда не NULL). \en Base surface (always not NULL). + MbSurface * basisSurface; ///< \ru Базовая поверхность (всегда не c3d_null). \en Base surface (always not c3d_null). double u0min; ///< \ru Минимальный параметр u базовой поверхности. \en Minimal parameter u of the base surface. double u0max; ///< \ru Максимальный параметр u базовой поверхности. \en Maximal parameter u of the base surface. double v0min; ///< \ru Минимальный параметр v базовой поверхности. \en Minimal parameter v of the base surface. @@ -197,14 +197,14 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли объект копией. \en Whether the object is a copy. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void Refresh(); // \ru Сбросить все временные данные \en Flush all the temporary data virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. @@ -303,7 +303,7 @@ public: virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии u. \en Curvature of u-line. virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии v. \en Curvature of v-line. // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Изменение носителя. \en Changing of carrier. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носимых элементов. \en Change a carrier elements. @@ -338,7 +338,7 @@ public: virtual bool IsLineV () const; // \ru Если true все производные по V выше первой равны нулю. \en If true, then all the derivatives by V higher the first one are equal to zero. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \brief \ru Проверить параметры. Аналог глобальной функции _CheckParams, оптимизированный под использование кэшей. \en Check parameters. Analogue of the global function _CheckParams, optimized for caches usage. \~ diff --git a/C3d/Include/surf_plane.h b/C3d/Include/surf_plane.h index e8642bb..a9a6973 100644 --- a/C3d/Include/surf_plane.h +++ b/C3d/Include/surf_plane.h @@ -209,8 +209,8 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равными. \en Make equal. @@ -304,7 +304,7 @@ public: virtual double CurvatureU ( double u, double v ) const; // \ru Кривизна линии u. \en Curvature of the line u. virtual double CurvatureV ( double u, double v ) const; // \ru Кривизна линии v. \en Curvature of the line v. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской \en Whether a surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской \en Whether a surface is planar. virtual MbSplineSurface * NurbsSurface( double u1, double u2, double v1, double v2, bool bmatch = false ) const; // \ru NURBS копия поверхности \en NURBS copy of surface. virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; @@ -322,10 +322,10 @@ public: virtual MbeItemLocation PointRelative ( const MbCartPoint3D & pnt, double eps = ANGLE_REGION ) const; virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & v, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & v, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность в направлении вектора. \en The nearest projection of a point to the surface in direction of the vector. virtual bool NearDirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vector, - double & u, double & v, bool ext, MbRect2D * uvRange = NULL, bool onlyPositiveDirection = false ) const; + double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null, bool onlyPositiveDirection = false ) const; // \ru Пересечения с кривой. \en Intersection with a curve. virtual MbeNewtonResult CurveIntersectNewton( const MbCurve3D &, double funcEpsilon, size_t limit, double & u, double & v, double & t, bool ext0, bool ext ) const; // \ru Нахождениe точки пересечения c кривой. \en Search of a point of intersection with curve. @@ -371,7 +371,7 @@ public: /** \ru \name Функции элементарных поверхностей \en \name Functions of elementary surfaces. \{ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \} */ /** \ru \name Функции плоскости \en \name Functions of plane. @@ -418,7 +418,7 @@ public: /// \ru Матрица для преобразования симметрии относительно плоскости. \en The matrix of symmetry transformation relative to the plane void Symmetry ( MbMatrix3D & m ) const { position.Symmetry(m); } /// \ru Инвертировать нормаль плоскости. \en Invert the normal of plane. - void Invert( MbMatrix * = NULL, MbRegTransform * ireg = NULL ); + void Invert( MbMatrix * = c3d_null, MbRegTransform * ireg = c3d_null ); /// \ru Сделать систему координат правой. \en Make the coordinate system right. void SetRightPlacement() { position.SetRight(); SetDirtyGabarit(); } diff --git a/C3d/Include/surf_polysurface.h b/C3d/Include/surf_polysurface.h index 01da7de..59bc181 100644 --- a/C3d/Include/surf_polysurface.h +++ b/C3d/Include/surf_polysurface.h @@ -84,12 +84,12 @@ public: \{ */ virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента \en Type of element virtual MbeSpaceType Type() const; // \ru Тип элемента \en Type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Cделать копию элемента \en Make a copy of an element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Cделать копию элемента \en Make a copy of an element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными \en Determine whether objects are equal virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным \en Make equal - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси \en Rotate about an axis + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси \en Rotate about an axis virtual void GetProperties( MbProperties & ) = 0; // \ru Выдать свойства объекта \en Get properties of the object virtual void SetProperties( const MbProperties & ) = 0; // \ru Записать свойства объекта \en Set properties of the object diff --git a/C3d/Include/surf_revolution_surface.h b/C3d/Include/surf_revolution_surface.h index e43466d..8b5b3d5 100644 --- a/C3d/Include/surf_revolution_surface.h +++ b/C3d/Include/surf_revolution_surface.h @@ -137,13 +137,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -241,9 +241,9 @@ public: virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии u = const \en A spatial copy of the line u = const. // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection on the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection on the surface. + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection on the surface. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces are similar to merge. virtual bool IsSimilarToSurface( const MbSurface & surf, VERSION version, double precision = METRIC_PRECISION ) const; diff --git a/C3d/Include/surf_ruled_surface.h b/C3d/Include/surf_ruled_surface.h index 1548bda..510a95c 100644 --- a/C3d/Include/surf_ruled_surface.h +++ b/C3d/Include/surf_ruled_surface.h @@ -115,13 +115,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties &properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties &properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -205,7 +205,7 @@ public: \{ */ virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line by u. virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии v. \en Curvature of v-line. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the count of polygons by u. virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. @@ -213,7 +213,7 @@ public: virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. // \ru Ближайшая проекция точки на поверхность. \en The nearest point projection onto the surface. - virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D & p, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Пересечение с кривой. \en Intersection with curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, diff --git a/C3d/Include/surf_section_surface.h b/C3d/Include/surf_section_surface.h index 2aa4992..c387d4b 100644 --- a/C3d/Include/surf_section_surface.h +++ b/C3d/Include/surf_section_surface.h @@ -1,8 +1,8 @@ //////////////////////////////////////////////////////////////////////////////// /** \file - \brief \ru Поверхность заметания переменного сечения. - \en The swept mutable section surface. \~ + \brief \ru Поверхность переменного сечения. + \en The mutable section surface. \~ */ //////////////////////////////////////////////////////////////////////////////// @@ -22,25 +22,25 @@ #include -#define _RO_MIN_ 0.05 // \ru Минимальный параметр переменного сечения. \en The minimum parameter of the swept section. +#define _RO_MIN_ 0.001 // \ru Минимальный параметр переменного сечения. \en The minimum parameter of the mutable section. #define _CIRCLE_ 0.4142135623730950488016887242097 // \ru Параметр дуги окружности в сечении. \en The parameter is corresponding to the circle. #define _PARABOLA_ 0.5 // \ru Параметр параболы в сечении. \en The parameter is corresponding to the parabola. -#define _RO_MAX_ 0.95 // \ru Максимальный параметр переменного сечения. \en The maximum parameter of the swept section. +#define _RO_MAX_ 0.999 // \ru Максимальный параметр переменного сечения. \en The maximum parameter of the mutable section. class MATH_CLASS MbSurfaceWorkingData; //------------------------------------------------------------------------------ -/** \brief \ru Поверхность заметания переменного сечения. - \en The swept mutable section surface. \~ +/** \brief \ru Поверхность переменного сечения. + \en The mutable section surface. \~ \details \ru Поверхность переменного (конического) сечения образуется путем движения плоской кривой, являющейся коническим сечением, вдоль опорной кривой. В процессе движения форма плоской кривой меняется в соответствии с дискриминантом конического сечения. Начало плоской кривой располагается на начальной направляющей кривой, а конец - на конечной направляющей кривой. Плоскость переменного сечения сохраняет ортогональность опорной кривой в процессе движения. Первый параметр поверхности совпадает с параметром опорной кривой. Второй параметр поверхности совпадает с параметром плоской кривой. - \en The swept (conic) section surface is formed by moving the flat conic section curve along the reference curve. + \en The mutable section surface is formed by moving the flat conic section curve along the reference curve. In the process of movement, the shape of the flat curve changes in accordance with the discriminant of the conic section. The beginning of the flat curve is located on the first guide curve and the end is located on the second guide curve. The plane of the conic section preserves the orthogonality to the reference curve during movement. @@ -51,15 +51,13 @@ class MATH_CLASS MbSurfaceWorkingData; // --- class MATH_CLASS MbSectionSurface : public MbSurface { -public: - protected: MbSpine * spine; ///< \ru Опорная кривая. \en The reference curve. - MbCurve3D * guide1; ///< \ru Первая направляющая кривая на первой поверхности (может быть NULL). \en The first guide curve on the first surface (may be NULL). - MbCurve3D * guide2; ///< \ru Вторая направляющая кривая на второй поверхности (может быть NULL). \en The second guide curve on the second surface (may be NULL). - std::vector curves; ///< \ru Дополнительные направляющие кривые (могут отсутствовать). \en The additional guide curves (may be empty). - MbFunction * function; ///< \ru Функция управления сечением (радиус или дискриминант, может быть NULL)). \en Section control function (radius or discriminant, may be NULL). - MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм NULL). \en Forming curve for form==cs_Shape (NULL on other case). + MbCurve3D * guide1; ///< \ru Первая направляющая кривая (может быть c3d_null). \en The first guide curve (may be c3d_null). + MbCurve3D * guide2; ///< \ru Вторая направляющая кривая (может быть c3d_null). \en The second guide curve (may be c3d_null). + std::vector curves; ///< \ru Дополнительные контрольные кривые (могут отсутствовать). \en The additional control curves (may be empty). + MbFunction * function; ///< \ru Функция управления сечением (радиус или дискриминант, может быть c3d_null)). \en Section control function (radius or discriminant, may be c3d_null). + MbPolyCurve * pattern; ///< \ru Образующая кривая при form==cs_Shape (для других форм c3d_null). \en Forming curve for form==cs_Shape (c3d_null on other case). std::vector shape; ///< \ru Описание сечения при form==cs_Shape (пуст в других случаях). \en Description of shape cross-section for form==cs_Shape (is empty on other case). std::vector knots; ///< \ru Узловой вектор сплайна. \en Knot vector of the spline. size_t order; ///< \ru Порядок сплайна (степень + 1). \en Order of spline (degree + 1). @@ -115,9 +113,9 @@ protected: protected: /** \brief \ru Конструктор поверхности переменного сечения. - \en Swept mutable section surface constructor. \~ + \en The mutable section surface constructor. \~ \details \ru Конструктор поверхности переменного сечения по опорной кривой и двум направляющим. - \en Swept section surface constructor by reference curve and guide curves. \~ + \en The mutable section surface constructor by reference curve and guide curves. \~ \param[in] sp - \ru Опорная кривая. \en The reference curve (spine). \~ \param[in] c1 - \ru Первая направляющая кривая. @@ -145,9 +143,9 @@ protected: MbPolyCurve * patt, std::vector & sh ); /** \brief \ru Конструктор поверхности переменного сечения. - \en Swept mutable section surface constructor. \~ + \en The mutable section surface constructor. \~ \details \ru Конструктор поверхности переменного сечения по осевой кривой и закону изменения радиуса вращения. - \en Swept mutable section surface constructor with axis curve and radius law. \~ + \en The mutable section surface constructor with axis curve and radius law. \~ \param[in] sp - \ru Опорная кривая. \en The reference curve (spine). \~ \param[in] c0 - \ru Осевая кривая. @@ -162,8 +160,6 @@ protected: \en Section radius function. \~ */ MbSectionSurface( MbSpine & sp, MbCurve3D & c0, MbeSectionShape f, double uBeg, double uEnd, MbFunction & func ); - -protected: // \ru Конструктор-копия. \en Copy constructor. MbSectionSurface( const MbSectionSurface &, MbRegDuplicate * ); private: @@ -175,18 +171,18 @@ public: public: VISITING_CLASS( MbSectionSurface ); - /** \brief \ru Создание поверхности заметания переменного сечения. - \en Swept mutable section surface creation. \~ - \details \ru Создание поверхности заметания переменного сечения по опорной кривой и двум направляющим. - \en Swept section surface creation by reference curve and guide curves. \~ + /** \brief \ru Создание поверхности переменного сечения. + \en The mutable section surface creation. \~ + \details \ru Создание поверхности переменного сечения по опорной кривой и двум направляющим. + \en The mutable section surface creation by reference curve and guide curves. \~ \param[in] rc - \ru Опорная кривая. \en The reference curve (spine). \~ \param[in] g1 - \ru Первая направляющая кривая. \en The first guide curve. \~ \param[in] g2 - \ru Вторая направляющая кривая (g1==g2 совпадает с первой при cs_Round). \en The second guide curve (g1==g2 the same first guide for st_Round). \~ - \param[in] c0 - \ru Дополнительная направляющая кривая (может быть NULL). - \en The additional guide curve (may be NULL). \~ + \param[in] c0 - \ru Дополнительная направляющая кривая (может быть c3d_null). + \en The additional guide curve (may be c3d_null). \~ \param[in] f - \ru Форма сечения поверхности. \en The form of the surface section. \~ \param[in] sense - \ru Направление нормали поверхности направляющей кривой (для guide1==guide2). @@ -228,13 +224,13 @@ public: \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента \en A type of element - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar ( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Move. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Move. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -321,7 +317,7 @@ public: \{ */ virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line by u. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether the surface is planar. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. @@ -359,39 +355,43 @@ public: virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the count of polygons by v. /** \} */ - /** \ru \name Функции поверхности заметания переменного сечения. - \en \name Functions of the swept mutable section surface. + /** \ru \name Функции поверхности переменного сечения. + \en \name Functions of the mutable section surface. \{ */ - /// \ru Направляющая. \en Guide curve. + /// \ru Дать опорный спайн. \en Get reference spine. const MbSpine & GetSpine() const { return *spine; } - /// \ru Направляющая кривая. \en The spine (reference) curve. + /// \ru Дать опорную кривую. \en Get reference curve. const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } - /// \ru Первая направляющая кривая на первой поверхности (может быть NULL). \en The first guide curve on the first surface (may be NULL). + /// \ru Дать первую направляющую кривую (может быть c3d_null). \en Get first guide curve (may be c3d_null). const MbCurve3D * GetGuide1() const { return guide1; } - /// \ru Вторая направляющая кривая на второй поверхности (может быть NULL). \en The second guide curve on the second surface (may be NULL). + /// \ru Дать вторую направляющую кривую (может быть c3d_null). \en Get second guide curve (may be c3d_null). const MbCurve3D * GetGuide2() const { return guide2; } - /// \ru Дополнительные направляющие кривые (могут отсутствовать). \en The additional guide curves (may be empty). - const MbCurve3D * GetCurve( size_t i ) const { return ( i < curves.size() ) ? curves[i] : NULL; } - /// \ru Функция управления сечением (радиус или дискриминант, может быть NULL)). \en Section control function (radius or discriminant, may be NULL). + /// \ru Дать кривую вершин (может отсутствовать). \en Get apex curve (may be c3d_null). + const MbCurve3D * GetApexCurve() const { return ( curves.size() > 0 ) ? curves[0] : c3d_null; } + /// \ru Дать дополнительную направляющую кривую (может отсутствовать). \en Get additional guide curve (may be absence). + const MbCurve3D * GetCurve( size_t i ) const { return ( i < curves.size() ) ? curves[i] : c3d_null; } + /// \ru Дать функцию управления сечением (радиус или дискриминант, может быть c3d_null)). \en Get section control function (radius or discriminant, may be c3d_null). const MbFunction * GetFunction() const { return function; } - /// \ru Образующая кривая при form==cs_Shape (для других форм NULL). \en Forming curve for form==cs_Shape (NULL on other case). + /// \ru Дать образующую кривую при form==cs_Shape (для других форм c3d_null). \en Get forming curve for form==cs_Shape (c3d_null on other case). const MbPolyCurve * GetPattern() const { return pattern; } - /// \ru Вычисление параметров направляющих кривых по второму параметру поверхности. \en Calculating the parameters of guide curves by the second surface parameter. - bool GuideParams( double v, double & t1, double & t2 ) const; - /// \ru Вычисление параметра вершинной кривой по второму параметру поверхности. \en Calculating the parameter of apex curve by the second surface parameter. - bool ApexParam( double v, double & t0 ) const; - /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of first the guide curves. - bool ParamByGuide1( double t1, MbCartPoint & p ) const; - /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of the second guide curves. - bool ParamByGuide2( double t2, MbCartPoint & p ) const; - /// \ru Вычисление второго параметра поверхности по параметру вершинной кривой. \en Calculating the second surface parameter by the parameter of the apex curve. - bool ParamByApex( double t0, double & v ) const; - /// \ru Вычисление точек поверхности по параметрам первой направляющей кривой. \en Calculating surface points by the first guide curve. - bool PointsByGuide1( std::vector & points ) const; - /// \ru Вычисление точек поверхности по параметрам второй направляющей кривой. \en Calculating surface points by the second guide curve. - bool PointsByGuide2( std::vector & points ) const; + /// \ru Вычисление параметров направляющих кривых по второму параметру поверхности. \en Calculating the parameters of guide curves by the second surface parameter. + bool GuideParams( double v, double & t1, double & t2 ) const; + /// \ru Вычисление параметра вершинной кривой по второму параметру поверхности. \en Calculating the parameter of apex curve by the second surface parameter. + bool ApexParam( double v, double & t0 ) const; + /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of first the guide curves. + bool ParamByGuide1( double t1, MbCartPoint & p ) const; + /// \ru Вычисление точки поверхности по параметру направляющей кривой. \en Calculating the surface point by the parameter of the second guide curves. + bool ParamByGuide2( double t2, MbCartPoint & p ) const; + /// \ru Вычисление второго параметра поверхности по параметру вершинной кривой. \en Calculating the second surface parameter by the parameter of the apex curve. + bool ParamByApex( double t0, double & v ) const; + /// \ru Вычисление точек поверхности по параметрам первой направляющей кривой. \en Calculating surface points by the first guide curve. + bool PointsByGuide1( std::vector & points ) const; + /// \ru Вычисление точек поверхности по параметрам второй направляющей кривой. \en Calculating surface points by the second guide curve. + bool PointsByGuide2( std::vector & points ) const; + /// \ru Вычисление точек пересечения направляющих кривых и кривой вершин с плоскостью сечения, заданной вторым параметром поверхности. \en Calculating the intersection points of guide curves and apex curve with the section plane specified by the second surface parameter. + bool PhantomPoints( double v, MbCartPoint3D & guideP1, MbCartPoint3D & guideP2, MbCartPoint3D & apex, double & discrim ) const; /** \} */ @@ -449,16 +449,16 @@ protected : void DeriveUUV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuv. \en The third derivative with respect to uuv. void DeriveUVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uvv. \en The third derivative with respect to uvv. void DeriveVVV( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по vvv. \en The third derivative with respect to vvv. - // \ru Вычисление точек для создания NURBS копии кривых поверхности. \en Points calculation for NURBS copy surface. - bool CollectNurbsPoints( double vin, double vax, size_t pCount, double angle, - SArray & params, - SArray & points1, - SArray & points2, - SArray & points_0, - SArray & points_1, - SArray & points_2, - SArray & points_3, - SArray & points_4 ) const; + // \ru Вычисление точек для создания NURBS копии кривых поверхности. \en Points calculation for NURBS copy surface. + bool CollectNurbsPoints( double vin, double vax, size_t pCount, double angle, + SArray & params, + SArray & points1, + SArray & points2, + SArray & points_0, + SArray & points_1, + SArray & points_2, + SArray & points_3, + SArray & points_4 ) const; private: void operator = ( const MbSectionSurface & ); // \ru Не реализовано. \en Not implemented. diff --git a/C3d/Include/surf_sector_surface.h b/C3d/Include/surf_sector_surface.h index a560b7a..c8902ac 100644 --- a/C3d/Include/surf_sector_surface.h +++ b/C3d/Include/surf_sector_surface.h @@ -66,13 +66,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента. \en Make a copy of an element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента. \en Make a copy of an element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать. \en Transform. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать. \en Transform. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -147,7 +147,7 @@ public: \en \name Common functions of surface. \{ */ virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна линии v. \en Curvature of v line. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru NURBS копия поверхности. \en NURBS copy of surface. diff --git a/C3d/Include/surf_smooth_surface.h b/C3d/Include/surf_smooth_surface.h index 0fce759..d27a783 100644 --- a/C3d/Include/surf_smooth_surface.h +++ b/C3d/Include/surf_smooth_surface.h @@ -37,8 +37,8 @@ class MATH_CLASS MbSurfaceIntersectionCurve; // --- class MATH_CLASS MbSmoothSurface : public MbSurface { protected: - MbSurfaceCurve * curve1; ///< \ru Опорная кривая на первой поверхности (всегда не NULL). \en Support curve on the first surface (it never equals NULL). - MbSurfaceCurve * curve2; ///< \ru Опорная кривая на второй поверхности (всегда не NULL). \en Support curve on the second surface (it never equals NULL). + MbSurfaceCurve * curve1; ///< \ru Опорная кривая на первой поверхности (всегда не c3d_null). \en Support curve on the first surface (it never equals c3d_null). + MbSurfaceCurve * curve2; ///< \ru Опорная кривая на второй поверхности (всегда не c3d_null). \en Support curve on the second surface (it never equals c3d_null). MbeSmoothForm form; ///< \ru Тип сопряжения. \en Conjugation type. double distance1; ///< \ru Радиус скругления или "катет" фаски со знаком для поверхности кривой curve1. \en Fillet radius or chamfer "cathetus" with sign for surface of curve1 curve. double distance2; ///< \ru Радиус скругления или "катет" фаски со знаком для поверхности кривой curve2. \en Fillet radius or chamfer "cathetus" with sign for surface of curve2 curve. @@ -116,12 +116,12 @@ public: \{ */ virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbeSpaceType Type() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties &properties ) = 0; // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties &properties ) = 0; // \ru Записать свойства объекта. \en Set properties of the object. @@ -215,8 +215,8 @@ public: \en Add to end (true) or add to start (false) \~ \param[in] matr - \ru Матрица преобразования объектов с init в данную поверхность, \en A matrix of transformation of objects from 'init' to the given surface, \~ - \param[in] seam - \ru Кривая другого разделяющего ребра (может быть NULL) - \en A curve of another splitting edge (possibly it is NULL) \~ + \param[in] seam - \ru Кривая другого разделяющего ребра (может быть c3d_null) + \en A curve of another splitting edge (possibly it is c3d_null) \~ */ virtual bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, const MbSurface & init, bool add, MbMatrix & matr, diff --git a/C3d/Include/surf_sphere_surface.h b/C3d/Include/surf_sphere_surface.h index 9151acb..cfef8af 100644 --- a/C3d/Include/surf_sphere_surface.h +++ b/C3d/Include/surf_sphere_surface.h @@ -109,10 +109,10 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -217,7 +217,7 @@ public: virtual MbCurve3D * CurveU( double v, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии v = const. \en A spatial copy of the line v = const. virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии u = const. \en A spatial copy of the line u = const. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Пересечение с кривой. \en Intersection with a curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -269,7 +269,7 @@ public: /** \ru \name Функции элементарных поверхностей \en \name Functions of elementary surfaces. \{ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \} */ /** \ru \name Функции конической поверхности \en \name Functions of conical surface diff --git a/C3d/Include/surf_spine.h b/C3d/Include/surf_spine.h index 75dadc3..1f08158 100644 --- a/C3d/Include/surf_spine.h +++ b/C3d/Include/surf_spine.h @@ -55,11 +55,11 @@ public: }; private: - SPtr curve; ///< \ru Направляющая кривая - всегда не NULL. \en Spine curve - it is always not NULL. + SPtr curve; ///< \ru Направляющая кривая - всегда не c3d_null. \en Spine curve - it is always not c3d_null. MbVector3D direction; ///< \ru Вектор ориентации матрицы преобразования. \en Vector of transformation matrix orientation. - SPtr optionalCurve; ///< \ru Кривая вектора ориентации матрицы преобразования (может быть NULL для простой траектории). \en A curve of the transformation matrix orientation (it may be NULL for a simple trajectory). - SPtr spineSurface; ///< \ru Поверхность направляющей кривой, если "curve" - кривая на поверхности, или NULL. \en The surface of the "curve", if it is curve on surface, or NULL. - SPtr featureCurve; ///< \ru Двумерная кривая, если "curve" - кривая на поверхности, или NULL. \en Two-dimensional curve of the "curve", if it is curve on surface, or NULL. + SPtr optionalCurve; ///< \ru Кривая вектора ориентации матрицы преобразования (может быть c3d_null для простой траектории). \en A curve of the transformation matrix orientation (it may be c3d_null for a simple trajectory). + SPtr spineSurface; ///< \ru Поверхность направляющей кривой, если "curve" - кривая на поверхности, или c3d_null. \en The surface of the "curve", if it is curve on surface, or c3d_null. + SPtr featureCurve; ///< \ru Двумерная кривая, если "curve" - кривая на поверхности, или c3d_null. \en Two-dimensional curve of the "curve", if it is curve on surface, or c3d_null. LocalAxes localAxes; ///< \ru Способы ориентации локальной системы координат вдоль направляющей кривой "curve". \en Methods of orientation of the local coordinate system along the guide curve "curve". double crossSize; ///< \ru Поперечный масштаб при построении optionalCurve. \en Transverse scale in construction of "optionalCurve". double ortParam; ///< \ru Параметр кривой, для которой рассчитаны ort0, ort1, ort2. \en Parameter of a curve with evaluated ort0, ort1 and ort2. @@ -253,7 +253,7 @@ public: /// \ru Тип элемента. \en A type of element. MbeSpaceType IsA() const { return curve->IsA(); } /// \ru Сделать копию элемента. \en Create a copy of the element. - MbSpine & Duplicate( MbRegDuplicate * = NULL ) const; + MbSpine & Duplicate( MbRegDuplicate * = c3d_null ) const; /// \ru Сделать равным. \en Make equal. bool SetEqual( const MbSpine & ); /// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. @@ -261,13 +261,13 @@ public: /// \ru Равны ли объекты. \en Whether the objects are equal. bool IsSame ( const MbSpine & other, double accuracy = LENGTH_EPSILON ) const; /// \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвиг. \en Translation. - void Move ( const MbVector3D &, MbRegTransform * = NULL ); + void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть вокруг оси. \en Rotate around an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /// \ru Изменить направление. \en Change the direction. - void Inverse( MbRegTransform * iReg = NULL ); + void Inverse( MbRegTransform * iReg = c3d_null ); /// \ru Сбросить временные данные объекта. \en Reset temporary data of an object. void Reset(); /** \} */ @@ -525,8 +525,8 @@ MATH_FUNC (void) MakeSpines( const MbSpine & sp, SArray & items ); Для внутреннего использования. \en Delete unused spines.\n For internal use only. \~ - \param[in,out] items - \ru Массив направляющих. - \en An array of spines. \~ + \param[in,out] spineDataItems - \ru Массив направляющих. + \en An array of spines. \~ */ // --- template void DeleteNonUsedSpines( SpineDataVector & spineDataItems ) diff --git a/C3d/Include/surf_spiral_surface.h b/C3d/Include/surf_spiral_surface.h index 762bc71..7c849f0 100644 --- a/C3d/Include/surf_spiral_surface.h +++ b/C3d/Include/surf_spiral_surface.h @@ -105,13 +105,13 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными. \en Determine whether the objects are similar. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -179,7 +179,7 @@ public: \en \name Common functions of surface. \{ */ virtual double CurvatureU ( double u, double v ) const; // \ru Kривизна линии по u. \en Curvature of line in u direction. - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru NURBS копия поверхности. \en NURBS copy of surface. @@ -189,7 +189,7 @@ public: virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии u = const. \en A spatial copy of the line u = const. // \ru Найти проекцию точки на поверхность. \en Find the projection of a point onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; diff --git a/C3d/Include/surf_spline_surface.h b/C3d/Include/surf_spline_surface.h index 3c5190b..9c37023 100644 --- a/C3d/Include/surf_spline_surface.h +++ b/C3d/Include/surf_spline_surface.h @@ -146,7 +146,7 @@ private: DPtr data; ///< \ru Дополнительные данные о поверхности. \en Additional data about a surface. DPtr wdata; ///< \ru Рабочие данные для расчета поверхности. \en Working data for the calculation of a surface. - double * wc; ///< \ru Рассчитанные в точке (uc,vc) значения весов (может быть NULL). \en Weights values calculated in the point (uc, vc) (may be NULL). + double * wc; ///< \ru Рассчитанные в точке (uc,vc) значения весов (может быть c3d_null). \en Weights values calculated in the point (uc, vc) (may be c3d_null). MbSplineSurfaceAuxiliaryData(); MbSplineSurfaceAuxiliaryData( const MbSplineSurfaceAuxiliaryData & init ); @@ -350,7 +350,7 @@ public: \en \name Common functions of geometric object. \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const; // \ru Cделать копию элемента. \en Make a copy of an element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const; // \ru Cделать копию элемента. \en Make a copy of an element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. @@ -497,12 +497,12 @@ public: */ MbSplineSurface * Trimmed( double uBeg, double uEnd, double vBeg, double vEnd ) const; - virtual bool IsPlanar() const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; // \ru Является ли поверхность плоской. \en Whether a surface is planar. // \ru Найти ближайшую проекцию точки на поверхность или ее продолжение по заданному начальному приближению. \en Find the neares projection of a point onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Являются ли узловые векторы равными? \en Are knotVectos equal? bool IsKnotsTheSame( const MbSplineSurface & e, bool sameDir, double precision ) const; @@ -767,8 +767,8 @@ public: \en Create a two-dimensional curve if a space curve is a surface boundary.\n \~ \param[in] curve - \ru Заданная пространственная кривая. \en A given space curve. \~ - \return \ru Ссылка на двумерную кривую на поверхности или NULL, если построить ее не удалось. - \en A reference to the two-dimensional curve on a surface or NULL if the construction of it is failed. \~ + \return \ru Ссылка на двумерную кривую на поверхности или c3d_null, если построить ее не удалось. + \en A reference to the two-dimensional curve on a surface or c3d_null if the construction of it is failed. \~ */ MbCurve * IsSplineBorder( const MbCurve3D & curve ) const; @@ -805,7 +805,7 @@ private: double GetKoef( bool isU ) const; // \ru Получить коэффициент пересчета из длины в параметры. \en Get a coefficient of recalculation of the length to the parameters. //--- - // \ru Служебные функции, которые используют заданный кэш (должен быть != NULL). \en Service functions that use a given cache (must != NULL). + // \ru Служебные функции, которые используют заданный кэш (должен быть != c3d_null). \en Service functions that use a given cache (must != c3d_null). bool CheckPoles( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов. \en Check poles existence. bool CatchMemory( MbSplineSurfaceAuxiliaryData * ) const; @@ -856,7 +856,7 @@ private: MbSplineSurfaceAuxiliaryData * ) const; //--- - double GetMinStep ( bool isU, const double * pRng = NULL ) const; + double GetMinStep ( bool isU, const double * pRng = c3d_null ) const; bool ApproxAsPlane() const; // \ru Можно ли аппроксимировать поверхность как плоскость. \en Whether a surface can be approximated by a plane. // \ru Вычислить аппроксимацию поверхности, считая, что ее можно аппроксимировать как плоскость. \en Calculate an approximation of surface assuming that it can be approximated by a plane. diff --git a/C3d/Include/surf_swept_surface.h b/C3d/Include/surf_swept_surface.h index bbe73f0..12d1d33 100644 --- a/C3d/Include/surf_swept_surface.h +++ b/C3d/Include/surf_swept_surface.h @@ -48,7 +48,7 @@ protected: MbSweptSurface( const MbCurve3D &, bool same ); MbSweptSurface( const MbSweptSurface &, MbRegDuplicate * ); MbSweptSurface() // \ru Используется только в конвертерах. \en This is used only in converters. - : curve( NULL ), umin( 0 ), vmin( 0 ), umax( 0 ), vmax( 0 ), uclosed( false ), vclosed( false ) {} + : curve( c3d_null ), umin( 0 ), vmin( 0 ), umax( 0 ), vmax( 0 ), uclosed( false ), vclosed( false ) {} private: MbSweptSurface( const MbSweptSurface & ); // \ru Не реализовано. \en Not implemented. @@ -63,12 +63,12 @@ public: \{ */ virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbeSpaceType Type() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const= 0; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const= 0; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвиг. \en Translation. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвиг. \en Translation. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual void GetProperties( MbProperties & properties ) = 0; // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ) = 0; // \ru Записать свойства объекта. \en Set properties of the object. diff --git a/C3d/Include/surf_tessellation.h b/C3d/Include/surf_tessellation.h index 2d2a883..8d0c79a 100644 --- a/C3d/Include/surf_tessellation.h +++ b/C3d/Include/surf_tessellation.h @@ -370,26 +370,26 @@ inline bool MbSurfaceWorkingData::Explore( double u0, double v0, bool ext0, doub bool resUV = false; bool resVV = false; - if ( uuDer == NULL ) + if ( uuDer == c3d_null ) resUU = true; else if ( ders[sdt_DeriveUU].x != UNDEFINED_DBL ) { uuDer->Init( ders[sdt_DeriveUU] ); resUU = true; } - if ( uvDer == NULL ) + if ( uvDer == c3d_null ) resUV = true; else if ( ders[sdt_DeriveUV].x != UNDEFINED_DBL ) { uvDer->Init( ders[sdt_DeriveUV] ); resUV = true; } - if ( vvDer == NULL ) + if ( vvDer == c3d_null ) resVV = true; else if ( ders[sdt_DeriveVV].x != UNDEFINED_DBL ) { vvDer->Init( ders[sdt_DeriveVV] ); resVV = true; } if ( resUU && resUV && resVV ) { - if ( nor == NULL ) + if ( nor == c3d_null ) res = true; else if ( norm.x != UNDEFINED_DBL ) { nor->Init( norm ); diff --git a/C3d/Include/surf_torus_surface.h b/C3d/Include/surf_torus_surface.h index d9e0a22..f64df3a 100644 --- a/C3d/Include/surf_torus_surface.h +++ b/C3d/Include/surf_torus_surface.h @@ -132,10 +132,10 @@ public: \en \name Common functions of a geometric object \{ */ virtual MbeSpaceType IsA() const; // \ru Тип элемента. \en A type of element. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const ; // \ru Сделать копию элемента. \en Create a copy of the element. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Равны ли объекты. \en Whether the objects are equal. virtual bool SetEqual( const MbSpaceItem & ); // \ru Сделать равным. \en Make equal. - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * = c3d_null ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. virtual void GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & properties ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -233,7 +233,7 @@ public: virtual MbCurve3D * CurveU( double v, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии v = const. \en A spatial copy of the line v = const. virtual MbCurve3D * CurveV( double u, MbRect1D * pRgn, bool bApprox = true ) const; // \ru Пространственная копия линии u = const. \en A spatial copy of the line u = const. // \ru Найти все проекции точки на поверхность вдоль вектора в любом из двух направлений. \en Find all a point projection onto the surface along a vector in either of two directions. - virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & p, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; // \ru Пересечение с кривой. \en Intersection with a curve. virtual void CurveIntersection( const MbCurve3D & curv, SArray & uv, SArray & tt, bool ext0, bool ext, bool touchInclude = false ) const; @@ -284,7 +284,7 @@ public: /** \ru \name Функции элементарных поверхностей \en \name Functions of elementary surfaces. \{ */ - virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool GetPointProjection( const MbCartPoint3D & p, bool init, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \} */ /** \ru \name Функции тороидальной поверхности \en \name Functions of toroidal surface diff --git a/C3d/Include/surface.h b/C3d/Include/surface.h index aed851c..39ca6b7 100644 --- a/C3d/Include/surface.h +++ b/C3d/Include/surface.h @@ -118,12 +118,12 @@ public: virtual MbeSpaceType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbeSpaceType Type() const; // \ru Групповой тип элемента. \en Group element type. virtual MbeSpaceType Family() const; // \ru Семейство объекта. \en Family of object. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Сделать копию объекта. \en Create a copy of the object. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * = c3d_null ) const = 0; // \ru Сделать копию объекта. \en Create a copy of the object. virtual bool IsSame ( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Являются ли объекты равными. \en Determine whether objects are equal. virtual bool SetEqual ( const MbSpaceItem & ) = 0; // \ru Сделать объекты равным. \en Make objects equal. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ) = 0; // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ) = 0; // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ) = 0; // \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ) = 0; // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube & c ) const; // \ru Добавить габарит поверхности в куб. \en Add the surface bounding box into a cube. virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. @@ -407,11 +407,11 @@ public: \param[out] vDer - \ru Производная по v. \en Derivative with respect to v. \~ \param[out] uuDer - \ru Вторая производная по u, если не ноль. - \en Second derivative with respect to u, if not NULL. \~ + \en Second derivative with respect to u, if not c3d_null. \~ \param[out] vvDer - \ru Вторая производная по v, если не ноль. - \en Second derivative with respect to v, if not NULL. \~ + \en Second derivative with respect to v, if not c3d_null. \~ \param[out] uvDer - \ru Вторая производная по u и по v, если не ноль. - \en Second derivative with respect to u and v, if not NULL. \~ + \en Second derivative with respect to u and v, if not c3d_null. \~ \ingroup Surfaces */ virtual void Explore( double & u, double & v, bool ext, @@ -770,7 +770,7 @@ public: /// \ru Является ли базовая поверхность копией базовой поверхности данного объекта. \en Whether a base surface is a copy of the base surface of the given object. virtual bool IsSameBase( const MbSurface & ) const; /// \ru Является ли поверхность плоской. \en Whether a surface is planar. - virtual bool IsPlanar() const; + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; /** \brief \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. \~ @@ -867,8 +867,8 @@ public: \en Parameters of construction in u direction. \~ \param[in] vParam - \ru Параметры построения по направлению v. \en Parameters of construction in v direction. \~ - \result \ru Построенная NURBS поверхность или NULL при неуспешном построении. - \en The constructed NURBS surface or NULL in a case of failure. \~ + \result \ru Построенная NURBS поверхность или c3d_null при неуспешном построении. + \en The constructed NURBS surface or c3d_null in a case of failure. \~ */ virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; @@ -1159,7 +1159,7 @@ public: \result \ru true - если найдена проекция, удовлетворяющая всем входным условиям. \en True - if there is found a projection which satisfies to all input conditions. \~ */ - virtual bool NearPointProjection( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + virtual bool NearPointProjection( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = c3d_null ) const; /// \ru Нахождение проекции точки на поверхность в направлении вектора. Для внутреннего использования. \en Finding of point projections to the surface in direction of the vector. For internal use only. virtual MbeNewtonResult DirectPointProjectionNewton( const MbCartPoint3D & p, const MbVector3D & vect, size_t iterLimit, double & u, double & v, double & w, bool ext ) const; @@ -1183,7 +1183,7 @@ public: \param[in] uvRange - \ru Диапазон изменения параметров поверхности, в котором надо найти решение. \en A range of surface parameters changing in which the solution should be found. \~ */ - virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = NULL ) const; + virtual void DirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, SArray & uv, bool ext, MbRect2D * uvRange = c3d_null ) const; /** \brief \ru Найти ближайшую проекцию точки на поверхность в направлении вектора. \en Find the nearest point projection to the surface in the vector direction. \~ @@ -1209,7 +1209,7 @@ public: \en True - if there is found a projection which satisfies to all input conditions. \~ */ virtual bool NearDirectPointProjection( const MbCartPoint3D & pnt, const MbVector3D & vect, double & u, double & v, bool ext, - MbRect2D * uvRange = NULL, bool onlyPositiveDirection = false ) const; + MbRect2D * uvRange = c3d_null, bool onlyPositiveDirection = false ) const; /// \ru Решение системы уравнений для определения пересечения поверхности и кривой. Для внутреннего использования. \en Solution of equation system for determination of intersections between a surface and a curve. For internal use only. virtual MbeNewtonResult CurveIntersectNewton( const MbCurve3D & curv1, double funcEpsilon, size_t iterLimit, double & u0, double & v0, double & t1, bool ext0, bool ext1 ) const; @@ -1453,7 +1453,7 @@ public: \param[in] s - \ru Поверхность-копия. \en A surface-copy. \~ */ - void CopyGabarit( const MbSurface & s, const MbVector3D * to = NULL ) { cube = s.cube; if ( (to != NULL) && !cube.IsEmpty() ) { cube.Move( *to ); } } + void CopyGabarit( const MbSurface & s, const MbVector3D * to = c3d_null ) { cube = s.cube; if ( (to != c3d_null) && !cube.IsEmpty() ) { cube.Move( *to ); } } /// \ru Вычислить диагональ габаритного куба. \en Calculate the diagonal of the bounding box. double GetGabDiagonal() const { if ( cube.IsEmpty() ) { MbCube tmp; CalculateGabarit( tmp ); } return cube.GetDiagonal(); } @@ -1978,8 +1978,6 @@ MATH_FUNC (MbeNewtonResult) NearestPoints( const MbSurface & surface0, bool ext0 \en V-parameter of a point on the surface 'surface1'. \~ \param[out] dmin - \ru Расстояние между точками поверхностей. \en The distance between points on surfaces. \~ - \param[in] checkCurvilinearBounds - \ru Всегда проверять по криволинейным границам (если они есть). - \en Check for curvilinear boundaries (if they are). \~ \return \ru Возвращает nr_Success (+1) или nr_Special(0) в случае успешного определения, в случае неудачи возвращает nr_Failure(-1). \en Return nr_Success (+1) or nr_Special(0) in a case of successful defining, return nr_Failure(-1) in a case of failure. \~ \ingroup Surfaces diff --git a/C3d/Include/system_atomic.h b/C3d/Include/system_atomic.h index 8eef130..a5f6ea0 100644 --- a/C3d/Include/system_atomic.h +++ b/C3d/Include/system_atomic.h @@ -2,9 +2,9 @@ /** \file \brief \ru Системозависимые атомарные операции. - Если требуются атомарные операции, должен использоваться этот файл ( не использовать!!!). + Если требуются атомарные операции, должен использоваться этот файл (atomic не использовать!!!). \en System-dependent atomic operations. - If atomic operations are required, this file should used ( must not be used!!!).\~ + If atomic operations are required, this file should be used (atomic must not be used!!!).\~ */ //////////////////////////////////////////////////////////////////////////////// @@ -15,6 +15,7 @@ #include #include + //------------------------------------------------------------------------------ // \ru Использование атомарных операций согласно стандарту C++11. // \en Using atomic operations according to C++11 standard. diff --git a/C3d/Include/system_cpp_standard.h b/C3d/Include/system_cpp_standard.h index 0846a11..9bb9a75 100644 --- a/C3d/Include/system_cpp_standard.h +++ b/C3d/Include/system_cpp_standard.h @@ -161,7 +161,7 @@ #endif //------------------------------------------------------------------------------ -/// \ru Обертка для c o n s t e x p r. \en Wrapper for c o n s t e x p r. +/// \ru Обертка для constexpr. \en Wrapper for constexpr. //--- #ifdef C3D_STANDARD_CXX_11 #define c3d_constexpr constexpr @@ -173,19 +173,22 @@ // \ru Нулевой указатель. \en Null pointer. //--- #ifdef C3D_STANDARD_CXX_11_PARTIAL - #define C3D_NULL_PTR nullptr + #define c3d_null nullptr #else - #define C3D_NULL_PTR NULL + #if !defined(NULL) + #define NULL 0 + #endif + #define c3d_null NULL #endif // C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ -// \ru Нулевой указатель. \en Null pointer. +// \ru Обертка для final. \en Wrapper for final. //--- #ifdef C3D_STANDARD_CXX_11 #define c3d_final final #else #define c3d_final -#endif // C3D_STANDARD_CXX_11_PARTIAL +#endif // C3D_STANDARD_CXX_11 #endif // __SYSTEM_CPP_STANDARD_H diff --git a/C3d/Include/system_types.h b/C3d/Include/system_types.h index 32edc5e..98bf473 100644 --- a/C3d/Include/system_types.h +++ b/C3d/Include/system_types.h @@ -230,7 +230,7 @@ c3d_constexpr size_t SIZE_OF_POINTER = sizeof(char *); */ //--- template -SignedType abs_t( const SignedType x ) { return ((x >= 0) ? x : -x); } //KYA K13+ x64 +SignedType abs_t( const SignedType x ) { return ((x >= 0) ? x : -x); } //------------------------------------------------------------------------------ diff --git a/C3d/Include/templ_array2.h b/C3d/Include/templ_array2.h index e1c1156..5d610a2 100644 --- a/C3d/Include/templ_array2.h +++ b/C3d/Include/templ_array2.h @@ -65,8 +65,8 @@ public: ~Array2() { set_array_size( *this, 0, 0 ); } public: - /// \ru Создать массив заданной размерности (возвращает NULL в случае неудачи). - /// \en Create an array of a given dimension (returns NULL in case of failure). + /// \ru Создать массив заданной размерности (возвращает c3d_null в случае неудачи). + /// \en Create an array of a given dimension (returns c3d_null in case of failure). static Array2 * Create( size_t lSize, size_t cSize ); public: // Общие методы матриц (двумерных массивов) @@ -221,13 +221,13 @@ inline Array2::Array2( const Array2 & source ) template inline Array2 * Array2::Create( size_t lSize, size_t cSize ) { - Array2 * arr = NULL; + Array2 * arr = c3d_null; if ( lSize * cSize < c3d::MATRIX_MAX_COUNT ) { try { arr = new Array2( lSize, cSize ); } catch ( const std::bad_alloc & ) { - arr = NULL; + arr = c3d_null; } } return arr; @@ -285,7 +285,7 @@ const Type * Array2::GetLine( size_t i ) const { PRECONDITION( i < l ); if ( i < l ) return parr[i]; - return NULL; + return c3d_null; } //------------------------------------------------------------------------------ @@ -296,7 +296,7 @@ Type * Array2::SetLine( size_t i ) { PRECONDITION( i < l ); if ( i < l ) return parr[i]; - return NULL; + return c3d_null; } //------------------------------------------------------------------------------ @@ -468,7 +468,7 @@ inline bool Array2::CatchLinePointers( size_t newCount ) } catch ( ... ) { if ( newCount == 0 ) {// \ru Не смогли удалить parr. \en Failed to delete parr. - parr = NULL; + parr = c3d_null; l = c = 0; } C3D_CONTROLED_THROW; @@ -529,7 +529,7 @@ inline bool realloc_line( Type *& line, size_t oldSize, size_t newSize ) } catch ( ... ) { if ( newSize == 0 )// \ru Не смогли удалить line. \en Failed to delete line. - line = NULL; + line = c3d_null; C3D_CONTROLED_THROW; return false; } @@ -602,7 +602,7 @@ bool set_array_size( Array2 & arr, size_t lSize, size_t cSize ) else if ( arr.l > oldL && arr.c > 0 ) { // \ru BUG_46010 KYA K12 А кто будет выделять память для новых строк \en BUG_46010 KYA K12 And who will allocate memory for new rows Type * newLine = 0; // \ru указатель на содержимое новой строки \en pointer to contents of new row for ( i = oldL; res && i < arr.l; i++ ) { - newLine = NULL; + newLine = c3d_null; res = ::realloc_line( newLine, 0, arr.c ); // \ru захватить память под строку \en allocate memory for one row if ( res ) { ::memset( newLine, 0, arr.c * sizeof(Type) ); diff --git a/C3d/Include/templ_balance_tree.h b/C3d/Include/templ_balance_tree.h index 82517a6..1615c67 100644 --- a/C3d/Include/templ_balance_tree.h +++ b/C3d/Include/templ_balance_tree.h @@ -120,7 +120,7 @@ static size_t countIsSame; ///< \ru Число сравнений (для от public: /// \ru Конструктор. \en Constructor. - BalanceTree( Compare_t c_t = SimplePointCompFuncT, Compare_v c_v = NULL/*SimplePointCompFuncV*/, + BalanceTree( Compare_t c_t = SimplePointCompFuncT, Compare_v c_v = c3d_null/*SimplePointCompFuncV*/, bool shouldDelete = true ); /// \ru Деструктор. \en Destructor. virtual ~BalanceTree(); @@ -204,7 +204,7 @@ public: BalanceTreeNode * node_m; PPNodeType typeRAB_m; public: - PPNode( BalanceTreeNode * node = NULL, PPNodeType t = iRoot ) + PPNode( BalanceTreeNode * node = c3d_null, PPNodeType t = iRoot ) : node_m(node) , typeRAB_m(t) {} @@ -321,8 +321,8 @@ inline void BalanceTreeNode::operator delete ( void * ptr, size_t size ) { template inline BalanceTreeNode::BalanceTreeNode( BalanceTree & parent, Type * content ) : parent_m ( parent ), - left_m ( NULL ), - right_m ( NULL ), + left_m ( c3d_null ), + right_m ( c3d_null ), // \ru КВН K8+ count_m ( 0 ), \en КВН K8+ count_m ( 0 ), balance_m ( ts_neutral ), content_m ( content ) @@ -367,7 +367,7 @@ inline void BalanceTreeNode::SetRight( BalanceTreeNode * p ){ // --- template inline BalanceTree::BalanceTree( Compare_t c_t, Compare_v c_v, bool shouldDelete ) : - root_m ( NULL ), + root_m ( c3d_null ), allCount_m ( 0 ), owns_m ( shouldDelete ), isBranchGrew_m( false ), @@ -418,7 +418,7 @@ inline void BalanceTree::Flush( DelType del ) { if( root_m ) { destroy_tree_node( *root_m, del ); delete root_m; - root_m = NULL; + root_m = c3d_null; } allCount_m = 0; @@ -464,7 +464,7 @@ inline bool BalanceTree::FindIt ( const Type * content ) const { #endif // C3D_DEBUG - Type * t = compT_m ? find_tree( *this, (void *)content, true/*compT*/ ) : NULL; + Type * t = compT_m ? find_tree( *this, (void *)content, true/*compT*/ ) : c3d_null; return !!t; } @@ -479,7 +479,7 @@ inline Type * BalanceTree::Find ( void * content ) const { countIsSame = 0; #endif // C3D_DEBUG - return compV_m ? find_tree( *this, content, false/*compT*/ ) : NULL; + return compV_m ? find_tree( *this, content, false/*compT*/ ) : c3d_null; } @@ -579,8 +579,8 @@ inline bool BalanceTree::AddToBalanceTree( Type & content, BalanceTreeNod case ts_neutral : node->balance_m = ts_negative; break; // \ru балансировка \en balancing case ts_negative : { - BalanceTreeNode * p1 = NULL; - BalanceTreeNode * p2 = NULL; + BalanceTreeNode * p1 = c3d_null; + BalanceTreeNode * p2 = c3d_null; p1 = node->left_m; if ( p1 ){ if ( p1->balance_m == ts_negative ) { // \ru однократный LL поворот \en single LL rotation @@ -612,8 +612,8 @@ inline bool BalanceTree::AddToBalanceTree( Type & content, BalanceTreeNod case ts_neutral : node->balance_m = ts_positive; break; // \ru балансировка \en balancing case ts_positive : { - BalanceTreeNode * p1 = NULL; - BalanceTreeNode * p2 = NULL; + BalanceTreeNode * p1 = c3d_null; + BalanceTreeNode * p2 = c3d_null; p1 = node->right_m; if ( p1 ) { if ( p1->balance_m == ts_positive ) { // \ru однократный RR поворот \en single RR rotation @@ -652,8 +652,8 @@ inline void BalanceTree::BalanceL( BalanceTreeNode *& node, bool & case ts_neutral : node->balance_m = ts_positive; isBranchGrew = false; break; // \ru балансировка \en balancing case ts_positive : { - BalanceTreeNode * p1 = NULL; - BalanceTreeNode * p2 = NULL; + BalanceTreeNode * p1 = c3d_null; + BalanceTreeNode * p2 = c3d_null; p1 = node->right_m; if ( p1 ) { if ( p1->balance_m >= ts_neutral ) { // \ru однократный RR поворот \en single RR rotation @@ -691,8 +691,8 @@ inline void BalanceTree::BalanceR( BalanceTreeNode *& node, bool & case ts_neutral : node->balance_m = ts_negative; isBranchGrew = false; break; // \ru балансировка \en balancing case ts_negative : { - BalanceTreeNode * p1 = NULL; - BalanceTreeNode * p2 = NULL; + BalanceTreeNode * p1 = c3d_null; + BalanceTreeNode * p2 = c3d_null; p1 = node->left_m; if ( p1 ) { if ( p1->balance_m <= ts_neutral ) { // \ru однократный LL поворот \en single LL rotation @@ -791,8 +791,8 @@ inline bool BalanceTree::DeleteFromBalanceTree( Type & content, BalanceTr } bool oldowns = owns_m; owns_m = del == Delete ? true : del == noDelete ? false : owns_m; - q->left_m = NULL; - q->right_m = NULL; + q->left_m = c3d_null; + q->right_m = c3d_null; delete q; owns_m = oldowns; allCount_m--; // \ru подсчитываем общее кол-во узлов \en compute the total count of nodes @@ -813,14 +813,14 @@ template void destroy_tree_node( BalanceTreeNode& treeNode, DelType del ) { delete treeNode.left_m; - treeNode.left_m = NULL; + treeNode.left_m = c3d_null; delete treeNode.right_m; - treeNode.right_m = NULL; + treeNode.right_m = c3d_null; bool shouldDelete = del == Delete || ( del == defDelete && treeNode.parent_m.owns_m ); if ( shouldDelete ) { delete treeNode.content_m; - treeNode.content_m = NULL; + treeNode.content_m = c3d_null; } } @@ -830,7 +830,7 @@ void destroy_tree_node( BalanceTreeNode& treeNode, DelType del ) { // --- template Type * find_tree( const BalanceTree& tree, void * content, bool compT ) { - Type * res = NULL; + Type * res = c3d_null; const BalanceTreeNode * node = tree.root_m; if ( node ) { ThreeStates compRres = ts_negative; @@ -881,7 +881,7 @@ inline void BalanceTreeIterator::Restart( IteratorType t ) { // --- template inline Type * BalanceTreeIterator::operator ++(int) { - Type * res = m_CurNode ? m_CurNode->content_m : NULL; + Type * res = m_CurNode ? m_CurNode->content_m : c3d_null; if ( m_CurNode ) Iterate( m_CurNode ); @@ -894,7 +894,7 @@ inline Type * BalanceTreeIterator::operator ++(int) { // --- template inline BalanceTreeIterator::operator Type * () const { - return m_CurNode ? m_CurNode->content_m : NULL; + return m_CurNode ? m_CurNode->content_m : c3d_null; } @@ -1016,10 +1016,10 @@ inline void BalanceTreeIterator::Iterate( BalanceTreeNode * node ) { Iterate( m_CurNode ); } else - m_CurNode = NULL; + m_CurNode = c3d_null; } else - m_CurNode = NULL; + m_CurNode = c3d_null; fRepeat = false; break; } diff --git a/C3d/Include/templ_c_array.h b/C3d/Include/templ_c_array.h index e116a25..dfce683 100644 --- a/C3d/Include/templ_c_array.h +++ b/C3d/Include/templ_c_array.h @@ -66,7 +66,7 @@ public : /// \ru Оператор доступа. \en An access operator. Type & operator []( size_t idx ) const { PRECONDITION( idx < count ); return parr[idx]; } /// \ru Выделена ли память? \en Is memory allocated? - bool IsNull () const { return parr == NULL; } + bool IsNull () const { return parr == c3d_null; } /// \ru Выдать адрес начала массива. \en Get address of the beginning of an array. const Type * GetAddr() const { return parr; } @@ -125,7 +125,7 @@ inline CcArray::CcArray( size_t _count ) template inline void CcArray::Copy( const void * from, size_t cnt, size_t offset ) { - PRECONDITION( (offset + cnt <= count) && (cnt ? from != NULL : true) ); + PRECONDITION( (offset + cnt <= count) && (cnt ? from != c3d_null : true) ); memcpy( parr + offset, from, cnt * sizeof(Type) ); } @@ -147,12 +147,12 @@ inline bool CcArray::SetArraySize( size_t newCount ) #endif #ifdef USE_REALLOC_IN_ARRAYS - if ( parr != NULL || newCount != 0 ) { - // \ru показывает утечки памяти, если parr==0 и newCount==0 \en Memory leaks happen if parr==0 and newCount==0 + if ( parr != c3d_null || newCount != 0 ) { + // \ru показывает утечки памяти, если parr==c3d_null и newCount==0 \en Memory leaks happen if parr==c3d_null and newCount==0 parr = static_cast( REALLOC_ARRAY_SIZE(parr, newCount * sizeof(Type), true/*clear*/) ); } #else - Type * p_tmp = newCount ? new Type[newCount] : NULL; + Type * p_tmp = newCount ? new Type[newCount] : c3d_null; delete[] parr; // \ru Удалять parr, если оператор new выполнился успешно. \en Delete parr if operator new is succeeded. parr = p_tmp; @@ -171,7 +171,7 @@ inline bool CcArray::SetArraySize( size_t newCount ) } catch ( ... ) { if ( newCount == 0 )// \ru Не смогли удалить parr. \en Failed to delete parr. - parr = NULL; + parr = c3d_null; C3D_CONTROLED_THROW; return false; } diff --git a/C3d/Include/templ_csp_array.h b/C3d/Include/templ_csp_array.h index 79d43d5..a123902 100644 --- a/C3d/Include/templ_csp_array.h +++ b/C3d/Include/templ_csp_array.h @@ -49,7 +49,7 @@ private: public: /// \ru Конструктор. \en Constructor. - CSPArray( size_t maxCnt = 0, uint16 delt = 1, bool shouldDelete = true, bool _keepEq = false, LessFuncPtr func = NULL ) + CSPArray( size_t maxCnt = 0, uint16 delt = 1, bool shouldDelete = true, bool _keepEq = false, LessFuncPtr func = c3d_null ) : SPArray( maxCnt, delt, shouldDelete ) , m_sort( true ) , m_keepEq( _keepEq ) @@ -181,9 +181,9 @@ inline void CSPArray::Sort( LessFuncPtr lessFunc ) template inline Type * CSPArray::RemoveObj( Type * delObject, DelType del ) { - C3D_ASSERT( SPArray::nowDeletedElem == 0 ); // \ru Bременно, для отладки \en Temporarily, for debugging. + C3D_ASSERT( SPArray::nowDeletedElem == c3d_null ); // \ru Bременно, для отладки \en Temporarily, for debugging. size_t i = Find( delObject ); - return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : 0; + return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : c3d_null; } @@ -248,7 +248,7 @@ void qp_sort_r2( Type ** arr, size_t minIndex, size_t maxIndex ) ptrdiff_t minInd = minIndex, maxInd = maxIndex; ptrdiff_t i = minInd, j = maxInd; ptrdiff_t im = 0; - Type *middle = NULL; + Type *middle = c3d_null; for ( ;; ) { i = minInd, j = maxInd; diff --git a/C3d/Include/templ_css_array.h b/C3d/Include/templ_css_array.h index e98362d..b6c7c74 100644 --- a/C3d/Include/templ_css_array.h +++ b/C3d/Include/templ_css_array.h @@ -53,14 +53,14 @@ public: , m_sort( other.m_sort ) {} /// \ru Конструктор копирования. \en Copy constructor. - CSSArray( const SArray & other, SArray * del = NULL ) + CSSArray( const SArray & other, SArray * del = c3d_null ) : SSArray( other ) , m_sort( false ) { ::q_sort( *this, del ); } /// \ru Конструктор копирования. \en Copy constructor. - CSSArray( const SArray< std::pair > & other, bool addFirst, SArray * del = NULL ) + CSSArray( const SArray< std::pair > & other, bool addFirst, SArray * del = c3d_null ) : SSArray( other.Count(), 1 ) , m_sort( false ) { @@ -100,7 +100,7 @@ public: Type * Add ( const Type & ); ///< \ru Добавить элемент с упорядочиванием по массиву. \en Add element with sorting. Type * Add ( const Type &, size_t & indexEnt ); ///< \ru Добавить элемент с упорядочиванием по массиву, возвращает индекс. \en Add element with sorting by array, returns index of the element. size_t Find( const Type & ); ///< \ru Найти элемент в упорядоченном массиве. \en Find an element in ordered array. - void Sort( SArray * del = NULL ); ///< \ru Выполнить сортировку элементов массива. \en Sort elements of array. + void Sort( SArray * del = c3d_null ); ///< \ru Выполнить сортировку элементов массива. \en Sort elements of array. size_t RemoveObj( const Type & delObject ); ///< \ru Удалить элемент из массива. \en Delete an element from array. void SetNoSort() { m_sort = false; } ///< \ru Сбросить флаг сортированности. \en Reset the flag of being sorted. @@ -121,7 +121,7 @@ public: // --- template inline Type * CSSArray::Add( const Type & el ) { - ::q_sort( *this, (SArray *)NULL ); + ::q_sort( *this, (SArray *)c3d_null ); return SSArray::Add( el ); } @@ -131,7 +131,7 @@ inline Type * CSSArray::Add( const Type & el ) { // --- template inline Type * CSSArray::Add( const Type & el, size_t & indexEl ) { - ::q_sort( *this, (SArray *)NULL ); + ::q_sort( *this, (SArray *)c3d_null ); return SSArray::Add( el, indexEl ); } @@ -146,7 +146,7 @@ inline void CSSArray::AddArray( const CSSArray & arr, bool doSort ) m_sort = false; (*this) += arr; if ( doSort ) - ::q_sort( *this, (SArray *)NULL ); + ::q_sort( *this, (SArray *)c3d_null ); } } @@ -161,7 +161,7 @@ inline void CSSArray::AddArray( const SArray & arr, bool doSort ) m_sort = false; (*this) += arr; if ( doSort ) - ::q_sort( *this, (SArray *)NULL ); + ::q_sort( *this, (SArray *)c3d_null ); } } @@ -171,7 +171,7 @@ inline void CSSArray::AddArray( const SArray & arr, bool doSort ) // --- template inline size_t CSSArray::Find( const Type & el ) { - ::q_sort( *this, (SArray *)NULL ); + ::q_sort( *this, (SArray *)c3d_null ); return SSArray::Find( el ); } diff --git a/C3d/Include/templ_dptr.h b/C3d/Include/templ_dptr.h index 1f59775..070ec4c 100644 --- a/C3d/Include/templ_dptr.h +++ b/C3d/Include/templ_dptr.h @@ -11,11 +11,6 @@ #define __TEMPL_DPTR_H -#ifndef NULL - #define NULL 0 -#endif - - #include #include @@ -94,8 +89,8 @@ private: // --- template DPtr::DPtr() - : m_Ptr ( NULL ) - , m_Owner( NULL ) + : m_Ptr ( c3d_null ) + , m_Owner( c3d_null ) { } @@ -106,9 +101,9 @@ DPtr::DPtr() template DPtr::DPtr( dtype * obj ) : m_Ptr ( obj ) - , m_Owner( NULL ) + , m_Owner( c3d_null ) { - if ( obj != NULL ) { + if ( obj != c3d_null ) { m_Owner = new Owner( obj ); m_Owner->m_RefCounter++; } @@ -123,7 +118,7 @@ DPtr::DPtr( const DPtr & dptr ) : m_Ptr( dptr.m_Ptr ) , m_Owner( dptr.m_Owner ) { - if ( m_Owner != NULL ) + if ( m_Owner != c3d_null ) m_Owner->m_RefCounter++; } @@ -136,11 +131,11 @@ DPtr & DPtr::operator = ( dtype * pObj ) { if ( m_Ptr != pObj ) { m_Ptr = pObj; - if ( m_Owner != NULL ) { + if ( m_Owner != c3d_null ) { m_Owner->Release(); - m_Owner = NULL; + m_Owner = c3d_null; } - if ( pObj != NULL ) { + if ( pObj != c3d_null ) { m_Owner = new Owner( pObj ); m_Owner->m_RefCounter++; } @@ -158,11 +153,11 @@ DPtr & DPtr::operator = ( const DPtr & dptr ) { if ( m_Ptr != dptr.m_Ptr ) { m_Ptr = dptr.m_Ptr; - if ( m_Owner != NULL ) { + if ( m_Owner != c3d_null ) { m_Owner->Release(); - m_Owner = NULL; + m_Owner = c3d_null; } - if ( dptr.m_Ptr != NULL ) { + if ( dptr.m_Ptr != c3d_null ) { m_Owner = dptr.m_Owner; m_Owner->m_RefCounter++; } diff --git a/C3d/Include/templ_fdp_array.h b/C3d/Include/templ_fdp_array.h index f34f6e9..50324e9 100644 --- a/C3d/Include/templ_fdp_array.h +++ b/C3d/Include/templ_fdp_array.h @@ -55,14 +55,14 @@ public : /// \ru Конструктор. \en Constructor. FDPArray() : RPArray() - , fDestroy( NULL ) - , nowDeletedElem(0) + , fDestroy( c3d_null ) + , nowDeletedElem(c3d_null) {} /// \ru Конструктор. \en Constructor. FDPArray( size_t i_upper, uint16 i_delta, DestroyFunc fd ) : RPArray( i_upper, i_delta) , fDestroy( fd ) - , nowDeletedElem(0) + , nowDeletedElem(c3d_null) {} /// \ru Деструктор. \en Destructor. virtual ~FDPArray(); @@ -141,8 +141,8 @@ FDPArray::FDPArray( FDPArray && _Right ) , fDestroy ( std::move(_Right.fDestroy) ) , nowDeletedElem( std::move(_Right.nowDeletedElem) ) { - _Right.fDestroy = nullptr; - _Right.nowDeletedElem = nullptr; + _Right.fDestroy = c3d_null; + _Right.nowDeletedElem = c3d_null; } //------------------------------------------------------------------------------ @@ -166,7 +166,7 @@ FDPArray & FDPArray::operator = ( FDPArray && _Right ) // --- template inline FDPArray::~FDPArray() { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); destroy_array( *this ); } @@ -177,7 +177,7 @@ inline FDPArray::~FDPArray() { // --- template inline void FDPArray::Flush( DelType del ) { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); if ( del==Delete || (del==defDelete && fDestroy) ) destroy_array( *this ); @@ -191,7 +191,7 @@ inline void FDPArray::Flush( DelType del ) { // --- template inline void FDPArray::Clear( typename FDPArray::TotalDestroyFunc fd ) { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); size_t oldCount = RPArray::count; RPArray::count = 0; // \ru сначала приведем в порядок массив ... \en put an array in order at first ... @@ -250,9 +250,9 @@ inline Type* FDPArray::RemoveInd( size_t delIndex, DelType del ) { template inline Type * FDPArray::RemoveObj( Type * delObject, DelType del ) { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); size_t i = find_in_array( *this, delObject ); - return (i != SYS_MAX_T) ? RemoveInd(i, del) : 0; + return (i != SYS_MAX_T) ? RemoveInd(i, del) : c3d_null; } @@ -295,9 +295,9 @@ inline Type* FDPArray::DestroyInd( size_t delIndex, typename FDPArray inline Type * FDPArray::DestroyObj( Type * delObject, typename FDPArray::DestroyFunc fd ) { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); size_t i = find_in_array( *this, delObject ); - return ( i != SYS_MAX_T ) ? DestroyInd( i, fd ) : 0; + return ( i != SYS_MAX_T ) ? DestroyInd( i, fd ) : c3d_null; } @@ -334,7 +334,7 @@ void destroy_array( FDPArray & arr ) template bool set_Farray_size( FDPArray & arr, size_t newSize, bool clear ) { - PRECONDITION( arr.nowDeletedElem == 0 ); + PRECONDITION( arr.nowDeletedElem == c3d_null ); if ( clear && arr.count ) arr.Flush(); // \ru будет arr.count = 0; \en arr.count will be equal 0; diff --git a/C3d/Include/templ_fdp_array_rw.h b/C3d/Include/templ_fdp_array_rw.h index 4587d92..569ec30 100644 --- a/C3d/Include/templ_fdp_array_rw.h +++ b/C3d/Include/templ_fdp_array_rw.h @@ -46,11 +46,11 @@ reader & operator >> ( reader & in, FDPArray & ref ) const Type ** parr = ref.GetAddr(); - if ( parr != NULL ) { + if ( parr != c3d_null ) { size_t i; // \ru поочередное чтение объектов массива \en successive reading of objects from an array for ( i = 0; i < count && in.good(); i++ ) { - Type * el = NULL; + Type * el = c3d_null; in >> el; parr[i] = el; } @@ -98,7 +98,7 @@ writer & operator << ( writer & out, const FDPArray & ref ) template reader & operator >> ( reader & in, FDPArray *& ptr ) { - ptr = NULL; + ptr = c3d_null; if ( in.good() ) { if ( in.MathVersion() < 0x06000012L ) ptr = new FDPArray; @@ -168,7 +168,7 @@ static void TotalDestroy( Type ** arr, size_t count ) { size_t i = 0; for ( Type** parr = arr; i < count; i++, parr++ ) { Type *del = *parr; - *parr = NULL; // \ru Cначала обнулить ... \en Set to null at first... + *parr = c3d_null; // \ru Cначала обнулить ... \en Set to null at first... delete del; // \ru ... потом удалить \en ... then delete } } diff --git a/C3d/Include/templ_ifc_array.h b/C3d/Include/templ_ifc_array.h index 7138cac..6402f21 100644 --- a/C3d/Include/templ_ifc_array.h +++ b/C3d/Include/templ_ifc_array.h @@ -50,7 +50,7 @@ public: typedef const value_type * pointer; public: - iterator() { m_curr = NULL; } + iterator() { m_curr = c3d_null; } iterator( const stored_type * ptr ) { m_curr = ptr; } iterator( const iterator & iter ) { m_curr = iter.m_curr; } stored_type operator*() const { return *m_curr; } @@ -165,10 +165,10 @@ public: template inline void IFCArray_Release( Type * & el ) { - if ( el != NULL && el->Release() == 0 ) + if ( el != c3d_null && el->Release() == 0 ) { // AS K11 27.05.2008 Обнулять, только если объект действительно удален. - el = NULL; + el = c3d_null; } } @@ -211,7 +211,7 @@ inline IFC_Array::~IFC_Array() // --- template inline void IFC_Array::Add( Type* ent ) { - if ( ent != NULL ) + if ( ent != c3d_null ) ent->AddRef(); RPArray::Add( ent ); } @@ -222,7 +222,7 @@ inline void IFC_Array::Add( Type* ent ) { // --- template inline void IFC_Array::AddAt( stored_type ent, size_t ind ) { - if ( ent != NULL ) + if ( ent != c3d_null ) ent->AddRef(); RPArray::AddAt( ent, ind ); } @@ -233,7 +233,7 @@ inline void IFC_Array::AddAt( stored_type ent, size_t ind ) { // --- template inline void IFC_Array::AddAfter( stored_type ent, size_t ind ) { - if ( ent != NULL ) + if ( ent != c3d_null ) ent->AddRef(); RPArray::AddAfter( ent, ind ); } @@ -244,10 +244,10 @@ inline void IFC_Array::AddAfter( stored_type ent, size_t ind ) { // --- template inline void IFC_Array::SetAt( stored_type ent, size_t ind ) { - if ( ent != NULL ) + if ( ent != c3d_null ) ent->AddRef(); Type * & el = RPArray::operator[](ind); - if ( el != NULL ) + if ( el != c3d_null ) el->Release(); el = ent; } diff --git a/C3d/Include/templ_im_array.h b/C3d/Include/templ_im_array.h index a15a6ae..5e625e0 100644 --- a/C3d/Include/templ_im_array.h +++ b/C3d/Include/templ_im_array.h @@ -73,8 +73,8 @@ public: void RemoveInd ( size_t delIndex, bool completely = true ); // \ru удалить элемент из массива \en delete an element from array void RemoveObj ( const size_t & delObject, bool completely = true ); // \ru удалить элемент из массива \en delete an element from array - Type * ReindexInd( size_t ind, size_t * = NULL ); // \ru заменить элемент с упорядочиванием по массиву \en replace element with sorting - size_t ReindexObj( Type * ent, size_t * = NULL ); // \ru заменить элемент с упорядочиванием по массиву \en replace element with sorting + Type * ReindexInd( size_t ind, size_t * = c3d_null ); // \ru заменить элемент с упорядочиванием по массиву \en replace element with sorting + size_t ReindexObj( Type * ent, size_t * = c3d_null ); // \ru заменить элемент с упорядочиванием по массиву \en replace element with sorting Type * ReindexMyInd( size_t ); // \ru заменить элемент с упорядочиванием по массиву \en replace element with sorting diff --git a/C3d/Include/templ_iterator.h b/C3d/Include/templ_iterator.h index 5292cb1..5377d21 100644 --- a/C3d/Include/templ_iterator.h +++ b/C3d/Include/templ_iterator.h @@ -53,9 +53,9 @@ public: /// \ru Сброс итератора. \en Reset iterator. virtual void Restart() { index = 0; } /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move an iterator to the next. - virtual Type * operator ++(int) { return (index < items.Count()) ? items[index++] : NULL; } + virtual Type * operator ++(int) { return (index < items.Count()) ? items[index++] : c3d_null; } /// \ru Получить текущий элемент \en Get the current element - virtual Type * operator() () const { return (index < items.Count()) ? items[index] : NULL; } + virtual Type * operator() () const { return (index < items.Count()) ? items[index] : c3d_null; } private: // \ru не реализовано \en not implemented PointersArrayIterator & operator = ( const PointersArrayIterator & ); diff --git a/C3d/Include/templ_kdtree.h b/C3d/Include/templ_kdtree.h index dcec6f7..ba3c8f4 100644 --- a/C3d/Include/templ_kdtree.h +++ b/C3d/Include/templ_kdtree.h @@ -235,7 +235,7 @@ inline bool PriorityQueue::Initialize( size_t _maxSize ) elements = new Element[maxSize]; } catch ( ... ) { - elements = NULL; + elements = c3d_null; maxSize = count = 0; C3D_CONTROLED_THROW; return false; diff --git a/C3d/Include/templ_lis_array.h b/C3d/Include/templ_lis_array.h index 810a74b..ffb078a 100644 --- a/C3d/Include/templ_lis_array.h +++ b/C3d/Include/templ_lis_array.h @@ -176,7 +176,7 @@ inline LiSArray & LiSArray::operator = ( const LiSArray & o ) set_array_size( *this, o.count ); // \ru обеспечить память на такое кол-во элементов \en allocate memory for the given number of elements count = o.count; C3D_ASSERT( count < 254 ); - if ( count > 0 && parr != NULL ) + if ( count > 0 && parr != c3d_null ) memcpy( parr, o.parr, count * sizeof(Type) ); return *this; @@ -190,7 +190,7 @@ inline LiSArray & LiSArray::operator += ( const LiSArray & o ) { if ( o.count ) { set_array_size( *this, count + o.count ); // \ru обеспечить память на такое кол-во элементов \en allocate memory for the given number of elements - if ( parr != NULL ) + if ( parr != c3d_null ) memcpy( parr+count, o.parr, o.count * sizeof(Type) ); count = (uint8)(count + o.count); diff --git a/C3d/Include/templ_multimap.h b/C3d/Include/templ_multimap.h index 0bdf1cd..afdc568 100644 --- a/C3d/Include/templ_multimap.h +++ b/C3d/Include/templ_multimap.h @@ -94,7 +94,7 @@ private: }; template struct Null { // \ru Нуль указателей. \en Null of pointers. - static inline T* val() { return NULL; } + static inline T* val() { return c3d_null; } }; // \ru LF_Linux: 25.03.11 g++ выдает ошибку на этот код - не использованы KeyType, ValType в полной специализации шаблона. // Однако непонятно, зачем нужна эта полная специализация - общая частичная специализация для тривиальных типов вполне подойдет. @@ -113,9 +113,9 @@ public: Pair * m_MaxPtr; public: - Iterator() : m_Ptr( NULL ), m_MaxPtr( NULL ) {} + Iterator() : m_Ptr( c3d_null ), m_MaxPtr( c3d_null ) {} Iterator( const Iterator & iter ) : m_Ptr( iter.m_Ptr ), m_MaxPtr( iter.m_MaxPtr ) {} - Iterator( const SArray & m_Pairs, const Pair & pair ) : m_Ptr( NULL ), m_MaxPtr( NULL ) + Iterator( const SArray & m_Pairs, const Pair & pair ) : m_Ptr( c3d_null ), m_MaxPtr( c3d_null ) { const size_t count = m_Pairs.Count(); if ( count > 0 ) { @@ -135,10 +135,10 @@ public: } } Iterator( const SArray & m_Pairs, const Iterator & iter1, const Iterator & iter2 ) // range - : m_Ptr( NULL ), m_MaxPtr( NULL ) + : m_Ptr( c3d_null ), m_MaxPtr( c3d_null ) { const size_t count = m_Pairs.Count(); - if ( count > 0 && iter1.m_Ptr != NULL ) { + if ( count > 0 && iter1.m_Ptr != c3d_null ) { size_t idx1 = MultiMap::LowerBoundEx( m_Pairs, iter1.m_Ptr->m_key ); size_t temp = idx1; while ( temp < m_Pairs.Count() && m_Pairs[temp].m_key == iter1.m_Ptr->m_key ) { @@ -149,7 +149,7 @@ public: temp++; } size_t idx2 = SYS_MAX_T; - if ( iter2.m_Ptr != NULL ) { + if ( iter2.m_Ptr != c3d_null ) { idx2 = MultiMap::UpperBoundEx( m_Pairs, iter2.m_Ptr->m_key ); if ( idx2 < m_Pairs.Count() ) { if ( idx2 > 0) diff --git a/C3d/Include/templ_p_array.h b/C3d/Include/templ_p_array.h index 518df40..ddfc5cc 100644 --- a/C3d/Include/templ_p_array.h +++ b/C3d/Include/templ_p_array.h @@ -52,13 +52,13 @@ public : PArray() : RPArray() , owns( true ) - , nowDeletedElem(0) + , nowDeletedElem(c3d_null) {} /// \ru Конструктор. \en Constructor. PArray( size_t i_upper, uint16 i_delta = 1, bool shouldDelete = true )//, bool shouldNullSet = false ) : RPArray( i_upper, i_delta )//, shouldNullSet ) , owns( shouldDelete ) - , nowDeletedElem(0) + , nowDeletedElem(c3d_null) {} /// \ru Деструктор. \en Destructor. virtual ~PArray(); @@ -221,7 +221,7 @@ private: // --- template inline PArray::~PArray() { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); if ( owns ) destroy_array( *this ); } @@ -232,7 +232,7 @@ inline PArray::~PArray() { // --- template inline void PArray::Flush( DelType del ) { - PRECONDITION( nowDeletedElem == 0 ); + PRECONDITION( nowDeletedElem == c3d_null ); if ( del==Delete || (del==defDelete && owns) ) destroy_array( *this ); @@ -289,10 +289,10 @@ inline Type * PArray::RemoveInd( size_t delIndex, DelType del ) { // --- template inline Type * PArray::RemoveObj( Type * delObject, DelType del ) { - PRECONDITION( nowDeletedElem == 0 ); // \ru временно, для отладки \en temporarily, for debugging + PRECONDITION( nowDeletedElem == c3d_null ); // \ru временно, для отладки \en temporarily, for debugging size_t i = find_in_array( *this, delObject ); - return (i != SYS_MAX_T) ? RemoveInd(i, del) : 0; + return (i != SYS_MAX_T) ? RemoveInd(i, del) : c3d_null; } @@ -326,7 +326,7 @@ void destroy_array( PArray & arr ) { // --- template bool set_Parray_size( PArray & arr, size_t newSize, bool clear ) { - PRECONDITION( arr.nowDeletedElem == 0 ); // \ru временно \en temporarily + PRECONDITION( arr.nowDeletedElem == c3d_null ); // \ru временно \en temporarily if ( clear && arr.count ) arr.Flush(); // \ru будет arr.count = 0; \en arr.count will be equal 0; @@ -354,7 +354,7 @@ bool set_Parray_size( PArray & arr, size_t newSize, bool clear ) { // --- //template //inline void PIArray::ForEachI( IteratorFunc func ) const { -// \ru C3D_ASSERT( PArray::nowDeletedElem == 0 ); // временно \en C3D_ASSERT( PArray::nowDeletedElem == 0 ); // temporarily +// \ru C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // временно \en C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // temporarily //#if !defined ( __INTEL_COMPILER ) /// for Intel C++ Compiler // for_each_in_array( *this, func ); //#endif // __INTEL_COMPILER @@ -366,7 +366,7 @@ bool set_Parray_size( PArray & arr, size_t newSize, bool clear ) { // --- template inline void PIArray::ForEachI( ParIteratorFunc func, void * pars ) const { - PRECONDITION( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == c3d_null ); for_each_in_array( *this, func, pars ); } @@ -376,7 +376,7 @@ inline void PIArray::ForEachI( ParIteratorFunc func, void * pars ) const { // --- template inline size_t PIArray::FirstThatI( CompareFunc func, void * pars, size_t from ) const { - PRECONDITION( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == c3d_null ); return first_that_in_array( *this, func, pars, from ); } @@ -386,7 +386,7 @@ inline size_t PIArray::FirstThatI( CompareFunc func, void * pars, size_t f // --- //template //inline void PMIArray::ForEach( IteratorMemFunc func ) const { -// \ru C3D_ASSERT( PArray::nowDeletedElem == 0 ); +// \ru C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); //#if !defined ( __INTEL_COMPILER ) /// for Intel C++ Compiler // for_each_in_array( *this, func ); //#endif // __INTEL_COMPILER @@ -398,7 +398,7 @@ inline size_t PIArray::FirstThatI( CompareFunc func, void * pars, size_t f // --- template inline void PMIArray::ForEach( ParIteratorMemFunc func, void * pars ) const { - PRECONDITION( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == c3d_null ); for_each_in_array( *this, func, pars ); } @@ -408,7 +408,7 @@ inline void PMIArray::ForEach( ParIteratorMemFunc func, void * pars ) cons // --- template inline size_t PMIArray::FirstThat( CompareMemFunc func, void * pars, size_t from ) const { - PRECONDITION( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == c3d_null ); return first_that_in_array( *this, func, pars, from ); } diff --git a/C3d/Include/templ_p_array_rw.h b/C3d/Include/templ_p_array_rw.h index 4b42c85..0757c5a 100644 --- a/C3d/Include/templ_p_array_rw.h +++ b/C3d/Include/templ_p_array_rw.h @@ -45,7 +45,7 @@ reader & operator >> ( reader & in, PArray & ref ) const Type ** parr = ref.GetAddr(); - if ( parr != NULL ) + if ( parr != c3d_null ) { ref.count = 0; // \ru Err #69421 сколько штук реально прочитано \en Err #69421 how many elements were actually counted @@ -53,7 +53,7 @@ reader & operator >> ( reader & in, PArray & ref ) // \ru поочередное чтение объектов массива \en successive reading of objects from an array for ( i = 0; i < count && in.good(); i++ ) { - Type * el = NULL; + Type * el = c3d_null; in >> el; parr[i] = el; @@ -121,7 +121,7 @@ writer & operator << ( writer& out, const PArray & ref ) template reader & operator >> ( reader & in, PArray *& ptr ) { - ptr = NULL; + ptr = c3d_null; if ( in.good() ) { if ( in.MathVersion() < 0x06000012L ) ptr = new PArray; diff --git a/C3d/Include/templ_pointer.h b/C3d/Include/templ_pointer.h index dbcd2f3..0aa987d 100644 --- a/C3d/Include/templ_pointer.h +++ b/C3d/Include/templ_pointer.h @@ -11,11 +11,6 @@ #define __TEMPL_POINTER_H -#ifndef NULL -#define NULL 0 -#endif - - #include @@ -43,31 +38,31 @@ public: T & operator * () const { return *P; } operator T* () const { return P; } - int operator ! () const { return (P == NULL);} - T * Relinquish() {T * p = P; P = NULL; return p;} + int operator ! () const { return (P == c3d_null);} + T * Relinquish() {T * p = P; P = c3d_null; return p;} T * Get() { return P; } const T * Get() const { return P; } protected: TPointerBase( T * pointer ) : P(pointer) {} - TPointerBase() : P( NULL ) {} + TPointerBase() : P( c3d_null ) {} protected: T * P; private: void * operator new( size_t ); // prohibit use of new - void operator delete( void * p ) { ((TPointerBase*)p)->P = NULL; } + void operator delete( void * p ) { ((TPointerBase*)p)->P = c3d_null; } // СМВ К15 MVS 2012 private: TPointerBase( const TPointerBase & other ); #ifdef C3D_STANDARD_CXX_11_PARTIAL public: - TPointerBase( TPointerBase && _Right ): P( _Right.P ) { _Right.P = nullptr; } + TPointerBase( TPointerBase && _Right ): P( _Right.P ) { _Right.P = c3d_null; } TPointerBase & operator = ( TPointerBase && _Right ) { if ( this != &_Right ) - { P = _Right.P; _Right.P = nullptr; } + { P = _Right.P; _Right.P = c3d_null; } return *this; } #endif // C3D_STANDARD_CXX_11_PARTIAL @@ -103,8 +98,8 @@ public: } return *this; } - T * operator ->() { return TPointerBase::P; } // Could throw exception if P==0 - const T * operator ->() const { return TPointerBase::P; } // Could throw exception if P==0 + T * operator ->() { return TPointerBase::P; } // Could throw exception if P==c3d_null + const T * operator ->() const { return TPointerBase::P; } // Could throw exception if P==c3d_null // СМВ К15 MVS 2012 #ifndef __MOBILE_VERSION__ @@ -123,7 +118,7 @@ public: { delete TPointerBase::P; TPointerBase::P = _Right.P; - _Right.P = nullptr; + _Right.P = c3d_null; } return *this; } @@ -165,7 +160,7 @@ public: } return *this; } - T * operator ->() { return TPointerBase::P; } // Could throw exception if P==0 + T * operator ->() { return TPointerBase::P; } // Could throw exception if P==c3d_null bool GetOwn() const { return own; } void SetOwn( bool val ) { own = val; } @@ -187,7 +182,7 @@ public: delete TPointerBase::P; TPointerBase::P = _Right.P; own = _Right.own; - _Right.P = nullptr; + _Right.P = c3d_null; } return *this; } @@ -226,7 +221,7 @@ public: } return *this; } - T & operator []( size_t i ) { return TPointerBase::P[i]; } // Could throw exception if P==0 + T & operator []( size_t i ) { return TPointerBase::P[i]; } // Could throw exception if P==c3d_null // СМВ К15 MVS 2012 //private: // g++4.7 KUbuntu @@ -242,7 +237,7 @@ public: { delete[] TPointerBase::P; TPointerBase::P = _Right.P; - _Right.P = nullptr; + _Right.P = c3d_null; } return *this; } @@ -284,7 +279,7 @@ public: { delete[] P; P = _Right.P; - _Right.P = nullptr; + _Right.P = c3d_null; } return *this; } diff --git a/C3d/Include/templ_psrt_array.h b/C3d/Include/templ_psrt_array.h index bf87551..fcdd487 100644 --- a/C3d/Include/templ_psrt_array.h +++ b/C3d/Include/templ_psrt_array.h @@ -108,13 +108,13 @@ public: void DetachRng ( size_t, size_t ); // \ru отцепить из массива диапазон указателей \en detach a range of pointers from array typedef int (*PArSortCompFunc)( const Type **, const Type ** ); - void Sort ( PArSortCompFunc, PArrayReg * = NULL ); // \ru быстрая сортировка в любом диапазоне \en quick sorting in any range + void Sort ( PArSortCompFunc, PArrayReg * = c3d_null ); // \ru быстрая сортировка в любом диапазоне \en quick sorting in any range void Sort ( const void *, PArSortRangeCompFunc, size_t armin = 0, size_t armax = SYS_MAX_T ); // \ru быстрая сортировка в заданном диапазоне \en quick sorting in a given range bool Find ( const Type *, PArSortAddress, size_t &, size_t armin = 0, size_t armax = SYS_MAX_T ); // \ru найти адрес в любом поле объекта \en find address in any field of object bool Find ( const size_t, PArSortAddress, size_t &, size_t armin = 0, size_t armax = SYS_MAX_T ); // \ru найти адрес в любом поле объекта \en find address in any field of object bool Find ( const void *, PArSortObj, size_t &, size_t armin = 0, size_t armax = SYS_MAX_T ); // \ru найти данный объект в сортированном массиве \en find a given object in sorted array - int FindObj ( const Type *, PArSortCompFunc, size_t &, PArrayReg * = NULL ) const; // \ru найти данный объект в сортированном массиве \en find a given object in sorted array + int FindObj ( const Type *, PArSortCompFunc, size_t &, PArrayReg * = c3d_null ) const; // \ru найти данный объект в сортированном массиве \en find a given object in sorted array Type * AddSort ( Type *, PArSortCompFunc, size_t & ); // \ru добавить элемент в сортированном порядке \en add element in sorted order void Inverse (); // \ru инверсия массива \en inversion of array @@ -210,7 +210,7 @@ inline void PArraySort::Insert( size_t index, Type * ent ) template void PArraySort::RemoveRng( size_t startIndex, size_t countRng, DelType del ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily // \ru если диапазон не пуст и индекс принадлежит массиву \en if range is not empty and index belongs to array if ( countRng && startIndex < PArray::count ) { @@ -226,14 +226,14 @@ void PArraySort::RemoveRng( size_t startIndex, size_t countRng, DelType de size_t i = 0; for( const Type ** parr = PArray::GetAddr() + startIndex; i < countRng; i++, parr++ ) { Type * d = (Type*)*parr; - *parr = 0; // \ru сначала обнулим указатель ... \en set pointer to null ... + *parr = c3d_null; // \ru сначала обнулим указатель ... \en set pointer to null ... C3D_ASSERT( !d || PArray::nowDeletedElem != d ); // \ru ЯТ - временно \en ЯТ - temporarily PArray::nowDeletedElem = d; delete d; - PArray::nowDeletedElem = 0; + PArray::nowDeletedElem = c3d_null; } } @@ -293,7 +293,7 @@ inline size_t PArraySort::CalculateDelta() template inline void PArraySort::CatchMemory() { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( PArray::upper == PArray::count ) set_Parray_size( *this, PArray::upper + CalculateDelta(), false/*clear*/ ); } @@ -305,7 +305,7 @@ inline void PArraySort::CatchMemory() template inline void PArraySort::Reserve( size_t n ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily // \ru если требуется памяти больше, чем есть сейчас, и больше, чем оказалось бы \en if there is required more memory that exists at the moment and more than it would become // \ru при следующем захвате, то захватить ее \en on the next allocation then allocate it size_t space = PArray::upper - PArray::count; @@ -320,7 +320,7 @@ inline void PArraySort::Reserve( size_t n ) template inline void PArraySort::Sort( PArSortCompFunc fcmp, PArrayReg * arReg ) { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( PArray::count > 1 ) { // \ru если хотя бы два элемента в массиве \en if there are at least two elements in array typedef int (*QCompFunc)( const void*, const void* ); if ( !arReg ) { @@ -345,7 +345,7 @@ inline void PArraySort::Sort( PArSortCompFunc fcmp, PArrayReg * arReg ) template inline void PArraySort::Sort( const void * obj, PArSortRangeCompFunc fcmp, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( PArray::count > 1 ) { // \ru если хотя бы два элемента в массиве \en if there are at least two elements in array if ( armax > armin ) { // \ru если диапазон сортировки правильный \en if the sorting range is correct if ( armin < PArray::count - 1 ) { // \ru если минимальная граница меньше максимального элемента в массиве \en if the minimum bound is less than the maximum element in array @@ -364,7 +364,7 @@ inline void PArraySort::Sort( const void * obj, PArSortRangeCompFunc fcmp, template void PArraySort::SortRange( const void * obj, PArSortRangeCompFunc fcmp, size_t ilo, size_t ihi ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily size_t lo = ilo; // \ru нижняя граница \en lower bound size_t hi = ihi; // \ru верхняя граница \en upper bound @@ -404,7 +404,7 @@ template inline bool PArraySort::Find( const size_t address, PArSortAddress fadr, size_t & findedAddress, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily bool res = false; findedAddress = SYS_MAX_T/*OV_x64 -1*/; @@ -432,7 +432,7 @@ inline bool PArraySort::Find( const size_t address, PArSortAddress fadr, s template inline bool PArraySort::Find( const Type * member, PArSortAddress fadr, size_t & findedAddress, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily return Find( fadr(member), fadr, findedAddress, armin, armax ); } @@ -443,7 +443,7 @@ inline bool PArraySort::Find( const Type * member, PArSortAddress fadr, si template inline bool PArraySort::Find( const void * obj, PArSortObj fobj, size_t & findedId, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily bool res = false; @@ -472,7 +472,7 @@ inline bool PArraySort::Find( const void * obj, PArSortObj fobj, size_t & template bool PArraySort::FindObject( const void * obj, PArSortObj fobj, size_t & findedId, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily bool res = false; // \ru флаг, который указывает существует ли искомый объект в массиве \en flag which specifies whether the required object is in array @@ -513,7 +513,7 @@ bool PArraySort::FindObject( const void * obj, PArSortObj fobj, size_t & f template bool PArraySort::FindAddress( const size_t address, PArSortAddress fadr, size_t & findedAddress, size_t armin, size_t armax ) { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily bool res = false; // \ru флаг, который указывает существует ли искомый адресс в массиве \en flag which specifies whether the required address is in array size_t id = armax - armin; // \ru количество элементов в диапазоне \en the number of elements in range @@ -612,7 +612,7 @@ bool PArraySort::FindAddress( const size_t address, PArSortAddress fadr, s template int PArraySort::FindObj( const Type * obj, PArSortCompFunc fcmp, size_t & iFnd, PArrayReg * arReg ) const { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( (PArray::count) > 0 ) { size_t id = PArray::count; // \ru количество элементов в диапазоне \en the number of elements in range id--; @@ -686,7 +686,7 @@ int PArraySort::FindObj( const Type * obj, PArSortCompFunc fcmp, size_t & template inline Type * PArraySort::AddSort( Type * obj, PArSortCompFunc fcmp, size_t & iFnd ) { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily int ires = FindObj( obj, fcmp, iFnd ); if ( (ires == -2) || (ires == 2) ) { iFnd = ( (ires == -2) ? 0 : PArray::count ); @@ -696,7 +696,7 @@ inline Type * PArraySort::AddSort( Type * obj, PArSortCompFunc fcmp, size_ if ( ires == -1 ) AddAt( obj, iFnd ); - return ires ? (*this)/*parr*/[iFnd] : NULL; + return ires ? (*this)/*parr*/[iFnd] : c3d_null; } @@ -706,7 +706,7 @@ inline Type * PArraySort::AddSort( Type * obj, PArSortCompFunc fcmp, size_ template void PArraySort::Inverse() { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + C3D_ASSERT( PArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( PArray::count ) { size_t endI = PArray::count - 1; // \ru проверено count > 0 \en count > 0 validated diff --git a/C3d/Include/templ_rp_array.h b/C3d/Include/templ_rp_array.h index bbf8b7e..528cb7f 100644 --- a/C3d/Include/templ_rp_array.h +++ b/C3d/Include/templ_rp_array.h @@ -105,7 +105,7 @@ public: /// \ru Оператор доступа по индексу. \en Access by index operator. Type *& operator []( size_t loc ) const; /// \ru Получить адрес последнего элемента в массиве. \en Get the address of the last element in the array. - Type * GetLast() const { return ((count > 0) ? parr[count-1] : (Type*)NULL); } + Type * GetLast() const { return ((count > 0) ? parr[count-1] : (Type*)c3d_null); } public: // \ru унификация с вектором STL \en unification with STL vector bool empty() const { return count == 0; } @@ -241,7 +241,7 @@ inline RPArray::RPArray( RPArray && _Right ) _Right.count = 0; _Right.upper = 0; _Right.delta = 1; - _Right.parr = nullptr; + _Right.parr = c3d_null; } //------------------------------------------------------------------------------ @@ -691,7 +691,7 @@ bool set_Rarray_size( RPArray & arr, size_t newSize ) } catch ( ... ) { if ( newSize == 0 )// \ru Не смогли корректно удалить arr.parr. \en Failed to delete arr.parr correctly. - arr.parr = NULL; + arr.parr = c3d_null; C3D_CONTROLED_THROW; return false; } diff --git a/C3d/Include/templ_rp_array_rw.h b/C3d/Include/templ_rp_array_rw.h index fe85cc2..b34a3c2 100644 --- a/C3d/Include/templ_rp_array_rw.h +++ b/C3d/Include/templ_rp_array_rw.h @@ -38,7 +38,7 @@ reader & operator >> ( reader & in, RPArray & ref ) const Type ** parr = ref.GetAddr(); - if ( parr != NULL ) { + if ( parr != c3d_null ) { size_t i; // \ru поочередное чтение объектов массива \en successive reading of objects from an array for ( i = 0; i < count && in.good(); i++ ) { @@ -88,7 +88,7 @@ writer& operator << ( writer& out, const RPArray& ref ) { // --- template reader& operator >> ( reader& in, RPArray*& ptr ) { - ptr = NULL; + ptr = c3d_null; if ( in.good() ) { uint8 existPtr; in >> existPtr; diff --git a/C3d/Include/templ_rp_stack.h b/C3d/Include/templ_rp_stack.h index 0f01451..a71110b 100644 --- a/C3d/Include/templ_rp_stack.h +++ b/C3d/Include/templ_rp_stack.h @@ -31,7 +31,7 @@ public: public: void Push( Type & obj ); ///< \ru Добавить элемент в стек. \en Add an element to the stack. - Type * Pop(); ///< \ru Извлечь один элемент стека, если возвращаетя NULL, значит достигнуто дно стека. \en Retrieve one element from the stack, if NULL is returned then the bottom of stack is reached. + Type * Pop(); ///< \ru Извлечь один элемент стека, если возвращаетя c3d_null, значит достигнуто дно стека. \en Retrieve one element from the stack, if c3d_null is returned then the bottom of stack is reached. Type * Top() const; ///< \ru Верхний элемент стека. \en The top element of the stack. // \ru Оставить доступными следующие методы: \en Leave an access to the next methods: @@ -65,7 +65,7 @@ Type * RPStack::Pop() { RPArray::count--; return ret; } - return NULL; + return c3d_null; } @@ -77,7 +77,7 @@ Type * RPStack::Top() const { if ( RPArray::count > 0 ) { return (*this)[RPArray::count-1]; } - return NULL; + return c3d_null; } diff --git a/C3d/Include/templ_rw_operator.h b/C3d/Include/templ_rw_operator.h index 7647336..aefad2e 100644 --- a/C3d/Include/templ_rw_operator.h +++ b/C3d/Include/templ_rw_operator.h @@ -21,7 +21,7 @@ template inline reader & ReadPtrByRefDCtor ( reader & in, Type *& ptr ) { - ptr = NULL; + ptr = c3d_null; char exist; in >> exist; @@ -42,7 +42,7 @@ inline reader & ReadPtrByRefDCtor ( reader & in, Type *& ptr ) template inline reader & ReadPtrByRefRWCtor ( reader & in, Type *& ptr ) { - ptr = NULL; + ptr = c3d_null; char exist; in >> exist; @@ -62,7 +62,7 @@ inline reader & ReadPtrByRefRWCtor ( reader & in, Type *& ptr ) template inline writer & WritePtrByRef ( writer & out, const Type * ptr ) { - char exist = (ptr != NULL); + char exist = (ptr != c3d_null); out << exist; if ( exist ) diff --git a/C3d/Include/templ_s_array.h b/C3d/Include/templ_s_array.h index 7696137..b26b7ea 100644 --- a/C3d/Include/templ_s_array.h +++ b/C3d/Include/templ_s_array.h @@ -390,13 +390,19 @@ inline bool SArray::AddMemory( size_t n ) { template inline void SArray::resize( size_t n, Type val ) { - size_t n0 = count; - if ( AddItems(n) != 0 ) { - if ( parr != NULL ) { - for ( size_t k = n0; k < count; k++ ) - parr[k] = val; + if ( n > count ) { + size_t n0 = count; + if ( AddItems( n - count ) != 0 ) { + if ( parr != c3d_null ) { + for ( size_t k = n0; k < n; ++k ) + parr[k] = val; + } } } + else if ( n < count ) { + count = n; + Adjust(); + } } @@ -417,7 +423,7 @@ template inline Type * SArray::Add() { if ( CatchMemory() ) return &parr[ count++ ]; - return NULL; + return c3d_null; } @@ -438,7 +444,7 @@ inline Type * SArray::Add( const Type & ent ) { if ( CatchMemory() ) return static_cast( memcpy(static_cast(parr+count++), static_cast(&ent), sizeof(Type)) ); - return NULL; + return c3d_null; } @@ -455,7 +461,7 @@ inline Type * SArray::AddAfter( const Type & ent, size_t index ) { return (Type*)memcpy( parr + index + 1, &ent, sizeof(Type) ); } - return NULL; + return c3d_null; } @@ -477,7 +483,7 @@ inline Type * SArray::InsertInd( size_t index, const Type & ent ) { return (Type*)memcpy( parr + index, &ent, sizeof(Type) ); // \ru записываем новый элемент \en writing new element } - return NULL; + return c3d_null; } @@ -495,7 +501,7 @@ inline Type * SArray::InsertInd( size_t index ) { return (Type*)( parr + index ); // \ru записываем новый элемент \en writing new element } - return NULL; + return c3d_null; } @@ -819,7 +825,7 @@ bool set_array_size( SArray & arr, size_t newSize, bool clear ) #else //YYK V15 #77319 Type * p_tmp = newSize ? (Type*)new char[ newSize * sizeOfType ] : 0; #ifdef C3D_WINDOWS //_MSC_VER // win - Type * p_tmp = newSize ? (Type*)_aligned_malloc( newSize * sizeOfType, 16 ) : NULL; + Type * p_tmp = newSize ? (Type*)_aligned_malloc( newSize * sizeOfType, 16 ) : c3d_null; #else Type * p_tmp = newSize ? (Type*)new char[newSize * sizeOfType] : 0; #endif // win @@ -851,7 +857,7 @@ bool set_array_size( SArray & arr, size_t newSize, bool clear ) } catch ( ... ) { if ( newSize == 0 ) { // \ru Не смогли корректно удалить arr.parr. \en Failed to delete arr.parr correctly. - arr.parr = NULL; + arr.parr = c3d_null; arr.upper = newSize; } newSize = 0; // \ru т.к. ниже есть код с применением newSize \en because there is a code with using of newSize below diff --git a/C3d/Include/templ_s_array_rw.h b/C3d/Include/templ_s_array_rw.h index 75d9eaf..5527664 100644 --- a/C3d/Include/templ_s_array_rw.h +++ b/C3d/Include/templ_s_array_rw.h @@ -41,7 +41,7 @@ reader & operator >> ( reader & in, SArray & ref ) ref.SetSize( count, true/*clear*/ ); C3D_ASSERT( ref.upper >= count ); - if ( ref.GetAddr() != NULL ) { + if ( ref.GetAddr() != c3d_null ) { size_t i; for ( i = 0; i < count && in.good(); i++ ) { @@ -95,7 +95,7 @@ writer& operator << ( writer& out, const SArray& ref ) { // template reader& operator >> ( reader& in, SArray*& ptr ) { - ptr = NULL; + ptr = c3d_null; if ( in.good() ) { if ( in.MathVersion() < 0x06000012L ) ptr = new SArray; diff --git a/C3d/Include/templ_s_list.h b/C3d/Include/templ_s_list.h index 77af271..de0460d 100644 --- a/C3d/Include/templ_s_list.h +++ b/C3d/Include/templ_s_list.h @@ -101,10 +101,10 @@ public: explicit List( bool ownsEl = true ) : owns( ownsEl ) , count( 0 ) - , first( 0 ) - , last( 0 ) - , nowDelItem( 0 ) - , nowDelElem( 0 ) + , first( c3d_null ) + , last( c3d_null ) + , nowDelItem( c3d_null ) + , nowDelElem( c3d_null ) {} virtual ~List(); @@ -138,21 +138,21 @@ public: void Split(); // \ru разомкнуть список \en split the list size_t Count() const { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); return count; } // \ru дать количество элементов в списке \en get the number of elements in the list size_t ReCalc() { return recalc_list(*this); }// \ru пересчитать количество элементов в списке \en count the number of elements in the list bool IsEmpty () const { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); return first == 0; } // \ru проверить, пустой ли список \en check whether the list is empty bool IsExist( const Type * d ) const { return is_exist_in_list(*this, d);} // \ru найти элемент по равенству указателей \en find an element by the equality of pointers Type * GetFirstData() const { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); PRECONDITION( first ); return first->data; } // \ru получить данные первого элемента списка \en get the data of the first element of the list Type * GetLastData() const { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); PRECONDITION( last ); return last->data; } // \ru получить данные последнего элемента списка \en get the data of the last element of the list protected: @@ -223,26 +223,26 @@ protected: ListItem * prev; public: - LIterator() : list( 0 ), curr( 0 ), prev( 0 ) {} - LIterator( const List & l ) : list( 0 ), curr( 0 ), prev( 0 ) { Set(l); } + LIterator() : list( c3d_null ), curr( c3d_null ), prev( c3d_null ) {} + LIterator( const List & l ) : list( c3d_null ), curr( c3d_null ), prev( c3d_null ) { Set(l); } LIterator( const LIterator &i ) : list( i.list ), curr( i.curr ), prev( i.prev ) {} virtual ~LIterator() {} void Set( const List& l ) { list = (List*)&l; Restart(); } - void Restart() { PRECONDITION(list); curr = list->first; prev = 0; } - Type * GetData() const { return curr ? curr->data : 0; } + void Restart() { PRECONDITION(list); curr = list->first; prev = c3d_null; } + Type * GetData() const { return curr ? curr->data : c3d_null; } Type * GetDataAndGo(); // \ru взять данные и продвинуть итератор \en take the data and move the iterator List * GetList() const { return list; } Type& operator* () const { PRECONDITION(curr && curr->data ); return *curr->data; } - Type* operator () () const { return curr ? curr->data : 0; } + Type* operator () () const { return curr ? curr->data : c3d_null; } operator ListItem* () const { return curr; } operator ListItem& () const { PRECONDITION(curr); return *curr; } - Type* operator ++() { prev = curr; if (curr) {curr=curr->next; return curr ? curr->data : 0;} else return 0; } - Type* operator ++(int) { prev = curr; if (curr) {Type* ret=curr->data; curr=curr->next; return ret;} else return 0; } - Type* operator --() { PRECONDITION(list); curr=prev; prev=list->findPrev(prev); return curr ? curr->data : 0; } - Type* operator --(int) { PRECONDITION(list); if (curr) {Type* ret=curr->data; curr=prev; prev=list->findPrev(prev); return ret;} else return 0; } - Type* operator ->() { return curr ? curr->data : 0; } + Type* operator ++() { prev = curr; if (curr) {curr=curr->next; return curr ? curr->data : c3d_null;} else return c3d_null; } + Type* operator ++(int) { prev = curr; if (curr) {Type* ret=curr->data; curr=curr->next; return ret;} else return c3d_null; } + Type* operator --() { PRECONDITION(list); curr=prev; prev=list->findPrev(prev); return curr ? curr->data : c3d_null; } + Type* operator --(int) { PRECONDITION(list); if (curr) {Type* ret=curr->data; curr=prev; prev=list->findPrev(prev); return ret;} else return c3d_null; } + Type* operator ->() { return curr ? curr->data : c3d_null; } bool operator == ( const LIterator &o ) const { return list==o.list && curr==o.curr; } bool operator != ( const LIterator &o ) const { return ! operator == (o); } @@ -258,7 +258,7 @@ public: void Remove( DelType = defDelete ); // \ru удалить элемент списка и продвинуть вперед \en delete an element from the list and move forward void Detach(); // \ru отсоединить элемент списка \en detach an element from the list - bool IsOK() const { return curr != 0; } + bool IsOK() const { return curr != c3d_null; } ListItem * Next() const { PRECONDITION(curr); return curr->next; } void Go() { prev = curr; if ( curr ) curr = curr->next; } void GoLast() { PRECONDITION(list); curr = list->last; prev = list->findPrev(curr); } @@ -279,7 +279,7 @@ public: //--- template inline List::~List() { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); Remove(); } @@ -290,7 +290,7 @@ inline List::~List() { //--- template inline void List::Add( Type* data ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( last ) last = new ListItem( data, *last ); @@ -306,7 +306,7 @@ inline void List::Add( Type* data ) { //--- template inline void List::Add( Type* data, const Type* after ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); add_to_list( *this, data, after ); } @@ -318,7 +318,7 @@ inline void List::Add( Type* data, const Type* after ) { template inline void List::Add( Type * data, bool /*check*/ ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( !IsExist(data) ) Add( data ); } @@ -330,8 +330,8 @@ inline void List::Add( Type * data, bool /*check*/ ) template inline void List::Add( ListItem & item ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); - item.next = 0; + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); + item.next = c3d_null; if ( last ) last->next = &item; @@ -350,7 +350,7 @@ inline void List::Add( ListItem & item ) template inline void List::AddAndEat( List & list ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( list.first ) { @@ -365,7 +365,7 @@ inline void List::AddAndEat( List & list ) count += list.count; list.count = 0; - list.first = list.last = 0; + list.first = list.last = c3d_null; } } @@ -376,7 +376,7 @@ inline void List::AddAndEat( List & list ) template inline void List::Insert( Type * data ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); Insert( *new ListItem(data) ); } @@ -387,7 +387,7 @@ inline void List::Insert( Type * data ) template inline void List::Insert( ListItem & item ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); ListItem* old = first; @@ -407,7 +407,7 @@ inline void List::Insert( ListItem & item ) template inline void List::InsertAndEat( List & list ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( list.first ) { if ( first ) { @@ -422,7 +422,7 @@ inline void List::InsertAndEat( List & list ) count += list.count; list.count = 0; - list.first = list.last = 0; + list.first = list.last = c3d_null; } } @@ -433,13 +433,13 @@ inline void List::InsertAndEat( List & list ) template inline bool List::Remove( Type * del, DelType shdl ) { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( Detach(del) ) { if ( shdl==Delete || (shdl==defDelete && owns) ) { nowDelElem = del; delete del; - nowDelElem = NULL; + nowDelElem = c3d_null; } return true; @@ -455,7 +455,7 @@ inline bool List::Remove( Type * del, DelType shdl ) template inline void List::Close() { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( last ) last->next = first; } @@ -467,9 +467,9 @@ inline void List::Close() template inline void List::Split() { - PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); + PRECONDITION( nowDelItem == c3d_null && nowDelElem == c3d_null ); if ( last ) - last->next = 0; + last->next = c3d_null; } @@ -485,7 +485,7 @@ inline void List::Split() template inline Type * LIterator::GetDataAndGo() { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( curr ) { Type * ret = curr->data; @@ -494,7 +494,7 @@ inline Type * LIterator::GetDataAndGo() return ret; } - return 0; + return c3d_null; } @@ -504,7 +504,7 @@ inline Type * LIterator::GetDataAndGo() template inline void LIterator::Add( Type * data ) { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list ) { if ( curr ) { @@ -525,7 +525,7 @@ inline void LIterator::Add( Type * data ) template inline void LIterator::AddAndEat( List & l ) { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list && l.first ) { @@ -539,7 +539,7 @@ inline void LIterator::AddAndEat( List & l ) list->count += l.count; l.count = 0; - l.first = l.last = 0; + l.first = l.last = c3d_null; } else list->AddAndEat( l ); // \ru съесть список l в конец данного списка \en destroy a list l and add it to the end of the given list @@ -553,7 +553,7 @@ inline void LIterator::AddAndEat( List & l ) template inline void LIterator::Insert( Type * data ) { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list ) { if ( prev ) { @@ -577,7 +577,7 @@ inline void LIterator::Insert( Type * data ) template inline void LIterator::InsertAndEat( List & l ) { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list && l.first ) { @@ -590,7 +590,7 @@ inline void LIterator::InsertAndEat( List & l ) list->count += l.count; l.count = 0; - l.first = l.last = 0; + l.first = l.last = c3d_null; } else list->InsertAndEat( l ); // \ru съесть список l в конец данного списка \en destroy a list l and add it to the end of the given list @@ -604,13 +604,13 @@ inline void LIterator::InsertAndEat( List & l ) template inline void LIterator::Remove( DelType shdl ) { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list && curr ) { if ( shdl==Delete || (shdl==defDelete && list->owns) ) { list->nowDelElem = curr->data; delete curr->data; - list->nowDelElem = 0; + list->nowDelElem = c3d_null; } Detach(); @@ -624,7 +624,7 @@ inline void LIterator::Remove( DelType shdl ) template inline void LIterator::Detach() { - PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); + PRECONDITION( list && list->nowDelItem == c3d_null && list->nowDelElem == c3d_null ); if ( list && curr ) { ListItem* next = curr->next; @@ -639,7 +639,7 @@ inline void LIterator::Detach() list->nowDelItem = curr; delete curr; - list->nowDelItem = 0; + list->nowDelItem = c3d_null; curr = next; prev = list->findPrev( curr ); @@ -652,7 +652,7 @@ inline void LIterator::Detach() template void add_to_list( List & list, Type * data, const Type * after ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); if ( after ) { ListItem *c = list.first; @@ -678,8 +678,8 @@ void add_to_list( List & list, Type * data, const Type * after ) template void add_to_list( List & to, List & from ) { - PRECONDITION( to.nowDelItem == 0 && to.nowDelElem == 0 ); - PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); + PRECONDITION( to.nowDelItem == c3d_null && to.nowDelElem == c3d_null ); + PRECONDITION( from.nowDelItem == c3d_null && from.nowDelElem == c3d_null ); ListItem *curr = from.first; while ( curr ) { @@ -696,8 +696,8 @@ void add_to_list( List & to, List & from ) template void insert_to_list( List & to, List & from ) { - PRECONDITION( to.nowDelItem == 0 && to.nowDelElem == 0 ); - PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); + PRECONDITION( to.nowDelItem == c3d_null && to.nowDelElem == c3d_null ); + PRECONDITION( from.nowDelItem == c3d_null && from.nowDelElem == c3d_null ); ListItem *curr = from.first; while ( curr ) { @@ -716,13 +716,13 @@ void insert_to_list( List & to, List & from ) template void remove_from_list( List & list, DelType shdl ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); bool del = shdl==Delete || (shdl==defDelete && list.owns); ListItem *first = list.first; - list.first = 0; - list.last = 0; + list.first = c3d_null; + list.last = c3d_null; list.count = 0; while ( first ) { ListItem *temp = first; @@ -731,12 +731,12 @@ void remove_from_list( List & list, DelType shdl ) if ( del ) { list.nowDelElem = temp->data; delete temp->data; - list.nowDelElem = 0; + list.nowDelElem = c3d_null; } list.nowDelItem = temp; delete temp; - list.nowDelItem = 0; + list.nowDelItem = c3d_null; } } @@ -747,11 +747,11 @@ void remove_from_list( List & list, DelType shdl ) template void remove_from_list_release( List & list ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); ListItem *first = list.first; - list.first = 0; - list.last = 0; + list.first = c3d_null; + list.last = c3d_null; list.count = 0; while ( first ) { ListItem *temp = first; @@ -760,11 +760,11 @@ void remove_from_list_release( List & list ) list.nowDelElem = temp->data; if ( temp->data ) temp->data->Release(); - list.nowDelElem = 0; + list.nowDelElem = c3d_null; list.nowDelItem = temp; delete temp; - list.nowDelItem = 0; + list.nowDelItem = c3d_null; } } @@ -776,8 +776,8 @@ template size_t remove_from_list( List & list, List & deList, DelType shdl ) { PRECONDITION( &list != &deList ); - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); - PRECONDITION( deList.nowDelItem == 0 && deList.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); + PRECONDITION( deList.nowDelItem == c3d_null && deList.nowDelElem == c3d_null ); if ( !list.first || !deList.first ) // \ru какой-то из списков пуст ! \en one of the lists is empty ! return 0; @@ -788,7 +788,7 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) ListItem *curr = list.first; // \ru начнем сначала \en start from the beginning ListItem *prev = list.last; ListItem *del = deList.first; // \ru текущий удаляемый \en the current deleted - ListItem *pdel = NULL; // \ru предыдущий удаляемый \en the previous deleted + ListItem *pdel = c3d_null; // \ru предыдущий удаляемый \en the previous deleted size_t deleted = 0; // \ru отцепленных 0 \en there are 0 detached while( del && list.first ) { // \ru есть еще пока чего удалять и откуда \en there are elements to delete @@ -801,8 +801,8 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) if ( list.first == list.last ) { // \ru если всего один элемент, то ничего не останется \en if there is only one element then nothing will be left list.count = 0; - list.first = NULL; - list.last = NULL; + list.first = c3d_null; + list.last = c3d_null; // \ru curr продвигать не нужно - все равно заканчиваем \en 'curr' should not be moved } else { @@ -820,12 +820,12 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) if ( willDel ) { // \ru если надо - удалим данные \en delete the data if it is necessary list.nowDelElem = condemned->data; delete condemned->data; - list.nowDelElem = 0; + list.nowDelElem = c3d_null; } list.nowDelItem = condemned; delete condemned; // \ru удалим квартиру \en delete condemned - list.nowDelItem = 0; + list.nowDelItem = c3d_null; deleted++; // \ru еще один удалили \en another one has been deleted break; @@ -849,7 +849,7 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) deList.nowDelItem = del; delete del; // \ru помним, что данные мы уже удалили \en remember that the data has already been deleted - deList.nowDelItem = 0; + deList.nowDelItem = c3d_null; deList.count--; } @@ -860,7 +860,7 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) } if ( list.last ) - list.last->next = 0; // \ru разорвать список \en split the list + list.last->next = c3d_null; // \ru разорвать список \en split the list return deleted; } @@ -870,10 +870,10 @@ size_t remove_from_list( List & list, List & deList, DelType shdl ) template bool detach_from_list( List & from, const Type * del ) { - PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); + PRECONDITION( from.nowDelItem == c3d_null && from.nowDelElem == c3d_null ); ListItem* curr = from.first; - ListItem* prev = 0; + ListItem* prev = c3d_null; while( curr ) { if ( curr->data == del ) { // \ru нашли \en found @@ -888,7 +888,7 @@ bool detach_from_list( List & from, const Type * del ) from.nowDelItem = curr; delete curr; - from.nowDelItem = 0; + from.nowDelItem = c3d_null; from.count--; return true; @@ -907,7 +907,7 @@ bool detach_from_list( List & from, const Type * del ) template size_t recalc_list( List & list ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); list.count = 0; ListItem *curr = list.first; @@ -923,7 +923,7 @@ size_t recalc_list( List & list ) template bool is_exist_in_list( const List & list, const Type * what ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); bool exist = false; ListItem * curr = list.first; @@ -940,7 +940,7 @@ bool is_exist_in_list( const List & list, const Type * what ) template ListItem * find_prev_in_list( const List & list, ListItem * now ) { - PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); + PRECONDITION( list.nowDelItem == c3d_null && list.nowDelElem == c3d_null ); if ( now ) { ListItem *tmp = list.first; @@ -949,7 +949,7 @@ ListItem * find_prev_in_list( const List & list, ListItem * no return tmp; } - return 0; + return c3d_null; } diff --git a/C3d/Include/templ_s_queue.h b/C3d/Include/templ_s_queue.h index 100802c..20b96ad 100644 --- a/C3d/Include/templ_s_queue.h +++ b/C3d/Include/templ_s_queue.h @@ -113,17 +113,17 @@ private: // --- template SQueue::SQueue( size_t capacity ) - : data( NULL ) - , qlast( NULL ) - , qp1( NULL ) - , qp2( NULL ) + : data( c3d_null ) + , qlast( c3d_null ) + , qp1( c3d_null ) + , qp2( c3d_null ) { if ( capacity > 0 ) { try { data = new Type[capacity]; } catch ( const std::bad_alloc & ) { - data = NULL; + data = c3d_null; throw; } } @@ -212,7 +212,7 @@ inline Type & SQueue::First() const template inline bool SQueue::IsFull() const { - return data == NULL || _IncPtr( qp2 ) == qp1; + return data == c3d_null || _IncPtr( qp2 ) == qp1; } @@ -336,7 +336,7 @@ bool SQueue::_NewCapacity( size_t max_len, bool clear ) { try { delete [] data; - data = qlast = qp1 = qp2 = NULL; + data = qlast = qp1 = qp2 = c3d_null; if ( max_len > 0 ) { data = new Type[max_len]; qlast = data + max_len - 1; @@ -344,7 +344,7 @@ bool SQueue::_NewCapacity( size_t max_len, bool clear ) } } catch ( ... ) { - data = qlast = qp1 = qp2 = NULL; + data = qlast = qp1 = qp2 = c3d_null; C3D_CONTROLED_THROW; return false; } @@ -352,7 +352,7 @@ bool SQueue::_NewCapacity( size_t max_len, bool clear ) else { PRECONDITION( qp1 != qp2 && max_len>0 && clear == false ); // \ru Выражение обязано быть истинным \en The expression should be true - Type * n_data = NULL; + Type * n_data = c3d_null; try { n_data = new Type[max_len]; if ( qp1 < qp2 ) // \ru Вариант без фрагментации \en A variant without fragmentation diff --git a/C3d/Include/templ_sfdp_array.h b/C3d/Include/templ_sfdp_array.h index 8afd418..79d0277 100644 --- a/C3d/Include/templ_sfdp_array.h +++ b/C3d/Include/templ_sfdp_array.h @@ -145,8 +145,8 @@ using RPArray::back; \en Find the index of the element using the comparison function. \details \ru Найти индекс элемента, используя функцию сравнения. \en Find the index of the element using the comparison function. - \return \ru Вернет точно найденный элемент или NULL, если элемент не найден. - \en Returns the found element or NULL, if element not found. + \return \ru Вернет точно найденный элемент или c3d_null, если элемент не найден. + \en Returns the found element or c3d_null, if element not found. */ Type * FindExact ( const Type & el ) const; @@ -240,7 +240,7 @@ inline SFDPArray::~SFDPArray() {} // --- template bool SFDPArray::Init( const SFDPArray & other ) { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily Flush(); // \ru сбросить себя \en reset itself @@ -253,7 +253,7 @@ bool SFDPArray::Init( const SFDPArray & other ) { // --- template inline size_t SFDPArray::AddTry( Type& ent, Type *&found ) { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily // \ru CatchMemory(); ЯТ \en CatchMemory(); ЯТ bool added = true; @@ -267,10 +267,10 @@ inline size_t SFDPArray::AddTry( Type& ent, Type *&found ) { // --- template inline bool SFDPArray::AddExact( Type& ent ) { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily // \ru CatchMemory(); ЯТ \en CatchMemory(); ЯТ - Type * found = NULL; + Type * found = c3d_null; bool added = true; add_to_array( *this, ent, found, added ); return ( &ent == found ); // \ru вернет true - добавлен, false - не добавлен \en if returns true then the element has been added, it has not been added otherwise @@ -283,10 +283,10 @@ inline bool SFDPArray::AddExact( Type& ent ) { // --- template inline bool SFDPArray::AddIfNotExist( Type& ent ) { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily // \ru CatchMemory(); ЯТ \en CatchMemory(); ЯТ - Type * found = NULL; + Type * found = c3d_null; bool added = true; add_to_array( *this, ent, found, added ); return ( added ); // \ru вернет true - добавлен, false - не добавлен \en if returns true then the element has been added, it has not been added otherwise @@ -298,7 +298,7 @@ inline bool SFDPArray::AddIfNotExist( Type& ent ) { // --- template inline size_t SFDPArray::FindNearest( const Type &el, Type *&found ) const { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily return find_in_array( *this, el, found ); } @@ -309,10 +309,10 @@ inline size_t SFDPArray::FindNearest( const Type &el, Type *&found ) const // --- template inline Type * SFDPArray::FindExact( const Type &el ) const { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily - Type * found = NULL; + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily + Type * found = c3d_null; size_t foundInd = find_in_array( *this, el, found ); - return ( foundInd != SYS_MAX_T ) ? found : NULL; + return ( foundInd != SYS_MAX_T ) ? found : c3d_null; } @@ -321,13 +321,13 @@ inline Type * SFDPArray::FindExact( const Type &el ) const { // --- template inline Type* SFDPArray::RemoveObj( Type *delObject, DelType del ) { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily if ( !delObject ) - return NULL; + return c3d_null; - Type * found = NULL; + Type * found = c3d_null; size_t i = find_in_array( *this, *delObject, found ); - return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : 0; + return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : c3d_null; } @@ -338,7 +338,7 @@ template inline bool SFDPArray::DetachObj( const Type *delObject ) { if ( !delObject ) return false; - Type * found = NULL; + Type * found = c3d_null; size_t i = find_in_array( *this, *delObject, found ); if ( i != SYS_MAX_T ) { @@ -355,8 +355,8 @@ inline bool SFDPArray::DetachObj( const Type *delObject ) { // --- template inline bool SFDPArray::IsExist( const Type &el ) const { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily - Type * found = NULL; + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily + Type * found = c3d_null; return find_in_array( *this, el, found ) != SYS_MAX_T; } @@ -513,7 +513,7 @@ size_t find_in_array( const SFDPArray& arr, const Type& el, Type *&found ) // --- template size_t SFDPArray::SearchIt ( size_t data, typename SFDPArray::SearchFunc fSearch, Type *&found ) const { - PRECONDITION( FDPArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily + PRECONDITION( FDPArray::nowDeletedElem == c3d_null ); // \ru ЯТ - временно \en ЯТ - temporarily PRECONDITION( fSearch ); // \ru без функции сравнения массив бессмысленен \en the array is useless without comparison function if ( !FDPArray::count ) diff --git a/C3d/Include/templ_sfp_array.h b/C3d/Include/templ_sfp_array.h index cb8f157..8cb8b3b 100644 --- a/C3d/Include/templ_sfp_array.h +++ b/C3d/Include/templ_sfp_array.h @@ -180,10 +180,10 @@ inline Type * SFPArray::FindByKey( void * key, size_t & index ) { // --- template inline Type * SFPArray::RemoveObj( Type *delObject, DelType del ) { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru Bременно, для отладки \en Temporarily, for debugging + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru Bременно, для отладки \en Temporarily, for debugging ::qp_sort( *this, false ); size_t i = find_in_array( *this, delObject ); - return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : 0; + return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : c3d_null; } @@ -425,14 +425,14 @@ Type * find_from_array_by_key( const SFPArray & arr, void * key, size_t & res = (*arr.fSearch_m)( arr[0], key ); switch ( res ) { case 0 : index = 0; return arr[0]; - case 1 : index = SYS_MAX_T; return NULL; + case 1 : index = SYS_MAX_T; return c3d_null; case -1 : break; } res = (*arr.fSearch_m)( arr[mxc], key ); switch ( res ) { case 0 : index = mxc; return arr[mxc]; - default : index = SYS_MAX_T; return NULL; + default : index = SYS_MAX_T; return c3d_null; } } else { @@ -440,14 +440,14 @@ Type * find_from_array_by_key( const SFPArray & arr, void * key, size_t & for( size_t i = 0, count = (size_t)arr.count; i < count; i++ ) { switch ( (*arr.fSearch_m)( arr[i], key ) ) { case 0 : index = i; return arr[i]; - case 1 : index = SYS_MAX_T; return NULL; + case 1 : index = SYS_MAX_T; return c3d_null; case -1 : break; } } } index = SYS_MAX_T; - return NULL; + return c3d_null; } diff --git a/C3d/Include/templ_sp_array.h b/C3d/Include/templ_sp_array.h index b8213d0..4f139d8 100644 --- a/C3d/Include/templ_sp_array.h +++ b/C3d/Include/templ_sp_array.h @@ -150,9 +150,9 @@ inline bool SPArray::IsExist( const Type * el ) const { template inline Type * SPArray::RemoveObj( Type * delObject, DelType del ) { - PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru Bременно, для отладки \en Temporarily, for debugging + PRECONDITION( PArray::nowDeletedElem == c3d_null ); // \ru Bременно, для отладки \en Temporarily, for debugging size_t i = find_from_array( *this, delObject ); - return ( i != SYS_MAX_T ) ? RemoveInd( i, del ) : 0; + return ( i != SYS_MAX_T ) ? RemoveInd( i, del ) : c3d_null; } @@ -172,8 +172,8 @@ inline size_t SPArray::PossibleIndex( const Type * el, bool & isPresent ) template Type * add_to_array( SPArray & arr, Type * el, size_t & indexEl ) { - if ( el == NULL ) // \ru LF_Linux: добавил проверку на NULL \en LF_Linux: added a check for NULL - return NULL; + if ( el == c3d_null ) // \ru LF_Linux: добавил проверку на c3d_null \en LF_Linux: added a check for c3d_null + return c3d_null; size_t mx = arr.count - 1; size_t mxc = mx; size_t mn = 0; @@ -286,7 +286,7 @@ size_t find_from_array_spec( const SPArray & arr, const Type * el, bool & { isPresent = false; - if ( el == NULL ) // \ru LF_Linux: добавил проверку на NULL \en LF_Linux: added a check for NULL + if ( el == c3d_null ) // \ru LF_Linux: добавил проверку на c3d_null \en LF_Linux: added a check for c3d_null return SYS_MAX_T; if ( !arr.count || *el < *arr/*.parr*/[0] ) @@ -355,7 +355,7 @@ size_t find_from_array_spec( const SPArray & arr, const Type * el, bool & template size_t find_from_array( const SPArray & arr, const Type * el ) { - if ( el == NULL ) // \ru LF_Linux: добавил проверку на NULL \en LF_Linux: added a check for NULL + if ( el == c3d_null ) // \ru LF_Linux: добавил проверку на c3d_null \en LF_Linux: added a check for c3d_null return SYS_MAX_T; // \ru общий случай - элементов больше 11 //LF_Linux: откуда 11??? \en the common case - the number of elements is more than 11 //LF_Linux: why 11?? if ( arr.count > 11 ) { diff --git a/C3d/Include/templ_sparse_array2.h b/C3d/Include/templ_sparse_array2.h new file mode 100644 index 0000000..05750d6 --- /dev/null +++ b/C3d/Include/templ_sparse_array2.h @@ -0,0 +1,614 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Двумерный массив объектов. + \en Two-dimensional array of objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TEMPL_SPARSE_ARRAY2_H +#define __TEMPL_SPARSE_ARRAY2_H + + +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Разреженный вектор объектов. + \en Sparse vector of objects. \~ + \details \ru Разреженный вектор объектов. \n + \en Sparse vector of objects. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class SparseRow { +public: + typedef std::pair NumberRange; + typedef std::pair NumberType; + typedef std::vector RowVector; + typedef std::map RowMap; + typedef typename RowMap::const_iterator RowMapConstIt; + typedef typename RowMap::iterator RowMapIt; + typedef typename std::pair RowMapRet; + +protected: + RowMap rowMap; ///< \ru Таблица ненулевых элементов. \en Map of nonzero elements. + RowVector rowVector; ///< \ru Вектор ненулевых элементов. \en Vector of nonzero elements. + size_t rowSize; ///< \ru Размер вектора. \en Vector size. + NumberRange nzRange; ///< \ru Диапазон ненулевых элементов [nz1,nz2]. \en Range of nonzero elements [nz1,nz2]. + +public: + static const Type defaultElem; ///< \ru Нулевой элемент (элемент по умолчанию). \en Zero element (default element). + +public: + /// \ru Конструктор. \en Constructor. + SparseRow() : rowMap(), rowVector(), rowSize(0), nzRange( SYS_MAX_ST, SYS_MIN_ST ) {} + /// \ru Конструктор копирования. \en Copy-constructor. + SparseRow( const SparseRow & ); + /// \ru Деструктор. \en Destructor. + virtual ~SparseRow() {} + +public: + /// \ru Оператор присваивания. \en The assignment operator. + const SparseRow & operator = ( const SparseRow & ); + +public: + void Clear() { rowMap.clear(); rowVector.clear(); ResetNzRange(); } + void SetSize( size_t rsz ) { Clear(); rowSize = rsz; } + + bool IsNzRange() const { return (nzRange.first <= nzRange.second); } + const NumberRange & NzRange() const { return nzRange; } + void ResetNzRange() { nzRange.first = SYS_MAX_ST; nzRange.second = SYS_MIN_ST; } + void EnlargeNzRange( ptrdiff_t n ) { nzRange.first = std_min( nzRange.first, n ); nzRange.second = std_max( nzRange.second, n ); } + + const Type & GetElem( size_t k ) const; + bool SetElem( size_t k, const Type & ); + bool SetLine( std::vector & ); + ptrdiff_t NzBegin() const { return nzRange.first; } + ptrdiff_t NzEnd () const { return IsNzRange() ? nzRange.second + 1 : nzRange.first; } + bool NzIndices( const NumberRange & searchRange, std::vector & ) const; + void NzUpdate(); + void Swap( SparseRow & ); + +protected: + bool CheckNzRange() const; + bool CheckBand( std::vector & ) const; +}; + + +//------------------------------------------------------------------------------ +// +// --- +template +const Type SparseRow::defaultElem = Type(); + + +//------------------------------------------------------------------------------ +// +// --- +template +SparseRow::SparseRow( const SparseRow & src ) + : rowMap ( src.rowMap ) + , rowVector( src.rowVector ) + , rowSize ( src.rowSize ) + , nzRange ( src.nzRange ) +{ +} + + +//------------------------------------------------------------------------------ +// +// --- +template +const SparseRow & SparseRow::operator = ( const SparseRow & src ) +{ + rowMap = src.rowMap; + rowVector = src.rowVector; + rowSize = src.rowSize; + nzRange = src.nzRange; + return *this; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseRow::CheckNzRange() const +{ + bool res = false; + + if ( 0 <= nzRange.first && nzRange.second <= (ptrdiff_t)rowSize ) { + res = true; + + if ( rowVector.empty() ) { + RowMapConstIt it = rowMap.begin(); + while ( res && it != rowMap.end() ) { + res = false; + if ( nzRange.first <= (ptrdiff_t)it->first && (ptrdiff_t)it->first <= nzRange.second ) + res = true; + ++it; + } + } + else { + size_t nzSize = nzRange.second - nzRange.first + 1; + if ( nzSize <= rowSize && nzSize == rowVector.size() ) + res = true; + } + } + + return res; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline const Type & SparseRow::GetElem( size_t k ) const +{ + //C3D_ASSERT( CheckNzRange() ); + + if ( nzRange.first <= (ptrdiff_t)k && (ptrdiff_t)k <= nzRange.second ) { + if ( rowVector.empty() ) { + RowMapConstIt it = rowMap.find( k ); + if ( it != rowMap.end() ) + return it->second; + } + else { + ptrdiff_t index = (ptrdiff_t)k - nzRange.first; + PRECONDITION( index >= 0 && index < (ptrdiff_t)rowVector.size() ); + if ( index >= 0 && index < (ptrdiff_t)rowVector.size() ) + return rowVector[index]; + } + } + return defaultElem; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseRow::SetElem( size_t k, const Type & item ) +{ + //C3D_ASSERT( CheckNzRange() ); + + PRECONDITION( k < rowSize ); + if ( k < rowSize ) { + if ( rowVector.empty() ) { + RowMapRet ret = rowMap.insert( std::make_pair( k, item ) ); + if ( !ret.second ) + ret.first->second = item; + EnlargeNzRange( k ); + return true; + } + else { + if ( nzRange.first <= (ptrdiff_t)k && (ptrdiff_t)k <= nzRange.second ) { + ptrdiff_t index = k - nzRange.first; + PRECONDITION( index >= 0 && index <= (ptrdiff_t)rowVector.size() ); + if ( index >= 0 && index < (ptrdiff_t)rowVector.size() ) + rowVector[index] = item; + } + else if ( (ptrdiff_t)k < nzRange.first ) { + size_t addCnt = nzRange.first - k; + std::reverse( rowVector.begin(), rowVector.end() ); + rowVector.resize( rowVector.size() + addCnt ); + rowVector.back() = item; + std::reverse( rowVector.begin(), rowVector.end() ); + EnlargeNzRange( k ); + } + else if ( (ptrdiff_t)k > nzRange.second ) { + size_t addCnt = k - nzRange.second; + rowVector.resize( rowVector.size() + addCnt ); + rowVector.back() = item; + EnlargeNzRange( k ); + } + return true; + } + } + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseRow::CheckBand( std::vector & row ) const +{ + bool res = true; + + size_t nzSize = row.size(); + + if ( nzSize > 0 ) { + if ( nzSize > 1 ) { + std::sort( row.begin(), row.end() ); + + size_t k; + for ( k = nzSize; k--; ) { + PRECONDITION( row[k].first < rowSize ); + if ( row[k].second == defaultElem ) { + row.erase( row.begin() + k ); + nzSize--; + } + else if ( row[k].first >= rowSize ) { + row.erase( row.begin() + k ); + nzSize--; + } + } + if ( nzSize > 1 ) { + size_t nzBegInd = row.front().first; + size_t nzEndInd = row.back().first; + size_t nzCnt = nzEndInd - nzBegInd + 1; + + if ( nzCnt > 2*nzSize ) { + res = false; + } + } + } + } + + return res; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseRow::SetLine( std::vector & row ) +{ + PRECONDITION( row.size() <= rowSize ); + + if ( row.size() > 0 && row.size() <= rowSize ) { + Clear(); + + if ( !CheckBand( row ) ) { + size_t nzSize = row.size(); + for ( size_t k = 0; k < nzSize; ++k ) { + size_t nzCurInd = row[k].first; + rowMap.insert( std::make_pair( nzCurInd, row[k].second ) ); + EnlargeNzRange( nzCurInd ); + } + } + else { + size_t nzSize = row.size(); + + size_t nzBegInd = row.front().first; + size_t nzEndInd = row.back().first; + size_t nzCnt = nzEndInd - nzBegInd + 1; + + rowVector.resize( nzCnt ); + for ( size_t k = 0; k < nzSize; ++k ) { + size_t nzCurInd = row[k].first; + rowVector[nzCurInd - nzBegInd] = row[k].second; + EnlargeNzRange( nzCurInd ); + } + } + + return true; + } + + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseRow::NzIndices( const NumberRange & searchRange, std::vector & indices ) const +{ + PRECONDITION( indices.empty() && searchRange.first <= searchRange.second ); + indices.clear(); + + if ( searchRange.first <= searchRange.second ) { + if ( rowVector.empty() ) { + RowMapConstIt it = rowMap.begin(); + while ( it != rowMap.end() ) { + if ( searchRange.first <= (ptrdiff_t)it->first && (ptrdiff_t)it->first <= searchRange.second ) + indices.push_back( it->first ); + ++it; + } + } + else { + size_t nzCnt = rowVector.size(); + indices.reserve( nzCnt ); + for ( size_t i = 0; i < nzCnt; ++i ) { + size_t index = nzRange.first + i; + if ( searchRange.first <= (ptrdiff_t)index && (ptrdiff_t)index <= searchRange.second ) { + if ( rowVector[i] != defaultElem ) + indices.push_back( index ); + } + } + } + if ( indices.size() > 1 ) + std::sort( indices.begin(), indices.end() ); + } + + return (indices.size() > 0); +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline void SparseRow::NzUpdate() +{ + bool doUpdate = false; + std::vector nzElems; + + if ( rowVector.empty() ) { + if ( !rowMap.empty() ) { + ResetNzRange(); + + nzElems.reserve( rowMap.size() ); + + RowMapIt it = rowMap.begin(); + + while ( it != rowMap.end() ) + { + if ( it->second == defaultElem ) { + it = c3d::older_stl_support::erase(rowMap, it ); + doUpdate = true; + } + else { + EnlargeNzRange( it->first ); + nzElems.push_back( std::make_pair( it->first, it->second ) ); + ++it; + } + } + } + } + else { + PRECONDITION( rowMap.empty() ); + size_t nzCnt = rowVector.size(); + nzElems.reserve( nzCnt ); + + for ( size_t k = 0; k < nzCnt; k++ ) { + if ( rowVector[k] != defaultElem ) + nzElems.push_back( std::make_pair( nzRange.first + k, rowVector[k] ) ); + else + doUpdate = true; + } + } + + if ( doUpdate ) { + SetLine( nzElems ); + } + + PRECONDITION( CheckNzRange() ); +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline void SparseRow::Swap( SparseRow & r2 ) +{ + SparseRow & r1 = *this; + std::swap( r1.rowMap, r2.rowMap ); + std::swap( r1.rowVector, r2.rowVector ); + PRECONDITION( r1.rowSize == r2.rowSize ); + std::swap( r1.rowSize, r2.rowSize ); + std::swap( r1.nzRange, r2.nzRange ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Двумерный разреженный массив объектов. + \en Two-dimensional sparse array of objects. \~ + \details \ru Двумерный разреженный массив объектов. \n + \en Two-dimensional sparse array of objects. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class SparseArray2 { +public: + typedef std::pair NumberRange; + typedef std::pair NumberType; + typedef std::vector< SparseRow > SparseData; + typedef SparseArray2 SparseMatrix; + +protected : + SparseData data; ///< \ru Данные. \en Data. + size_t nColumns; ///< \ru Количество столбцов массива. \en Count of columns of array. + +protected: + /// \ru Конструктор по заданной размерности. \en The constructor by a given dimension. + SparseArray2( size_t lsz, size_t csz ) : data(), nColumns(0) { SetSize( lsz, csz ); } +public: + /// \ru Конструктор. \en Constructor. + SparseArray2() : data(), nColumns(0) {} + /// \ru Конструктор ограниченной размерности. \en The constructor of restricted dimension. + SparseArray2( const uint16 & lsz, const uint16 & csz ) : data(), nColumns(0) { SetSize( lsz, csz ); } + /// \ru Конструктор копирования. \en Copy-constructor. + explicit SparseArray2( const SparseArray2 & src ) : data(), nColumns(0) { Init( src ); } + /// \ru Деструктор. \en Destructor. + virtual ~SparseArray2() { SetSize( 0, 0 ); } + +public: + /// \ru Конструктор по заданной размерности. \en The constructor by a given dimension. + static SparseMatrix * Create( size_t lsz, size_t csz ); + +public: // Общие методы матриц (двумерных массивов) + size_t Lines () const { return data.size(); } ///< \ru Количество строк. \en Count of rows. + size_t Columns() const { return nColumns; } ///< \ru Количество столбцов. \en Count of columns. + size_t Count () const { return (data.size()*nColumns); } ///< \ru Количество элементов. \en Count of elements. + c3d::IndicesPair GetSize() const { return c3d::IndicesPair( data.size(), nColumns ); } ///< \ru Дать размер массива. \en Give the size of the array. + bool SetSize( c3d::IndicesPair sz ) { return SetSize( sz.first, sz.second ); } ///< \ru Установить размер. \en Set size. + bool SetSize( size_t lsz, size_t csz ); ///< \ru Установить размер. \en Set size. + bool SetSize( size_t sz ) { return SetSize( sz, sz ); } ///< \ru Установить размер. \en Set size. + + /// \ru Получить элемент массива. \en Get an element of the array. + const Type & GetElem( size_t ln, size_t cn ) const; + /// \ru Установить элемент массива. \en Set an element of the array. + bool SetElem( size_t ln, size_t cn, const Type & ); + /// \ru Оператор доступа по индексам. \en Access by indices operator. + const Type & operator () ( size_t ln, size_t cn ) const { C3D_ASSERT( ln < data.size() && cn < nColumns ); return GetElem( ln, cn ); } + /// \ru Расписать массив нулями. \en Assign zeros to array. + SparseMatrix & SetZero(); + /// \ru Функция присваивания. \en An assignment function. + bool Init( const SparseMatrix & ); + /// \ru Оператор присваивания. \en The assignment operator. + SparseMatrix & operator = ( const SparseMatrix & src ) { Init( src ); return *this; } + /// \ru Поменять местами строки. \en Swap lines. + bool SwapLines( size_t ln1, size_t ln2 ); + +public: + /// \ru Установить ненулевые элементы строки. \en Set nonzero elements of the row. + bool SetLine( size_t ln, std::vector & ); + /// \ru Индекс первого ненулевого элемента. \en Index of the first nonzero element. + size_t NzBegin( size_t ln ) const { C3D_ASSERT(ln < data.size()); if ( ln < data.size() ) return data[ln].NzBegin(); return SYS_MAX_ST; } + /// \ru Завершающий индекс последовательности ненулевых элементов. \en The final index of the sequence of non-zero elements. + size_t NzEnd ( size_t ln ) const { C3D_ASSERT(ln < data.size()); if ( ln < data.size() ) return data[ln].NzEnd(); return SYS_MIN_ST; } + /// \ru Получить индексы ненулевых элементов строки. \en Get indices of nonzero elements of the row. + bool NzIndices( size_t ln, const NumberRange & searchRange, std::vector & ) const; + /// \ru Обновить строку (удалить нулевые элементы по возможности). \en Update the row (delete zero elements as far as possible). + void NzUpdate(); +}; + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseArray2::SetSize( size_t lsz, size_t csz ) +{ + if ( lsz*csz <= c3d::MATRIX_MAX_COUNT ) + { + data.clear(); + data.resize( lsz ); + for ( size_t k = data.size(); k--; ) + data[k].SetSize( csz ); + nColumns = csz; + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline SparseArray2 * SparseArray2::Create( size_t lsz, size_t csz ) +{ + if ( lsz*csz <= c3d::MATRIX_MAX_COUNT ) + return new SparseMatrix( lsz, csz ); + return c3d_null; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +bool SparseArray2::Init( const SparseArray2 & src ) +{ + data.assign( src.data.begin(), src.data.end() ); + nColumns = src.nColumns; + return true; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline const Type & SparseArray2::GetElem( size_t ln, size_t cn ) const +{ + PRECONDITION( ln < data.size() && cn < nColumns ); + if ( ln < data.size() && cn < nColumns ) + return data[ln].GetElem( cn ); + return SparseRow::defaultElem; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseArray2::SetElem( size_t ln, size_t cn, const Type & item ) +{ + PRECONDITION( ln < data.size() && cn < nColumns ); + if ( ln < data.size() && cn < nColumns ) + return data[ln].SetElem( cn, item ); + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline SparseArray2 & SparseArray2::SetZero() +{ + std::for_each( data.begin(), data.end(), std::mem_fun_ref( &SparseRow::Clear ) ); + return *this; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseArray2::SetLine( size_t ln, std::vector & newRow ) +{ + PRECONDITION( ln < data.size() && newRow.size() <= nColumns ); + if ( ln < data.size() && newRow.size() <= nColumns ) + return data[ln].SetLine( newRow ); + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseArray2::SwapLines( size_t ln1, size_t ln2 ) +{ + size_t nLines = data.size(); + PRECONDITION( ln1 < nLines && ln2 < nLines ); + if ( ln1 < nLines && ln2 < nLines ) { + data[ln1].Swap( data[ln2] ); + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline bool SparseArray2::NzIndices( size_t ln, const NumberRange & searchRange, std::vector & indices ) const +{ + PRECONDITION( ln < data.size() ); + if ( ln < data.size() ) + return data[ln].NzIndices( searchRange, indices ); + return false; +} + + +//------------------------------------------------------------------------------ +// +// --- +template +inline void SparseArray2::NzUpdate() +{ + std::for_each( data.begin(), data.end(), std::mem_fun_ref( &SparseRow::NzUpdate ) ); +} + + +#endif // __TEMPL_SPARSE_ARRAY2_H diff --git a/C3d/Include/templ_sptr.h b/C3d/Include/templ_sptr.h index 9fa0882..df3e294 100644 --- a/C3d/Include/templ_sptr.h +++ b/C3d/Include/templ_sptr.h @@ -15,14 +15,14 @@ //------------------------------------------------------------------------------ -/** \brief \ru Отладочная проверка на NULL. - \en Debug check for NULL. \~ - \details \ru Отладочная проверка на NULL. \n - \en Debug check for NULL. \n \~ +/** \brief \ru Отладочная проверка на c3d_null. + \en Debug check for c3d_null. \~ + \details \ru Отладочная проверка на c3d_null. \n + \en Debug check for c3d_null. \n \~ \ingroup Base_Tools_SmartPointers */ // --- -#define NULL_CHECK PRECONDITION( m_pI != C3D_NULL_PTR ); +#define NULL_CHECK PRECONDITION( m_pI != c3d_null ); //------------------------------------------------------------------------------ @@ -42,20 +42,20 @@ class SPtr public: /// \ru Конструктор. \en Constructor. - SPtr () : m_pI( C3D_NULL_PTR ) {} + SPtr () : m_pI( c3d_null ) {} /// \ru Конструктор по указателю. \en Constructor by pointer. explicit SPtr ( T * elem ) { - if ( (m_pI = elem) != C3D_NULL_PTR ) + if ( (m_pI = elem) != c3d_null ) m_pI->AddRef(); } /// \ru Конструктор копирования. \en Copy constructor. - SPtr( const SPtr & ptr ) : m_pI( C3D_NULL_PTR ) { assign(ptr.m_pI); } + SPtr( const SPtr & ptr ) : m_pI( c3d_null ) { assign(ptr.m_pI); } /// \ru Конструктор по совместимому указателю \en Constructor by compatible pointer template - SPtr( const SPtr<_T> & ptr ) : m_pI( ptr.get() ) { if ( m_pI != C3D_NULL_PTR ) { m_pI->AddRef();} } + SPtr( const SPtr<_T> & ptr ) : m_pI( ptr.get() ) { if ( m_pI != c3d_null ) { m_pI->AddRef();} } /// \ru Деструктор. \en Destructor. - ~SPtr() { if( m_pI != C3D_NULL_PTR ) m_pI->Release(); } + ~SPtr() { if( m_pI != c3d_null ) m_pI->Release(); } public: // \ru Перегрузка операторов \en Operators overloading /// \ru Оператор преобразования к типу T* . \en An operator for conversion to the type T*. @@ -103,13 +103,13 @@ public: /// \ru Функция присваивания указателем. \en A function of assignment by pointer. SPtr & assign( T * elem ); /// \ru Функция освобождения объекта. \en A function of release an object. - SPtr & reset( void ) { if( m_pI != C3D_NULL_PTR ) { m_pI->Release(); m_pI = C3D_NULL_PTR; } return *this; } + SPtr & reset( void ) { if( m_pI != c3d_null ) { m_pI->Release(); m_pI = c3d_null; } return *this; } /// \ru Функция доступа к элементу данных. \en A function of access to data element. T * get() const { return m_pI; } /// \ru Функция отсоединяет объект. \en A function detaches an object. - T * detach() { T * obj = m_pI; m_pI = C3D_NULL_PTR; if ( obj != C3D_NULL_PTR ) obj->DecRef(); return obj; } + T * detach() { T * obj = m_pI; m_pI = c3d_null; if ( obj != c3d_null ) obj->DecRef(); return obj; } /// \ru Нулевой указатель? \en Is null pointer? - bool is_null() const { return (( C3D_NULL_PTR == m_pI ) ? true : false ); } + bool is_null() const { return (( c3d_null == m_pI ) ? true : false ); } #ifdef C3D_STANDARD_CXX_11_PARTIAL public: @@ -138,8 +138,8 @@ inline SPtr & SPtr::assign( T * elem ) { if ( m_pI != elem ) { - if ( elem != C3D_NULL_PTR ) { elem->AddRef(); } - if ( m_pI != C3D_NULL_PTR ) { m_pI->Release(); } + if ( elem != c3d_null ) { elem->AddRef(); } + if ( m_pI != c3d_null ) { m_pI->Release(); } m_pI = elem; } return *this; @@ -150,10 +150,10 @@ inline SPtr & SPtr::assign( T * elem ) /** \brief \ru Автоматическая ссылка на объекты с подсчетом ссылок. \en Smart reference to objects with reference counter. \~ \details \ru Автоматическая ссылка (smart reference) на объекты с подсчетом ссылок. - Фактически тоже самое, что и SPtr, но без возможности равенства NULL.\n + Фактически тоже самое, что и SPtr, но без возможности равенства c3d_null.\n Требует от параметра шаблона реализации функций AddRef() и Release(). \n \en Smart reference to objects with reference counter. - Actually it is the same as SPtr but without the possibility of equality to NULL \n + Actually it is the same as SPtr but without the possibility of equality to c3d_null \n It requires Implementation of functions AddRef() and Release() from the template parameter. \n \~ \ingroup Base_Tools_SmartPointers */ diff --git a/C3d/Include/templ_stack.h b/C3d/Include/templ_stack.h index 8b0011f..2109dee 100644 --- a/C3d/Include/templ_stack.h +++ b/C3d/Include/templ_stack.h @@ -36,7 +36,7 @@ public: {} public: void Push( const Type & obj ); ///< \ru Добавить элемент в стек. \en Add an element to the stack. - Type & Pop(); ///< \ru Извлечь один элемент стека, если возвращаетя NULL, значит достигнуто дно стека. \en Retrieve one element from the stack, if NULL is returned then the bottom of stack is reached. + Type & Pop(); ///< \ru Извлечь один элемент стека, если возвращаетя c3d_null, значит достигнуто дно стека. \en Retrieve one element from the stack, if c3d_null is returned then the bottom of stack is reached. Type & Top() const; ///< \ru Верхний элемент стека (последний внесенный). \en The top element of the stack (the last added). // \ru Оставить доступными следующие методы: \en Leave an access to the next methods: diff --git a/C3d/Include/templ_t_list.h b/C3d/Include/templ_t_list.h index ce51fb3..e6d90f8 100644 --- a/C3d/Include/templ_t_list.h +++ b/C3d/Include/templ_t_list.h @@ -86,7 +86,7 @@ writer& operator << ( writer& out, const List& ref ) { // template reader& operator >> ( reader& in, List*& ptr ) { - ptr = NULL; + ptr = c3d_null; if ( in.good() ) { if ( in.MathVersion() < 0x06000012L ) diff --git a/C3d/Include/tool_enabler.h b/C3d/Include/tool_enabler.h index 5a7151f..6baae0d 100644 --- a/C3d/Include/tool_enabler.h +++ b/C3d/Include/tool_enabler.h @@ -21,7 +21,7 @@ \ingroup Base_Tools */ // --- -MATH_FUNC (void) EnableMathModules( const char * name, int nameLength, const char * key, int keyLength ); +extern "C" MATH_FUNC (void) EnableMathModules( const char * name, int nameLength, const char * key, int keyLength ); //------------------------------------------------------------------------------ @@ -32,7 +32,7 @@ MATH_FUNC (void) EnableMathModules( const char * name, int nameLength, const cha \ingroup Base_Tools */ // --- -MATH_FUNC (bool) VerifyLicenseKey( const char * name, const char * key, const char * pub_key ); +extern "C" MATH_FUNC (bool) VerifyLicenseKey( const char * name, const char * key, const char * pub_key ); //------------------------------------------------------------------------------ @@ -43,7 +43,7 @@ MATH_FUNC (bool) VerifyLicenseKey( const char * name, const char * key, const ch \ingroup Base_Tools */ // --- -MATH_FUNC (bool) IsMathModelerEnable(); +extern "C" MATH_FUNC (bool) IsMathModelerEnable(); //------------------------------------------------------------------------------ @@ -54,7 +54,7 @@ MATH_FUNC (bool) IsMathModelerEnable(); \ingroup Base_Tools */ // --- -MATH_FUNC (bool) IsMathConverterEnable(); +extern "C" MATH_FUNC (bool) IsMathConverterEnable(); //------------------------------------------------------------------------------ @@ -65,7 +65,7 @@ MATH_FUNC (bool) IsMathConverterEnable(); \ingroup Base_Tools */ // --- -MATH_FUNC (bool) IsMathSolverEnable(); +extern "C" MATH_FUNC (bool) IsMathSolverEnable(); //------------------------------------------------------------------------------ @@ -76,7 +76,7 @@ MATH_FUNC (bool) IsMathSolverEnable(); \ingroup Base_Tools */ // --- -MATH_FUNC (bool) IsMathVisionEnable(); +extern "C" MATH_FUNC (bool) IsMathVisionEnable(); //------------------------------------------------------------------------------ @@ -87,7 +87,7 @@ MATH_FUNC (bool) IsMathVisionEnable(); \ingroup Base_Tools */ // --- -MATH_FUNC (bool) IsMathBShaperEnable(); +extern "C" MATH_FUNC (bool) IsMathBShaperEnable(); //------------------------------------------------------------------------------ @@ -98,7 +98,7 @@ MATH_FUNC (bool) IsMathBShaperEnable(); \ingroup Base_Tools */ // --- -MATH_FUNC (void) FreeMathModulesChecker(); +extern "C" MATH_FUNC (void) FreeMathModulesChecker(); #endif // _TOOL_ENABLER_H_ diff --git a/C3d/Include/tool_memory_debug.h b/C3d/Include/tool_memory_debug.h index fb2d0a7..ac4e5cd 100644 --- a/C3d/Include/tool_memory_debug.h +++ b/C3d/Include/tool_memory_debug.h @@ -66,7 +66,7 @@ public: virtual void ReallocArrayStatistic( void * oldParr, size_t oldSize, void * newParr, size_t newSize, uint arrayType ) = 0; /// \ru Отчет по статистике изменений размера массива. \en A report by the statistics of array size changes. \~ \ingroup Base_Tools - virtual void ReallocReport( bool clear, const char * title = NULL ) = 0; + virtual void ReallocReport( bool clear, const char * title = c3d_null ) = 0; }; @@ -242,7 +242,7 @@ inline void * ReallocArraySize( void * arr_parr, size_t newBytesCount, bool ) void * tmp_parr = ::realloc( arr_parr, newBytesCount ); #endif - PRECONDITION( newBytesCount == 0 || tmp_parr != NULL ); // \ru проверка на нехватку памяти в массивах \en check the memory deficit in arrays + PRECONDITION( newBytesCount == 0 || tmp_parr != c3d_null ); // \ru проверка на нехватку памяти в массивах \en check the memory deficit in arrays #ifdef __MEMSET_USED_FREE_HEAP_HEAR__ if ( clear ) { diff --git a/C3d/Include/tool_multithreading.h b/C3d/Include/tool_multithreading.h index 63712ff..cb55318 100644 --- a/C3d/Include/tool_multithreading.h +++ b/C3d/Include/tool_multithreading.h @@ -222,19 +222,19 @@ class CacheManager : public CacheCleaner { bool _valid; List( unsigned int id, T* data ) : _id( id ), - _data( data != NULL ? data : new T() ), // Always _data != NULL. - _next( NULL ), + _data( data != c3d_null ? data : new T() ), // Always _data != c3d_null. + _next( c3d_null ), _valid( true ) {} ~List() { - if ( _data != NULL ) + if ( _data != c3d_null ) delete _data; - _data = NULL; - if ( _next != NULL ) // Also deletes linked List. + _data = c3d_null; + if ( _next != c3d_null ) // Also deletes linked List. delete _next; - _next = NULL; + _next = c3d_null; } private: - List() : _id( 0 ), _data( NULL ), _next( NULL ) {} + List() : _id( 0 ), _data( c3d_null ), _next( c3d_null ) {} }; private: @@ -310,9 +310,9 @@ private: // --- template inline CacheManager::CacheManager( bool createLock ) - : longTerm ( NULL ) - , tcache ( NULL ) - , lock ( NULL ) + : longTerm ( c3d_null ) + , tcache ( c3d_null ) + , lock ( c3d_null ) { if ( createLock ) { lock = new CommonMutex(); @@ -327,11 +327,11 @@ inline CacheManager::CacheManager( bool createLock ) // --- template inline CacheManager::CacheManager( const CacheManager & item ) - : longTerm ( NULL ) - , tcache ( NULL ) - , lock ( NULL ) + : longTerm ( c3d_null ) + , tcache ( c3d_null ) + , lock ( c3d_null ) { - if ( item.longTerm != NULL ) + if ( item.longTerm != c3d_null ) longTerm = new T( *item.longTerm ); #ifndef CACHE_DELETE_LOCK lock = new CommonMutex(); @@ -346,9 +346,9 @@ template inline CacheManager::~CacheManager() { CleanAll( false, true ); - if ( longTerm != NULL ) + if ( longTerm != c3d_null ) delete longTerm; - if ( lock != NULL ) + if ( lock != c3d_null ) delete lock; } @@ -362,7 +362,7 @@ template inline T* CacheManager::LongTerm () { try { - if ( longTerm == NULL ) + if ( longTerm == c3d_null ) longTerm = new T(); } catch ( const std::bad_alloc & ) { @@ -378,10 +378,10 @@ inline T* CacheManager::LongTerm () template inline CommonMutex* CacheManager::GetLockHard() { - if ( lock == NULL ) { + if ( lock == c3d_null ) { CommonMutex* ll = GetGlobalLock(); ll->lock(); - if ( lock == NULL ) + if ( lock == c3d_null ) lock = new CommonMutex(); ll->unlock(); } @@ -396,27 +396,27 @@ template inline T * CacheManager::operator()() { // \ru Создать данные по данным кэша главного потока. \en Create data using the data of the main thread cache. -#define INIT_BY_LONGTERM ( longTerm != NULL ? new T( *longTerm ) : new T() ) +#define INIT_BY_LONGTERM ( longTerm != c3d_null ? new T( *longTerm ) : new T() ) if ( !IsSafeMultithreading() || !IsInParallel() ) { CleanAll( true ); return LongTerm(); } - T * res = NULL; + T * res = c3d_null; unsigned int threadKey = GetThreadKey(); if ( FatalErrorHandler::HasError() ) return LongTerm(); - if ( tcache == NULL ) { + if ( tcache == c3d_null ) { // \ru Подписаться на сборку мусора, так как используются многопоточные кэши. // \en Subscribe on garbage collection because using multithreaded caches. SubcribeOnCleaning(); { // \ru Используется блокировка при изменении списка кэшей. \en Use lock when changing the cache list. ScopedLock sl( GetLock(), false ); - if ( tcache == NULL ) { + if ( tcache == c3d_null ) { try { tcache = new List( threadKey, INIT_BY_LONGTERM ); return tcache->_data; @@ -430,7 +430,7 @@ inline T * CacheManager::operator()() } List* entry = tcache; - while( entry != NULL ) { + while( entry != c3d_null ) { if ( entry->_id == threadKey ) { if ( !entry->_valid ) { try { @@ -450,7 +450,7 @@ inline T * CacheManager::operator()() } // \ru Если кэш не найден в списке, 'entry' содержит последний (на данный момент) элемент в списке. // \en If cache not found in the list, 'entry' contains the last element in the list (at that point). - if ( entry->_next == NULL ) + if ( entry->_next == c3d_null ) break; entry = entry->_next; } @@ -462,7 +462,7 @@ inline T * CacheManager::operator()() List * newList = new List( threadKey, res ); // \ru На данный момент, entry может быть не последним элементом в списке. // \en At that point, entry could be not a last element in the list. - while ( entry->_next != NULL ) { + while ( entry->_next != c3d_null ) { entry = entry->_next; } entry->_next = newList; @@ -485,10 +485,10 @@ inline T * CacheManager::operator()() template inline void CacheManager::Reset( bool resetLongTerm ) { - if ( tcache != NULL ) { + if ( tcache != c3d_null ) { ScopedLock sl( GetLock() ); List* entry = tcache; - while ( entry != NULL ) { + while ( entry != c3d_null ) { entry->_valid = false; entry = entry->_next; } @@ -496,13 +496,13 @@ inline void CacheManager::Reset( bool resetLongTerm ) if ( resetLongTerm ) { ScopedLock sl( GetLock() ); delete longTerm; - longTerm = NULL; + longTerm = c3d_null; // \ru Если нет параллельности, удаляется блокировка. \en If no parallelism, delete the lock. #ifdef CACHE_DELETE_LOCK if ( !sl.IsLocked() ) { - if ( lock != NULL ) + if ( lock != c3d_null ) delete lock; - lock = NULL; + lock = c3d_null; } #endif } @@ -516,24 +516,24 @@ template inline void CacheManager::CleanAll( bool doPostproc, bool force ) { if ( force || CacheCleanupAllowed() ) { - if ( tcache != NULL ) { + if ( tcache != c3d_null ) { if ( doPostproc ) Postprocess(); delete tcache; - tcache = NULL; + tcache = c3d_null; } #ifdef CACHE_DELETE_LOCK - if ( lock != NULL ) { + if ( lock != c3d_null ) { delete lock; - lock = NULL; + lock = c3d_null; } #endif if ( IsSubscribed() ) UnsubcribeOnCleaning(); #ifdef CACHE_DELETE_LOCK - if ( lock != NULL ) { + if ( lock != c3d_null ) { delete lock; - lock = NULL; + lock = c3d_null; } #endif } @@ -546,11 +546,11 @@ inline void CacheManager::CleanAll( bool doPostproc, bool force ) template inline void CacheManager::Postprocess() { - if ( tcache != NULL ) { + if ( tcache != c3d_null ) { LongTerm(); // Create longTerm List * entry = tcache; // Incorporate thread data into main thread data. - while ( entry != NULL && longTerm->MergeWith( entry->_data ) ) { + while ( entry != c3d_null && longTerm->MergeWith( entry->_data ) ) { entry = entry->_next; } } @@ -563,18 +563,18 @@ inline void CacheManager::Postprocess() template inline void CacheManager::HardReset() { - if ( tcache != NULL ) { + if ( tcache != c3d_null ) { delete tcache; - tcache = NULL; + tcache = c3d_null; } - if ( longTerm != NULL ) { + if ( longTerm != c3d_null ) { delete longTerm; - longTerm = NULL; + longTerm = c3d_null; } - if ( lock != NULL ) { + if ( lock != c3d_null ) { delete lock; - lock = NULL; + lock = c3d_null; } } diff --git a/C3d/Include/tool_mutex.h b/C3d/Include/tool_mutex.h index dce561d..571ed92 100644 --- a/C3d/Include/tool_mutex.h +++ b/C3d/Include/tool_mutex.h @@ -421,8 +421,8 @@ public: */ void Unlock() const; - // \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. - // \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. + // \ru Выдать указатель на объект мьютекса. Возращает c3d_null, если параллельности нет. Для использования в ScopedLock. + // \en Get a pointer to the mutex object. Return c3d_null if no parallelism. For use in ScopedLock. CommonMutex * GetLock() const; }; @@ -453,8 +453,8 @@ public: */ void Unlock() const; - /** \brief \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. - \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. + /** \brief \ru Выдать указатель на объект мьютекса. Возращает c3d_null, если параллельности нет. Для использования в ScopedLock. + \en Get a pointer to the mutex object. Return c3d_null if no parallelism. For use in ScopedLock. */ CommonRecursiveMutex * GetLock() const; }; diff --git a/C3d/Include/tool_quick_sort.h b/C3d/Include/tool_quick_sort.h index 2228ea4..5750ddb 100644 --- a/C3d/Include/tool_quick_sort.h +++ b/C3d/Include/tool_quick_sort.h @@ -222,17 +222,17 @@ void Swap( Type* arr, size_t ind1, size_t ind2 ) Analog of strcmp for strings, supplied by user for comparing the array elements. Accepts 2 pointers to elements and returns: negative value, if 1<2; 0, if 1=2; positive value, if 1>2. \~ - \param[out] base2 - \ru Указатель на второй массив (может быть NULL). - \en Pointer to the second array (could be NULL). \~ - \param[out] base3 - \ru Указатель на третий массив (может быть NULL). - \en Pointer to the third array (could be NULL). \~ + \param[out] base2 - \ru Указатель на второй массив (может быть c3d_null). + \en Pointer to the second array (could be c3d_null). \~ + \param[out] base3 - \ru Указатель на третий массив (может быть c3d_null). + \en Pointer to the third array (could be c3d_null). \~ \ingroup Base_Algorithms */ //--- template void InsertSort( Type * base, size_t num, - KsQSortCompFunc compareFunc, Type2* base2 = NULL, Type3* base3 = NULL ) + KsQSortCompFunc compareFunc, Type2* base2 = c3d_null, Type3* base3 = c3d_null ) { if ( num < 2 ) @@ -241,9 +241,9 @@ void InsertSort( Type * base, if ( num == 2 ) { if ( compareFunc( base, base + 1 ) >= 0 ) { Swap( base, 0, 1 ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, 0, 1 ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, 0, 1 ); } } @@ -253,9 +253,9 @@ void InsertSort( Type * base, for ( ptrdiff_t i = 1; i < (ptrdiff_t)num; ++i ) { for ( ptrdiff_t j = i; j > 0 && compareFunc( base + j - 1, base + j ) >= 0; j-- ) { Swap( base, j - 1, j ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, j - 1, j ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, j - 1, j ); } } @@ -291,17 +291,17 @@ void InsertSort( Type * base, negative value, if 1<2; 0, if 1=2, positive value, if 1>2. \~ - \param[out] base2 - \ru Указатель на второй массив (может быть NULL). - \en Pointer to the second array (could be NULL). \~ - \param[out] base3 - \ru Указатель на третий массив (может быть NULL). - \en Pointer to the third array (could be NULL). \~ + \param[out] base2 - \ru Указатель на второй массив (может быть c3d_null). + \en Pointer to the second array (could be c3d_null). \~ + \param[out] base3 - \ru Указатель на третий массив (может быть c3d_null). + \en Pointer to the third array (could be c3d_null). \~ \ingroup Base_Algorithms */ //--- template void QuickSort( Type * base, size_t num, - KsQSortCompFunc compareFunc, Type2* base2 = NULL, Type3* base3 = NULL ) + KsQSortCompFunc compareFunc, Type2* base2 = c3d_null, Type3* base3 = c3d_null ) { #define QSORT_THRESHOLD 25 // \ru Порог перехода на другой тип сортировки.\en Threshold of transition to another sorting. @@ -317,9 +317,9 @@ void QuickSort( Type * base, if ( num == 2 ) { if ( compareFunc( base, base + 1 ) >= 0 ) { Swap( base, 0, 1 ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, 0, 1 ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, 0, 1 ); } } @@ -338,9 +338,9 @@ void QuickSort( Type * base, // \ru Выбирается базовый элемент (используется средний). \en Select a base element (use the middle one). midIndex = ( rightIndex + leftIndex ) / 2; Swap( base, midIndex, leftIndex ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, midIndex, leftIndex ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, midIndex, leftIndex ); } @@ -369,17 +369,17 @@ void QuickSort( Type * base, break; Swap( base, lInd, rInd ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, lInd, rInd ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, lInd, rInd ); } } Swap( base, leftIndex, rInd ); - if ( base2 != NULL ) { + if ( base2 != c3d_null ) { Swap( base2, leftIndex, rInd ); - if ( base3 != NULL ) + if ( base3 != c3d_null ) Swap( base3, leftIndex, rInd ); } diff --git a/C3d/Include/tool_string_util.h b/C3d/Include/tool_string_util.h index c06b678..7e6aa3a 100644 --- a/C3d/Include/tool_string_util.h +++ b/C3d/Include/tool_string_util.h @@ -44,7 +44,7 @@ inline const char* strret( const char* str ) { return str; } /// \ru Возвр inline char * strnewdup( const char * str, size_t minLen = 0 ) { if ( !str ) - return NULL; + return c3d_null; size_t len = strlen( str ); @@ -65,7 +65,7 @@ inline char * strnewdup( const char * str, size_t minLen = 0 ) inline wchar_t * wcsnewdup( const wchar_t * str, size_t minLen = 0 ) { if ( !str ) - return NULL; + return c3d_null; size_t len = wcslen( str ); @@ -85,15 +85,15 @@ inline wchar_t * wcsnewdup( const wchar_t * str, size_t minLen = 0 ) //--- inline wchar_t * mbsnewwcs( const char * str ) { - wchar_t * res = NULL; + wchar_t * res = c3d_null; if ( str ) { #ifndef __MOBILE_VERSION__ #ifdef C3D_WINDOWS // _MSC_VER - size_t n = mbstowcs( NULL, str, 0 ); + size_t n = mbstowcs( c3d_null, str, 0 ); #else // C3D_WINDOWS - size_t n = std::mbstowcs( NULL, str, 0 ); + size_t n = std::mbstowcs( c3d_null, str, 0 ); #endif // C3D_WINDOWS if ( n != NSIZE ) @@ -154,15 +154,15 @@ inline wchar_t * mbsnewwcs( const char * str ) //--- inline char * wcsnewmbs( const wchar_t * str ) { - char * res = NULL; + char * res = c3d_null; if ( str ) { // \ru один WCHAR может занять более одного CHAR! \en one WCHAR may replace more than one CHAR! #ifdef C3D_WINDOWS // _MSC_VER - size_t n = wcstombs( NULL, str, 0 ); + size_t n = wcstombs( c3d_null, str, 0 ); #else // C3D_WINDOWS - size_t n = std::wcstombs( NULL, str, 0 ); + size_t n = std::wcstombs( c3d_null, str, 0 ); #endif // C3D_WINDOWS if ( n != NSIZE ) @@ -371,10 +371,10 @@ inline const char * strret( const char * str ) { return str; } /// \ru В \ingroup Base_Tools_String */ //--- -inline uint32* Utf16ToUcs4( uint16* source, size_t* calculateCountSymbol = NULL ) +inline uint32* Utf16ToUcs4( uint16* source, size_t* calculateCountSymbol = c3d_null ) { size_t count = 0; // \ru количество символов в строке \en a number of symbols in string - uint32 * outBuf = NULL; + uint32 * outBuf = c3d_null; if ( source ) { while (source[count] != 0) @@ -400,10 +400,10 @@ inline uint32* Utf16ToUcs4( uint16* source, size_t* calculateCountSymbol = NULL \ingroup Base_Tools_String */ //--- -inline uint16* Ucs4ToUtf16( uint32* source, size_t* calculateCountSymbol = NULL ) +inline uint16* Ucs4ToUtf16( uint32* source, size_t* calculateCountSymbol = c3d_null ) { size_t count = 0; // \ru количество символов в строке \en a number of symbols in string - uint16 * outBuf = NULL; + uint16 * outBuf = c3d_null; if ( source ) { while (source[count] != 0) diff --git a/C3d/Include/tool_time_test.h b/C3d/Include/tool_time_test.h index 6c6ec3e..37943d0 100644 --- a/C3d/Include/tool_time_test.h +++ b/C3d/Include/tool_time_test.h @@ -193,7 +193,7 @@ MATH_FUNC(void) TimeTestReport( const TCHAR * fileName ); //------------------------------------------------------------------------------ // \ru выдать все результаты \en return all results // --- -MATH_FUNC(TimeTest *)GetTimeTestResults (); +MATH_FUNC(TimeTest *) GetTimeTestResults (); MATH_FUNC(void) SortResultMeasuring( TimeTest &, std::vector & ); diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 0010e4f..1040ef9 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -249,10 +249,10 @@ public : virtual MbeTopologyType IsA() const; // \ru Тип элемента. \en A type of element. /// \ru Создать новую вершину копированием всех данных исходной вершины. \en Create new vertex by copying all data of the initial vertex. - virtual MbVertex * DataDuplicate( MbRegDuplicate * = NULL ) const; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate around an axis. + virtual MbVertex * DataDuplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate around an axis. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. @@ -315,10 +315,10 @@ IMPL_PERSISTENT_OPS( MbVertex ) // --- class MATH_CLASS MbEdge : public MbTopologyItem { protected : - MbCurve3D * curve; ///< \ru Кривая, по которой проходит ребро (всегда не NULL). \en A curve, an edge passes by (it is always not NULL). + MbCurve3D * curve; ///< \ru Кривая, по которой проходит ребро (всегда не c3d_null). \en A curve, an edge passes by (it is always not c3d_null). bool sameSense; ///< \ru Признак совпадения направления ребра с направлением кривой. \en An attribute of coincidence between direction of curve and direction of edge. - MbVertex * begVertex; ///< \ru Вершина-начало (всегда не NULL). \en Start vertex (always not NULL). - MbVertex * endVertex; ///< \ru Вершина-конец (всегда не NULL). \en End vertex (always not NULL). + MbVertex * begVertex; ///< \ru Вершина-начало (всегда не c3d_null). \en Start vertex (always not c3d_null). + MbVertex * endVertex; ///< \ru Вершина-конец (всегда не c3d_null). \en End vertex (always not c3d_null). protected : /// \ru Конструктор копирования. \en Copy constructor. @@ -358,10 +358,10 @@ public : virtual MbeTopologyType IsA() const; // \ru Тип элемента. \en A type of element. /// \ru Создать новое ребро копированием всех данных исходного ребра. \en Create new edge by copying all data of the initial edge. - virtual MbEdge * DataDuplicate( MbRegDuplicate * = NULL ) const; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Трансформация. \en Transformation. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Перемещение. \en Moving. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Вращение. \en Rotation. + virtual MbEdge * DataDuplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Трансформация. \en Transformation. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Перемещение. \en Moving. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Вращение. \en Rotation. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. @@ -443,7 +443,7 @@ public : bool IsClosed() const; /// \ru Установить метку себе и вершинам. \en Set a label for self and vertices. - void SetLabelThrough( MbeLabelState l, void * key = NULL ) const; + void SetLabelThrough( MbeLabelState l, void * key = c3d_null ) const; /// \ru Установить метку себе и вершинам. \en Set a label for self and vertices. void SetLabelThrough( MbeLabelState l, void * key, bool setLock ) const; /// \ru Удалить частную метку себе и вершинам. \en Remove private label for self and vertices. @@ -585,7 +585,7 @@ public : virtual MbeTopologyType IsA() const; // \ru Тип элемента. \en A type of element. /// \ru Создать новое ребро копированием всех данных исходного ребра. \en Create new edge by copying all data of the initial edge. - virtual MbCurveEdge * DataDuplicate( MbRegDuplicate * = NULL ) const; + virtual MbCurveEdge * DataDuplicate( MbRegDuplicate * = c3d_null ) const; virtual void SetOwnChangedThrough( MbeChangedType ); // \ru Установить флаг изменения в положение измененного объекта. \en Set the flag that the object has been changed. virtual void Reverse(); // \ru Изменить направление ребра на противоположной, не изменяя кривую. \en Change direction of edge without changing a curve. /// \ru Являются ли объекты равными? \en Determine whether objects are equal. @@ -627,7 +627,7 @@ public : bool IsUsual( bool tolerantIsUsual ) const; /// \ru Установить метки ориентированных ребер. \en Set labels of oriented edges. - void SetOrientedEdgesLabel( MbeLabelState, void * key = NULL ); + void SetOrientedEdgesLabel( MbeLabelState, void * key = c3d_null ); /// \ru Найти ориентированное ребро. \en Find an oriented edge. bool FindOrientedEdge( bool orient, const MbFace * face, MbLoop *& findLoop, size_t & index ) const; /// \ru Найти ориентированное ребро. \en Find an oriented edge. @@ -712,7 +712,7 @@ public : The calculation is correct for edges which do not change a convexity. Returns ts_neutral for smooth edges. \~ */ - ThreeStates IsConvex( double angleEps = EXTENT_EPSILON, const MbRect1D * tRange = NULL ) const; + ThreeStates IsConvex( double angleEps = EXTENT_EPSILON, const MbRect1D * tRange = c3d_null ) const; /**\ru Скопировать из копии готовые метрические оценки, которые в оригинале не были рассчитаны. \en Copy from the copy ready estimates which were not calculated in the original. \~ @@ -834,7 +834,7 @@ public : \en Prolong an edge. \~ \details \ru Продолжить кривую пересечения ребра до параметра t, лежащего за пределами области определения. \n \en Continue the intersection curve of edge by the parameter t, lying outside of the curve. \n \~ - \param[in/out] t - \ru Параметра на продолжении кривой ребра. + \param[in,out] t - \ru Параметра на продолжении кривой ребра. \en Parameter outside of the intersection curve. \~ \param[in] begin - \ru Начало (true) или конец (false) ребра продолжить. \en The edge should be prolonged by the beginning (true) or by the ending (false). \~ @@ -855,20 +855,18 @@ public : \en Merging of two connected edges: \n Before the call AddRef should be done on the edges, since one of the edges may be deleted, and after the call and using the edges Release should be done on them. \n \~ - \param[in/out] edge2 - \ru Присоединяемое ребро. + \param[in,out] edge2 - \ru Присоединяемое ребро. \en Merging edge. \~ \param[in] begin1 - \ru К началу (true) или к концу (false) ребра this стыкуется присоединяемое ребро. \en This edge is joined by the beginning (true) or by the ending (false). \~ \param[in] begin2 - \ru Началом (true) или концом (false) стыкуется присоединяемое ребро к ребру this. \en The edge2 is joined by the beginning (true) or by the ending (false). \~ - \param[in] version - \ru Версия операции. - \en Version of operation. \~ - \param[in] addParentNamesAttributes - \ru Добавить атрибут имени с именами слитых ребер. - \en Add name attribute with names of merged edges. \~ + \param[in] snMaker - \ru Именователь с версией операции. + \en Names maker with a version of operation. \~ \return \ru Возвращает поглощенное ребро edge2, которое можно удалять. \en Returns absorbed edge (edge2), which can be removed. \~ */ - MbCurveEdge * MergeEdges( MbCurveEdge & edge2, bool begin1, bool begin2, VERSION version, bool addParentNamesAttributes ); + MbCurveEdge * MergeEdges( MbCurveEdge & edge2, bool begin1, bool begin2, const MbSNameMaker & snMaker ); /// \ru Собрать все ребра, стыкующиеся с заданным ребром в его начале begin==true (конце begin==false). \en Collect all edges which are connected with the given edge at its start vertex (begin==true) or at its end vertex (begin==false). void GetConnectedEdges( bool begin, RPArray & edges, SArray & orients ) const; @@ -925,7 +923,7 @@ IMPL_PERSISTENT_OPS( MbCurveEdge ) // --- class MATH_CLASS MbOrientedEdge : public MbTopItem { protected: - MbCurveEdge * curveEdge; ///< \ru Ребро грани (всегда не NULL). \en Face edge (always not NULL). + MbCurveEdge * curveEdge; ///< \ru Ребро грани (всегда не c3d_null). \en Face edge (always not c3d_null). bool orientation; ///< \ru Направление ребра грани в цикле. \en Direction of a face edge in the loop. mutable MbLabel label; ///< \ru Временная метка для выполнения операций. \en Temporary label for performing of operations. public : @@ -994,7 +992,7 @@ public : template void GetVerticesArray( VerticesVector & vertices, bool findSame = true ) const { - const MbVertex * lastVertex= NULL; + const MbVertex * lastVertex= c3d_null; if ( vertices.size() > 0 ) lastVertex = vertices.back(); @@ -1021,15 +1019,15 @@ public : void SetOrientation( bool o ); /// \ru Получить метку. \en Get label. - MbeLabelState GetLabel( void * key = NULL ) const { return (MbeLabelState)label.GetLabel(key);} + MbeLabelState GetLabel( void * key = c3d_null ) const { return (MbeLabelState)label.GetLabel(key);} /// \ru Установить свою метку. \en Set label. - void SetOwnLabel( MbeLabelState l, void * key = NULL ) const { label.SetLabel( l, key ); } + void SetOwnLabel( MbeLabelState l, void * key = c3d_null ) const { label.SetLabel( l, key ); } /// \ru Установить метку ориентированному ребру, ребру грани и вершинам ребра. \en Set label for oriented edge, face edge and vertices of edge. - void SetLabelThrough( MbeLabelState l, void * key = NULL ) const; + void SetLabelThrough( MbeLabelState l, void * key = c3d_null ) const; /// \ru Установить метку ориентированному ребру, ребру грани и вершинам ребра. \en Set label for oriented edge, face edge and vertices of edge. void SetLabelThrough( MbeLabelState l, void * key, bool setLock ) const; /// \ru Удалить частную метку. \en Remove private label. - void RemovePrivateLabel ( void * key = NULL ) const { label.DeletePrivate(key); } + void RemovePrivateLabel ( void * key = c3d_null ) const { label.DeletePrivate(key); } /// \ru Удалить частную метку ориентированному ребру, ребру грани и вершинам ребра. \en Remove private label for oriented edge, face edge and vertices of edge. void RemovePrivateLabelThrough( void * key ) const; @@ -1126,21 +1124,21 @@ public : size_t GetEdgesCount() const { return edgeList.size(); } /// \ru Получить метку цикла. \en Get a label of the loop. - MbeLabelState GetLabel( void * key = NULL ) const { return (MbeLabelState)label.GetLabel(key); } + MbeLabelState GetLabel( void * key = c3d_null ) const { return (MbeLabelState)label.GetLabel(key); } /// \ru Установить метку. \en Set a label of the loop. - void SetOwnLabel( MbeLabelState l, void * key = NULL ) const { label.SetLabel( l, key ); } + void SetOwnLabel( MbeLabelState l, void * key = c3d_null ) const { label.SetLabel( l, key ); } /// \ru Установить метку себе и ребрам цикла. \en Set a label for self and loop vertices. - void SetLabelThrough( MbeLabelState l, void * key = NULL ) const; + void SetLabelThrough( MbeLabelState l, void * key = c3d_null ) const; /// \ru Установить метку себе и ребрам цикла. \en Set a label for self and loop vertices. void SetLabelThrough( MbeLabelState l, void * key, bool setLock ) const; /// \ru Удалить частную метку себе и ребрам цикла. \en Remove private label for self and loop edges. void RemovePrivateLabelThrough( void * key ) const; /// \ru Установить метку ребрам. \en Set a label for edges. - void SetCurveEdgesLabel( MbeLabelState, void * key = NULL ) const; + void SetCurveEdgesLabel( MbeLabelState, void * key = c3d_null ) const; /// \ru Проверить метки рёбер и установить свою метку. \en Check edges labels and set own label. - void CheckEdgesLabel( void * key = NULL ) const; + void CheckEdgesLabel( void * key = c3d_null ) const; /// \ru Удалить частную метку. \en Remove private label. - void RemovePrivateLabel ( void * key = NULL ) const { label.DeletePrivate(key); } + void RemovePrivateLabel ( void * key = c3d_null ) const { label.DeletePrivate(key); } /// \ru Выдать множество вершин цикла. \en Get a set of loop vertices. template @@ -1183,7 +1181,7 @@ public : /// \ru Замена базового ребра. \en Replacement of the basis edge. void InitOrientedEdge( size_t edgeIndex, MbCurveEdge & initEdge, bool initOrientation, bool replaceVertices ); /// \ru Выдать ориентированное ребро по номеру. \en Get an oriented edge by the number. - MbOrientedEdge * GetOrientedEdge( size_t index ) const { return (index < edgeList.size()) ? edgeList[index] : NULL; } + MbOrientedEdge * GetOrientedEdge( size_t index ) const { return (index < edgeList.size()) ? edgeList[index] : c3d_null; } /// \ru Выдать ориентированное ребро по номеру без проверки корректности индекса. \en Get an oriented edge by the number without check of correctness of the index. MbOrientedEdge *_GetOrientedEdge( size_t index ) const { return edgeList[index]; } @@ -1205,9 +1203,9 @@ public : /// \ru Удалить ребро с заданным индексом. \en Delete an edge at the given index. void DeleteEdge ( size_t index ); /// \ru Отцепить все ребра от цикла. \en Detach all edges from the loop. - void DetachEdges(); + void DetachEdges( bool setNullToFace = false ); /// \ru Удалить все ребра из цикла. \en Delete all edges of the loop. - void DeleteEdges(); + void DeleteEdges( bool setNullToFace = false ); /// \ru Дать номер ребра грани в цикле. \en Get the number of a face edge in the loop. size_t GetEdgeIndex( const MbCurveEdge & edge, bool orient ) const; @@ -1220,7 +1218,7 @@ public : void Inverse(); /// \ru Принадлежит ли вершина пути. \en Does a vertex belong a path? - bool IsVertexOn( const MbVertex * vertex, size_t * index = NULL ) const; + bool IsVertexOn( const MbVertex * vertex, size_t * index = c3d_null ) const; /// \ru Замена указателей на поверхность. \en Replacement of the pointers to a surface. void ChangeSurface( MbSurface & oldSurf, MbSurface & newSurf, bool orient ); @@ -1264,11 +1262,11 @@ public : void SetProperties( const MbProperties & ); /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - void Move ( const MbVector3D &, MbRegTransform * = NULL ); + void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); /// \ru Сдвинуть двумерные кривые вдоль вектора в области параметров поверхности (все сразу). \en Move two-dimensional curves along the vector in the surface parameter region (all at once). void Move( MbVector &, const MbSurface &, bool ); /// \ru Является ли контур граничным? \en Is a contour boundary? @@ -1301,7 +1299,7 @@ public: const MbCurveEdge * edge; ///< \ru Ребро цикла. \en Loop edge. double curveParam; ///< \ru Параметр двумерной кривой ребра, лежащей на поверхности грани. \en The parameter of two-dimensional curve that lies on the surface of a face and is contained in the edge. public: - LoopCrossParam() : loopIndex( SYS_MAX_T), edge( NULL ), curveParam( UNDEFINED_DBL ) {} + LoopCrossParam() : loopIndex( SYS_MAX_T), edge( c3d_null ), curveParam( UNDEFINED_DBL ) {} LoopCrossParam( size_t li, const MbCurveEdge * e, double t ) : loopIndex( li ), edge( e ), curveParam( t ) {} LoopCrossParam( const LoopCrossParam & obj ) : loopIndex( obj.loopIndex ), edge( obj.edge ), curveParam( obj.curveParam ) {} @@ -1360,7 +1358,7 @@ public: // --- class MATH_CLASS MbFace : public MbTopologyItem, public MbSyncItem { protected: - MbSurface * surface; ///< \ru Поверхность грани (всегда не NULL). \en Face surface (always not NULL). + MbSurface * surface; ///< \ru Поверхность грани (всегда не c3d_null). \en Face surface (always not c3d_null). 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). private: @@ -1380,11 +1378,11 @@ public: , loops( bnds.size(), 1 ) , surface( const_cast(&surf) ) , sameSense( sense ) // признак совпадения нормали - , temporal( NULL ) + , temporal( c3d_null ) { surface->AddRef(); for ( size_t i = 0, cnt = bnds.size(); i < cnt; ++i ) { - if ( bnds[i] != NULL ) + if ( bnds[i] != c3d_null ) AddLoop( *bnds[i] ); } } @@ -1401,10 +1399,10 @@ public: virtual MbeTopologyType IsA() const; // \ru Тип элемента. \en A type of element. /// \ru Создать новую грань копированием всех данных исходной грани. \en Create new face by copying all data of the initial face. - virtual MbFace * DataDuplicate( MbRegDuplicate * = NULL ) const; - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Трансформация. \en Transformation. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Перемещение. \en Moving. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Вращение. \en Rotation. + virtual MbFace * DataDuplicate( MbRegDuplicate * = c3d_null ) const; + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Трансформация. \en Transformation. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Перемещение. \en Moving. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Вращение. \en Rotation. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. @@ -1414,7 +1412,7 @@ public: /// \ru Выдать поверхность грани для модификации. \en Get a surface of a face for modifications. virtual MbSurface & SetSurface(); /// \ru Является ли грань плоской? \en Is a face planar? - virtual bool IsPlanar() const; + virtual bool IsPlanar( double accuracy = METRIC_EPSILON ) const; /// \ru Дать плоскость (или только возможность ее выдачи). \en Get a plane (or only a possibility of getting a plane) virtual bool GetPlacement( MbPlacement3D * ) const; /// \ru Выдать направление нормали грани по отношению к нормали поверхности. \en Get direction of face normal in relation to the direction of surface normal. @@ -1441,7 +1439,7 @@ public: /// \ru Выдать количество циклов (границ) грани . \en Get the number of loops (boundaries) of face. size_t GetLoopsCount() const { return loops.size(); } /// \ru Установить метку грани, циклам, рёбрам и вершинам. \en Set a label of face to its loops, edges and vertices. - void SetLabelThrough( MbeLabelState l, void * key = NULL ) const; + void SetLabelThrough( MbeLabelState l, void * key = c3d_null ) const; /// \ru Установить метку грани, циклам, рёбрам и вершинам. \en Set a label of face to its loops, edges and vertices. void SetLabelThrough( MbeLabelState l, void * key, bool setLock ) const; /// \ru Удалить частную метку грани, циклам, рёбрам и вершинам. \en Remove a private label of face to its loops, edges and vertices. @@ -1457,7 +1455,7 @@ public: size_t loopsCnt = loops.size(); vertices.reserve( vertices.size() + loopsCnt * 4 ); for ( size_t i = 0; i < loopsCnt; ++i ) { - if ( loops[i] != NULL ) + if ( loops[i] != c3d_null ) loops[i]->GetVertices( vertices ); } } @@ -1474,7 +1472,7 @@ public: bool HasNeighborFace() const; /// \ru Выдать границу (цикл) с проверкой корректности индекса. \en Get a boundary (a loop) with a check of index correctness. - MbLoop * GetLoop( size_t index ) const { size_t cnt = loops.size(); return cnt ? loops[index % cnt] : NULL; } + MbLoop * GetLoop( size_t index ) const { size_t cnt = loops.size(); return cnt ? loops[index % cnt] : c3d_null; } /// \ru Выдать границу (цикл) без проверки корректности индекса. \en Get a boundary (a loop) without a check of index correctness. MbLoop *_GetLoop( size_t index ) const { return loops[index]; } /// \ru Обнулить количество ребер в цикле с указанным индексом. \en Set to null the number of edges in loop with the given index. @@ -1498,9 +1496,9 @@ public: /// \ru Установить указатели ребер цикла на грань. \en Set the pointers of loop edges to the face. void SetFaceToLoopEdges( MbLoop & ); - /// \ru Установить указатели на грань слева или грань справа в ребрах цикла на NULL. \en Set to null the pointers to the face on the left or to the face on the right in edges of loop. + /// \ru Установить указатели на грань слева или грань справа в ребрах цикла на c3d_null. \en Set to null the pointers to the face on the left or to the face on the right in edges of loop. void SetNullToLoopEdges( MbLoop & ); - /// \ru Установить указатели на грань слева или грань справа в ребрах циклов на NULL. \en Set to null the pointers to the face on the left or to the face on the right in edges of loops. + /// \ru Установить указатели на грань слева или грань справа в ребрах циклов на c3d_null. \en Set to null the pointers to the face on the left or to the face on the right in edges of loops. void SetNullToLoopsEdges(); /// \ru Обнулить указатели на грань слева или грань справа, указывающие на смежную грань delFace, в ребрах циклов. \en Set to null pointers to the face on the left or to the face on the right which point to the adjacent face delFace in edges of loops. void SetNullToFace( const MbFace * delFace ); @@ -1510,7 +1508,7 @@ public: void MakeRight( bool setBounds = false ); /// \ru Принадлежит ли вершина грани? \en Does a vertex belong an edge? - bool IsVertexOn( const MbVertex * vertex, size_t * indLoop = NULL, size_t * indEdge = NULL ) const; + bool IsVertexOn( const MbVertex * vertex, size_t * indLoop = c3d_null, size_t * indEdge = c3d_null ) const; /** \brief \ru Изменить ориентацию грани. \en Change an orientation of a face. \~ @@ -1548,7 +1546,7 @@ public: void CalculateWire( const MbStepData & stepData, MbMesh & mesh ) const // The method deprecated. It will be removed at 2019. Use CalculateMesh( stepData, MbFormNote(true, false), mesh ); \~ { CalculateMesh( stepData, MbFormNote(true, false), mesh ); } /// \ru Связаны ли грани? \en Are faces connected? - bool IsConnectedWith( const MbFace * face, RPArray * commonEdges = NULL ) const; + bool IsConnectedWith( const MbFace * face, RPArray * commonEdges = c3d_null ) const; /// \ru Подобны ли поверхности для объединения трансформацией по матрице (первичная проверка)? \en Are surfaces similar for merge by transformation by the matrix (a primary check)? bool IsSimilarToFace( const MbFace & face, bool & normal, bool & planeType, VERSION version, double precision = METRIC_PRECISION ) const; /// \ru Подобны ли поверхности для объединения путем замены (первичная проверка)? \en Are surfaces similar for merge by replacement (a primary check)? @@ -1594,7 +1592,7 @@ public: const MbCurveEdge * FindEdgeByName( const MbName & ) const; /// \ru Установить метку ориентированного ребра. \en Set a label for an oriented edge. - void SetOrientedLabel ( const MbCurveEdge & edge, MbeLabelState n, void * key = NULL ); + void SetOrientedLabel ( const MbCurveEdge & edge, MbeLabelState n, void * key = c3d_null ); /// \ru Вычислить ближайшее расстояние до ребра и ближайшие точки грани и ребра. \en Calculate the nearest distance to an edge and the nearest points of an edge. double DistanceToEdge ( const MbCurveEdge & edge, MbCartPoint3D & p, MbCartPoint3D & edgeP ) const; /// \ru Вычислить ближайшее расстояние до грани и ближайшие точки граней. \en Calculate the nearest distance to a face and the nearest points of faces. @@ -1772,7 +1770,7 @@ public: public: /// \ru Создан ли временный объект сопровождения грани? \en Is a temporary object for the maintenance of a face created? - bool IsTemporal() const { return (temporal != NULL); } + bool IsTemporal() const { return (temporal != c3d_null); } /// \ru Удалить временный объект сопровождения. \en Delete a temporary maintenance object. void RemoveTemporal() const; /// \ru Создать новый временный объект сопровождения. \en Create new temporary maintenance object. @@ -1803,7 +1801,7 @@ void MbFace::GetEdges( EdgesVector & edges, size_t mapThreshold ) const if ( edges.size() < 1 ) { size_t checkCnt = 0; for ( size_t i = 0; i < loopsCnt; ++i ) { - if ( loops[i] != NULL ) { + if ( loops[i] != c3d_null ) { checkCnt += loops[i]->GetEdgesCount(); if ( checkCnt > mapThreshold ) { useMap = true; @@ -1819,9 +1817,9 @@ void MbFace::GetEdges( EdgesVector & edges, size_t mapThreshold ) const c3d::EdgeSPtr edge; for ( size_t i = 0; i < loopsCnt; ++i ) { MbLoop * loop = loops[i]; - if ( loop != NULL ) { + if ( loop != c3d_null ) { for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) { - if ( loop->_GetOrientedEdge( j ) != NULL ) { + if ( loop->_GetOrientedEdge( j ) != c3d_null ) { edge = &loop->_GetOrientedEdge( j )->GetCurveEdge(); mapIt = mapEdges.find( edge ); if ( mapIt == mapEdges.end() ) { @@ -1838,7 +1836,7 @@ void MbFace::GetEdges( EdgesVector & edges, size_t mapThreshold ) const } if ( !useMap ) { for ( size_t i = 0; i < loopsCnt; ++i ) { - if ( loops[i] != NULL ) + if ( loops[i] != c3d_null ) loops[i]->GetEdges( edges ); } } @@ -1858,7 +1856,7 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const if ( edges.size() < 1 ) { size_t checkCnt = 0; - if ( loops.front() != NULL ) { + if ( loops.front() != c3d_null ) { checkCnt += loops.front()->GetEdgesCount(); if ( checkCnt > mapThreshold ) useMap = true; @@ -1871,7 +1869,7 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const c3d::EdgeSPtr edge; MbLoop * loop = loops.front(); for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) { - if ( loop->_GetOrientedEdge( j ) != NULL ) { + if ( loop->_GetOrientedEdge( j ) != c3d_null ) { edge = &loop->_GetOrientedEdge( j )->GetCurveEdge(); mapIt = mapEdges.find( edge ); if ( mapIt == mapEdges.end() ) { @@ -1885,7 +1883,7 @@ void MbFace::GetOuterEdges( EdgesVector & edges, size_t mapThreshold ) const } } if ( !useMap ) { - if ( loops.front() != NULL ) + if ( loops.front() != c3d_null ) loops.front()->GetEdges( edges ); } } @@ -1899,12 +1897,12 @@ void MbFace::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const { for ( size_t i = 0, loopsCnt = loops.size(); i < loopsCnt; ++i ) { const MbLoop * loop = loops[i]; - if ( loop == NULL ) + if ( loop == c3d_null ) continue; c3d::EdgeSPtr edge; for ( size_t j = 0, edgesCnt = loop->GetEdgesCount(); j < edgesCnt; ++j ) { const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( j ); - if ( orientEdge == NULL ) + if ( orientEdge == c3d_null ) continue; edge = const_cast( &orientEdge->GetCurveEdge() ); if ( edge->IsBoundaryFace() ) { @@ -1933,7 +1931,7 @@ void MbFace::GetNeighborFaces( FacesVector & neighborFaces ) const size_t neighborsCnt0 = neighborFaces.size(); for ( k = 0; k < neighborsCnt0; k++ ) { const MbFace * neighborFace = neighborFaces[k]; - if ( neighborFace != NULL ) + if ( neighborFace != c3d_null ) facesLabels.push_back( std::make_pair( neighborFace, neighborFace->GetLabel() ) ); } neighborsCnt0 = facesLabels.size(); @@ -1941,14 +1939,14 @@ void MbFace::GetNeighborFaces( FacesVector & neighborFaces ) const // mark neighbour faces by the first label for ( k = 0; k < loopsCnt; ++k ) { const MbLoop * loop = loops[k]; - if ( loop == NULL ) + if ( loop == c3d_null ) continue; for ( size_t edgeInd = 0, edgesCnt = loop->GetEdgesCount(); edgeInd < edgesCnt; ++edgeInd ) { const MbOrientedEdge * edge = loop->_GetOrientedEdge( edgeInd ); - if ( edge == NULL ) + if ( edge == c3d_null ) continue; const MbFace * neighborFace = edge->GetFaceMinus(); - if ( neighborFace != NULL && neighborFace != this ) { + if ( neighborFace != c3d_null && neighborFace != this ) { facesLabels.push_back( std::make_pair( neighborFace, neighborFace->GetLabel() ) ); // save initial label neighborFace->SetOwnLabel( ls_Used ); } diff --git a/C3d/Include/topology_faceset.h b/C3d/Include/topology_faceset.h index 2dd6d92..a3365c5 100644 --- a/C3d/Include/topology_faceset.h +++ b/C3d/Include/topology_faceset.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -162,7 +163,7 @@ public : \return \ru Копия объекта или оригинал(в случае режима копирования cm_Same). \en Copy of an object or original (in a case of the mode cm_Same). \~ */ - MbFaceShell * Copy( MbeCopyMode sameShell, MbShellHistory * history = NULL, MbRegDuplicate * iReg = NULL ); + MbFaceShell * Copy( MbeCopyMode sameShell, MbShellHistory * history = c3d_null, MbRegDuplicate * iReg = c3d_null ); /** \brief \ru Создать копию. \en Create a copy. \~ @@ -171,7 +172,7 @@ public : \return \ru Копия объекта. \en Copy of the object. \~ */ - MbFaceShell * Duplicate( MbRegDuplicate * iReg = NULL ) const; + MbFaceShell * Duplicate( MbRegDuplicate * iReg = c3d_null ) const; /// \ru Замкнутая ли оболочка? \en Is shell closed? bool IsClosed() const { return closed; } @@ -191,7 +192,7 @@ public : bool delTemporal = false; for ( size_t i = 0, cnt = newFaces.size(); i < cnt; ++i ) { const MbFace * newFace = newFaces[i]; - if ( newFace == NULL ) + if ( newFace == c3d_null ) continue; if ( justAdd || ( std::find( faceSet.begin(), faceSet.end(), newFace ) == faceSet.end() ) ) { faceSet.push_back( const_cast(newFace) ); @@ -230,7 +231,7 @@ public : for ( size_t k = 0; k < facesCnt; ++k ) { face = faceSet[k]; ::DecRefItem( faceSet[k] ); - faceSet[k] = C3D_NULL_PTR; + faceSet[k] = c3d_null; detachFaces.push_back( face ); ::DetachItem( face ); } @@ -259,7 +260,7 @@ public : \param[in] iReg - \ru Регистратор объектов. \en Registrator of objects: \~ */ - void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); + void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ); /** \brief \ru Сдвинуть вдоль вектора. \en Move along a vector. \~ @@ -274,7 +275,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. \~ */ - void Move( const MbVector3D & to, MbRegTransform * iReg = NULL ); + void Move( const MbVector3D & to, MbRegTransform * iReg = c3d_null ); /** \brief \ru Повернуть вокруг оси. \en Rotate around an axis. \~ @@ -291,7 +292,7 @@ public : \param[in] iReg - \ru Регистратор. \en Registrator. \~ */ - void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); + void Rotate( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ); /// \ru Рассчитать расстояние до точки. \en Calculate the distance to a point. double DistanceToPoint( const MbCartPoint3D & to ) const; /// \ru Вывернуть оболочку наизнанку - переориентировать все грани. \en Revert the shell - reorientation of the whole set of faces. @@ -299,7 +300,7 @@ public : /// \ru Являются ли объекты равными. \en Determine whether objects are equal. bool IsSame( const MbFaceShell & faces, double accuracy ) const; /// \ru Установить метки всем объектам, имеющим таковые. \en Set labels for all objects which have them. - void SetLabelThrough( MbeLabelState, void * = NULL ) const; + void SetLabelThrough( MbeLabelState, void * = c3d_null ) const; /// \ru Установить метки всем объектам, имеющим таковые. \en Set labels for all objects which have them. void SetLabelThrough( MbeLabelState, void *, bool ) const; /// \ru Удалить частные метки всем объектам, имеющим таковые. \en Remove private labels for all objects which have them. @@ -307,15 +308,15 @@ public : /// \ru Установить флаги изменённости объектов. \en Set flags that objects have been changed. void SetOwnChangedThrough( MbeChangedType n ); /// \ru Установить флаги в начальное состояние. \en Set flags to initial state. - void ResetFlags( void * = NULL ); + void ResetFlags( void * = c3d_null ); /// \ru Забрать в оболочку множество граней из оболочки faces. \en Move a set of faces to the shell from another shell. - bool UnionWith( MbFaceShell & faces, c3d::FacesSet * sharedSet = NULL ); + bool UnionWith( MbFaceShell & faces, c3d::FacesSet * sharedSet = c3d_null ); /// \ru Установить заданную метку всем вершинам оболочки. \en Set the given label for all vertices of the shell. - size_t SetVerticesLabel( MbeLabelState, void * = NULL) const; + size_t SetVerticesLabel( MbeLabelState, void * = c3d_null) const; /// \ru Установить заданную метку всем рёбрам оболочки. \en Set the given label for all edges of the shell. - size_t SetEdgesLabel ( MbeLabelState, void * = NULL) const; + size_t SetEdgesLabel ( MbeLabelState, void * = c3d_null) const; /// \ru Установить заданную метку всем граням оболочки. \en Set the given label for all faces of the shell. - void SetFacesLabel ( MbeLabelState, void * = NULL) const; + void SetFacesLabel ( MbeLabelState, void * = c3d_null) const; /// \ru Выдать множество вершин оболочки. \en Get a set of vertices of the shell. template @@ -327,10 +328,27 @@ public : if ( edges.size() < 1 ) ::GetEdges< RPArray, EdgesVector >( faceSet, edges ); else { - size_t count = faceSet.size(); - edges.reserve( edges.size() + count * 2 ); - for ( size_t i = 0; i < count; i++ ) - faceSet[i]->GetEdges( edges ); + size_t i, facesCnt = faceSet.size(); + + size_t allEdgesCnt = 0; + for ( i = 0; i < facesCnt; ++i ) { + const MbFace * face = faceSet[i]; + if ( face != c3d_null ) { + size_t loopsCnt = face->GetLoopsCount(); + for ( size_t j = 0; j < loopsCnt; ++j ) { + const MbLoop * loop = face->_GetLoop( j ); + if ( loop != c3d_null ) + allEdgesCnt += loop->GetEdgesCount(); + } + } + } + + edges.reserve( edges.size() + allEdgesCnt ); + + for ( i = 0; i < facesCnt; ++i ) { + if ( faceSet[i] != c3d_null ) + faceSet[i]->GetEdges( edges ); + } } } /// \ru Выдать множество граней оболочки. \en Get a set of faces of the shell. @@ -350,7 +368,7 @@ public : void GetFacesSet( FacesSet & faces ) const { for ( size_t k = 0, kcnt = faceSet.size(); k < kcnt; ++k ) { - if ( faceSet[k] != NULL ) + if ( faceSet[k] != c3d_null ) faces.insert( faceSet[k] ); } } @@ -358,7 +376,8 @@ public : template void GetItems( VerticesVector & vertices, EdgesVector & edges ) const; /// \ru Выдать множество вершин, множество ребер и множество граней оболочки. \en Get a set of vertices, a set of edges and a set of faces of the shell. - void GetItems( RPArray & list ) const; + template + void GetItems( TopologyItemsVector & ) const; /// \ru Выдать вершину по индексу. \en Get a vertex by an index. MbVertex * GetVertex ( size_t index ) const; @@ -423,9 +442,10 @@ public : \return \ru Удалось ли определить расстояния от точки до оболочки. \en Whether the distance from a point to the shell was successfully defined.. \~ */ - bool DistanceToBound( const MbCartPoint3D & pnt, double accuracy, - MbPntLoc & finFaceData, - MbeItemLocation & rShell ) const; + bool DistanceToBound( const MbCartPoint3D & pnt, + double accuracy, + MbPntLoc & finFaceData, + MbeItemLocation & rShell ) const; /** \brief \ru Определить положение точки относительно оболочки. \en Define the point location relative to the shell. \~ @@ -444,9 +464,11 @@ public : \return \ru Удалось ли определить положение точки относительно оболочки. \en Whether the point location relative to the shell was successfully defined. \~ */ - bool PointClassification( const MbCartPoint3D & pnt, double accuracy, - MbCartPoint3D & shellPoint, MbVector3D & shellNormal, - MbeItemLocation & rShell ) const; + bool PointClassification( const MbCartPoint3D & pnt, + double accuracy, + MbCartPoint3D & shellPoint, + MbVector3D & shellNormal, + MbeItemLocation & rShell ) const; /** \brief \ru Определить положение точки относительно оболочки. \en Define the point location relative to the shell. \~ @@ -465,9 +487,11 @@ public : \return \ru Удалось ли определить положение точки относительно оболочки. \en Whether the point location relative to the shell was successfully defined. \~ */ - bool PointClassification( const MbCartPoint3D & pnt, double accuracy, - MbCartPoint3D & shellPoint, MbVector3D & shellNormal, - MbPntLoc & rShell ) const; + bool PointClassification( const MbCartPoint3D & pnt, + double accuracy, + MbCartPoint3D & shellPoint, + MbVector3D & shellNormal, + MbPntLoc & rShell ) const; /** \brief \ru Вычислить точку оболочки. \en Calculate a point of the shell. \~ @@ -594,8 +618,16 @@ public : */ void CurveIntersection( const MbCurve3D & curve, SArray & nn, SArray & uv, SArray & tt ) const; - /// \ru Добавить свой габарит в габаритный куб. \en Add your own bounding box into bounding cube. - void AddYourGabaritTo( MbCube & ) const; + /** \brief \ru Добавить свой габарит в габаритный куб. + \en Add your own bounding box into bounding cube. \~ + \details \ru Добавить свой габарит в габаритный куб. + \en Add your own bounding box into bounding cube. \~ + \param[out] gab -\ru Габаритный куб для добавления габарита оболочки. + \en Bounding box for adding a bounding box of the shell. \~ + \param[out] vec -\ru Контейнер для расширенных габаритов граней оболочки. + \en Сontainer for extended bounding boxes of shell faces. \~ + */ + void AddYourGabaritTo( MbCube & gab, std::vector> * vec = c3d_null ) const; /// \ru Рассчитать габарит оболочки. \en Calculate bounding box of the shell. void CalculateGabarit( MbCube & ) const; /// \ru Рассчитать габарит в локальной системы координат, заданной матрицей matrToLocal преобразования в неё \en Calculate bounding box in the local coordinate system which is given by the matrix 'matrToLocal ' of transformation to it. @@ -624,14 +656,14 @@ public : /** \brief \ru Установить главное имя и вставить старое в индекс копирования. \en Set the main name and insert an old name to the copy index. \~ - \details \ru Установить главное имя и вставить старое в индекс копирования. Объекты с пустыми имена пропускаются. - \en Set the main name and insert an old name to the copy index. Objects with empty names are skipped. \~ - \param[in] newMainName - \ru Новое главное имя. - \en The new main name. \~ + \details \ru Установить главное имя элементам оболочки и вставить старое в индекс копирования. Объекты с пустыми имена пропускаются. + \en Set the main name of topology items and insert an old name to the copy index. Objects with empty names are skipped. \~ + \param[in] newNameMaker - \ru Именователь с новым главным именем. + \en Name maker with a new main name. \~ \param[in] addOldMainName - \ru Вставить старое в индекс копирования. \en Insert an old name to the copy index. \~ */ - void SetMainName ( SimpleName newMainName, bool addOldMainName ); + void SetItemsMainName( const MbSNameMaker & newNameMaker, bool addOldMainName ); /** \brief \ru Вставить индекс копирования. \en Insert copying index. \~ \details \ru Вставить индекс копирования. @@ -646,15 +678,15 @@ public : \en Replace main name by new one, insert old main name and given copy index into name copy indices. Objects with empty names are skipped. \~ \param[in] index - \ru Индекс копирования. \en Copying index. \~ - \param[in] newMainName - \ru Новое главное имя. - \en The new main name. \~ + \param[in] newMainName - \ru Именователь с новым главным именем. + \en A name maker with a new main name. \~ */ - void SetNamesCopyIndex( SimpleName index, const SimpleName & newMainName ); + void SetNamesCopyIndex( SimpleName index, const MbSNameMaker & newNameMaker ); /// \ru Установить главное имя и модифицировать имена граней, рёбер и вершин для оболочки-копии для предотвращения совпадения имен нескольких копий. \en Set the main name and modify names of faces, edges and vertices for the shell-copy in order to prevent coincidence of several copies names. - void MakeNewNames ( SimpleName mainName, SimpleName modifier ); + void MakeItemsNewNames( const MbSNameMaker &, SimpleName modifier ); /// \ru Установить главное имя и модифицировать имена граней для оболочки-копии для предотвращения совпадения имен нескольких копий. \en Set the main name and modify names of faces for the shell-copy in order to prevent coincidence of several copies names. - void MakeNewNames ( const MbSNameMaker &, SimpleName modifier ); + void MakeFacesNewNames( const MbSNameMaker &, SimpleName modifier ); /// \ru Проименовать грани, рёбра и вершины оболочки. \en Rename faces, edges and vertices of the shell. void SetShellNames( const MbSNameMaker & ); @@ -667,7 +699,13 @@ public : \en Clear the names of all shell elements: faces, edges, and vertices. \~ */ void ClearShellNames(); - /// \ru Очистить имена ребер в оболочке. \en Clear all shell edges names. + /** \brief \ru Очистить имена ребер в оболочке. + \en Clear all shell edges names. \~ + \details \ru Очистить имена ребер (и вершин) в оболочке. + \en Clear all shell edges (and vertices) names. \~ + \param[in] clearVerticesNames - \ru Очистить также и имена вершин. + \en Clean up also names of vertices. \~ + */ void ClearEdgesNames( bool clearVerticesNames = true ); /** \brief \ru Проверка оболочки: вершин (удаление совпадающих и лишних), ребер (со слиянием). @@ -751,7 +789,7 @@ public : bool MergeSimilarFaces( SimpleName simMainName = c3d::SIMPLENAME_MAX ); /// \ru Создан ли временный объект сопровождения? \en Is a temporary object for the maintenance created? - bool IsTemporal() const { return (temporal != NULL); } + bool IsTemporal() const { return (temporal != c3d_null); } /// \ru Удалить временный объект сопровождения. \en Delete a temporary maintenance object. void RemoveTemporal( bool removeFacesTemporal = false ) const; /// \ru Создать новый временный объект сопровождения. \en Create new temporary maintenance object. @@ -795,10 +833,10 @@ MbFaceShell::MbFaceShell( const Faces & initFaces ) : MbTopItem() , faceSet ( initFaces.size(), 1 ) , closed ( true ) - , temporal ( NULL ) + , temporal ( c3d_null ) { for ( size_t i = 0, cnt = initFaces.size(); i < cnt; ++i ) { - if ( initFaces[i] != NULL ) + if ( initFaces[i] != c3d_null ) AddFace( *initFaces[i] ); } } @@ -815,7 +853,7 @@ void MbFaceShell::GetVertices( VerticesVector & vertices ) const ptrdiff_t maxCount = SetVerticesLabel( ls_Used ); vertices.reserve( vertices.size() + maxCount ); - SPtr vertex; + c3d::VertexSPtr vertex; // reset label for ( size_t i = 0, fcount = faceSet.size(); i < fcount; ++i ) { @@ -938,6 +976,86 @@ void MbFaceShell::GetItems( VerticesVector & vertices, EdgesVector & edges ) con } +//------------------------------------------------------------------------------ +// \ru Выдать множество вершин, множество ребер и множество граней оболочки. \en Get a set of vertices, a set of edges and a set of faces of the shell. +// --- +template +void MbFaceShell::GetItems( TopologyItemsVector & list ) const +{ + size_t maxCount = 1; + + // поднимаем флаг // set up labels + size_t i, fcount = faceSet.size(); + for ( i = 0; i < fcount; ++i ) { + const MbFace * face = faceSet[i]; + if ( face == c3d_null ) + continue; + + for ( size_t j = 0, lcount = face->GetLoopsCount(); j < lcount; ++j ) { + const MbLoop * loop = face->_GetLoop(j); + if ( loop == c3d_null ) + continue; + + size_t ecount = loop->GetEdgesCount(); + for ( size_t k = 0; k < ecount; ++k ) { + const MbCurveEdge * edge = &loop->_GetOrientedEdge(k)->GetCurveEdge(); + + edge->SetOwnLabel( ls_Used ); + edge->GetBegVertex().SetOwnLabel( ls_Used ); + edge->GetEndVertex().SetOwnLabel( ls_Used ); + } + + maxCount += 2 * ecount; + } + } + + list.reserve( list.size() + faceSet.size() + maxCount ); + + // опускаем флаг // reset labels + for ( i = 0; i < fcount; ++i ) { + MbFace * face = faceSet[i]; + if ( face == c3d_null ) + continue; + + list.push_back( face ); + + c3d::EdgeSPtr edge; + c3d::VertexSPtr vertex; + + for ( size_t j = 0, lcount = face->GetLoopsCount(); j < lcount; ++j ) { + const MbLoop * loop = face->_GetLoop(j); + if ( loop == c3d_null ) + continue; + + for ( size_t k = 0, ecount = loop->GetEdgesCount(); k < ecount; ++k ) { + edge = &loop->_GetOrientedEdge(k)->GetCurveEdge(); + + if ( edge->GetLabel() == ls_Used ) { + list.push_back( edge ); + edge->SetOwnLabel( ls_Null ); + } + + vertex = const_cast( &edge->GetBegVertex() ); + if ( vertex->GetLabel() == ls_Used ) { + list.push_back( vertex ); + vertex->SetOwnLabel( ls_Null ); + } + ::DetachItem( vertex ); + + vertex = const_cast( &edge->GetEndVertex() ); + if ( vertex->GetLabel() == ls_Used ) { + list.push_back( vertex ); + vertex->SetOwnLabel( ls_Null ); + } + ::DetachItem( vertex ); + + ::DetachItem( edge ); + } + } + } +} + + //------------------------------------------------------------------------------ // \ru Для множества граней найти множество их комбинированных номеров. \en For a set of faces find a set of their combined indices. // --- @@ -960,7 +1078,7 @@ bool MbFaceShell::FindIndexByFaces( const FacesPointersVector & initFaces, ItemI for ( size_t i = 0; i < initFacesCount; ++i ) { const MbFace * face = initFaces[i]; - if ( face != NULL ) { + if ( face != c3d_null ) { size_t i0 = SYS_MAX_T; c3d::ConstFaceIndexMap::iterator it = fiMap.find( face ); if ( it != fiMap.end() ) @@ -976,7 +1094,7 @@ bool MbFaceShell::FindIndexByFaces( const FacesPointersVector & initFaces, ItemI if ( directFind ) { for ( size_t i = 0; i < initFacesCount; ++i ) { const MbFace * face = initFaces[i]; - if ( face != NULL ) { + if ( face != c3d_null ) { size_t i0 = GetFaceIndex( *face ); if ( i0 != SYS_MAX_T ) { index.Init( *face, i0 ); @@ -1001,7 +1119,7 @@ bool MbFaceShell::FindConstFacesByIndex( const ItemIndices & indices, ConstFaces for ( size_t j = 0, indicesCnt = indices.size(); j < indicesCnt; ++j ) { MbItemIndex & index = const_cast(indices[j]); // у stl доступ честный как const, у SArray дает на редактирование findFace = FindFaceByIndex( index ); - if ( findFace != NULL ) { + if ( findFace != c3d_null ) { initFaces.push_back( findFace ); ::DetachItem( findFace ); } @@ -1022,7 +1140,7 @@ bool MbFaceShell::FindFacesByIndex( const ItemIndices & indices, FacesPointersVe for ( size_t j = 0, indicesCnt = indices.size(); j < indicesCnt; ++j ) { MbItemIndex & index = const_cast(indices[j]); // у stl доступ честный как const, у SArray дает на редактирование findFace = const_cast(FindFaceByIndex( index )); - if ( findFace != NULL ) { + if ( findFace != c3d_null ) { initFaces.push_back( findFace ); ::DetachItem( findFace ); } @@ -1041,15 +1159,15 @@ bool MbFaceShell::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const const size_t boundaryCnt = boundaryEdges.size(); for ( size_t i = 0, facesCnt = faceSet.size(); i < facesCnt; ++i ) { const MbFace * face = faceSet[i]; - if ( face == NULL ) + if ( face == c3d_null ) continue; for ( size_t j = 0, loopsCnt = face->GetLoopsCount(); j < loopsCnt; ++j ) { const MbLoop * loop = face->_GetLoop( j ); - if ( loop == NULL ) + if ( loop == c3d_null ) continue; for ( size_t k = 0, edgesCnt = loop->GetEdgesCount(); k < edgesCnt; ++k ) { const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( k ); - if ( orientEdge != NULL ) { + if ( orientEdge != c3d_null ) { c3d::ConstEdgeSPtr edge( &orientEdge->GetCurveEdge() ); if ( edge->IsBoundaryFace() ) boundaryEdges.push_back( edge ); @@ -1076,37 +1194,28 @@ bool MbFaceShell::GetBoundaryEdges( ConstEdgesVector & boundaryEdges ) const struct MATH_CLASS MbCheckTopologyParams { protected: bool mergeEdges; ///< \ru Флаг слияния ребер. \en Merge flag for edges. - bool addNameAttributes; ///< \ru Добавить атрибут имени с именами слитых ребер. \en Add name attribute with names of merged edges. - VERSION version; ///< \ru Версия. \en Version. + SPtr nameMaker; ///< \ru Именователь с версией операции. \en Names maker with operation version. SimpleName lastMainName; ///< \ru Главное имя именователя последней операции. \en Main name of the last operation name maker. c3d::ConstFacesVector controlFaces; ///< \ru Грани, по которым может быть взведена ошибка. \en Faces where an error may occur. c3d::ConstEdgesVector boundaryEdges; ///< \ru Исходные краевые ребра (до операции). \en Initial boundary edges (before an operation). public: - explicit MbCheckTopologyParams( bool doMergingEdges, const MbSNameMaker & nameMaker ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( nameMaker.GetParentNamesAttributes() ) - , version ( nameMaker.GetMathVersion() ) - , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. - , controlFaces ( ) - , boundaryEdges ( ) - {} - explicit MbCheckTopologyParams( bool doMergingEdges, VERSION ver, bool addNameAttrs ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( addNameAttrs ) - , version ( ver ) - , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. - , controlFaces ( ) - , boundaryEdges ( ) + explicit MbCheckTopologyParams( bool doMergingEdges, + const MbSNameMaker & nMaker ) + : mergeEdges ( doMergingEdges ) + , nameMaker ( &nMaker.Duplicate() ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. + , controlFaces ( ) + , boundaryEdges( ) {} template - explicit MbCheckTopologyParams( bool doMergingEdges, const MbSNameMaker & nameMaker, - const Faces & faces ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( nameMaker.GetParentNamesAttributes() ) - , version ( nameMaker.GetMathVersion() ) - , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. - , controlFaces ( ) - , boundaryEdges ( ) + explicit MbCheckTopologyParams( bool doMergingEdges, + const MbSNameMaker & nMaker, + const Faces & faces ) + : mergeEdges ( doMergingEdges ) + , nameMaker ( &nMaker.Duplicate() ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. + , controlFaces ( ) + , boundaryEdges( ) { size_t facesCnt = faces.size(); if ( facesCnt > 0 ) { @@ -1117,32 +1226,15 @@ public: } } template - explicit MbCheckTopologyParams( bool doMergingEdges, VERSION ver, bool addNameAttrs, - const Faces & faces ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( addNameAttrs ) - , version ( ver ) - , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. - , controlFaces ( ) - , boundaryEdges ( ) - { - size_t facesCnt = faces.size(); - if ( facesCnt > 0 ) { - controlFaces.reserve( facesCnt ); - for ( size_t k = 0; k < facesCnt; ++k ) - controlFaces.push_back( faces[k] ); - std::sort( controlFaces.begin(), controlFaces.end() ); - } - } - template - explicit MbCheckTopologyParams( bool doMergingEdges, const MbSNameMaker & nameMaker, - const Faces & faces, const c3d::ConstEdgesVector & edges ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( nameMaker.GetParentNamesAttributes() ) - , version ( nameMaker.GetMathVersion() ) - , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. - , controlFaces ( ) - , boundaryEdges ( edges ) + explicit MbCheckTopologyParams( bool doMergingEdges, + const MbSNameMaker & nMaker, + const Faces & faces, + const c3d::ConstEdgesVector & edges ) + : mergeEdges ( doMergingEdges ) + , nameMaker ( &nMaker.Duplicate() ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. + , controlFaces ( ) + , boundaryEdges( edges ) { size_t facesCnt = faces.size(); if ( facesCnt > 0 ) { @@ -1154,10 +1246,12 @@ public: std::sort( boundaryEdges.begin(), boundaryEdges.end() ); } ~MbCheckTopologyParams() {} +public: + const MbSNameMaker & NameMaker() const { return *nameMaker; } public: bool MergeEdges () const { return mergeEdges; } - bool AddNameAttributes() const { return addNameAttributes; } - VERSION MathVersion () const { return version; } + bool AddNameAttributes() const { return nameMaker->GetParentNamesAttributes(); } + VERSION MathVersion () const { return nameMaker->GetMathVersion(); } SimpleName LastMainName() const { return lastMainName; } void SetLastMainName( const SimpleName & lmn ) { lastMainName = lmn; } @@ -1174,14 +1268,14 @@ public: if ( controlFaces.size() > 0 && sortedDelFaces.size() > 0 ) { for ( size_t k = controlFaces.size(); k--; ) { if ( std::binary_search( sortedDelFaces.begin(), sortedDelFaces.end(), controlFaces[k] ) ) { - controlFaces[k] = NULL; + controlFaces[k] = c3d_null; res = true; } } if ( res ) { std::sort( controlFaces.begin(), controlFaces.end() ); controlFaces.erase( std::unique( controlFaces.begin(), controlFaces.end() ), controlFaces.end() ); - if ( controlFaces.front() == NULL ) + if ( controlFaces.front() == c3d_null ) controlFaces.erase( controlFaces.begin() ); } } @@ -1215,19 +1309,19 @@ private: public: /// \ru Конструктор по умолчанию \en Default constructor - MbEdgeFunction () : edge(NULL), function(NULL), slideway(NULL) {} + MbEdgeFunction () : edge(c3d_null), function(c3d_null), slideway(c3d_null) {} /// \ru Конструктор по ребру и функции. \en Constructor by an edge and function. - MbEdgeFunction ( const MbCurveEdge * e, const MbFunction * f ) : edge(e), function(f), slideway(NULL) {} + MbEdgeFunction ( const MbCurveEdge * e, const MbFunction * f ) : edge(e), function(f), slideway(c3d_null) {} /// \ru Конструктор по ребру и опорной кривой. \en Constructor by an edge and a supporting curve. - MbEdgeFunction ( const MbCurveEdge * e, const MbCurve3D * c ) : edge(e), function(NULL), slideway(c) {} + MbEdgeFunction ( const MbCurveEdge * e, const MbCurve3D * c ) : edge(e), function(c3d_null), slideway(c) {} /// \ru Конструктор по другому ребру с функцией. \en Constructor by other edge with a function. MbEdgeFunction ( const MbEdgeFunction & other ) : edge(other.edge), function(other.function), slideway(other.slideway) {} ~MbEdgeFunction() {} public: /// \ru Инициализация по ребру и функции. \en Initialization by an edge and a function. - void Init( const MbCurveEdge * e, const MbFunction * f ) { edge = e; function = f; slideway = NULL; } + void Init( const MbCurveEdge * e, const MbFunction * f ) { edge = e; function = f; slideway = c3d_null; } /// \ru Инициализация по ребру и опорной кривой. \en Initialization by an edge and a supporting curve. - void Init( const MbCurveEdge * e, const MbCurve3D * c ) { edge = e; function = NULL; slideway = c; } + void Init( const MbCurveEdge * e, const MbCurve3D * c ) { edge = e; function = c3d_null; slideway = c; } /// \ru Дать ребро. \en Get an edge. const MbCurveEdge * Edge() const { return edge; } /// \ru Дать функцию изменения радиуса. \en Get a function of radius changing. @@ -1425,7 +1519,7 @@ public: /// \ru Конструктор по умолчанию. \en Default constructor. MbPntLoc() : pntLoc ( iloc_Undefined ) - , shell ( NULL ) + , shell ( c3d_null ) , ind ( SYS_MAX_T ) , dist ( MB_MAXDOUBLE ) , n ( MB_MAXDOUBLE ) @@ -1449,7 +1543,7 @@ public: /// \ru Получить положение пространственной точки. \en Get location of spatial point MbeItemLocation GetLocation() const { return pntLoc; } /// \ru Выбрана ли грань? \en Is a face chosen? - bool IsFaceSelected() const { return ((shell != NULL) && (ind < shell->GetFacesCount()) && (shell->GetFace(ind) != NULL)); } + bool IsFaceSelected() const { return ((shell != c3d_null) && (ind < shell->GetFacesCount()) && (shell->GetFace(ind) != c3d_null)); } /// \ru Выполнена ли классификация по грани? \en Is classification by the face performed? bool IsFaceData() const { return (IsFaceSelected() && !shell->IsTemporal(ind)) ? true : false; } /// \ru Выполнена ли классификация по грани сопровождения? \en Is classification by the face of maintenance performed? @@ -1458,7 +1552,7 @@ public: /// \ru Получить индекс грани. \en Get an index of a face. size_t GetFaceIndex() const { return ind; } /// \ru Получить грань. \en Get a face. - const MbFace * GetFace() const { return (IsFaceSelected() ? shell->GetFace(ind) : NULL); } + const MbFace * GetFace() const { return (IsFaceSelected() ? shell->GetFace(ind) : c3d_null); } /// \ru Получить расстояние до точки проекции. \en Get the distance to projection point. double GetDistance() const { return dist; } /// \ru Получить двумерную точку проекции. \en Get two-dimensional projection point. @@ -1478,7 +1572,7 @@ public: bool IsCorner() const { return corn; } /// \ru Получить поверхности грани. \en Get surfaces of a face. - const MbSurface * GetFaceSurface() const { return (IsFaceSelected() ? &shell->GetFace(ind)->GetSurface() : NULL); } + const MbSurface * GetFaceSurface() const { return (IsFaceSelected() ? &shell->GetFace(ind)->GetSurface() : c3d_null); } /// \ru Получить ориентацию грани относительно поверхности. \en Get face orientation relative a surface. bool GetFaceSense() const { return (IsFaceSelected() ? shell->GetFace(ind)->IsSameSense() : true); } /// \ru Получить поверхность смежной грани. \en Get a surface of adjacent face. @@ -1494,7 +1588,7 @@ public: void Reset() { pntLoc = iloc_Undefined; - shell = NULL; + shell = c3d_null; ind = SYS_MAX_T; dist = MB_MAXDOUBLE; n = MB_MAXDOUBLE; @@ -1549,33 +1643,6 @@ public: }; -//------------------------------------------------------------------------------ -/** \brief \ru Установить главное имя. - \en Set main name. \~ - \details \ru Установить главное имя mainName для имени name. \n - \en Set the main name 'mainName' for the name 'name'. \n \~ - \param[out] name - \ru Имя. - \en Name. \~ - \param[in] mainName - \ru Главное имя. - \en The main name. \~ - \param[in] addOldMainName - \ru При true запомнить заменяемое главное имя в индексе копирования. - \en When it is true remember replaced main name in the copying index. \~ - \ingroup Algorithms_3D -*/ -// --- -inline -bool SetMainName( MbName & name, SimpleName mainName, bool addOldMainName ) -{ - if ( !name.IsEmpty() ) { - if ( addOldMainName ) - name.SetCopyIndex( name.GetMainName() ); - name.SetMainName( mainName ); - return true; - } - return false; -} - - //------------------------------------------------------------------------------ /** \brief \ru Установить заданную метку всем рёбрам оболочки. \en Set the specified label to all edges of the shell. \~ @@ -1589,7 +1656,7 @@ bool SetMainName( MbName & name, SimpleName mainName, bool addOldMainName ) */ // --- template -size_t SetEdgesLabel( const FacesVector & faceSet, MbeLabelState label, void * key = NULL ) +size_t SetEdgesLabel( const FacesVector & faceSet, MbeLabelState label, void * key = c3d_null ) { size_t maxCount = 1; diff --git a/C3d/Include/topology_item.h b/C3d/Include/topology_item.h index 57be739..79f517a 100644 --- a/C3d/Include/topology_item.h +++ b/C3d/Include/topology_item.h @@ -103,11 +103,11 @@ public: /// \ru Деструктор. \en Destructor without parameters. ~MbLabel(); /// \ru Установить частную или собственную метку (соответствующую ключу). \en Set own or private label (according to the key). - void SetLabel( const MbeLabelState, void * key = NULL ); + void SetLabel( const MbeLabelState, void * key = c3d_null ); /// \ru Установить частную или собственную метку (соответствующую ключу). \en Set own or private label (according to the key). void SetLabel( const MbeLabelState, void * key, bool setLock ); /// \ru Получить частную или собственную метку (соответствующую ключу). \en Get own or private label (according to thew key). - int8 GetLabel( void * key = NULL ); + int8 GetLabel( void * key = c3d_null ); /// \ru Удалить частные метки(освободить память) соответствующие ключу. \en Remove private labels (free memory) according to the key. void DeletePrivate( void * key ); /// \ru Присвоить значение собственной метке. \en Assign values to own label. @@ -232,7 +232,7 @@ public : \en Registrator. \~ \ingroup Topology_Items */ - virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = NULL ) = 0; + virtual void Transform( const MbMatrix3D & matr, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Сдвинуть вдоль вектора. \en Move along a vector. \~ @@ -250,7 +250,7 @@ public : \en Registrator. \~ \ingroup Topology_Items */ - virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = NULL ) = 0; + virtual void Move ( const MbVector3D & to, MbRegTransform * iReg = c3d_null ) = 0; /** \brief \ru Повернуть вокруг оси. \en Rotate around an axis. \~ @@ -270,7 +270,7 @@ public : \en Registrator. \~ \ingroup Topology_Items */ - virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ) = 0; + virtual void Rotate ( const MbAxis3D & axis, double angle, MbRegTransform * iReg = c3d_null ) = 0; /// \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual double DistanceToPoint( const MbCartPoint3D & ) const = 0; @@ -324,15 +324,15 @@ public : bool IsOwnChangedWeakly() const; /// \ru Получить метку. \en Get label. - MbeLabelState GetLabel( void * key = NULL ) const { return (MbeLabelState)label.GetLabel(key); } + MbeLabelState GetLabel( void * key = c3d_null ) const { return (MbeLabelState)label.GetLabel(key); } /// \ru Установить метку. \en Set a label of the loop. - void SetOwnLabel( MbeLabelState l, void * key = NULL ) const { label.SetLabel( l, key ); } + void SetOwnLabel( MbeLabelState l, void * key = c3d_null ) const { label.SetLabel( l, key ); } /// \ru Установить метку. \en Set a label of the loop. void SetOwnLabel( MbeLabelState l, void * key, bool setLock ) const { if ( setLock || GetUseCount() > 1 ) return SetOwnLabel( l, key ); label.SetLabel( l, key ); } /// \ru Предназначен ли объект для удаления? Определяется по меткам. \en Is this object intended for deletion? This is defined by labels. - bool ToDelete() const { return( (MbeLabelState)label.GetLabel(NULL) == ls_Delete || (MbeLabelState)label.GetLabel(NULL) == ls_Error ); } + bool ToDelete() const { return( (MbeLabelState)label.GetLabel(c3d_null) == ls_Delete || (MbeLabelState)label.GetLabel(c3d_null) == ls_Error ); } /// \ru Удалить частную метку. \en Remove private label. - void RemovePrivateLabel ( void * key = NULL ) const { label.DeletePrivate(key); } + void RemovePrivateLabel ( void * key = c3d_null ) const { label.DeletePrivate(key); } /// \ru Копирование данных объекта. \en Copying of the object data. void Assign( const MbTopologyItem & ); @@ -403,11 +403,11 @@ public: /// \ru Тип элемента. \en A type of element. virtual MbeTopologyType IsA() const; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); //\ru Повернуть вокруг оси. \en Rotate around an axis. - virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = c3d_null ); public: // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. virtual double DistanceToPoint( const MbCartPoint3D & ) const; diff --git a/C3d/Include/tri_face.h b/C3d/Include/tri_face.h index 6be17c4..a1fd4a7 100644 --- a/C3d/Include/tri_face.h +++ b/C3d/Include/tri_face.h @@ -47,12 +47,12 @@ class MATH_CLASS MbCube; \ingroup Triangulation */ // --- -MATH_FUNC (void) CalculateGrid( const MbFace & face, +MATH_FUNC (void) CalculateGrid( const MbFace & face, const MbStepData & stepData, - MbGrid & grid, - bool dualSeams = true, - bool quad = false, - bool fair = false ); + MbGrid & grid, + bool dualSeams = true, + bool quad = false, + bool fair = false ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/tri_lump.h b/C3d/Include/tri_lump.h index e2934f5..934f116 100644 --- a/C3d/Include/tri_lump.h +++ b/C3d/Include/tri_lump.h @@ -12,24 +12,21 @@ #include -#include +#include +#include #include -class MATH_CLASS MbGrid; - - //---------------------------------------------------------------------------------------- /** \brief \ru Математическая грань и ее рассчитанная решетка. \en Mathematical face and its calculated grid. \~ \ingroup Polygonal_Objects */ // --- -class MATH_CLASS MbFaceAndGrid -{ - SPtr face; ///< \ru Грань. \en A face. +class MATH_CLASS MbFaceAndGrid { + c3d::ConstFaceSPtr face; ///< \ru Грань. \en A face. public: - SPtr grid; ///< \ru Триангуляция грани. \en A face triangulation. + c3d::ConstGridSPtr grid; ///< \ru Триангуляция грани. \en A face triangulation. public: /** \brief \ru Конструктор по грани и ее триангуляции.\n @@ -68,7 +65,8 @@ public: return *this; } - const MbFace & GetFace() const { return *face; } // deprecated + DEPRECATE_DECLARE + const MbFace & GetFace() const { return *face; } // deprecated }; @@ -110,13 +108,13 @@ public: {} /** \brief \ru Добавить грань с триангуляцией. \en Add face with triangulation. \~ - \param[in] face - \ru Грань с триангулюционной решеткой. + \param[in] face - \ru Грань с триангуляционной решеткой. \en A face with triangulation grid. \~ */ void AddFace( const MbFaceAndGrid & face ) { faces.push_back( face ); } // \ru Объявление конструктора копирования и оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration without implementation of the copy-constructor and assignment operator to prevent an assignment by default. - OBVIOUS_PRIVATE_COPY(MbLumpAndFaces); +OBVIOUS_PRIVATE_COPY(MbLumpAndFaces) }; diff --git a/C3d/Include/wire_frame.h b/C3d/Include/wire_frame.h index bad9f89..6802164 100644 --- a/C3d/Include/wire_frame.h +++ b/C3d/Include/wire_frame.h @@ -1,452 +1,452 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Трехмерный проволочный каркас. - \en Three-dimensional wire frame. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __WIRE_FRAME_H -#define __WIRE_FRAME_H - - -#include -#include -#include -#include -#include -#include -#include - -class MATH_CLASS MbWireFrame; - - -namespace c3d // namespace C3D -{ -typedef SPtr WireFrameSPtr; -typedef SPtr ConstWireFrameSPtr; - -typedef std::vector WireFramesVector; -typedef std::vector ConstWireFramesVector; - -typedef std::vector WireFramesSPtrVector; -typedef std::vector ConstWireFramesSPtrVector; -} // namespace C3D - - -//------------------------------------------------------------------------------ -/** \brief \ru Трехмерный проволочный каркас. - \en Three-dimensional wire frame. \~ - \details \ru Трехмерный проволочный каркас состоит из множества рёбер MbEdge. \n - Каркас может состоять из нескольких связных частей. - Связная часть может иметь топологию звезды, при которой в одной вершине стыкуется более двух рёбер. - Каркас может быть разбит на отдельные связные части. Каждая связная часть обладает функциями составной кривой. - \en Three-dimensional wire frame consists of a set of edges of a type MbEdge. \n - A wire frame may consist of several connected parts. - A connected part may have a topology of a star where one vertex is coincident with more than two edges - A wire frame may be split into separate connected parts. Each connected part has functions of a composite curve. \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbWireFrame : public MbItem { -protected : - c3d::WireEdgesVector edges; ///< \ru Множество рёбер каркаса. \en A set of edges of the frame. - size_t partsCount; ///< \ru Количество связных частей объекта. \en A number of connected parts of an object. - bool closed; ///< \ru Замкнутость указывает на возможность получит множество замкнутых кривых. \en Closedness indicates to a possibility to get a set of closed curves. - mutable bool normal; ///< \ru Разложен ли каркас на связные части? \en Is a frame split into connected parts? - -private : - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbWireFrame( const MbWireFrame &, MbRegDuplicate * ); -public : - /// \ru Конструктор без параметров. \en Constructor without parameters. - MbWireFrame(); - /// \ru Конструктор по кривой и строителю. \en Constructor by a curve and creator. - MbWireFrame( const MbCurve3D &, const MbCreator * = NULL ); - /// \ru Конструктор по множеству кривых и строителю. \en Constructor by a set of curves and creator. - MbWireFrame( const RPArray &, const MbCreator * = NULL ); - /// \ru Конструктор по множеству кривых и строителю. \en Constructor by a set of curves and creator. - MbWireFrame( const c3d::SpaceCurvesSPtrVector &, const MbCreator * = NULL ); - /// \ru Конструктор по ребру и строителю. \en Constructor by an edge and creator. - MbWireFrame( const MbEdge &, const MbCreator * = NULL, bool same = true ); - /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. - MbWireFrame( const RPArray &, const MbCreator * = NULL, bool same = true ); - /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. - MbWireFrame( const c3d::WireEdgesSPtrVector &, const MbCreator * = NULL, bool same = true ); - /// \ru Деструктор. \en Destructor. - virtual ~MbWireFrame(); - -public : - VISITING_CLASS( MbWireFrame ); - - // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. - - virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en An object type. - virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = NULL ) const; // \ru Создать копию. \en Create a copy. - virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); // \ru Повернуть вокруг оси. \en Rotate about an axis. - virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? - virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? - virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равными. \en Make the objects equal. - virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. - virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate the bounding box in a local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты. \en Get the basis objects. - virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - virtual bool GetPlacement( MbPlacement3D & ) const; // \ru Проинициализировать присланную локальную систему координат (совместить плоскость XY), если каркас плоский. \en Initialize the sent local coordinate system (combine the plane XY) if the frame is planar. - // \ru Перестроить объект по журналу построения. \en Reconstruct object according to the history tree. - virtual bool RebuildItem( MbeCopyMode sameShell, RPArray * items, IProgressIndicator * progInd ); - - // \ru Создать полигональный объект - упрощенную копию данного объекта. \en Create a polygonal object - a simplified copy of the given object. - virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; - - /** \ru \name Общие функции каркаса. - \en \name Common functions of a frame. - \{ */ - - /// \ru Выдать количество ребер каркаса. \en Get the number of edges of the frame. - size_t GetEdgesCount() const { return edges.size(); } - /// \ru Выдать объект по индексу. \en Get the item by index. - const MbEdge * GetEdge( size_t i ) const { return (i < edges.size()) ? edges[i] : NULL; } - /// \ru Выдать объект по индексу для возможного редактирования. \en Get the item by index for the possible editing. - MbEdge * SetEdge( size_t i ) { return (i < edges.size()) ? edges[i] : NULL; } - - /// \ru Получить ребра. \en Get edges. - template - void GetEdges( EdgesVector & dstEdges ) const - { - if ( !edges.empty() ) { - size_t addCnt = edges.size(); - dstEdges.reserve( dstEdges.size() + addCnt ); - c3d::ConstWireEdgeSPtr edge; - for ( size_t k = 0; k < addCnt; ++k ) { - edge = edges[k]; - dstEdges.push_back( edge ); - } - } - } - /// \ru Получить ребра для возможного редактирования. \en Get edges for the possible editing. - template - void SetEdges( EdgesVector & dstEdges ) - { - if ( !edges.empty() ) { - size_t addCnt = edges.size(); - dstEdges.reserve( dstEdges.size() + addCnt ); - c3d::WireEdgeSPtr edge; - for ( size_t k = 0; k < addCnt; ++k ) { - edge = edges[k]; - dstEdges.push_back( edge ); - } - } - } - /// \ru Добавить ребро по кривой и ее ориентации в ребре. \en Add an edge by a curve and its orientation in relation to an edge. - void AddEdge( const MbCurve3D &, bool sense = true ); - /// \ru Добавить ребро (оригинал, не копию). \en Add an edge (an original, not a copy). - void AddEdge( const MbEdge &, bool same = true ); - /// \ru Добавить массив ребер (оригиналы, не копии). \en Add an array of edges (originals, not copies). - template - void AddEdges( const WireEdgesVector &, bool same = true ); - /// \ru Вставить ребро по индексу (оригинал, не копию). \en Insert an edge by index (an original, not a copy). - void InsertEdge( size_t index, const MbEdge & item, bool same = true ); - /// \ru Отцепить ребро по индексу. \en Detach an edge by index. - MbEdge * DetachEdge( size_t index ); - /// \ru Удалить все рёбра. \en Delete all edges. - void DeleteEdges(); - /// \ru Удалить ребро по индексу. \en Delete an edge by index. - bool DeleteEdge( size_t index ); - /// \ru Удалить ребро, если таковое имеется. \en Delete an edge if it already exists. - bool DeleteEdge( MbEdge * ); - - /// \ru Выдать массив вершин ребер каркаса. \en Get an array of frame edges vertices. - void GetVerticesArray ( RPArray & ); - /// \ru Выдать массив вершин ребер каркаса. \en Get an array of frame edges vertices. - void GetVerticesArray ( RPArray & ) const; - /// \ru выдать индекс вершины. \en Get vertex index. - size_t GetVertexIndex( const MbVertex & find ) const; - /// \ru выдать вершину по индексу \en Get vertex by index. - MbVertex * GetVertex( size_t index ) const; - /// \ru выдать индекс ребра. \en Get edge index. - size_t GetEdgeIndex( const MbEdge & find ) const; - /// \ru Получить вершины. \en Get vertices. - template - void GetVerticesSet( VerticesSet & dstVertices ) const - { - if ( !edges.empty() ) { - size_t addCnt = edges.size(); - c3d::ConstWireEdgeSPtr edge; - c3d::ConstVertexSPtr vertex; - for ( size_t k = 0; k < addCnt; ++k ) { - edge = edges[k]; - vertex = &edge->GetBegVertex(); - dstVertices.insert( vertex ); - if ( &edge->GetEndVertex() != &edge->GetBegVertex() ) { - vertex = &edge->GetEndVertex(); - dstVertices.insert( vertex ); - } - } - } - } - - /// \ru Выдать вершину-начало каркаса. \en Get the start vertex of a frame. - const MbVertex * GetBegVertex() const; - /// \ru Выдать вершину-конец каркаса. \en Get the end vertex of a frame. - const MbVertex * GetEndVertex() const; - - /// \ru Найти вершину по имени. \en Find vertex by name. - const MbVertex * FindVertexByName( const MbName & ) const; - /// \ru Найти ребро по имени. \en Find edge by name. - const MbEdge * FindEdgeByName ( const MbName & ) const; - - /** \brief \ru Разбить ребро по параметрам его кривой на несколько его частей. - \en Split the edge using the curve parameters into several pieces. \~ - \details \ru . Если beginSafe == true - ребро сохранит начальный участок, - Если beginSafe == false - ребро сохранит конечный участок. - По параметру 'eps' отсеиваются значения в контейнере 'params', совпадающие друг с другом и с начальным и конечным параметрами кривой. - Контейнер 'edges' содержит отрезанные части. - \en . If beginSafe == true then the edge saves its starting piece, - If beginSafe == false then the edge saves its ending piece. - According to the parameter 'eps' drop out value in the container 'params', coinciding with each other and with the initial and final parameters of the curve. - The container 'edges' contains cut parts. \~ - \params[in, out] targetEdge - \ru Ребро для разрезания. Возвращается урезанный кусок с учетом флага beginSafe или NULL, - если параметр разрезания находится на расстоянии меньшим еps от соответствующего конца кривой, - \en Edge for cutting. The return value of 'targetEdge' is the shortened edge according to 'beginSafe' flag - or NULL, if the cut param in 'params' lies at the distance less than 'eps' from the corresponding end of the curve, - \param[in] params - \ru Параметры кривой для разбиения ребра, - \en Parameters of intersection curve of edge to split, \~ - \param[in] beginSafe - \ru Ребро сохранит начальную часть (true) или ребро сохранит конечную часть (false), - \en The edge will keep a beginning piece (true) or the edge will keep an end piece (false) \~ - \param[in] eps - \ru Точность совпадения параметров разбиения, - \en Precision matching options of parameters to split, \~ - \param[out] edges - \ru Отрезанные части ребра. - \en The container of cut parts. \~ - \return \ru Возвращает true, если ребро было разрезано. - \en Returns true, if the edge was cut. \~ - */ - bool CuttingEdge( MbEdge *& targetEdge, SArray & params, bool beginSafe, double eps, RPArray & edges ); - - /// \ru Замкнут ли каркас? \en Is frame closed? - bool IsClosed(); - /// \ru Является ли каркас многосвязным? \en Is frame multiply connected? - bool IsMultiWireFrame(); - /// \ru Количество связных частей каркаса. \en A number of connected parts of a frame. - size_t GetPartsCount(); - - /// \ru Является ли объект плоским? \en Is the object planar? - bool IsPlanar() const; - /// \ru Дать плоскую кривую и ее систему координат, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерные кривые). \en Get planar coordinate system if the space curve is planar (after the using call DeleteItem for two-dimensional curves) - 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; - /// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. - template - void GetCurves( CurvesVector & ) const; - /// \ru Разложен ли каркас на связные части? \en Is a frame split into connected parts? - 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 Отделение частей каркаса с сохранением исходного объекта. - Если исходный каркас распадается на части, то все части складываются в parts. \n - \en Detachment of frame parts with saving an initial object. - If the initial frame is decomposed, all the parts are put into array 'parts'. \n \~ - \param[out] parts - \ru Каркасы, полученные из frame. - \en Frames obtained from 'frame'. \~ - \result \ru Возвращает количество каркасов в parts. - \en Returns a number of frames in 'parts'. \~ - */ - size_t CreateParts( RPArray & parts ); - /** \} */ - - /// \ru Установить заданный флаг измененности для всех рёбер и вершин. \en Set flag of changes for all edges and vertices. - void SetOwnChangedThrough( MbeChangedType ); - -private: - /// \ru Связано ли ребро с каким-либо ребром каркаса. \en Whether an edge is connected with another edge of a frame. - bool IsConnectedWith( const MbEdge & ); - /// \ru Нормализовать ребро (выставить общую вершину замкнутого ребра) \en Normalize an edge (set the common vertex af a closed edge) - void NormalizeEdge( MbEdge & ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireFrame ) -OBVIOUS_PRIVATE_COPY( MbWireFrame ) -}; - -IMPL_PERSISTENT_OPS( MbWireFrame ) - - -//------------------------------------------------------------------------------ -// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. -// --- -template -void MbWireFrame::GetCurves( CurvesVector & curves ) const -{ - size_t edgesCnt = edges.size(); - curves.reserve( curves.size() + edgesCnt ); - c3d::SpaceCurveSPtr curve; - for ( size_t k = 0; k < edgesCnt; ++k ) { - const MbEdge * edge = edges[k]; - if ( edge != NULL ) { - curve = const_cast( &edge->GetCurve() ); - curves.push_back( curve ); - ::DetachItem( curve ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Добавить массив ребер (оригиналы, не копии). \en Add an array of edges (originals, not copies). -// --- -template -void MbWireFrame::AddEdges( const WireEdgesVector & items, bool same ) -{ - bool add = false; - MbRegDuplicate * iReg = NULL; - MbAutoRegDuplicate autoReg( iReg ); - - size_t addCnt = items.size(); - edges.reserve( edges.size() + addCnt ); - - c3d::WireEdgeSPtr edge; - for ( size_t k = 0; k < addCnt; ++k ) { - const MbEdge * item = items[k]; - - if ( item != NULL ) { - edge = same ? const_cast(item) : item->DataDuplicate( iReg ); - edge->AddRef(); - edges.push_back( edge ); - add = true; - } - } - if ( add ) { - normal = false; - AttributesChange(); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Забрать кривые и удалить каркас, если он не используется. - \en Take curves and delete a frame if it is not used. \~ - \details \ru Забрать кривые и удалить каркас, если он не используется. \n - \en Take curves and delete a frame if it is not used. \n \~ - \param[in] wireFrame - \ru Каркас, подлежащий удалению. - \en A frame to delete. \~ - \param[out] curves - \ru Кривые, полученные из каркаса. - \en Curves obtained from the frame. \~ - \ingroup Curve3D_Modeling -*/ -// --- -template -void ExtractCurvesDeleteFrame( MbWireFrame *& wireFrame, - CurvesVector & curves ) -{ - if ( wireFrame != NULL ) { - c3d::SpaceCurvesSPtrVector wireCurves; - wireFrame->GetCurves( wireCurves ); - ::DeleteItem( wireFrame ); - - size_t wireCurvesCnt = wireCurves.size(); - - if ( wireCurvesCnt > 0 ) { - curves.reserve( curves.size() + wireCurvesCnt ); - for ( size_t k = 0; k < wireCurvesCnt; ++k ) { - MbCurve3D * curve = ::DetachItem( wireCurves[k] ); - if ( curve != NULL ) { - curves.push_back( curve ); - } - } - } - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Забрать первую кривую и удалить каркас, если он пуст и не используется. - \en Take the first curve and delete a frame if it is empty and not used. \~ - \details \ru Забрать первую кривую и удалить каркас, если он пуст и не используется. \n - \en Take the first curve and delete a frame if it is empty and not used. \n \~ - \param[in] wireFrame - \ru Каркас, подлежащий удалению. - \en A frame to delete. \~ - \param[out] curve - \ru Кривая, полученная из каркаса. - \en A curve obtained from the frame. \~ - \ingroup Curve3D_Modeling -*/ -// --- -inline -void ExtractCurveDeleteFrame( MbWireFrame *& wireFrame, - MbCurve3D *& curve ) -{ - if ( wireFrame != NULL ) { - c3d::WireEdgeSPtr edge( wireFrame->DetachEdge( 0 ) ); // \ru Отцепить объект \en Detach an object - ::DeleteItem( wireFrame ); - - if ( edge != NULL ) { - curve = &edge->SetCurve(); - ::AddRefItem( curve ); - edge = NULL; - ::DecRefItem( curve ); - } - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать каркас по множеству кривых. - \en Create a frame by a set of curves. \~ - \details \ru Создать или обновить каркас по множеству кривых. \n - \en Create or update a frame by a set of curves. \n \~ - \param[out] result - \ru Каркас, подлежащий замене или построению. - \en A frame to replace or construct. \~ - \param[in] curves - \ru Кривые для построения каркаса. - \en Curves for the frame construction. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[in] creator - \ru Строитель каркаса. - \en A creator of a frame. \~ - \result \ru Возвращает true, если присланный каркас обновился, или был создан новый при отсутствии каркаса на входе. - \en Returns true if the sent frame has been updated or if the new frame has been created without a frame in the input. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, - const RPArray & curves, - const MbSNameMaker & snMaker, - const MbCreator * creator = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать каркас по кривой. - \en Create a frame by a curve. \~ - \details \ru Создать или обновить каркас по кривой. \n - \en Create or update a frame by a curve. \n \~ - \param[out] result - \ru Каркас, подлежащий замене или построению. - \en A frame to replace or construct. \~ - \param[in] curve - \ru Кривая для построения каркаса. - \en A curve for the frame construction. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[in] creator - \ru Строитель каркаса. - \en A creator of a frame. \~ - \result \ru Возвращает true, если присланный каркас обновился, или был создан новый при отсутствии каркаса на входе. - \en Returns true if the sent frame has been updated or if the new frame has been created without a frame in the input. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, - const MbCurve3D & curve, - const MbSNameMaker & snMaker, - const MbCreator * creator = NULL ); - - -#endif // __WIRE_FRAME_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Трехмерный проволочный каркас. + \en Three-dimensional wire frame. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __WIRE_FRAME_H +#define __WIRE_FRAME_H + + +#include +#include +#include +#include +#include +#include +#include + +class MATH_CLASS MbWireFrame; + + +namespace c3d // namespace C3D +{ +typedef SPtr WireFrameSPtr; +typedef SPtr ConstWireFrameSPtr; + +typedef std::vector WireFramesVector; +typedef std::vector ConstWireFramesVector; + +typedef std::vector WireFramesSPtrVector; +typedef std::vector ConstWireFramesSPtrVector; +} // namespace C3D + + +//------------------------------------------------------------------------------ +/** \brief \ru Трехмерный проволочный каркас. + \en Three-dimensional wire frame. \~ + \details \ru Трехмерный проволочный каркас состоит из множества рёбер MbEdge. \n + Каркас может состоять из нескольких связных частей. + Связная часть может иметь топологию звезды, при которой в одной вершине стыкуется более двух рёбер. + Каркас может быть разбит на отдельные связные части. Каждая связная часть обладает функциями составной кривой. + \en Three-dimensional wire frame consists of a set of edges of a type MbEdge. \n + A wire frame may consist of several connected parts. + A connected part may have a topology of a star where one vertex is coincident with more than two edges + A wire frame may be split into separate connected parts. Each connected part has functions of a composite curve. \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbWireFrame : public MbItem { +protected : + c3d::WireEdgesVector edges; ///< \ru Множество рёбер каркаса. \en A set of edges of the frame. + size_t partsCount; ///< \ru Количество связных частей объекта. \en A number of connected parts of an object. + bool closed; ///< \ru Замкнутость указывает на возможность получит множество замкнутых кривых. \en Closedness indicates to a possibility to get a set of closed curves. + mutable bool normal; ///< \ru Разложен ли каркас на связные части? \en Is a frame split into connected parts? + +private : + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbWireFrame( const MbWireFrame &, MbRegDuplicate * ); +public : + /// \ru Конструктор без параметров. \en Constructor without parameters. + MbWireFrame(); + /// \ru Конструктор по кривой и строителю. \en Constructor by a curve and creator. + MbWireFrame( const MbCurve3D &, const MbCreator * = c3d_null ); + /// \ru Конструктор по множеству кривых и строителю. \en Constructor by a set of curves and creator. + MbWireFrame( const RPArray &, const MbCreator * = c3d_null ); + /// \ru Конструктор по множеству кривых и строителю. \en Constructor by a set of curves and creator. + MbWireFrame( const c3d::SpaceCurvesSPtrVector &, const MbCreator * = c3d_null ); + /// \ru Конструктор по ребру и строителю. \en Constructor by an edge and creator. + MbWireFrame( const MbEdge &, const MbCreator * = c3d_null, bool same = true ); + /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. + MbWireFrame( const RPArray &, const MbCreator * = c3d_null, bool same = true ); + /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. + MbWireFrame( const c3d::WireEdgesSPtrVector &, const MbCreator * = c3d_null, bool same = true ); + /// \ru Деструктор. \en Destructor. + virtual ~MbWireFrame(); + +public : + VISITING_CLASS( MbWireFrame ); + + // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. + + virtual MbeSpaceType IsA() const; // \ru Тип объекта. \en An object type. + virtual MbSpaceItem & Duplicate( MbRegDuplicate * iReg = c3d_null ) const; // \ru Создать копию. \en Create a copy. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = c3d_null ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. + virtual void Move ( const MbVector3D &, MbRegTransform * = c3d_null ); // \ru Сдвинуть вдоль вектора. \en Translate along a vector. + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = c3d_null ); // \ru Повернуть вокруг оси. \en Rotate about an axis. + virtual bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Are the objects equal? + virtual bool IsSimilar( const MbSpaceItem & ) const; // \ru Являются ли объекты подобными? \en Are the objects similar? + virtual bool SetEqual ( const MbSpaceItem & ); // \ru Сделать объекты равными. \en Make the objects equal. + virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. + virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate the bounding box in a local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual void SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual void GetBasisItems ( RPArray & ); // \ru Дать базовые объекты. \en Get the basis objects. + virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + virtual bool GetPlacement( MbPlacement3D & ) const; // \ru Проинициализировать присланную локальную систему координат (совместить плоскость XY), если каркас плоский. \en Initialize the sent local coordinate system (combine the plane XY) if the frame is planar. + // \ru Перестроить объект по журналу построения. \en Reconstruct object according to the history tree. + virtual bool RebuildItem( MbeCopyMode sameShell, RPArray * items, IProgressIndicator * progInd ); + + // \ru Создать полигональный объект - упрощенную копию данного объекта. \en Create a polygonal object - a simplified copy of the given object. + virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; + + /** \ru \name Общие функции каркаса. + \en \name Common functions of a frame. + \{ */ + + /// \ru Выдать количество ребер каркаса. \en Get the number of edges of the frame. + size_t GetEdgesCount() const { return edges.size(); } + /// \ru Выдать объект по индексу. \en Get the item by index. + const MbEdge * GetEdge( size_t i ) const { return (i < edges.size()) ? edges[i] : c3d_null; } + /// \ru Выдать объект по индексу для возможного редактирования. \en Get the item by index for the possible editing. + MbEdge * SetEdge( size_t i ) { return (i < edges.size()) ? edges[i] : c3d_null; } + + /// \ru Получить ребра. \en Get edges. + template + void GetEdges( EdgesVector & dstEdges ) const + { + if ( !edges.empty() ) { + size_t addCnt = edges.size(); + dstEdges.reserve( dstEdges.size() + addCnt ); + c3d::ConstWireEdgeSPtr edge; + for ( size_t k = 0; k < addCnt; ++k ) { + edge = edges[k]; + dstEdges.push_back( edge ); + } + } + } + /// \ru Получить ребра для возможного редактирования. \en Get edges for the possible editing. + template + void SetEdges( EdgesVector & dstEdges ) + { + if ( !edges.empty() ) { + size_t addCnt = edges.size(); + dstEdges.reserve( dstEdges.size() + addCnt ); + c3d::WireEdgeSPtr edge; + for ( size_t k = 0; k < addCnt; ++k ) { + edge = edges[k]; + dstEdges.push_back( edge ); + } + } + } + /// \ru Добавить ребро по кривой и ее ориентации в ребре. \en Add an edge by a curve and its orientation in relation to an edge. + void AddEdge( const MbCurve3D &, bool sense = true ); + /// \ru Добавить ребро (оригинал, не копию). \en Add an edge (an original, not a copy). + void AddEdge( const MbEdge &, bool same = true ); + /// \ru Добавить массив ребер (оригиналы, не копии). \en Add an array of edges (originals, not copies). + template + void AddEdges( const WireEdgesVector &, bool same = true ); + /// \ru Вставить ребро по индексу (оригинал, не копию). \en Insert an edge by index (an original, not a copy). + void InsertEdge( size_t index, const MbEdge & item, bool same = true ); + /// \ru Отцепить ребро по индексу. \en Detach an edge by index. + MbEdge * DetachEdge( size_t index ); + /// \ru Удалить все рёбра. \en Delete all edges. + void DeleteEdges(); + /// \ru Удалить ребро по индексу. \en Delete an edge by index. + bool DeleteEdge( size_t index ); + /// \ru Удалить ребро, если таковое имеется. \en Delete an edge if it already exists. + bool DeleteEdge( MbEdge * ); + + /// \ru Выдать массив вершин ребер каркаса. \en Get an array of frame edges vertices. + void GetVerticesArray ( RPArray & ); + /// \ru Выдать массив вершин ребер каркаса. \en Get an array of frame edges vertices. + void GetVerticesArray ( RPArray & ) const; + /// \ru выдать индекс вершины. \en Get vertex index. + size_t GetVertexIndex( const MbVertex & find ) const; + /// \ru выдать вершину по индексу \en Get vertex by index. + MbVertex * GetVertex( size_t index ) const; + /// \ru выдать индекс ребра. \en Get edge index. + size_t GetEdgeIndex( const MbEdge & find ) const; + /// \ru Получить вершины. \en Get vertices. + template + void GetVerticesSet( VerticesSet & dstVertices ) const + { + if ( !edges.empty() ) { + size_t addCnt = edges.size(); + c3d::ConstWireEdgeSPtr edge; + c3d::ConstVertexSPtr vertex; + for ( size_t k = 0; k < addCnt; ++k ) { + edge = edges[k]; + vertex = &edge->GetBegVertex(); + dstVertices.insert( vertex ); + if ( &edge->GetEndVertex() != &edge->GetBegVertex() ) { + vertex = &edge->GetEndVertex(); + dstVertices.insert( vertex ); + } + } + } + } + + /// \ru Выдать вершину-начало каркаса. \en Get the start vertex of a frame. + const MbVertex * GetBegVertex() const; + /// \ru Выдать вершину-конец каркаса. \en Get the end vertex of a frame. + const MbVertex * GetEndVertex() const; + + /// \ru Найти вершину по имени. \en Find vertex by name. + const MbVertex * FindVertexByName( const MbName & ) const; + /// \ru Найти ребро по имени. \en Find edge by name. + const MbEdge * FindEdgeByName ( const MbName & ) const; + + /** \brief \ru Разбить ребро по параметрам его кривой на несколько его частей. + \en Split the edge using the curve parameters into several pieces. \~ + \details \ru . Если beginSafe == true - ребро сохранит начальный участок, + Если beginSafe == false - ребро сохранит конечный участок. + По параметру 'eps' отсеиваются значения в контейнере 'params', совпадающие друг с другом и с начальным и конечным параметрами кривой. + Контейнер 'edges' содержит отрезанные части. + \en . If beginSafe == true then the edge saves its starting piece, + If beginSafe == false then the edge saves its ending piece. + According to the parameter 'eps' drop out value in the container 'params', coinciding with each other and with the initial and final parameters of the curve. + The container 'edges' contains cut parts. \~ + \params[in, out] targetEdge - \ru Ребро для разрезания. Возвращается урезанный кусок с учетом флага beginSafe или c3d_null, + если параметр разрезания находится на расстоянии меньшим еps от соответствующего конца кривой, + \en Edge for cutting. The return value of 'targetEdge' is the shortened edge according to 'beginSafe' flag + or c3d_null, if the cut param in 'params' lies at the distance less than 'eps' from the corresponding end of the curve, + \param[in] params - \ru Параметры кривой для разбиения ребра, + \en Parameters of intersection curve of edge to split, \~ + \param[in] beginSafe - \ru Ребро сохранит начальную часть (true) или ребро сохранит конечную часть (false), + \en The edge will keep a beginning piece (true) or the edge will keep an end piece (false) \~ + \param[in] eps - \ru Точность совпадения параметров разбиения, + \en Precision matching options of parameters to split, \~ + \param[out] edges - \ru Отрезанные части ребра. + \en The container of cut parts. \~ + \return \ru Возвращает true, если ребро было разрезано. + \en Returns true, if the edge was cut. \~ + */ + bool CuttingEdge( MbEdge *& targetEdge, SArray & params, bool beginSafe, double eps, RPArray & edges ); + + /// \ru Замкнут ли каркас? \en Is frame closed? + bool IsClosed(); + /// \ru Является ли каркас многосвязным? \en Is frame multiply connected? + bool IsMultiWireFrame(); + /// \ru Количество связных частей каркаса. \en A number of connected parts of a frame. + size_t GetPartsCount(); + + /// \ru Является ли объект плоским? \en Is the object planar? + bool IsPlanar() const; + /// \ru Дать плоскую кривую и ее систему координат, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерные кривые). \en Get planar coordinate system if the space curve is planar (after the using call DeleteItem for two-dimensional curves) + 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; + /// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. + template + void GetCurves( CurvesVector & ) const; + /// \ru Разложен ли каркас на связные части? \en Is a frame split into connected parts? + 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 Отделение частей каркаса с сохранением исходного объекта. + Если исходный каркас распадается на части, то все части складываются в parts. \n + \en Detachment of frame parts with saving an initial object. + If the initial frame is decomposed, all the parts are put into array 'parts'. \n \~ + \param[out] parts - \ru Каркасы, полученные из frame. + \en Frames obtained from 'frame'. \~ + \result \ru Возвращает количество каркасов в parts. + \en Returns a number of frames in 'parts'. \~ + */ + size_t CreateParts( RPArray & parts ); + /** \} */ + + /// \ru Установить заданный флаг измененности для всех рёбер и вершин. \en Set flag of changes for all edges and vertices. + void SetOwnChangedThrough( MbeChangedType ); + +private: + /// \ru Связано ли ребро с каким-либо ребром каркаса. \en Whether an edge is connected with another edge of a frame. + bool IsConnectedWith( const MbEdge & ); + /// \ru Нормализовать ребро (выставить общую вершину замкнутого ребра) \en Normalize an edge (set the common vertex af a closed edge) + void NormalizeEdge( MbEdge & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbWireFrame ) +OBVIOUS_PRIVATE_COPY( MbWireFrame ) +}; + +IMPL_PERSISTENT_OPS( MbWireFrame ) + + +//------------------------------------------------------------------------------ +// \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. +// --- +template +void MbWireFrame::GetCurves( CurvesVector & curves ) const +{ + size_t edgesCnt = edges.size(); + curves.reserve( curves.size() + edgesCnt ); + c3d::SpaceCurveSPtr curve; + for ( size_t k = 0; k < edgesCnt; ++k ) { + const MbEdge * edge = edges[k]; + if ( edge != c3d_null ) { + curve = const_cast( &edge->GetCurve() ); + curves.push_back( curve ); + ::DetachItem( curve ); + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Добавить массив ребер (оригиналы, не копии). \en Add an array of edges (originals, not copies). +// --- +template +void MbWireFrame::AddEdges( const WireEdgesVector & items, bool same ) +{ + bool add = false; + MbRegDuplicate * iReg = c3d_null; + MbAutoRegDuplicate autoReg( iReg ); + + size_t addCnt = items.size(); + edges.reserve( edges.size() + addCnt ); + + c3d::WireEdgeSPtr edge; + for ( size_t k = 0; k < addCnt; ++k ) { + const MbEdge * item = items[k]; + + if ( item != c3d_null ) { + edge = same ? const_cast(item) : item->DataDuplicate( iReg ); + edge->AddRef(); + edges.push_back( edge ); + add = true; + } + } + if ( add ) { + normal = false; + AttributesChange(); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Забрать кривые и удалить каркас, если он не используется. + \en Take curves and delete a frame if it is not used. \~ + \details \ru Забрать кривые и удалить каркас, если он не используется. \n + \en Take curves and delete a frame if it is not used. \n \~ + \param[in] wireFrame - \ru Каркас, подлежащий удалению. + \en A frame to delete. \~ + \param[out] curves - \ru Кривые, полученные из каркаса. + \en Curves obtained from the frame. \~ + \ingroup Curve3D_Modeling +*/ +// --- +template +void ExtractCurvesDeleteFrame( MbWireFrame *& wireFrame, + CurvesVector & curves ) +{ + if ( wireFrame != c3d_null ) { + c3d::SpaceCurvesSPtrVector wireCurves; + wireFrame->GetCurves( wireCurves ); + ::DeleteItem( wireFrame ); + + size_t wireCurvesCnt = wireCurves.size(); + + if ( wireCurvesCnt > 0 ) { + curves.reserve( curves.size() + wireCurvesCnt ); + for ( size_t k = 0; k < wireCurvesCnt; ++k ) { + MbCurve3D * curve = ::DetachItem( wireCurves[k] ); + if ( curve != c3d_null ) { + curves.push_back( curve ); + } + } + } + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Забрать первую кривую и удалить каркас, если он пуст и не используется. + \en Take the first curve and delete a frame if it is empty and not used. \~ + \details \ru Забрать первую кривую и удалить каркас, если он пуст и не используется. \n + \en Take the first curve and delete a frame if it is empty and not used. \n \~ + \param[in] wireFrame - \ru Каркас, подлежащий удалению. + \en A frame to delete. \~ + \param[out] curve - \ru Кривая, полученная из каркаса. + \en A curve obtained from the frame. \~ + \ingroup Curve3D_Modeling +*/ +// --- +inline +void ExtractCurveDeleteFrame( MbWireFrame *& wireFrame, + MbCurve3D *& curve ) +{ + if ( wireFrame != c3d_null ) { + c3d::WireEdgeSPtr edge( wireFrame->DetachEdge( 0 ) ); // \ru Отцепить объект \en Detach an object + ::DeleteItem( wireFrame ); + + if ( edge != c3d_null ) { + curve = &edge->SetCurve(); + ::AddRefItem( curve ); + edge = c3d_null; + ::DecRefItem( curve ); + } + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать каркас по множеству кривых. + \en Create a frame by a set of curves. \~ + \details \ru Создать или обновить каркас по множеству кривых. \n + \en Create or update a frame by a set of curves. \n \~ + \param[out] result - \ru Каркас, подлежащий замене или построению. + \en A frame to replace or construct. \~ + \param[in] curves - \ru Кривые для построения каркаса. + \en Curves for the frame construction. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[in] creator - \ru Строитель каркаса. + \en A creator of a frame. \~ + \result \ru Возвращает true, если присланный каркас обновился, или был создан новый при отсутствии каркаса на входе. + \en Returns true if the sent frame has been updated or if the new frame has been created without a frame in the input. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, + const RPArray & curves, + const MbSNameMaker & snMaker, + const MbCreator * creator = c3d_null ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать каркас по кривой. + \en Create a frame by a curve. \~ + \details \ru Создать или обновить каркас по кривой. \n + \en Create or update a frame by a curve. \n \~ + \param[out] result - \ru Каркас, подлежащий замене или построению. + \en A frame to replace or construct. \~ + \param[in] curve - \ru Кривая для построения каркаса. + \en A curve for the frame construction. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[in] creator - \ru Строитель каркаса. + \en A creator of a frame. \~ + \result \ru Возвращает true, если присланный каркас обновился, или был создан новый при отсутствии каркаса на входе. + \en Returns true if the sent frame has been updated or if the new frame has been created without a frame in the input. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, + const MbCurve3D & curve, + const MbSNameMaker & snMaker, + const MbCreator * creator = c3d_null ); + + +#endif // __WIRE_FRAME_H diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index 707cd1c..601689d 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 cce4a13..44cf4ad 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 4574a4f..6a39645 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 9d9f1c4..b468be8 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ