diff --git a/C3d/Include/action.h b/C3d/Include/action.h index 670ccf1..bd6569e 100644 --- a/C3d/Include/action.h +++ b/C3d/Include/action.h @@ -1,1276 +1,1319 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Функции работы с кривыми, поверхностями, оболочками, телами. - \en Functions for operating with curves, surfaces, shells and solids. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_H -#define __ACTION_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbPlanarGrid; -class MATH_CLASS MbGrid; -class MATH_CLASS MbSNameMaker; -class IProgressIndicator; - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить оболочку на предмет разделения на отдельные части. - \en Check if the shell can be subdivided into separate parts. \~ - \details \ru Проверить замкнутую оболочку на предмет разделения на отдельные части с анализом вложенности. \n - \en Check if the closed shell can be subdivided into separate parts with inclusion analysis. \n \~ - \param[in] shell - \ru Исходная оболочка. - \en The initial shell. \~ - \result \ru Возвращает true, если оболочка состоит из нескольких частей. - \en Returns 'true' if the shell consists of several parts. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsMultiShell( const MbFaceShell * shell, bool checkNesting = true ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отделить части оболочки. - \en Separate parts from a shell. \~ - \details \ru Отделить части оболочки без анализа вложенности. - Если sort == true, то наибольшая часть оболочки останется в исходной оболочке, - а отделившиеся от неё части будут сложены в parts с сортировкой по убыванию габарита. \n - \en Separate parts from a shell without inclusion analysis. - If 'sort' == 'true', the greatest part of the shell will remain in the initial shell, - separated parts will be collected in array 'parts' sorted by bounding box size in descending order. \n \~ - \param[in] shell - \ru Исходная оболочка. - \en The initial shell. \~ - \param[out] parts - \ru Оболочки, полученные из shell. - \en The shells separated from 'shell'. \~ - \param[in] sort - \ru Выполнять ли сортировку частей оболочки по убыванию габарита? - \en If 'sort' == true, the parts separated from the initial shell will be sorted by bounding box size in descending order. \~ - \result \ru Возвращает количество оболочек в parts. - \en Returns number of shells in 'parts'. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, RPArray & parts, bool sort ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отделить части оболочки. - \en Separate parts from a shell. \~ - \details \ru Отделить части оболочки без анализа вложенности. - Исходная оболочка всегда остаётся неизменённой. - Если исходная оболочка распадается на части, то все части складываются в parts. \n - \en Separate parts from a shell without inclusion analysis. - The initial shell always remains unchangeable. - If the initial shell is decomposed, all the parts are put into array 'parts'. \n \~ - \param[in] shell - \ru Исходная оболочка. - \en The initial shell. \~ - \param[out] parts - \ru Оболочки, полученные из shell. - \en The shells separated from 'shell'. \~ - \result \ru Возвращает количество оболочек в parts. - \en Returns number of shells in 'parts'. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (size_t) CreateShells( MbFaceShell & shell, RPArray & parts ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку выдавливанием плоских контуров. - \en Create a shell by extrusion of planar contours. \~ - \details \ru Построить оболочку выдавливанием плоских контуров. \n - \en Create a shell by extrusion of planar contours. \n \~ - \param[in] surface - \ru Поверхность контуров. - \en A surface that contains the contours. \~ - \param[in] contours - \ru Набор двумерных контуров. - \en A set of planar contours. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] params - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] cNames - \ru Набор именователей контуров. - \en A set of objects defining names of the contours. \~ - \param[out] result - \ru Результат операции - оболочка. - \en Result of the operation - a shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtrusionShell( const MbSurface & surface, - RPArray & contours, - const MbVector3D & direction, - const ExtrusionValues & params, - const MbSNameMaker & operNames, - RPArray & cNames, - MbFaceShell *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку вращением плоских контуров. - \en Create a shell by revolution of planar contours. \~ - \details \ru Построить оболочку вращением плоских контуров. \n - \en Create a shell by revolution of planar contours. \n \~ - \param[in] surface - \ru Поверхность контуров. - \en A surface that contains the contours. \~ - \param[in] contours - \ru Набор двумерных контуров. - \en A set of planar contours. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] params - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] cNames - \ru Набор именователей контуров. - \en A set of objects defining names of the contours. \~ - \param[out] result - \ru Результат операции - оболочка. - \en Result of the operation - a shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RevolutionShell( const MbSurface & surface, - RPArray & contours, - const MbAxis3D & axis, - const RevolutionValues & params, - const MbSNameMaker & operNames, - RPArray & cNames, - MbFaceShell *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Объединить компланарные грани. - \en Unite complanar faces. \~ - \details \ru Объединить компланарные грани оболочки и проверить оболочку. \n - \en Unite complanar faces of a shell and validate the shell. \n \~ - \param[in] shell - \ru Модифицируемая оболочка. - \en A shell to be modified. \~ - \param[in] nameMaker - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] checkBaseSurfaces - \ru Найти и устранить общие поверхности-подложки в гранях. - \en Find and eliminate common underlying surfaces of faces \~ - \return \ru Возвращает true, если оболочка была успешно изменена. - \en Returns 'true' if the shell has been successfully modified. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) UnifyOwnComplanarFaces( MbFaceShell & shell, - const MbSNameMaker & nameMaker, - 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. \~ - \details \ru Захватить грани одним из способов распространения по связной оболочке. \n - \en Capture the faces in one of methods of propagation in connected shell. \n \~ - \param[in] fp - \ru Cпособ захвата граней. - \en A method of capturing the faces. \~ - \param[in,out] face_set - \ru Набор граней. - \en A set of faces. \~ - \param[in] dir - \ru Направление уклона. - \en A direction of inclination. \~ - \warning \ru Вспомогательная функция операции DraftSolid. - \en An auxillary function of operation DraftSolid. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) FacePropagate( const MbeFacePropagation fp, - RPArray & face_set, - const MbVector3D & dir ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Масштабировать каверны литейной формы. - \en Scale cavities of a mold. \~ - \details \ru Масштабировать каверны литейной формы относительно неподвижной точки. \n - \en Scale cavities of a mold relative to a fixed point. \n \~ - \param[in,out] solids - \ru Модифицируемые тела. - \en The solids to be modified. \~ - \param[in] fixedPoint - \ru Неподвижная точка масштабирования. - \en The fixed point of scaling. \~ - \param[in] deltaX - \ru Относительное приращение размера по направлению X. - \en Relative increment of size in X-direction. \~ - \param[in] deltaY - \ru Относительное приращение размера по направлению Y. - \en Relative increment of size in Y-direction. \~ - \param[in] deltaZ - \ru Относительное приращение размера по направлению Z. - \en Relative increment of size in Z-direction. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) MouldCavitySolids( RPArray & solids, - MbCartPoint3D * fixedPoint, - double deltaX, - double deltaY, - double deltaZ ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить тела на пересечение. - \en Check intersection of solids. \~ - \details \ru Проверить тела на пересечение без уточнения характера пересечения \n - (проверяем до первого пересечения граней). \n - \en Check if solids intersect each other without definition of intersection type \n - (check until the first intersection is detected). \n \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \return \ru Возвращает true, если найдено хотя бы одно пересечение. - \en Returns 'true' if at least one intersection is detected. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsSolidsIntersection( const MbSolid & solid1, const MbSolid & solid2, const MbSNameMaker & snMaker ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить пересечение тел в сборке. - \en Check intersection of solids in an assembly. \~ - \details \ru Определить пересечение тел в сборке. \n - \en Check intersection of solids in an assembly. \n \~ - \param[in] solid1 - \ru Первое тело в локальной системе координат (ЛСК). - \en The first solid in local coordinate system (LCS). \~ - \param[in] matr1 - \ru Матрица преобразования в глобальную СК (ГСК). - \en Matrix of transformation to the global coordinate system (GCS). \~ - \param[in] solid2 - \ru Второе тело в ЛСК. - \en The second solid in LCS. \~ - \param[in] matr2 - \ru Матрица преобразования в ГСК. - \en Matrix of transformation to GCS. \~ - \param[in] checkTangent - \ru Считать касания пересечениями. - \en Consider tangencies as intersections. \~ - \param[in] getIntersectionSolids - \ru Получить не касательные пересечения в виде тел. - \en Get non-tangent intersections in the form of bodies. \~ - \param[in] checkTouchPoints - \ru Искать точки касания. - \en Find touch points. \~ - \param[out] intData - \ru Информация о пересечении двух тел. - \en Information about two solids intersection. \~ - \return \ru Возвращает true, если найдено хотя бы одно пересечение. - \en Returns 'true' if at least one intersection is detected. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsSolidsIntersection( const MbSolid & solid1, const MbMatrix3D & matr1, - const MbSolid & solid2, const MbMatrix3D & matr2, - bool checkTangent, // \ru Считать касания пересечениями \en Consider tangencies as intersections - bool getIntersectionSolids, // \ru Получить не касательные пересечения в виде тел \en Get non-tangency intersection as solids - bool checkTouchPoints, // \ru Искать точки касания \en Find touch points - RPArray & intData ); - -//------------------------------------------------------------------------------ -/** \brief \ru Определить минимальное расстояние между телами в сборке. - \en Determine the minimum distance between solids in an assembly. \~ - \details \ru Определить минимальное расстояние между телами в сборке. В случае пересечения или касания тел возвращается нулевая дистанция.\n - При многократном использовании первого тела следует установить isMultipleUseSolid1 = true, иначе false. Аналогично для второго тела.\n - \en Determine the minimum distance between solids in an assembly. In case of intersection or tangent of the shells returns to zero distance.\n - With multiple use of the first body should be set isMultipleUseSolid1 = true, else false. Similarly for the second body.\n \~ - \param[in] solid1 - \ru Первое тело в локальной системе координат (ЛСК). - \en The first solid in local coordinate system (LCS). \~ - \param[in] matr1 - \ru Матрица преобразования в глобальную СК (ГСК). - \en Matrix of transformation to the global coordinate system (GCS). \~ - \param[in] isMultipleUseSolid1 - \ru Множественное использование первого тела. - \en Multiple use of the first body. \~ - \param[in] solid2 - \ru Второе тело в ЛСК. - \en The second solid in LCS. \~ - \param[in] matr2 - \ru Матрица преобразования в ГСК. - \en Matrix of transformation to GCS. \~ - \param[in] isMultipleUseSolid2 - \ru Множественное использование второго тела. - \en Multiple use of the second body. \~ - \param[in] lowerLimitDistance - \ru Минимальное допустимое расстояние. - \en Minimum allowed distance. \~ - \param[in] tillFirstLowerLimit - \ru Искать до первого найденного удовлетворяющего минимально допустимому расстоянию. - \en Search until the first found that satisfies the minimum acceptable distance. \~ - \param[out] shellsDistanceData - \ru Информация о расстоянии между телами. - \en Information about the distance between solids. \~ - \return \ru Возвращает true, если определено хотя бы одно расстояние. - \en Returns 'true' if at least one distance is obtained. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MinimumSolidsDistance( const MbSolid & solid1, const MbMatrix3D & matr1, bool isMultipleUseSolid1, - const MbSolid & solid2, const MbMatrix3D & matr2, bool isMultipleUseSolid2, - double lowerLimitDistance, bool tillFirstLowerLimit, - std::vector & shellsDistanceData ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния от контура на плоскости до поверхности. - \en Find the distances from a contour on a plane to a surface. \~ - \details \ru Найти расстояния от контура на плоскости до поверхности. \n - Прямое направление - это направление оси Z системы координат двумерной кривой. \n - Расстояние в прямом направлении найдено, если значение не отрицательное. \n - Расстояние в обратном направлении найдено, если значение не положительное. \n - \en Find the distances from a contour on a plane to a surface. \n - A forward direction is a direction of Z-axis of two-dimensional curve coordinate system. \n - The distance in a forward direction is found if the value is non-negative. \n - The distance in a backward direction is found if the value is non-positive. \n \~ - \param[in] pl - \ru Система координат двумерной кривой. - \en A coordinate system of two-dimensional curve. \~ - \param[in] curve - \ru Двумерная кривая. - \en A two-dimensional curve. \~ - \param[in] surf - \ru Поверхность, до которой проводится поиск расстояний. - \en A surface to measure the distances up to. \~ - \param[out] lPlus - \ru Расстояние в прямом направлении. - \en The distance in a forward direction. \~ - \param[out] lMinus - \ru Расстояние в обратном направлении. - \en The distance in a backward direction. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) GetDistanceToSurface( const MbPlacement3D & pl, - const MbCurve * curve, - const MbSurface * surf, - double & lPlus, - double & lMinus ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создание поверхностей сечения выдавливания плоского контура. - \en Create cutter surfaces for extrusion of planar contours. \~ - \details \ru Создание поверхностей сечения выдавливания плоского контура и определение направлений выдавливаний. \n - \en Create cutter surfaces for extrusion of planar contours and define directions of extrusions. \n \~ - \param[in] surface - \ru Поверхность контуров. - \en A surface that contains the contours. \~ - \param[in] contours - \ru Набор двумерных контуров. - \en A set of planar contours. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] params - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] version - \ru Версия построения. - \en The version of construction. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \param[out] surfAndDir- \ru Результат операции - поверхности и направление относительно direction. - \en Result of the operation - surfaces and directions relative to parameter direction. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (void) CreateExtrusionCutSurfaces( const MbSurface & surface, - const c3d::PlaneContoursSPtrVector & contours, - const MbVector3D & direction, - ExtrusionValues & params, - VERSION version, - MbResultType & resType, - std::vector< std::pair> & surfAndDir ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния от контура на поверхности до габаритного куба оболочки. - \en Find the distances from a contour on a surface to the bounding box of a shell. \~ - \details \ru Найти расстояния от контура на поверхности до габаритного куба оболочки. \n - Расстояние в прямом направлении найдено, если значение не отрицательное. \n - Расстояние в обратном направлении найдено, если значение не положительное. \n - \en Find the distances from a contour on a surface to the bounding box of a shell. \n - The distance in a forward direction is found if the value is nonnegative. \n - The distance in a backward direction is found if the value is non-positive. \n \~ - \param[in] surface - \ru Поверхность, на которой лежит двумерная кривая. - \en A surface that contains the two-dimensional curve. \~ - \param[in] direction - \ru Направление поиска (выдавливания) - \en A direction of the distance calculation (an extrusion direction). \~ - \param[in] curve - \ru Двумерная кривая, лежащая на поверхности surface. - \en A two-dimensional curve on surface 'surface'. \~ - \param[in] cube - \ru Габаритный куб оболочки. - \en The bounding box of the shell. \~ - \param[out] lPlus - \ru Расстояние в прямом направлении. - \en The distance in a forward direction. \~ - \param[out] lMinus - \ru Расстояние в обратном направлении. - \en The distance in a backward direction. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) GetDistanceToCube( const MbSurface & surface, - const MbVector3D & direction, - const MbCurve & curve, - const MbCube & cube, - double & lPlus, - double & lMinus, - MbResultType & resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния от набора кривых на поверхности до габаритного куба оболочки. - \en Find the distances from curves on a surface to the bounding box of a shell. \~ - \details \ru Найти расстояния от набора кривых на поверхности до габаритного куба оболочки. \n - Расстояние в прямом направлении найдено, если значение не отрицательное. \n - Расстояние в обратном направлении найдено, если значение не положительное. \n - \en Find the distances from curves on a surface to the bounding box of a shell. \n - The distance in a forward direction is found if the value is nonnegative. \n - The distance in a backward direction is found if the value is nonpositive. \n \~ - \param[in] surface - \ru Поверхность, на которой лежат двумерные кривые. - \en A surface that contains two-dimensional curves. \~ - \param[in] direction - \ru Направление поиска (выдавливания) - \en A direction of the distance calculation (an extrusion direction). \~ - \param[in] curves - \ru Набор двумерных кривых на поверхности surface. - \en A set of two-dimensional curves on the surface 'surface'. \~ - \param[in] cube - \ru Габаритный куб оболочки. - \en The bounding box of the shell. \~ - \param[out] lPlus - \ru Расстояние в прямом направлении. - \en The distance in a forward direction. \~ - \param[out] lMinus - \ru Расстояние в обратном направлении. - \en The distance in a backward direction. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) GetDistanceToCube( const MbSurface & surface, - const MbVector3D & direction, - const RPArray & curves, - const MbCube & cube, - double & lPlus, - double & lMinus, - MbResultType & resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния от плоскости до габаритного куба оболочки. - \en Find the distances from a plane to the bounding box of a shell. \~ - \details \ru Найти расстояния от плоскости до габаритного куба оболочки. \n - Расстояние в прямом направлении найдено, если значение не отрицательное. \n - Расстояние в обратном направлении найдено, если значение не положительное. \n - Использует расчет габарита относительно локальной системы координат. \n - Если система координат плоскости лежит вне габаритного куба, \n - то при взведенном флаге findMax ищется максимальное расстояние до куба. \n - \en Find the distances from a plane to the bounding box of a shell. \n - The distance in a forward direction is found if the value is non-negative. \n - The distance in a backward direction is found if the value is non-positive. \n - Calculation of the distance relative to the local coordinate system is used. \n - If a plane coordinate system is out of the bounding box, \n - then if the flag 'findMax' is set to 'true', the maximal distance to bounding box is calculated. \n \~ - \param[in] pl - \ru Система координат плоскости. - \en The plane coordinate system. \~ - \param[in] shell - \ru Целевая оболочка. - \en A target shell. \~ - \param[out] dPlus - \ru Расстояние в прямом направлении. - \en The distance in a forward direction. \~ - \param[out] dMinus - \ru Расстояние в обратном направлении. - \en The distance in a backward direction. \~ - \param[in] findMax - \ru Искать максимальное расстояние до габаритного куба. - \en The maximal distance to bounding box is to be calculated. \~ - \return \ru Возвращает true, если найдено хотя бы одно из расстояний. - \en Returns 'true' if at least one of the distances has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) GetDistanceToCube( const MbPlacement3D & pl, - const MbFaceShell * shell, - double & dPlus, - double & dMinus, - bool findMax = true ); // \ru Искать максимальное \en Find the maximal distance - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния/углы от контура до куба или до поверхности. - \en Find the distances/angles from a contour to a bounding box or to a surface. \~ - \details \ru Найти расстояния/углы от контура до куба или до поверхности. \n - Нужно учесть уклон в двух направлениях. \n - \en Find the distances/angles from a contour to a bounding box or to a surface. \n - The inclination in two directions is to be considered. \n \~ - \param[in] curve - \ru Кривая. - \en A curve. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] rotation - \ru Вращение (true) или выдавливание (false) - \en Rotation (true) or extrusion (false) \~ - \param[in] operationDirection - \ru Вперед (true) или назад (false) - \en Forward (true) or backward (false) \~ - \param[in] toCube - \ru До куба, если указатель ненулевой - \en Up to a cube if the pointer is not null. \~ - \param[in] toSurface - \ru До поверхности, если указатель ненулевой. - \en Up to a surface if the pointer is not null. \~ - \param[in,out] params: -\ru Должны быть заданы параметры: \n - params.side1.rake - Уклон в направлении direction (для плоской образующей). \n - params.side2.rake - Уклон в направлении direction, обратном direction (для плоской образующей). \n - params.thikness1 - Толщина стенки в прямом направлении - (в положительном направлении нормали объекта (грани, поверхности, плоскости кривой)). \n - params.thikness2 - Толщина стенки в обратном направлении. \n - Заполняются параметры: \n - params.side1.scalarValue - Расстояние выдавливания в направлении direction (если operationDirection == true), - иначе обратном. \n - params.side2.scalarValue - Расстояние выдавливания в направлении, обратном direction (если operationDirection == true), - иначе в прямом. \n -\en The following parameters should be defined: \n - params.side1.rake - The inclination in direction 'direction' (for a planar generatrix). \n - params.side2.rake - The inclination in direction opposite to 'direction' (for a planar generatrix). \n - params.thikness1 - Wall thickness in forward direction. - (in the positive direction of the normal of an object (a face, a surface, the plane of a curve)). \n - params.thikness2 - The wall thickness in the backward direction. \n - The output parameters: \n - params.side1.scalarValue - The extrusion distance in the direction 'direction' (if 'operationDirection' == true), - else in the opposite direction. \n - params.side2.scalarValue - The extrusion distance in the direction opposite to 'direction' (if 'operationDirection' == true), - else in the forward direction. \n \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) GetRangeToCubeOrSurface( const MbCurve3D & curve, - const MbVector3D & direction, - const MbAxis3D & axis, - const bool rotation, - bool operationDirection, - const MbCube * toCube, - const MbSurface * toSurface, - SweptValuesAndSides & params, - MbResultType & resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". - \en Find the nearest solids while extruding with option 'up to the nearest object'. \~ - \details \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". \n - Возвращает номерa (nPlus и nMinus) ближайших тел с положительной и отрицательной стороны эскиза. - \en Find the nearest solids while extruding with option 'up to the nearest object'. \n - Returns the numbers (nPlus and nMinus) of nearest solids on the positive and the negative sides of the sketch. \~ - \param[in] pl - \ru Локальная система координат. - \en A local coordinate system. \~ - \param[in] c - \ru Множество двумерных контуров. - \en An array of two-dimensional contours. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] solids - \ru Целевой набор тел. - \en A target set of solids. \~ - \param[out] nPlus - \ru Номер ближайшего тела в положительном направлении. - \en The number of the nearest solid in the positive direction. \~ - \param[out] nMinus - \ru Номер ближайшего тела в отрицательном направлении. - \en The number of the nearest solid in the negative direction. \~ - \return \ru Возвращает true, если найдено тело хотя бы в одном из направлений. - \en Returns 'true' if a solid is found in at least one of directions. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) GetNearestSolid( const MbPlacement3D & pl, - RPArray & c, - MbSweptLayout::Direction direction, - RPArray & solids, - size_t & nPlus, - size_t & nMinus ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". - \en Find the nearest solids while extruding with option 'up to the nearest object'. \~ - \details \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". \n - возвращает номерa (nPlus и nMinus) ближайших тел ближайших тел в прямом и обратном направлении. - \en Find the nearest solids while extruding with option 'up to the nearest object'. \n - returns numbers (nPlus and nMinus) of the nearest solids in the forward and the backward direction. \~ - \param[in] curves - \ru Набор кривых. - \en A set of curves. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] operationDirection - \ru Параметры выдавливания "до ближайшего объекта". - \en Parameters of extrusion 'up to the nearest object'. \~ - \param[in] solids - \ru Целевой набор тел. - \en A target set of solids. \~ - \param[out] nPlus - \ru Номер ближайшего тела в положительном направлении. - \en The number of the nearest solid in the positive direction. \~ - \param[out] nMinus - \ru Номер ближайшего тела в отрицательном направлении. - \en The number of the nearest solid in the negative direction. \~ - \return \ru Возвращает true, если найдено тело хотя бы в одном из направлений. - \en Returns 'true' if a solid is found in at least one of directions. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) GetNearestSolid( RPArray & curves, - const MbVector3D & direction, - MbSweptLayout::Direction operationDirection, - RPArray & solids, - size_t & nPlus, - size_t & nMinus ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить оболочку или тело, состоящее из NURBS поверхностей. - \en Check a shell or a solid that consists of NURBS surfaces. \~ - \details \ru Проверить корректность оболочки или тела, состоящего из NURBS поверхностей. \n - \en Check the correctness of a shell or a solid that consists of NURBS surfaces. \n \~ - \param[in] params - \ru Исходные параметры операции. - \en Initial parameters of the operation. \~ - \param[in] nsSolid - \ru Тело - результат операции. - \en A solid - the result of the operation. \~ - \param[in] progBar - \ru Индикатор прогресса выполнения операции. - \en A progress indicator of the operation. \~ - \return \ru Возвращает rt_Success, если тело успешно прошло проверку. - \en Returns rt_Success if the solid has successfully passed the validation. \~ - \warning \ru Проверочная функция операции NurbsSurfacesShell. - \en A checking function of the operation NurbsSurfacesShell. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) CheckNurbsShell( const NurbsSurfaceValues & params, - const MbSolid & nsSolid, - IProgressIndicator * progBar ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Положить эскиз в массив усекающих объектов. - \en Add a sketch to the array of truncating objects. \~ - \details \ru Положить эскиз в массив усекающих объектов путем создания пространственных кривых. \n - \en Add a sketch to the array of truncating objects by creation of spatial curves. \n \~ - \param[in] sketchPlace - \ru Локальная система координат двумерного эскиза. - \en A local coordinate system of two-dimensional sketch. \~ - \param[in] sketchCurves - \ru Двумерные кривые эскиза. - \en Two-dimensional curves of the sketch. \~ - \param[out] items - \ru Выходной массив пространственных объектов. - \en The output array of spatial objects. \~ - \return \ru - Возвращает true в случае добавления элементов в выходной массив. - \en - Returns 'true' if elements are added into output array. \~ - \warning \ru Вспомогательная функция операции TruncateShell. - \en Auxiliary function of the operation TruncateShell. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) AddTruncatingSketch( const MbPlacement3D & sketchPlace, - RPArray & sketchCurves, - RPArray & items ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Положить кривую в массив усекающих объектов. - \en Add a curve to the array of truncating objects. \~ - \details \ru Положить кривую в массив усекающих объектов - (с разбором кривой на составляющие, в случае необходимости). \n - \en Add a curve to the array of truncating objects - (with decomposition of the curve if necessary). \n \~ - \param[in] curve - \ru Пространственная кривая. - \en A space curve. \~ - \param[out] items - \ru Выходной массив пространственных объектов. - \en The output array of spatial objects. \~ - \warning \ru Вспомогательная функция операции TruncateShell. - \en Auxillary function of the operation TruncateShell. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) AddTruncatingCurve( const MbCurve3D & curve, - RPArray & items ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить корректность вскрываемых граней для создания тонкостенного тела. - \en Check the correctness of shelling faces for creation of a thin-walled solid. \~ - \details \ru Проверить корректность набора вскрываемых граней для создания тонкостенного тела. \n - Удаляет из массива не подходящие для операции грани (гладко сопряженные с невыбранными гранями). \n - \en Check the correctness of shelling faces set for creation of a thin-walled solid. \n - Removes unsuitable for the operation faces from the array (Delete faces smoothly connected to unselected faces). \n \~ - \param[in] params - \ru Параметры тонкой стенки. - \en Parameters of a thin wall. \~ - \param[in,out] faces - \ru Множество вскрываемых граней тела. - \en An array of shelling faces of the solid. \~ - \warning \ru Вспомогательная функция операции построения тонкостенного тела. - \en An auxiliary function of thin-walled solid construction operation. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) CheckShellingFaces( const SweptValues & params, RPArray & faces ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить компоненты проекции вектора, заданного в точке на поверхности. - \en Calculate the components of projection of a vector defined at a point on the surface. \~ - \details \ru Вычислить компоненты x и y проекции пространственного вектора, заданного в точке на поверхности. \n - \en Calculate x and y components of projection of a space vector defined at a point on a surface. \n \~ - \param[in] v3d - \ru Пространственный вектор. - \en A space vector. \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] p2d - \ru Параметрическая точка на поверхности. - \en A parametric point on the surface. \~ - \param[out] v2d - \ru Проекция пространственного вектора на поверхность. - \en The projection of the space vector on the surface. \~ - \return \ru - Возвращает true в случае успешного вычисления проекции вектора. - \en - Returns 'true' if the vector projection has been successfully calculated. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) ProjectVectorOn( const MbVector3D & v3d, const MbSurface & surface, const MbCartPoint & p2d, - MbVector & v2d ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Расширить поверхность для резки тела. - \en Extend a surface for cutting a solid. \~ - \details \ru Расширить поверхность до заданного габарита для резки тела. \n - \en Extend a surface to a given bounding box for cutting a solid. \n \~ - \param[in,out] gabarit - \ru Желаемый габарит расширения. - \en A desirable bounding box of the extended surface. \~ - \param[in] surf - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] prolongState - \ru Состояние типа продления секущих поверхностей. - \en State of prolongation types of cutter surfaces. \~ - \param[in] version - \ru Версия построения. - \en The version of construction. \~ - \return \ru - Возвращает расширенную поверхность, если получилось ее создать. - \en - Returns the extended surface if it has been successfully created. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbSurface *) GetExtendedSurfaceCopy( MbCube & gabarit, - const MbSurface & surf, - const MbShellCuttingParams::ProlongState & prolongState, - VERSION version ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить набор граней с топологией призмы. - \en Create a set of faces with topology of a prism. \~ - \details \ru Построить набор граней с топологией призмы. \n - \en Create a set of faces with topology of a prism. \n \~ - \param[in] place - \ru Локальная система координат (ЛСК). - \en A local coordinate system (LCS). \~ - \param[in] contour - \ru Двумерный контур в ЛСК. - \en A two-dimensional curve in LCS. \~ - \param[in] der - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] sense - \ru Ориентация выходного массива граней как замкнутой оболочки. - \en An orientation of the output array of faces as a closed shell. \~ - \param[in] n - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in,out] initFaces - \ru Множество созданных граней. - \en The array of created faces. \~ - \param[in] useAddCount - \ru Использовать количество граней initFaces на входе для именования новых граней. - \en The number of input faces initFaces is to be used for naming the new faces. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) CreateFaces( const MbPlacement3D & place, const MbContour & contour, - const MbVector3D & der, bool sense, const MbSNameMaker & n, - RPArray & initFaces, bool useAddCount = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Оценить параметры выдавливания для ребра жёсткости. - \en Estimate parameters of extrusion for a rib. \~ - \details \ru Оценить параметры выдавливания для построения ребра жёсткости. \n - \en Estimate parameters of extrusion for creating a rib. \n \~ - \param[in] shell - \ru Целевая оболочка. - \en A target shell. \~ - \param[in] place - \ru Локальная система координат контура. - \en A local coordinate system of the contour. \~ - \param[in] contour - \ru Двумерный контур. - \en A two-dimensional contour. \~ - \param[in] index - \ru Номер сегмента контура. - \en A number of the contour segment. \~ - \param[out] side - \ru Сторона заполнения пространства телом ребра. - \en The side to place the rib on. \~ - \param[out] origin - \ru Точка. - \en A point. \~ - \param[out] dir3D - \ru Вектор. - \en A vector. \~ - \warning \ru Вспомогательная функция операции RibSolid. - \en An auxillary function of the operation RibSolid. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) GetAutoReference( MbFaceShell & shell, - const MbPlacement3D & place, - const MbContour & contour, - ptrdiff_t index, - RibValues::ExtrudeSide & side, - MbCartPoint3D & origin, - MbVector3D & dir3D ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую в параметрах поверхности. - \en Create a curve in the parameter space of a surface. \~ - \details \ru Создать кривую в параметрах поверхности, если нужно - проекционную. \n - Если проекционную кривую создавать не нужно, возвращает дубль двумерной кривой в параметрах поверхности. \n - После использования кривую нужно удалить. \n - \en Create a curve in the parameter space of a surface. The projection curve can be created if necessary. \n - If it is not required to create the projection curve, returns a copy of two-dimensional curve in the parameter space of the surface. \n - The curve is to be deleted after use. \n \~ - \param[in] intersectCurve - \ru Кривая пересечения. - \en The intersection curve \~ - \param[in] first - \ru true - Первая поверхность, false - вторая поверхность. - \en True - The first surface, false - the second surface. \~ - \return \ru Возвращает кривую, если ее получилось построить. - \en Returns the curve if it has been successfully created. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbCurve *) GetProjCurveOnSurface( const MbSurfaceIntersectionCurve & intersectCurve, bool first ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить неизменность вектора кинематической направляющий в разных версиях. - \en Check the invariance of the vector of spine direction in different versions. \~ - \details \ru Проверить, можно ли сохранить кинематическую направляющую из одной версии в другую без изменения формы. \n - \en Check if the spine direction can be preserved between versions without any change of the shape. \n \~ - \param[in] curve - \ru Направляющая кривая. - \en The spine curve. \~ - \param[in] srcVersion - \ru Рабочая версия. - \en The current version. \~ - \param[in] dstVersion - \ru Целевая версия. - \en The target version. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsSameSpineDirection( const MbCurve3D & curve, VERSION srcVersion, VERSION dstVersion ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Классифицировать положения второго контура относительно первого. - \en Classify the position of the second contour relative to the first one. \~ - \details \ru Классифицировать положения второго контура относительно первого: \n - iloc_OutOfItem - снаружи, \n - iloc_OnItem - пересекается, \n - iloc_InItem - внутри. \n - \en Classify the position of the second contour relative to the first one: \n - iloc_OutOfItem - outside, \n - iloc_OnItem - intersects, \n - iloc_InItem - inside. \n \~ - \param[in] contour1 - \ru Первый контур. - \en The first contour. \~ - \param[in] contour2 - \ru Второй контур. - \en The second contour. \~ - \param[in] xEpsilon - \ru Погрешность по x. - \en Tolerance in x direction. \~ - \param[in] yEpsilon - \ru Погрешность по y. - \en Tolerance in y direction. \~ - \return \ru Возвращает результат классификации положения. - \en Returns the result of classification of the relative position. \~ - \ingroup Algorithms_2D -*/ -// --- -MATH_FUNC (MbeItemLocation) SecondContourLocation( const MbContour & contour1, const MbContour & contour2, - double xEpsilon, double yEpsilon ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить, близка ли первая кривая ко второй кривой. - \en Determine whether the first curve is close to the second curve. \~ - \details \ru Определить, близка ли кривая curve1 к кривой curve2 с заданной точностью. \n - Близость определяется близостью точек первой кривой, полученных шаганием \n - по кривой с заданным угловым отклонением, ко второй кривой. \n - \en Determine whether curve 'curve1' is close to curve 'curve2' within the given precision. \n - The proximity is defined by the closeness of points of the first curve obtained by sampling \n - with the given turning angle to the second curve. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[in] xEpsilon - \ru Близость по x. - \en Proximity tolerance in x direction. \~ - \param[in] yEpsilon - \ru Близость по y. - \en Proximity tolerance in y direction. \~ - \param[in] devSag - \ru Максимальное угловое отклонение при шагании по кривой. - \en The maximal turning angle for sampling the curve. \~ - \return \ru Возвращает true, если кривые близки. - \en Returns 'true' if the curves are close. \~ - \ingroup Algorithms_2D -*/ -// --- -MATH_FUNC (bool) IsSpaceNear( const MbCurve & curve1, const MbCurve & curve2, double xEpsilon, double yEpsilon, - double devSag = 5.0 * Math::deviateSag ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить, близка ли кривая к поверхности. - \en Determine whether a curve is close to a surface. \~ - \details \ru Определить, близка ли кривая к поверхности с заданной точностью. \n - Выполняется проверка по пробным точкам кривой, полученных шаганием по угловому отклонению. \n - \en Determine whether a curve is close to a surface within the given tolerance. \n - The check uses sample points of curves obtained by sampling with maximal turning angle. \n \~ - \param[in] curv - \ru Кривая. - \en A curve. \~ - \param[in] surf - \ru Поверхность. - \en A surface. \~ - \param[in] surfExt - \ru Проверять на расширенной поверхности. - \en Perform the check for the extended surface. \~ - \param[in] mEps - \ru Метрическая близость. - \en The metric proximity tolerance. \~ - \param[in] devSag - \ru Максимальное угловое отклонение при шагании по кривой. - \en The maximal turning angle for sampling the curve. \~ - \return \ru Возвращает true, если кривая близка к поверхности. - \en Returns 'true' if the curve is close to the surface. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsSpaceNear( const MbCurve3D & curv, const MbSurface & surf, bool surfExt, - double mEps, double devSag = 5.0 * Math::deviateSag ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать грань по произвольной поверхности. - \en Create the face on the base of arbitrary surface. \~ - \details \ru Создать грань по произвольной поверхности без самопересечений. \n - \en Create the face on the base of arbitrary surface without selfintersections. \n \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[out] face - \ru Грань. - \en The face. \~ - \return \ru Возвращает true, если грань создана. - \en Returns 'true' if the face was created. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) SurfaceFace( const MbSurface & surface, SPtr & face ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создание трёхмерной сетки по двумерной сетке. - \en Creating a three-dimensional grid on a two-dimensional grid. \~ - \details \ru Создание трёхмерной сетки по двумерной сетке. \n - \en Creating a three-dimensional grid on a two-dimensional grid. \n \~ - \param[in] place - \ru Локальная система координат в трёхмерном пространстве. - \en Local coordinate system in three dimensional space. \~ - \param[out] planarGrid - \ru Триангуляция двумерной области. - \en Triangulation of a two-dimensional region. \~ - \return \ru Возвращает true, если грань создана. - \en Returns 'true' if the face was created. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbGrid *) SpaceGrid( const MbPlacement3D & place, const MbPlanarGrid & planarGrid, bool exact = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Заменить элемент на вставку, если расстояние от начала координат до центра - его габарита, превышает размер габаритного куба в заданное число раз \~ - \en Replace an item by an instance if the length from it's bounding box to the - world origin is greater than it's diagonal by specified factor. - \details \ru Объект или его копия смещается на вектор из начала координат до центра габаритного куба объекта - и размещается во вставке, обеспечивающей смещение на вектор противоположного направления. \~ - Обрабатываются только объекты, не являющиеся вставками. \~ - Нулевое или отрицательное значение параметра ratioThreashhold запрещает преобразование. \~ - \en The item or it's replica is moved bey the vector from the origin of the world to the center of the - item's bounding box, then put in the instance, providing the displacement by the reversed vector. \~ - Function processes objects of all types except for instances. \~ - Null or negative value of the ratioThreashhold parameter blocks the transformation. \~ - \param[out] item - \ru Обрабатываемый объект. \~ - \en Processable item. \~ - \param[in] ratioThreashhold - \ru Пороговое значение отношения расстояния до центра габаритного куба и его диагонали, - при превышении которого происходит замена. \~ - \en The replacement threshold value of the ratio of the bounding box's center to the - origin of the world to it's diagonal length. \~ - \param[in] makeCopy - \ru Производить ли трансформацию на копии объекта. \~ - \en Is the copy of the object must be transformed. \~ - \return \ru Возвращает вставку объекта. - \en Returns instance of object. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbItem *) ReplaceByInstance( MbItem * item, double ratioThreashhold = -1.0, bool makeCopy = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построениe «залитого» объема, расположенного между внутренней поверхностью сосуда и ограничивающей поверхностью или телом. \~ - \en The construction of a "flood fill" volume located between the inner surface of the vessel and the bounding surface or body. \~ - \details \ru На вход подаётся тело, дополнительная поверхность или дополнительное тело и координаты источника. - На выходе получаем объём, построенный от источника и ограниченный со всех сторон оболочкой тела и дополнительными объектами. \~ - \en The body, an additional surface or an additional body and the coordinates of the source are fed to the input. - On the output we get the volume, constructed from the source and bounded from all sides by the shell of the body and by additional objects. \~ - \param[in] vessel - \ru Тело сосуда. \~ - \en The vessel. \~ - \param[in] sameShell - \ru Режим копирования тела сосуда. - \en Whether to copy the vessel. \~ - \param[in] bungData - \ru Поверхность уровня или тело пробки. \~ - \en The surface of the level or body of the bung. \~ - \param[in] origin - \ru Точка внутри сосуда. \~ - \en The point inside the vessel. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) FloodFillResult( MbSolid & vessel, - MbeCopyMode sameShell, - const MbSweptData & bungData, - const MbCartPoint3D & origin, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать крепеж по трехмерной точке. НЕ ИСПОЛЬЗОВАТЬ ВНЕ ТЕСТОВОГО ПРИЛОЖЕНИЯ!!! ФУНКЦИЯ НАХОДИТСЯ В РАЗРАБОТКЕ!!! - \en Create fastener using 3D point. \~ - \details \ru Создать крепеж по трехмерной точке. \n - \en Create fastener using 3D point. \n \~ - \param[in] solids - \ru Множество тел для скрепления. - \en An array of bodies to fasten. - \param[in] sameShell - \ru Режим копирования тел. - \en Whether to copy the solids. \~ - \param[in] point - \ru Трехмерная точка, на основе проецирования которой определяется положение крепежа. - \en 3d point. \~ - \param[in] params - \ru Параметры крепежа ( его тип, размеры и т.д. ). - \en Fastener parameters ( type, diameter, etc. ). \~ - \param[in] names - \ru Именователь новых граней. - \en An object defining the name of a new faces. \~ - \param[out] results - \ru Множество тел для скрепления с набором отверстий и набор тел крепежа в отверстиях. - \en Array of bodies with a holes and fastener body. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateFastener ( const RPArray & solids, - MbeCopyMode sameShell, - const MbCartPoint3D & point, - const FastenersValues & params, - const MbSNameMaker & names, - RPArray & results ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Cоздать набор крепежных элементов по трехмерной кривой. НЕ ИСПОЛЬЗОВАТЬ ВНЕ ТЕСТОВОГО ПРИЛОЖЕНИЯ!!! ФУНКЦИЯ НАХОДИТСЯ В РАЗРАБОТКЕ!!! - \en Create an array of fastener elements using 3d curve. \~ - \details \ru Cоздать набор крепежных элементов по трехмерной кривой. - \en Create an array of fastener elements using 3d curve. \~ - \param[in] solids - \ru Множество тел для скрепления. - \en Array of bodies with a hole and fastener body. \~ - \param[in] sameShell - \ru Режим копирования тел. - \en Whether to copy the solids. \~ - \param[in] curve - \ru Трехмерная кривая, на основе проецирования точек которой определяются положения крепежных элементов. - \en 3D curve. \~ - \param[in] number - \ru Количество точек на кривой. Точки расположены равномерно по длине кривой. - \en Number of points on the curve. Points are uniformly located along the length of the curve. \~ - \param[in] params - \ru Параметры крепежа ( его тип, размеры и т.д. ). - \en Fastener parameters ( type, diameter, etc. ). \~ - \param[in] names - \ru Именователь новых граней. - \en An object defining the name of a new faces. \~ - \param[out] results - \ru Множество тел для скрепления с набором отверстий и набор тел крепежа в отверстиях. - \en Array of bodies with a holes and fastener bodies. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateFasteners( const RPArray & solids, - MbeCopyMode sameShell, - const MbCurve3D & curve, - size_t number, - const FastenersValues & params, - const MbSNameMaker & names, - RPArray & results ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Слить несколько граней тела в одну грань. - \en Create a solid with one face instead selected faces. \~ - \details \ru Заменить указанные гладко стыкующиеся грани тела одной геометрически совпадающей гранью. \n - \en To replace these smooth abutting faces to form a single geometrically matching face. \n - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en Whether to copy the source solid. \~ - \param[in] faces - \ru Объединяемые грани тела. - \en The faces of solid to be merged. \~ - \param[in] uParam - \ru Параметры u направления объединяющей поверхности. - \en The operation parameters for common surface in u direction. \~ - \param[in] vParam - \ru Параметры v направления объединяющей поверхности. - \en The operation parameters for common surface in v direction. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] prolong - \ru Параметр добавления гладко стыкующихся граней с faces (prolong>0). - \en The parameter of adding prolong faces (prolong>0). \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateMerging( MbSolid & solid, - MbeCopyMode sameShell, - c3d::FacesVector & faces, - const MbNurbsParameters & uParam, - const MbNurbsParameters & vParam, - const MbSNameMaker & names, - bool prolong, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти грани тел, имеющие контактные площадки. \~ - \en To find contacted faces of bodies. \~ - \details \ru Найти номера контактирующих граней тел, имеющих противоположно направленные нормали, у которых есть общие участки с конечной площадью перекрытия. \~ - \en To find contacted faces of bodies with oppositely directed normals which have a finite overlap area. \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] precision - \ru Точность операции. - \en The precision of operation. \~ - \param[out] facesNumbers - \ru Пары номеров касающихся граней с противоположно направленными нормалями. - \en The couples of number of contacted faces with oppositely directed normals. \~ - \return \ru Возвращает true, если грани контакта найдены. - \en Returns true, if contacted faces were found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) FindTouchedFaces( const MbSolid & solid1, - const MbSolid & solid2, - double precision, - c3d::IndicesPairsVector & facesNumbers ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разбить контактирующие грани тел. \~ - \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 Первое тело. - \en The first solid. \~ - \param[in/out] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] precision - \ru Точность операции. - \en The precision of operation. \~ - \param[in] facesNumbers - \ru Множество пар номеров соприкасающихся граней, у которых требуется построить общие пятна контакта (может быть пустым). - \en The container with pairs of contact face numbers that need to have common contact spots (it can be empty). \~ - \return \ru Возвращает true, если грани контакта найдены. - \en Returns true, if contacted faces were found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) SplitTouchedFaces( MbSolid & solid1, - MbSolid & solid2, - double precision, - c3d::IndicesPairsVector & facesNumbers ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Объединить тела, имеющие контактирующие грани. \~ - \en The function performs unite the bodies with contacted faces. \~ - \details \ru Объединить тела, удалив контактирующие грани. \~ - \en The function performs unite the bodies and removing the contacting faces. \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] sameShell1 - \ru Способ копирования граней первого тела. - \en Method of copying the faces of the first solid. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] sameShell2 - \ru Способ копирования граней второго тела. - \en Method of copying the faces of the second solid. \~ - \param[in] precision - \ru Точность операции. - \en The precision of operation. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) TouchedSolidsMerging( MbSolid & solid1, - MbeCopyMode sameShell1, - MbSolid & solid2, - MbeCopyMode sameShell2, - const MbSNameMaker & names, - double precision, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить трансформированную копию тела. \~ - \en Get transformed copy of a solid. \~ - \details \ru Получить трансформированную копию тела, если матрица трансформации не единичная или оригинал, если единичная. \~ - \en Get transformed copy of a solid if a matrix is not identity matrix or original of the solid if the matrix is identity matrix. \~ - \param[in] solid - \ru Тело. - \en A solid. \~ - \param[in,out] copyMode - \ru Исходный режим копирования тела. - \en An initial copy mode. \~ - \param[in] matr - \ru Матрица преобразования. - \en Transformation matrix. \~ - \param[in] transformedMainName - \ru Главное имя для операции трансформации. - \en Main name of transformation operation. \~ - \return \ru Возвращает копию или оригинал тела. - \en Returns copy or original of the solid. \~ - \ingroup Algorithms_3D -*/ -// --- -inline -c3d::SolidSPtr GetTransformedSolid( c3d::SolidSPtr & solid, MbeCopyMode & copyMode, const MbMatrix3D & matr, SimpleName transformedMainName = ct_TransformedSolid ) -{ - c3d::SolidSPtr resSolid( solid ); - - if ( (resSolid != NULL) && !matr.IsSingle() ) { - MbSNameMaker n( transformedMainName, MbSNameMaker::i_SideNone, 0 ); - - MbSolid * resSolidPtr = NULL; - TransformValues tv( matr ); - ::TransformedSolid( *solid, cm_Copy, tv, n, resSolidPtr ); - if ( resSolidPtr != NULL ) { - resSolid = resSolidPtr; - copyMode = cm_Same; - } - } - return resSolid; -} - -//------------------------------------------------------------------------------ -/** \brief \ru Получить трансформированную копию объекта. \~ - \en Get transformed copy of object. \~ - \details \ru Получить трансформированную копию объекта, если матрица трансформации не единичная или оригинал, если единичная. \~ - \en Get transformed copy of an object if a matrix is not identity matrix or original of the solid if the matrix is identity matrix. \~ - \param[in] item - \ru Объект. - \en An object. \~ - \param[in] matr - \ru Матрица преобразования. - \en Transformation matrix. \~ - \return \ru Возвращает копию или оригинал объекта. - \en Returns copy or original of the object. \~ - \ingroup Algorithms_3D -*/ -// --- -template -SPtr GetTransformedItem( SPtr & item, const MbMatrix3D & matr, MbRegDuplicate * iDupReg = NULL, MbRegTransform * iTransReg = NULL ) -{ - SPtr resItem( item ); - if ( (resItem != NULL) && !matr.IsSingle() ) { - resItem = static_cast( &item->Duplicate( iDupReg ) ); - resItem->Transform( matr, iTransReg ); - } - return resItem; -} - - -#endif // __ACTION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Функции работы с кривыми, поверхностями, оболочками, телами. + \en Functions for operating with curves, surfaces, shells and solids. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_H +#define __ACTION_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbPlanarGrid; +class MATH_CLASS MbGrid; +class MATH_CLASS MbSNameMaker; +class IProgressIndicator; + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить оболочку на предмет разделения на отдельные части. + \en Check if the shell can be subdivided into separate parts. \~ + \details \ru Проверить замкнутую оболочку на предмет разделения на отдельные части с анализом вложенности. \n + \en Check if the closed shell can be subdivided into separate parts with inclusion analysis. \n \~ + \param[in] shell - \ru Исходная оболочка. + \en The initial shell. \~ + \result \ru Возвращает true, если оболочка состоит из нескольких частей. + \en Returns 'true' if the shell consists of several parts. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsMultiShell( const MbFaceShell * shell, bool checkNesting = true ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отделить части оболочки. + \en Separate parts from a shell. \~ + \details \ru Отделить части оболочки без анализа вложенности. + Если sort == true, то наибольшая часть оболочки останется в исходной оболочке, + а отделившиеся от неё части будут сложены в parts с сортировкой по убыванию габарита. \n + \en Separate parts from a shell without inclusion analysis. + If 'sort' == 'true', the greatest part of the shell will remain in the initial shell, + separated parts will be collected in array 'parts' sorted by bounding box size in descending order. \n \~ + \param[in] shell - \ru Исходная оболочка. + \en The initial shell. \~ + \param[out] parts - \ru Оболочки, полученные из shell. + \en The shells separated from 'shell'. \~ + \param[in] sort - \ru Выполнять ли сортировку частей оболочки по убыванию габарита? + \en If 'sort' == true, the parts separated from the initial shell will be sorted by bounding box size in descending order. \~ + \result \ru Возвращает количество оболочек в parts. + \en Returns number of shells in 'parts'. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (size_t) DetachShells( MbFaceShell & shell, RPArray & parts, bool sort ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отделить части оболочки. + \en Separate parts from a shell. \~ + \details \ru Отделить части оболочки без анализа вложенности. + Исходная оболочка всегда остаётся неизменённой. + Если исходная оболочка распадается на части, то все части складываются в parts. \n + \en Separate parts from a shell without inclusion analysis. + The initial shell always remains unchangeable. + If the initial shell is decomposed, all the parts are put into array 'parts'. \n \~ + \param[in] shell - \ru Исходная оболочка. + \en The initial shell. \~ + \param[out] parts - \ru Оболочки, полученные из shell. + \en The shells separated from 'shell'. \~ + \result \ru Возвращает количество оболочек в parts. + \en Returns number of shells in 'parts'. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (size_t) CreateShells( MbFaceShell & shell, RPArray & parts ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку выдавливанием плоских контуров. + \en Create a shell by extrusion of planar contours. \~ + \details \ru Построить оболочку выдавливанием плоских контуров. \n + \en Create a shell by extrusion of planar contours. \n \~ + \param[in] surface - \ru Поверхность контуров. + \en A surface that contains the contours. \~ + \param[in] contours - \ru Набор двумерных контуров. + \en A set of planar contours. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] params - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] cNames - \ru Набор именователей контуров. + \en A set of objects defining names of the contours. \~ + \param[out] result - \ru Результат операции - оболочка. + \en Result of the operation - a shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtrusionShell( const MbSurface & surface, + RPArray & contours, + const MbVector3D & direction, + const ExtrusionValues & params, + const MbSNameMaker & operNames, + RPArray & cNames, + MbFaceShell *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку вращением плоских контуров. + \en Create a shell by revolution of planar contours. \~ + \details \ru Построить оболочку вращением плоских контуров. \n + \en Create a shell by revolution of planar contours. \n \~ + \param[in] surface - \ru Поверхность контуров. + \en A surface that contains the contours. \~ + \param[in] contours - \ru Набор двумерных контуров. + \en A set of planar contours. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] params - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] cNames - \ru Набор именователей контуров. + \en A set of objects defining names of the contours. \~ + \param[out] result - \ru Результат операции - оболочка. + \en Result of the operation - a shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RevolutionShell( const MbSurface & surface, + RPArray & contours, + const MbAxis3D & axis, + const RevolutionValues & params, + const MbSNameMaker & operNames, + RPArray & cNames, + MbFaceShell *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Объединить компланарные грани. + \en Unite complanar faces. \~ + \details \ru Объединить компланарные грани оболочки и проверить оболочку. \n + \en Unite complanar faces of a shell and validate the shell. \n \~ + \param[in] shell - \ru Модифицируемая оболочка. + \en A shell to be modified. \~ + \param[in] nameMaker - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] checkBaseSurfaces - \ru Найти и устранить общие поверхности-подложки в гранях. + \en Find and eliminate common underlying surfaces of faces \~ + \return \ru Возвращает true, если оболочка была успешно изменена. + \en Returns 'true' if the shell has been successfully modified. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) UnifyOwnComplanarFaces( MbFaceShell & shell, + const MbSNameMaker & nameMaker, + 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. \~ + \details \ru Захватить грани одним из способов распространения по связной оболочке. \n + \en Capture the faces in one of methods of propagation in connected shell. \n \~ + \param[in] fp - \ru Cпособ захвата граней. + \en A method of capturing the faces. \~ + \param[in,out] face_set - \ru Набор граней. + \en A set of faces. \~ + \param[in] dir - \ru Направление уклона. + \en A direction of inclination. \~ + \warning \ru Вспомогательная функция операции DraftSolid. + \en An auxillary function of operation DraftSolid. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) FacePropagate( const MbeFacePropagation fp, + RPArray & face_set, + const MbVector3D & dir ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Масштабировать каверны литейной формы. + \en Scale cavities of a mold. \~ + \details \ru Масштабировать каверны литейной формы относительно неподвижной точки. \n + \en Scale cavities of a mold relative to a fixed point. \n \~ + \param[in,out] solids - \ru Модифицируемые тела. + \en The solids to be modified. \~ + \param[in] fixedPoint - \ru Неподвижная точка масштабирования. + \en The fixed point of scaling. \~ + \param[in] deltaX - \ru Относительное приращение размера по направлению X. + \en Relative increment of size in X-direction. \~ + \param[in] deltaY - \ru Относительное приращение размера по направлению Y. + \en Relative increment of size in Y-direction. \~ + \param[in] deltaZ - \ru Относительное приращение размера по направлению Z. + \en Relative increment of size in Z-direction. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) MouldCavitySolids( RPArray & solids, + MbCartPoint3D * fixedPoint, + double deltaX, + double deltaY, + double deltaZ ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить тела на пересечение. + \en Check intersection of solids. \~ + \details \ru Проверить тела на пересечение без уточнения характера пересечения \n + (проверяем до первого пересечения граней). \n + \en Check if solids intersect each other without definition of intersection type \n + (check until the first intersection is detected). \n \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \return \ru Возвращает true, если найдено хотя бы одно пересечение. + \en Returns 'true' if at least one intersection is detected. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsSolidsIntersection( const MbSolid & solid1, const MbSolid & solid2, const MbSNameMaker & snMaker ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить пересечение тел в сборке. + \en Check intersection of solids in an assembly. \~ + \details \ru Определить пересечение тел в сборке. \n + \en Check intersection of solids in an assembly. \n \~ + \param[in] solid1 - \ru Первое тело в локальной системе координат (ЛСК). + \en The first solid in local coordinate system (LCS). \~ + \param[in] matr1 - \ru Матрица преобразования в глобальную СК (ГСК). + \en Matrix of transformation to the global coordinate system (GCS). \~ + \param[in] solid2 - \ru Второе тело в ЛСК. + \en The second solid in LCS. \~ + \param[in] matr2 - \ru Матрица преобразования в ГСК. + \en Matrix of transformation to GCS. \~ + \param[in] checkTangent - \ru Считать касания пересечениями. + \en Consider tangencies as intersections. \~ + \param[in] getIntersectionSolids - \ru Получить не касательные пересечения в виде тел. + \en Get non-tangent intersections in the form of bodies. \~ + \param[in] checkTouchPoints - \ru Искать точки касания. + \en Find touch points. \~ + \param[out] intData - \ru Информация о пересечении двух тел. + \en Information about two solids intersection. \~ + \return \ru Возвращает true, если найдено хотя бы одно пересечение. + \en Returns 'true' if at least one intersection is detected. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsSolidsIntersection( const MbSolid & solid1, const MbMatrix3D & matr1, + const MbSolid & solid2, const MbMatrix3D & matr2, + bool checkTangent, // \ru Считать касания пересечениями \en Consider tangencies as intersections + bool getIntersectionSolids, // \ru Получить не касательные пересечения в виде тел \en Get non-tangency intersection as solids + bool checkTouchPoints, // \ru Искать точки касания \en Find touch points + RPArray & intData ); + +//------------------------------------------------------------------------------ +/** \brief \ru Определить минимальное расстояние между телами в сборке. + \en Determine the minimum distance between solids in an assembly. \~ + \details \ru Определить минимальное расстояние между телами в сборке. В случае пересечения или касания тел возвращается нулевая дистанция.\n + При многократном использовании первого тела следует установить isMultipleUseSolid1 = true, иначе false. Аналогично для второго тела.\n + \en Determine the minimum distance between solids in an assembly. In case of intersection or tangent of the shells returns to zero distance.\n + With multiple use of the first body should be set isMultipleUseSolid1 = true, else false. Similarly for the second body.\n \~ + \param[in] solid1 - \ru Первое тело в локальной системе координат (ЛСК). + \en The first solid in local coordinate system (LCS). \~ + \param[in] matr1 - \ru Матрица преобразования в глобальную СК (ГСК). + \en Matrix of transformation to the global coordinate system (GCS). \~ + \param[in] isMultipleUseSolid1 - \ru Множественное использование первого тела. + \en Multiple use of the first body. \~ + \param[in] solid2 - \ru Второе тело в ЛСК. + \en The second solid in LCS. \~ + \param[in] matr2 - \ru Матрица преобразования в ГСК. + \en Matrix of transformation to GCS. \~ + \param[in] isMultipleUseSolid2 - \ru Множественное использование второго тела. + \en Multiple use of the second body. \~ + \param[in] lowerLimitDistance - \ru Минимальное допустимое расстояние. + \en Minimum allowed distance. \~ + \param[in] tillFirstLowerLimit - \ru Искать до первого найденного удовлетворяющего минимально допустимому расстоянию. + \en Search until the first found that satisfies the minimum acceptable distance. \~ + \param[out] shellsDistanceData - \ru Информация о расстоянии между телами. + \en Information about the distance between solids. \~ + \return \ru Возвращает true, если определено хотя бы одно расстояние. + \en Returns 'true' if at least one distance is obtained. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MinimumSolidsDistance( const MbSolid & solid1, const MbMatrix3D & matr1, bool isMultipleUseSolid1, + const MbSolid & solid2, const MbMatrix3D & matr2, bool isMultipleUseSolid2, + double lowerLimitDistance, bool tillFirstLowerLimit, + std::vector & shellsDistanceData ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Классифицировать набор тел относительно другого набора тел. + \en Classify a set of solids relative to another set of solids. \~ + \details \ru Классифицировать набор тел относительно другого набора тел. Тела находятся в одной системе координат. \n + Каждое классифицируемое тело в результате имеет 3 состояния: 1) Находится вне относительного набора тел; \n + 2) Содержится только в одном теле, тогда есть информация об индексе относительного тела; \n + 3) Во всех остальных случаях тело пересекается с относительным набором тел. \n + \en Classify a set of solids relative to another set of solids. The solids are in the same coordinate system. \n + Each classified solids as result has 3 states: 1) It is outside relative set of bodies; \n + 2) Contained in only one solid, then there is information about the index of the relative body; \n + 3) In all other cases, solid intersects with relative set of solids. \n \~ + \param[in] solids - \ru Классифицируемый набор тел. + \en The classified set of solids. \~ + \param[in] relativeSolids - \ru Набор тел относительно которых осуществляется классификация. + \en A set of solids relative to which classification is performed. \~ + \param[out] info - \ru Информация о нахождении тел относительно другого набора тел. + \en Information about finding solids relative to another set of solids. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC( void ) MultipleSolidsClassification( const RPArray & solids, + const RPArray & relativeSolids, + std::vector & info ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния от контура на плоскости до поверхности. + \en Find the distances from a contour on a plane to a surface. \~ + \details \ru Найти расстояния от контура на плоскости до поверхности. \n + Прямое направление - это направление оси Z системы координат двумерной кривой. \n + Расстояние в прямом направлении найдено, если значение не отрицательное. \n + Расстояние в обратном направлении найдено, если значение не положительное. \n + \en Find the distances from a contour on a plane to a surface. \n + A forward direction is a direction of Z-axis of two-dimensional curve coordinate system. \n + The distance in a forward direction is found if the value is non-negative. \n + The distance in a backward direction is found if the value is non-positive. \n \~ + \param[in] pl - \ru Система координат двумерной кривой. + \en A coordinate system of two-dimensional curve. \~ + \param[in] curve - \ru Двумерная кривая. + \en A two-dimensional curve. \~ + \param[in] surf - \ru Поверхность, до которой проводится поиск расстояний. + \en A surface to measure the distances up to. \~ + \param[out] lPlus - \ru Расстояние в прямом направлении. + \en The distance in a forward direction. \~ + \param[out] lMinus - \ru Расстояние в обратном направлении. + \en The distance in a backward direction. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) GetDistanceToSurface( const MbPlacement3D & pl, + const MbCurve * curve, + const MbSurface * surf, + double & lPlus, + double & lMinus ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создание поверхностей сечения выдавливания плоского контура. + \en Create cutter surfaces for extrusion of planar contours. \~ + \details \ru Создание поверхностей сечения выдавливания плоского контура и определение направлений выдавливаний. \n + \en Create cutter surfaces for extrusion of planar contours and define directions of extrusions. \n \~ + \param[in] surface - \ru Поверхность контуров. + \en A surface that contains the contours. \~ + \param[in] contours - \ru Набор двумерных контуров. + \en A set of planar contours. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] params - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] version - \ru Версия построения. + \en The version of construction. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \param[out] surfAndDir- \ru Результат операции - поверхности и направление относительно direction. + \en Result of the operation - surfaces and directions relative to parameter direction. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (void) CreateExtrusionCutSurfaces( const MbSurface & surface, + const c3d::PlaneContoursSPtrVector & contours, + const MbVector3D & direction, + ExtrusionValues & params, + VERSION version, + MbResultType & resType, + std::vector< std::pair> & surfAndDir ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния от контура на поверхности до габаритного куба оболочки. + \en Find the distances from a contour on a surface to the bounding box of a shell. \~ + \details \ru Найти расстояния от контура на поверхности до габаритного куба оболочки. \n + Расстояние в прямом направлении найдено, если значение не отрицательное. \n + Расстояние в обратном направлении найдено, если значение не положительное. \n + \en Find the distances from a contour on a surface to the bounding box of a shell. \n + The distance in a forward direction is found if the value is nonnegative. \n + The distance in a backward direction is found if the value is non-positive. \n \~ + \param[in] surface - \ru Поверхность, на которой лежит двумерная кривая. + \en A surface that contains the two-dimensional curve. \~ + \param[in] direction - \ru Направление поиска (выдавливания) + \en A direction of the distance calculation (an extrusion direction). \~ + \param[in] curve - \ru Двумерная кривая, лежащая на поверхности surface. + \en A two-dimensional curve on surface 'surface'. \~ + \param[in] cube - \ru Габаритный куб оболочки. + \en The bounding box of the shell. \~ + \param[out] lPlus - \ru Расстояние в прямом направлении. + \en The distance in a forward direction. \~ + \param[out] lMinus - \ru Расстояние в обратном направлении. + \en The distance in a backward direction. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) GetDistanceToCube( const MbSurface & surface, + const MbVector3D & direction, + const MbCurve & curve, + const MbCube & cube, + double & lPlus, + double & lMinus, + MbResultType & resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния от набора кривых на поверхности до габаритного куба оболочки. + \en Find the distances from curves on a surface to the bounding box of a shell. \~ + \details \ru Найти расстояния от набора кривых на поверхности до габаритного куба оболочки. \n + Расстояние в прямом направлении найдено, если значение не отрицательное. \n + Расстояние в обратном направлении найдено, если значение не положительное. \n + \en Find the distances from curves on a surface to the bounding box of a shell. \n + The distance in a forward direction is found if the value is nonnegative. \n + The distance in a backward direction is found if the value is nonpositive. \n \~ + \param[in] surface - \ru Поверхность, на которой лежат двумерные кривые. + \en A surface that contains two-dimensional curves. \~ + \param[in] direction - \ru Направление поиска (выдавливания) + \en A direction of the distance calculation (an extrusion direction). \~ + \param[in] curves - \ru Набор двумерных кривых на поверхности surface. + \en A set of two-dimensional curves on the surface 'surface'. \~ + \param[in] cube - \ru Габаритный куб оболочки. + \en The bounding box of the shell. \~ + \param[out] lPlus - \ru Расстояние в прямом направлении. + \en The distance in a forward direction. \~ + \param[out] lMinus - \ru Расстояние в обратном направлении. + \en The distance in a backward direction. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) GetDistanceToCube( const MbSurface & surface, + const MbVector3D & direction, + const RPArray & curves, + const MbCube & cube, + double & lPlus, + double & lMinus, + MbResultType & resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния от плоскости до габаритного куба оболочки. + \en Find the distances from a plane to the bounding box of a shell. \~ + \details \ru Найти расстояния от плоскости до габаритного куба оболочки. \n + Расстояние в прямом направлении найдено, если значение не отрицательное. \n + Расстояние в обратном направлении найдено, если значение не положительное. \n + Использует расчет габарита относительно локальной системы координат. \n + Если система координат плоскости лежит вне габаритного куба, \n + то при взведенном флаге findMax ищется максимальное расстояние до куба. \n + \en Find the distances from a plane to the bounding box of a shell. \n + The distance in a forward direction is found if the value is non-negative. \n + The distance in a backward direction is found if the value is non-positive. \n + Calculation of the distance relative to the local coordinate system is used. \n + If a plane coordinate system is out of the bounding box, \n + then if the flag 'findMax' is set to 'true', the maximal distance to bounding box is calculated. \n \~ + \param[in] pl - \ru Система координат плоскости. + \en The plane coordinate system. \~ + \param[in] shell - \ru Целевая оболочка. + \en A target shell. \~ + \param[out] dPlus - \ru Расстояние в прямом направлении. + \en The distance in a forward direction. \~ + \param[out] dMinus - \ru Расстояние в обратном направлении. + \en The distance in a backward direction. \~ + \param[in] findMax - \ru Искать максимальное расстояние до габаритного куба. + \en The maximal distance to bounding box is to be calculated. \~ + \return \ru Возвращает true, если найдено хотя бы одно из расстояний. + \en Returns 'true' if at least one of the distances has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) GetDistanceToCube( const MbPlacement3D & pl, + const MbFaceShell * shell, + double & dPlus, + double & dMinus, + bool findMax = true ); // \ru Искать максимальное \en Find the maximal distance + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния/углы от контура до куба или до поверхности. + \en Find the distances/angles from a contour to a bounding box or to a surface. \~ + \details \ru Найти расстояния/углы от контура до куба или до поверхности. \n + Нужно учесть уклон в двух направлениях. \n + \en Find the distances/angles from a contour to a bounding box or to a surface. \n + The inclination in two directions is to be considered. \n \~ + \param[in] curve - \ru Кривая. + \en A curve. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] rotation - \ru Вращение (true) или выдавливание (false) + \en Rotation (true) or extrusion (false) \~ + \param[in] operationDirection - \ru Вперед (true) или назад (false) + \en Forward (true) or backward (false) \~ + \param[in] toCube - \ru До куба, если указатель ненулевой + \en Up to a cube if the pointer is not null. \~ + \param[in] toSurface - \ru До поверхности, если указатель ненулевой. + \en Up to a surface if the pointer is not null. \~ + \param[in,out] params: +\ru Должны быть заданы параметры: \n + params.side1.rake - Уклон в направлении direction (для плоской образующей). \n + params.side2.rake - Уклон в направлении direction, обратном direction (для плоской образующей). \n + params.thikness1 - Толщина стенки в прямом направлении + (в положительном направлении нормали объекта (грани, поверхности, плоскости кривой)). \n + params.thikness2 - Толщина стенки в обратном направлении. \n + Заполняются параметры: \n + params.side1.scalarValue - Расстояние выдавливания в направлении direction (если operationDirection == true), + иначе обратном. \n + params.side2.scalarValue - Расстояние выдавливания в направлении, обратном direction (если operationDirection == true), + иначе в прямом. \n +\en The following parameters should be defined: \n + params.side1.rake - The inclination in direction 'direction' (for a planar generatrix). \n + params.side2.rake - The inclination in direction opposite to 'direction' (for a planar generatrix). \n + params.thikness1 - Wall thickness in forward direction. + (in the positive direction of the normal of an object (a face, a surface, the plane of a curve)). \n + params.thikness2 - The wall thickness in the backward direction. \n + The output parameters: \n + params.side1.scalarValue - The extrusion distance in the direction 'direction' (if 'operationDirection' == true), + else in the opposite direction. \n + params.side2.scalarValue - The extrusion distance in the direction opposite to 'direction' (if 'operationDirection' == true), + else in the forward direction. \n \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) GetRangeToCubeOrSurface( const MbCurve3D & curve, + const MbVector3D & direction, + const MbAxis3D & axis, + const bool rotation, + bool operationDirection, + const MbCube * toCube, + const MbSurface * toSurface, + SweptValuesAndSides & params, + MbResultType & resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". + \en Find the nearest solids while extruding with option 'up to the nearest object'. \~ + \details \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". \n + Возвращает номерa (nPlus и nMinus) ближайших тел с положительной и отрицательной стороны эскиза. + \en Find the nearest solids while extruding with option 'up to the nearest object'. \n + Returns the numbers (nPlus and nMinus) of nearest solids on the positive and the negative sides of the sketch. \~ + \param[in] pl - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] c - \ru Множество двумерных контуров. + \en An array of two-dimensional contours. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] solids - \ru Целевой набор тел. + \en A target set of solids. \~ + \param[out] nPlus - \ru Номер ближайшего тела в положительном направлении. + \en The number of the nearest solid in the positive direction. \~ + \param[out] nMinus - \ru Номер ближайшего тела в отрицательном направлении. + \en The number of the nearest solid in the negative direction. \~ + \return \ru Возвращает true, если найдено тело хотя бы в одном из направлений. + \en Returns 'true' if a solid is found in at least one of directions. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) GetNearestSolid( const MbPlacement3D & pl, + RPArray & c, + MbSweptLayout::Direction direction, + RPArray & solids, + size_t & nPlus, + size_t & nMinus ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". + \en Find the nearest solids while extruding with option 'up to the nearest object'. \~ + \details \ru Найти ближайшие тела при выдавливании с опцией "до ближайшего объекта". \n + возвращает номерa (nPlus и nMinus) ближайших тел ближайших тел в прямом и обратном направлении. + \en Find the nearest solids while extruding with option 'up to the nearest object'. \n + returns numbers (nPlus and nMinus) of the nearest solids in the forward and the backward direction. \~ + \param[in] curves - \ru Набор кривых. + \en A set of curves. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] operationDirection - \ru Параметры выдавливания "до ближайшего объекта". + \en Parameters of extrusion 'up to the nearest object'. \~ + \param[in] solids - \ru Целевой набор тел. + \en A target set of solids. \~ + \param[out] nPlus - \ru Номер ближайшего тела в положительном направлении. + \en The number of the nearest solid in the positive direction. \~ + \param[out] nMinus - \ru Номер ближайшего тела в отрицательном направлении. + \en The number of the nearest solid in the negative direction. \~ + \return \ru Возвращает true, если найдено тело хотя бы в одном из направлений. + \en Returns 'true' if a solid is found in at least one of directions. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) GetNearestSolid( RPArray & curves, + const MbVector3D & direction, + MbSweptLayout::Direction operationDirection, + RPArray & solids, + size_t & nPlus, + size_t & nMinus ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить оболочку или тело, состоящее из NURBS поверхностей. + \en Check a shell or a solid that consists of NURBS surfaces. \~ + \details \ru Проверить корректность оболочки или тела, состоящего из NURBS поверхностей. \n + \en Check the correctness of a shell or a solid that consists of NURBS surfaces. \n \~ + \param[in] params - \ru Исходные параметры операции. + \en Initial parameters of the operation. \~ + \param[in] nsSolid - \ru Тело - результат операции. + \en A solid - the result of the operation. \~ + \param[in] progBar - \ru Индикатор прогресса выполнения операции. + \en A progress indicator of the operation. \~ + \return \ru Возвращает rt_Success, если тело успешно прошло проверку. + \en Returns rt_Success if the solid has successfully passed the validation. \~ + \warning \ru Проверочная функция операции NurbsSurfacesShell. + \en A checking function of the operation NurbsSurfacesShell. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) CheckNurbsShell( const NurbsSurfaceValues & params, + const MbSolid & nsSolid, + IProgressIndicator * progBar ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Положить эскиз в массив усекающих объектов. + \en Add a sketch to the array of truncating objects. \~ + \details \ru Положить эскиз в массив усекающих объектов путем создания пространственных кривых. \n + \en Add a sketch to the array of truncating objects by creation of spatial curves. \n \~ + \param[in] sketchPlace - \ru Локальная система координат двумерного эскиза. + \en A local coordinate system of two-dimensional sketch. \~ + \param[in] sketchCurves - \ru Двумерные кривые эскиза. + \en Two-dimensional curves of the sketch. \~ + \param[out] items - \ru Выходной массив пространственных объектов. + \en The output array of spatial objects. \~ + \return \ru - Возвращает true в случае добавления элементов в выходной массив. + \en - Returns 'true' if elements are added into output array. \~ + \warning \ru Вспомогательная функция операции TruncateShell. + \en Auxiliary function of the operation TruncateShell. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) AddTruncatingSketch( const MbPlacement3D & sketchPlace, + RPArray & sketchCurves, + RPArray & items ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Положить кривую в массив усекающих объектов. + \en Add a curve to the array of truncating objects. \~ + \details \ru Положить кривую в массив усекающих объектов + (с разбором кривой на составляющие, в случае необходимости). \n + \en Add a curve to the array of truncating objects + (with decomposition of the curve if necessary). \n \~ + \param[in] curve - \ru Пространственная кривая. + \en A space curve. \~ + \param[out] items - \ru Выходной массив пространственных объектов. + \en The output array of spatial objects. \~ + \warning \ru Вспомогательная функция операции TruncateShell. + \en Auxillary function of the operation TruncateShell. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) AddTruncatingCurve( const MbCurve3D & curve, + RPArray & items ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить корректность вскрываемых граней для создания тонкостенного тела. + \en Check the correctness of shelling faces for creation of a thin-walled solid. \~ + \details \ru Проверить корректность набора вскрываемых граней для создания тонкостенного тела. \n + Удаляет из массива не подходящие для операции грани (гладко сопряженные с невыбранными гранями). \n + \en Check the correctness of shelling faces set for creation of a thin-walled solid. \n + Removes unsuitable for the operation faces from the array (Delete faces smoothly connected to unselected faces). \n \~ + \param[in] params - \ru Параметры тонкой стенки. + \en Parameters of a thin wall. \~ + \param[in,out] faces - \ru Множество вскрываемых граней тела. + \en An array of shelling faces of the solid. \~ + \warning \ru Вспомогательная функция операции построения тонкостенного тела. + \en An auxiliary function of thin-walled solid construction operation. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) CheckShellingFaces( const SweptValues & params, RPArray & faces ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить компоненты проекции вектора, заданного в точке на поверхности. + \en Calculate the components of projection of a vector defined at a point on the surface. \~ + \details \ru Вычислить компоненты x и y проекции пространственного вектора, заданного в точке на поверхности. \n + \en Calculate x and y components of projection of a space vector defined at a point on a surface. \n \~ + \param[in] v3d - \ru Пространственный вектор. + \en A space vector. \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] p2d - \ru Параметрическая точка на поверхности. + \en A parametric point on the surface. \~ + \param[out] v2d - \ru Проекция пространственного вектора на поверхность. + \en The projection of the space vector on the surface. \~ + \return \ru - Возвращает true в случае успешного вычисления проекции вектора. + \en - Returns 'true' if the vector projection has been successfully calculated. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) ProjectVectorOn( const MbVector3D & v3d, const MbSurface & surface, const MbCartPoint & p2d, + MbVector & v2d ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Расширить поверхность для резки тела. + \en Extend a surface for cutting a solid. \~ + \details \ru Расширить поверхность до заданного габарита для резки тела. \n + \en Extend a surface to a given bounding box for cutting a solid. \n \~ + \param[in,out] gabarit - \ru Желаемый габарит расширения. + \en A desirable bounding box of the extended surface. \~ + \param[in] surf - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] prolongState - \ru Состояние типа продления секущих поверхностей. + \en State of prolongation types of cutter surfaces. \~ + \param[in] version - \ru Версия построения. + \en The version of construction. \~ + \return \ru - Возвращает расширенную поверхность, если получилось ее создать. + \en - Returns the extended surface if it has been successfully created. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbSurface *) GetExtendedSurfaceCopy( MbCube & gabarit, + const MbSurface & surf, + const MbShellCuttingParams::ProlongState & prolongState, + VERSION version ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить набор граней с топологией призмы. + \en Create a set of faces with topology of a prism. \~ + \details \ru Построить набор граней с топологией призмы. \n + \en Create a set of faces with topology of a prism. \n \~ + \param[in] place - \ru Локальная система координат (ЛСК). + \en A local coordinate system (LCS). \~ + \param[in] contour - \ru Двумерный контур в ЛСК. + \en A two-dimensional curve in LCS. \~ + \param[in] der - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] sense - \ru Ориентация выходного массива граней как замкнутой оболочки. + \en An orientation of the output array of faces as a closed shell. \~ + \param[in] n - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in,out] initFaces - \ru Множество созданных граней. + \en The array of created faces. \~ + \param[in] useAddCount - \ru Использовать количество граней initFaces на входе для именования новых граней. + \en The number of input faces initFaces is to be used for naming the new faces. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) CreateFaces( const MbPlacement3D & place, const MbContour & contour, + const MbVector3D & der, bool sense, const MbSNameMaker & n, + RPArray & initFaces, bool useAddCount = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Оценить параметры выдавливания для ребра жёсткости. + \en Estimate parameters of extrusion for a rib. \~ + \details \ru Оценить параметры выдавливания для построения ребра жёсткости. \n + \en Estimate parameters of extrusion for creating a rib. \n \~ + \param[in] shell - \ru Целевая оболочка. + \en A target shell. \~ + \param[in] place - \ru Локальная система координат контура. + \en A local coordinate system of the contour. \~ + \param[in] contour - \ru Двумерный контур. + \en A two-dimensional contour. \~ + \param[in] index - \ru Номер сегмента контура. + \en A number of the contour segment. \~ + \param[out] side - \ru Сторона заполнения пространства телом ребра. + \en The side to place the rib on. \~ + \param[out] origin - \ru Точка. + \en A point. \~ + \param[out] dir3D - \ru Вектор. + \en A vector. \~ + \warning \ru Вспомогательная функция операции RibSolid. + \en An auxillary function of the operation RibSolid. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) GetAutoReference( MbFaceShell & shell, + const MbPlacement3D & place, + const MbContour & contour, + ptrdiff_t index, + RibValues::ExtrudeSide & side, + MbCartPoint3D & origin, + MbVector3D & dir3D ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую в параметрах поверхности. + \en Create a curve in the parameter space of a surface. \~ + \details \ru Создать кривую в параметрах поверхности, если нужно - проекционную. \n + Если проекционную кривую создавать не нужно, возвращает дубль двумерной кривой в параметрах поверхности. \n + После использования кривую нужно удалить. \n + \en Create a curve in the parameter space of a surface. The projection curve can be created if necessary. \n + If it is not required to create the projection curve, returns a copy of two-dimensional curve in the parameter space of the surface. \n + The curve is to be deleted after use. \n \~ + \param[in] intersectCurve - \ru Кривая пересечения. + \en The intersection curve \~ + \param[in] first - \ru true - Первая поверхность, false - вторая поверхность. + \en True - The first surface, false - the second surface. \~ + \return \ru Возвращает кривую, если ее получилось построить. + \en Returns the curve if it has been successfully created. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbCurve *) GetProjCurveOnSurface( const MbSurfaceIntersectionCurve & intersectCurve, bool first ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить неизменность вектора кинематической направляющий в разных версиях. + \en Check the invariance of the vector of spine direction in different versions. \~ + \details \ru Проверить, можно ли сохранить кинематическую направляющую из одной версии в другую без изменения формы. \n + \en Check if the spine direction can be preserved between versions without any change of the shape. \n \~ + \param[in] curve - \ru Направляющая кривая. + \en The spine curve. \~ + \param[in] srcVersion - \ru Рабочая версия. + \en The current version. \~ + \param[in] dstVersion - \ru Целевая версия. + \en The target version. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsSameSpineDirection( const MbCurve3D & curve, VERSION srcVersion, VERSION dstVersion ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Классифицировать положения второго контура относительно первого. + \en Classify the position of the second contour relative to the first one. \~ + \details \ru Классифицировать положения второго контура относительно первого: \n + iloc_OutOfItem - снаружи, \n + iloc_OnItem - пересекается, \n + iloc_InItem - внутри. \n + \en Classify the position of the second contour relative to the first one: \n + iloc_OutOfItem - outside, \n + iloc_OnItem - intersects, \n + iloc_InItem - inside. \n \~ + \param[in] contour1 - \ru Первый контур. + \en The first contour. \~ + \param[in] contour2 - \ru Второй контур. + \en The second contour. \~ + \param[in] xEpsilon - \ru Погрешность по x. + \en Tolerance in x direction. \~ + \param[in] yEpsilon - \ru Погрешность по y. + \en Tolerance in y direction. \~ + \return \ru Возвращает результат классификации положения. + \en Returns the result of classification of the relative position. \~ + \ingroup Algorithms_2D +*/ +// --- +MATH_FUNC (MbeItemLocation) SecondContourLocation( const MbContour & contour1, const MbContour & contour2, + double xEpsilon, double yEpsilon ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить, близка ли первая кривая ко второй кривой. + \en Determine whether the first curve is close to the second curve. \~ + \details \ru Определить, близка ли кривая curve1 к кривой curve2 с заданной точностью. \n + Близость определяется близостью точек первой кривой, полученных шаганием \n + по кривой с заданным угловым отклонением, ко второй кривой. \n + \en Determine whether curve 'curve1' is close to curve 'curve2' within the given precision. \n + The proximity is defined by the closeness of points of the first curve obtained by sampling \n + with the given turning angle to the second curve. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[in] xEpsilon - \ru Близость по x. + \en Proximity tolerance in x direction. \~ + \param[in] yEpsilon - \ru Близость по y. + \en Proximity tolerance in y direction. \~ + \param[in] devSag - \ru Максимальное угловое отклонение при шагании по кривой. + \en The maximal turning angle for sampling the curve. \~ + \return \ru Возвращает true, если кривые близки. + \en Returns 'true' if the curves are close. \~ + \ingroup Algorithms_2D +*/ +// --- +MATH_FUNC (bool) IsSpaceNear( const MbCurve & curve1, const MbCurve & curve2, double xEpsilon, double yEpsilon, + double devSag = 5.0 * Math::deviateSag ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить, близка ли кривая к поверхности. + \en Determine whether a curve is close to a surface. \~ + \details \ru Определить, близка ли кривая к поверхности с заданной точностью. \n + Выполняется проверка по пробным точкам кривой, полученных шаганием по угловому отклонению. \n + \en Determine whether a curve is close to a surface within the given tolerance. \n + The check uses sample points of curves obtained by sampling with maximal turning angle. \n \~ + \param[in] curv - \ru Кривая. + \en A curve. \~ + \param[in] surf - \ru Поверхность. + \en A surface. \~ + \param[in] surfExt - \ru Проверять на расширенной поверхности. + \en Perform the check for the extended surface. \~ + \param[in] mEps - \ru Метрическая близость. + \en The metric proximity tolerance. \~ + \param[in] devSag - \ru Максимальное угловое отклонение при шагании по кривой. + \en The maximal turning angle for sampling the curve. \~ + \return \ru Возвращает true, если кривая близка к поверхности. + \en Returns 'true' if the curve is close to the surface. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsSpaceNear( const MbCurve3D & curv, const MbSurface & surf, bool surfExt, + double mEps, double devSag = 5.0 * Math::deviateSag ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать грань по произвольной поверхности. + \en Create the face on the base of arbitrary surface. \~ + \details \ru Создать грань по произвольной поверхности без самопересечений. \n + \en Create the face on the base of arbitrary surface without selfintersections. \n \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[out] face - \ru Грань. + \en The face. \~ + \return \ru Возвращает true, если грань создана. + \en Returns 'true' if the face was created. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) SurfaceFace( const MbSurface & surface, SPtr & face ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создание трёхмерной сетки по двумерной сетке. + \en Creating a three-dimensional grid on a two-dimensional grid. \~ + \details \ru Создание трёхмерной сетки по двумерной сетке. \n + \en Creating a three-dimensional grid on a two-dimensional grid. \n \~ + \param[in] place - \ru Локальная система координат в трёхмерном пространстве. + \en Local coordinate system in three dimensional space. \~ + \param[out] planarGrid - \ru Триангуляция двумерной области. + \en Triangulation of a two-dimensional region. \~ + \return \ru Возвращает true, если грань создана. + \en Returns 'true' if the face was created. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbGrid *) SpaceGrid( const MbPlacement3D & place, const MbPlanarGrid & planarGrid, bool exact = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Заменить элемент на вставку, если расстояние от начала координат до центра + его габарита, превышает размер габаритного куба в заданное число раз \~ + \en Replace an item by an instance if the length from it's bounding box to the + world origin is greater than it's diagonal by specified factor. + \details \ru Объект или его копия смещается на вектор из начала координат до центра габаритного куба объекта + и размещается во вставке, обеспечивающей смещение на вектор противоположного направления. \~ + Обрабатываются только объекты, не являющиеся вставками. \~ + Нулевое или отрицательное значение параметра ratioThreashhold запрещает преобразование. \~ + \en The item or it's replica is moved bey the vector from the origin of the world to the center of the + item's bounding box, then put in the instance, providing the displacement by the reversed vector. \~ + Function processes objects of all types except for instances. \~ + Null or negative value of the ratioThreashhold parameter blocks the transformation. \~ + \param[out] item - \ru Обрабатываемый объект. \~ + \en Processable item. \~ + \param[in] ratioThreashhold - \ru Пороговое значение отношения расстояния до центра габаритного куба и его диагонали, + при превышении которого происходит замена. \~ + \en The replacement threshold value of the ratio of the bounding box's center to the + origin of the world to it's diagonal length. \~ + \param[in] makeCopy - \ru Производить ли трансформацию на копии объекта. \~ + \en Is the copy of the object must be transformed. \~ + \return \ru Возвращает вставку объекта. + \en Returns instance of object. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbItem *) ReplaceByInstance( MbItem * item, double ratioThreashhold = -1.0, bool makeCopy = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построениe «залитого» объема, расположенного между внутренней поверхностью сосуда и ограничивающей поверхностью или телом. \~ + \en The construction of a "flood fill" volume located between the inner surface of the vessel and the bounding surface or body. \~ + \details \ru На вход подаётся тело, дополнительная поверхность или дополнительное тело и координаты источника. + На выходе получаем объём, построенный от источника и ограниченный со всех сторон оболочкой тела и дополнительными объектами. \~ + \en The body, an additional surface or an additional body and the coordinates of the source are fed to the input. + On the output we get the volume, constructed from the source and bounded from all sides by the shell of the body and by additional objects. \~ + \param[in] vessel - \ru Тело сосуда. \~ + \en The vessel. \~ + \param[in] sameShell - \ru Режим копирования тела сосуда. + \en Whether to copy the vessel. \~ + \param[in] bungData - \ru Поверхность уровня или тело пробки. \~ + \en The surface of the level or body of the bung. \~ + \param[in] origin - \ru Точка внутри сосуда. \~ + \en The point inside the vessel. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) FloodFillResult( MbSolid & vessel, + MbeCopyMode sameShell, + const MbSweptData & bungData, + const MbCartPoint3D & origin, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать крепеж по трехмерной точке. НЕ ИСПОЛЬЗОВАТЬ ВНЕ ТЕСТОВОГО ПРИЛОЖЕНИЯ!!! ФУНКЦИЯ НАХОДИТСЯ В РАЗРАБОТКЕ!!! + \en Create fastener using 3D point. \~ + \details \ru Создать крепеж по трехмерной точке. \n + \en Create fastener using 3D point. \n \~ + \param[in] solids - \ru Множество тел для скрепления. + \en An array of bodies to fasten. + \param[in] sameShell - \ru Режим копирования тел. + \en Whether to copy the solids. \~ + \param[in] point - \ru Трехмерная точка, на основе проецирования которой определяется положение крепежа. + \en 3d point. \~ + \param[in] params - \ru Параметры крепежа ( его тип, размеры и т.д. ). + \en Fastener parameters ( type, diameter, etc. ). \~ + \param[in] names - \ru Именователь новых граней. + \en An object defining the name of a new faces. \~ + \param[out] results - \ru Множество тел для скрепления с набором отверстий и набор тел крепежа в отверстиях. + \en Array of bodies with a holes and fastener body. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateFastener ( const RPArray & solids, + MbeCopyMode sameShell, + const MbCartPoint3D & point, + const FastenersValues & params, + const MbSNameMaker & names, + RPArray & results ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Cоздать набор крепежных элементов по трехмерной кривой. НЕ ИСПОЛЬЗОВАТЬ ВНЕ ТЕСТОВОГО ПРИЛОЖЕНИЯ!!! ФУНКЦИЯ НАХОДИТСЯ В РАЗРАБОТКЕ!!! + \en Create an array of fastener elements using 3d curve. \~ + \details \ru Cоздать набор крепежных элементов по трехмерной кривой. + \en Create an array of fastener elements using 3d curve. \~ + \param[in] solids - \ru Множество тел для скрепления. + \en Array of bodies with a hole and fastener body. \~ + \param[in] sameShell - \ru Режим копирования тел. + \en Whether to copy the solids. \~ + \param[in] curve - \ru Трехмерная кривая, на основе проецирования точек которой определяются положения крепежных элементов. + \en 3D curve. \~ + \param[in] number - \ru Количество точек на кривой. Точки расположены равномерно по длине кривой. + \en Number of points on the curve. Points are uniformly located along the length of the curve. \~ + \param[in] params - \ru Параметры крепежа ( его тип, размеры и т.д. ). + \en Fastener parameters ( type, diameter, etc. ). \~ + \param[in] names - \ru Именователь новых граней. + \en An object defining the name of a new faces. \~ + \param[out] results - \ru Множество тел для скрепления с набором отверстий и набор тел крепежа в отверстиях. + \en Array of bodies with a holes and fastener bodies. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateFasteners( const RPArray & solids, + MbeCopyMode sameShell, + const MbCurve3D & curve, + size_t number, + const FastenersValues & params, + const MbSNameMaker & names, + RPArray & results ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Слить несколько граней тела в одну грань. + \en Create a solid with one face instead selected faces. \~ + \details \ru Заменить указанные гладко стыкующиеся грани тела одной геометрически совпадающей гранью. \n + \en To replace these smooth abutting faces to form a single geometrically matching face. \n + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en Whether to copy the source solid. \~ + \param[in] faces - \ru Объединяемые грани тела. + \en The faces of solid to be merged. \~ + \param[in] uParam - \ru Параметры u направления объединяющей поверхности. + \en The operation parameters for common surface in u direction. \~ + \param[in] vParam - \ru Параметры v направления объединяющей поверхности. + \en The operation parameters for common surface in v direction. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] prolong - \ru Параметр добавления гладко стыкующихся граней с faces (prolong>0). + \en The parameter of adding prolong faces (prolong>0). \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateMerging( MbSolid & solid, + MbeCopyMode sameShell, + c3d::FacesVector & faces, + const MbNurbsParameters & uParam, + const MbNurbsParameters & vParam, + const MbSNameMaker & names, + bool prolong, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти грани тел, имеющие контактные площадки. \~ + \en To find contacted faces of bodies. \~ + \details \ru Найти номера контактирующих граней тел, имеющих противоположно направленные нормали, у которых есть общие участки с конечной площадью перекрытия. \~ + \en To find contacted faces of bodies with oppositely directed normals which have a finite overlap area. \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] precision - \ru Точность операции. + \en The precision of operation. \~ + \param[out] facesNumbers - \ru Пары номеров касающихся граней с противоположно направленными нормалями. + \en The couples of number of contacted faces with oppositely directed normals. \~ + \return \ru Возвращает true, если грани контакта найдены. + \en Returns true, if contacted faces were found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) FindTouchedFaces( const MbSolid & solid1, + const MbSolid & solid2, + double precision, + c3d::IndicesPairsVector & facesNumbers ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разбить контактирующие грани тел. \~ + \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 Первое тело. + \en The first solid. \~ + \param[in/out] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] precision - \ru Точность операции. + \en The precision of operation. \~ + \param[in] facesNumbers - \ru Множество пар номеров соприкасающихся граней, у которых требуется построить общие пятна контакта (может быть пустым). + \en The container with pairs of contact face numbers that need to have common contact spots (it can be empty). \~ + \return \ru Возвращает true, если грани контакта найдены. + \en Returns true, if contacted faces were found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) SplitTouchedFaces( MbSolid & solid1, + MbSolid & solid2, + double precision, + c3d::IndicesPairsVector & facesNumbers ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Объединить тела, имеющие контактирующие грани. \~ + \en The function performs unite the bodies with contacted faces. \~ + \details \ru Объединить тела, удалив контактирующие грани. \~ + \en The function performs unite the bodies and removing the contacting faces. \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] sameShell1 - \ru Способ копирования граней первого тела. + \en Method of copying the faces of the first solid. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] sameShell2 - \ru Способ копирования граней второго тела. + \en Method of copying the faces of the second solid. \~ + \param[in] precision - \ru Точность операции. + \en The precision of operation. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) TouchedSolidsMerging( MbSolid & solid1, + MbeCopyMode sameShell1, + MbSolid & solid2, + MbeCopyMode sameShell2, + const MbSNameMaker & names, + double precision, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Починить тело. \~ + \en Solid repairing. \~ + \details \ru Найти дефекты и починить грани, рёбра, вершины тела. \~ + \en Find defects and repair faces, edges, vertices of the solid. \~ + \param[in] solid - \ru Тело для ремонта. + \en The initial solid. \~ + \param[in] accuracy - \ru Точность для поиска дефектов тела. + \en The accuracy for finding defects of the solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SolidRepairing( MbSolid & solid, double accuracy ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить трансформированную копию тела. \~ + \en Get transformed copy of a solid. \~ + \details \ru Получить трансформированную копию тела, если матрица трансформации не единичная или оригинал, если единичная. \~ + \en Get transformed copy of a solid if a matrix is not identity matrix or original of the solid if the matrix is identity matrix. \~ + \param[in] solid - \ru Тело. + \en A solid. \~ + \param[in,out] copyMode - \ru Исходный режим копирования тела. + \en An initial copy mode. \~ + \param[in] matr - \ru Матрица преобразования. + \en Transformation matrix. \~ + \param[in] transformedMainName - \ru Главное имя для операции трансформации. + \en Main name of transformation operation. \~ + \return \ru Возвращает копию или оригинал тела. + \en Returns copy or original of the solid. \~ + \ingroup Algorithms_3D +*/ +// --- +inline +c3d::SolidSPtr GetTransformedSolid( c3d::SolidSPtr & solid, MbeCopyMode & copyMode, const MbMatrix3D & matr, SimpleName transformedMainName = ct_TransformedSolid ) +{ + c3d::SolidSPtr resSolid( solid ); + + if ( (resSolid != NULL) && !matr.IsSingle() ) { + MbSNameMaker n( transformedMainName, MbSNameMaker::i_SideNone, 0 ); + + MbSolid * resSolidPtr = NULL; + TransformValues tv( matr ); + ::TransformedSolid( *solid, cm_Copy, tv, n, resSolidPtr ); + if ( resSolidPtr != NULL ) { + resSolid = resSolidPtr; + copyMode = cm_Same; + } + } + return resSolid; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить трансформированную копию объекта. \~ + \en Get transformed copy of object. \~ + \details \ru Получить трансформированную копию объекта, если матрица трансформации не единичная или оригинал, если единичная. \~ + \en Get transformed copy of an object if a matrix is not identity matrix or original of the solid if the matrix is identity matrix. \~ + \param[in] item - \ru Объект. + \en An object. \~ + \param[in] matr - \ru Матрица преобразования. + \en Transformation matrix. \~ + \return \ru Возвращает копию или оригинал объекта. + \en Returns copy or original of the object. \~ + \ingroup Algorithms_3D +*/ +// --- +template +SPtr GetTransformedItem( SPtr & item, const MbMatrix3D & matr, MbRegDuplicate * iDupReg = NULL, MbRegTransform * iTransReg = NULL ) +{ + SPtr resItem( item ); + if ( (resItem != NULL) && !matr.IsSingle() ) { + resItem = static_cast( &item->Duplicate( iDupReg ) ); + resItem->Transform( matr, iTransReg ); + } + return resItem; +} + + +#endif // __ACTION_H diff --git a/C3d/Include/action_analysis.h b/C3d/Include/action_analysis.h index f84c5a9..068ba44 100644 --- a/C3d/Include/action_analysis.h +++ b/C3d/Include/action_analysis.h @@ -1,334 +1,384 @@ -//////////////////////////////////////////////////////////////////////////////// -/** -\file -\brief \ru Функции для анализа кривизны поверхности. -\en Functions for surface curvature analysis. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_CURVATURE_ANALYSIS_H -#define __ACTION_CURVATURE_ANALYSIS_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Алгоритмы поиска экстремумов на поверхности. - \en Algorithms for finding extremes on the surface. \~ - \details \ru Константы, задающие вызываемый алгоритм поиска экстремальных значений функции на поверхности. - \en Constants defining the called algorithm for searching for extreme values of a function on a surface. \~ - \ingroup Algorithms_3D -*/ -enum MbeExtremsSearchingMethod -{ - esm_GradientDescent = 1, ///< \ru Mетод градиентного спуска. \en Gradient Descent Method. - esm_LineSegregation = 2 ///< \ru Mетод выделения линий смены убывания / возрастания функции по u и по v. \en The method of segregation of lines of change of decrease / increase of the function in u and v directions. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Функция, заданная на поверхности. - \en The function define on the surface. \~ - \details \ru Рассчитывает значение самой функции и ее градиент. - \en Calculates the value of the function itself and its gradient. \~ - \ingroup Algorithms_3D -*/ -typedef void( *SurfaceFunction )( const MbSurface & surf, // Поверхность, - const MbCartPoint & pnt, // точка на поверхности - double & func, // рассчитываемое значение функции, - MbVector * der );// рассчитываемое значение вектора градиента (если указатель не нулевой). - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности минимальную нормальную кривизну, а также ее градиент. - \en Calculate at the point of the surface the minimum normal curvature, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) MinSurfaceCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности максимальну нормальную кривизну, а также ее градиент. - \en Calculate at the point of the surface the maximum normal curvature, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) MaxSurfaceCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности гауссову кривизну, а также ее градиент. - \en Calculate at a surface point the Gaussian curvature, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) GaussCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности среднюю кривизну, а также ее градиент. - \en Calculate at the point of the surface the mean curvature, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) MeanCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности нормальную кривизна в направлении u , а также ее градиент. - \en Calculate at the surface point the normal curvature in the direction of u, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) UNormalCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить в точке поверхности нормальную кривизна в направлении v, а также ее градиент. - \en Calculate at the surface point the normal curvature in the direction of v, as well as its gradient. \~ - \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). - \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] func - \ru Рассчитываемое значение кривизны. - \en Calculated curvature value. \~ - \param[out] der - \ru Рассчитываемое значение градиента кривизны. - \en The calculated value of the curvature gradient. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) VNormalCurvature( const MbSurface & surf, const MbCartPoint & pnt, double & func, MbVector * der = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки поверхности, в которых выбранная кривизна принимает наибольшие по модулю значения. - \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] func - \ru Функция расчета кривизны в точке. - \en The function of calculating the curvature at a point. \~ - \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). - \en The largest in modulus value negative curvature (0, if there is no such). \~ - \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The point at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). - \en The greatest positive value of curvature (0, if there is no such). \~ - \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. - \en The point at which the curvature takes the most positive value. \~ - \param[in] method - \ru Алгоритм поиска экстремумов. - \en Extremum search algorithm. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) SurfaceMinMaxCurvature(const MbSurface & surface, SurfaceFunction func, double & maxNegCurv, MbCartPoint & maxNegLoc, - double & maxPosCurv, MbCartPoint & maxPosLoc, MbeExtremsSearchingMethod method = esm_LineSegregation ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки оболочки, в которых выбранная кривизна принимает наибольшие по модулю значения. - \en Find the points of the shell at which the selected curvature takes the most modulo values. \~ - \details \ru Ищутся точки на оболочке, в которых выбранная кривизна принимают наибольшее положительное и наименьшее отрицательное значение. - \en Finds points on the shell at which the selected curvature takes the largest positive and lowest negative values. \~ - \param[in] faces - \ru Грани оболочки. - \en Faces of the shell. \~ - \param[in] func - \ru Функция расчета кривизны в точке. - \en The function of calculating the curvature at a point. \~ - \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). - \en The largest in modulus value negative curvature (0, if there is no such). \~ - \param[out] maxNegFace - \ru Грань, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The face at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The point at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). - \en The greatest positive value of curvature (0, if there is no such). \~ - \param[out] maxPosFace - \ru Грань, в которой кривизна принимает наибольшее положительное значение. - \en The face at which the curvature takes the most positive value. \~ - \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. - \en The point at which the curvature takes the most positive value. \~ - \param[in] borderControl - \ru Учитывать границы граней при поиске экстремумов. - \en Take into account the boundaries of the faces when searching for extrema. \~ - \param[in] method - \ru Алгоритм поиска экстремумов. - \en Extremum search algorithm. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, SurfaceFunction func, double & maxNegCurv, MbFace *& maxNegFace, MbCartPoint & maxNegLoc, - double & maxPosCurv, MbFace *& maxPosFace, MbCartPoint & maxPosLoc, bool borderControl = false, - MbeExtremsSearchingMethod method = esm_LineSegregation ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки на поверхности, в которых главные нормальные кривизны принимают наибольшие по модулю значения. - \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[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). - \en The largest in modulus value negative curvature (0, if there is no such). \~ - \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The point at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). - \en The greatest positive value of curvature (0, if there is no such). \~ - \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. - \en The point at which the curvature takes the most positive value. \~ - \param[in] method - \ru Алгоритм поиска экстремумов. - \en Extremum search algorithm. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) SurfaceMinMaxCurvature(const MbSurface & surface, double & maxNegCurv, MbCartPoint & maxNegLoc, - double & maxPosCurv, MbCartPoint & maxPosLoc, MbeExtremsSearchingMethod method = esm_LineSegregation ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки на оболочке, в которых главные нормальные кривизны принимают наибольшие по модулю значения. - \en Find the points on the shell at which the major normal curvatures take the largest values in the module. \~ - \details \ru Ищутся точки на оболочке, в которых главные нормальные кривизны принимают наибольшее положительное и наименьшее отрицательное значение. - \en Looks for points on the shell at which the major normal curvatures take the largest positive and smallest negative values. \~ - \param[in] faces - \ru Грани оболочки. - \en Faces of the shell. \~ - \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). - \en The largest in modulus value negative curvature (0, if there is no such). \~ - \param[out] maxNegFace - \ru Грань, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The face at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. - \en The point at which the curvature takes the largest in modulus negative value. \~ - \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). - \en The greatest positive value of curvature (0, if there is no such). \~ - \param[out] maxPosFace - \ru Грань, в которой кривизна принимает наибольшее положительное значение. - \en The face at which the curvature takes the most positive value. \~ - \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. - \en The point at which the curvature takes the most positive value. \~ - \param[in] borderControl - \ru Учитывать границы граней при поиске экстремумов. - \en Take into account the boundaries of the faces when searching for extrema. \~ - \param[in] method - \ru Алгоритм поиска экстремумов. - \en Extremum search algorithm. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, double & maxNegCurv, MbFace *& maxNegFace, MbCartPoint & maxNegLoc, - double & maxPosCurv, MbFace *& maxPosFace, MbCartPoint & maxPosLoc, bool borderControl = false, - MbeExtremsSearchingMethod method = esm_LineSegregation ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Ориентированная кривизна для плоской кривой. - \en Oriented curvature for a plane curve. \~ - \details \ru Для плоской кривой функция возвращает кривизну в точке, ориентированную относительно нормали плоскости, - в которой она лежит. Для неплоской кривой функция просто возвращает кривизну в точке. - \en For a flat curve, the function returns the curvature at a point oriented relative to the normal to the plane, - in which she lies. For a non-flat curve, the function simply returns the curvature at the point. \~ - \param[in] curve - \ru Исследуемая кривая. - \en Test curve. \~ - \param[in] param - \ru Параметр на кривой. - \en Parameter on the curve. \~ - \param[in] planeNorm - \ru Нормаль плоскости, в которой лежит кривая. Если нормаль не передается в функцию, алгоритм самостоятельно - выполняет проверку, лежит ли кривая в плоскости, и вычисляет нормаль, если проверка выполняется. - \en The normal of the plane in which the curve lies. If the normal is not passed to the function, the algorithm itself - checks if the curve is in the plane and calculates normal if the test is being performed. \~ - \return \ru Возвращается значение ориентированной кривизны в точке. - \en The value of the oriented curvature at the point is returned. \~ - - \ingroup Algorithms_3D -*/ -MATH_FUNC( double ) CurveOrientedCurvature(const MbCurve3D & curve, double & param, const MbVector3D * planeNorm = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки на кривой, в которых кривизна принимает наибольшее и наименьшее значения. - \en Find the points on the curve at which the curvature takes the largest and smallest values. \~ - \details \ru Для плоской кривой наибольшее и наименьшее значение может уходить в отрицательную область. - Для неплоской кривой наибольшее и наименьшее значение всегда неотрицательны. - \en For a flat curve, the largest and smallest value may go into the negative region. - For a non-planar curve, the largest and smallest values are always non-negative. \~ - \param[in] curve - \ru Исследуемая кривая. - \en Test curve. \~ - \param[out] maxCurv - \ru Наибольшее значение кривизны. - \en The greatest value of curvature. \~ - \param[out] maxParam - \ru Точка, в которой кривизна принимает наибольшее значение. - \en The point at which the curvature takes the largest value. \~ - \param[out] minCurv - \ru Наименьшее значение кривизны. - \en The smallest value of curvature. \~ - \param[out] minParam - \ru Точка, в которой кривизна принимает наибольшее значение. - \en The point at which the curvature takes the smallest value. \~ - \param[out] bendPoints - \ru Mассив параметров точек перегиба. - \en Array of parameters of bend points. \~ - \param[out] maxPoints - \ru Mассив параметров, в которых достигается локальный максимум кривизны по модулю. - \en An array of parameters in which the local maximum curvature modulo is reached. \~ - \param[out] minPoints - \ru Mассив параметров, в которых достигается локальный минимум кривизны по модулю. - \en An array of parameters in which the local minimum curvature modulo is reached. \~ - \param[out] rapPoints - \ru Mассив параметров, в которых кривизна терпит разрыв. - Для каждого разрыва вставляются две точки, до и после. - \en Array of parameters in which curvature breaks. - For each break two points are inserted, before and after. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) CurveMinMaxCurvature( const MbCurve3D & curve, double & maxCurv, double & maxParam, double & minCurv, double & minParam, - std::vector * bendPoints = NULL, std::vector * maxPoints = NULL, - std::vector * minPoints = NULL, std::vector * rapPoints = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Направление максимальной нормальной кривизны поверхности. - \en The direction of the maximum normal surface curvature. \~ - \details \ru Вычисляется направление на поверхности, в котором нормальная кривизна поверхности принимает максимальное значение. - \en The direction on the surface is calculated in which the normal curvature of the surface takes a maximum value. \~ - \param[in] surf - \ru Поверхность. - \en Surface. \~ - \param[in] pnt - \ru Точка расчета. - \en Point of calculation. \~ - \param[out] dir - \ru Рассчитываемое направление. - \en The calculated direction. \~ - \ingroup Algorithms_3D -*/ -MATH_FUNC( void ) SurfaceMaxCurvatureDirection( const MbSurface & surf, const MbCartPoint & pnt, MbVector & dir ); - -#endif // __ACTION_CURVATURE_ANALYSIS_H +//////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief \ru Функции для анализа нормалей и кривизны поверхностей и кривых. + \en Functions for normals and curvature analysis of surfaces and curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_CURVATURE_ANALYSIS_H +#define __ACTION_CURVATURE_ANALYSIS_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Алгоритмы поиска экстремумов на поверхности. + \en Algorithms for finding extremes on the surface. \~ + \details \ru Константы, задающие вызываемый алгоритм поиска экстремальных значений функции на поверхности. + \en Constants defining the called algorithm for searching for extreme values of a function on a surface. \~ + \ingroup Algorithms_3D +*/ +enum MbeExtremsSearchingMethod +{ + esm_GradientDescent = 1, ///< \ru Mетод градиентного спуска. \en Gradient Descent Method. + esm_LineSegregation = 2 ///< \ru Mетод выделения линий смены убывания / возрастания функции по u и по v. \en The method of segregation of lines of change of decrease / increase of the function in u and v directions. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Функция, заданная на поверхности. + \en The function define on the surface. \~ + \details \ru Рассчитывает значение самой функции и ее градиент. + \en Calculates the value of the function itself and its gradient. \~ + \ingroup Algorithms_3D +*/ +typedef void( *SurfaceFunction )( const MbSurface & surf, // Поверхность, + const MbCartPoint & pnt, // точка на поверхности + double & func, // рассчитываемое значение функции, + MbVector * der );// рассчитываемое значение вектора градиента (если указатель не нулевой). + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности минимальную нормальную кривизну, а также ее градиент. + \en Calculate at the point of the surface the minimum normal curvature, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) MinSurfaceCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности максимальную нормальную кривизну, а также ее градиент. + \en Calculate at the point of the surface the maximum normal curvature, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) MaxSurfaceCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности гауссову кривизну, а также ее градиент. + \en Calculate at a surface point the Gaussian curvature, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) GaussCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности среднюю кривизну, а также ее градиент. + \en Calculate at the point of the surface the mean curvature, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) MeanCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности нормальную кривизна в направлении u , а также ее градиент. + \en Calculate at the surface point the normal curvature in the direction of u, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) UNormalCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить в точке поверхности нормальную кривизна в направлении v, а также ее градиент. + \en Calculate at the surface point the normal curvature in the direction of v, as well as its gradient. \~ + \details \ru Вычисляется значение кривизны и опционально значение ее градиента в точке (если передается ненулевой указатель). + \en The curvature value is calculated and, optionally, its gradient value at a point (if a non-zero pointer is passed). \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] func - \ru Рассчитываемое значение кривизны. + \en Calculated curvature value. \~ + \param[out] der - \ru Рассчитываемое значение градиента кривизны. + \en The calculated value of the curvature gradient. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) VNormalCurvature( const MbSurface & surf, + const MbCartPoint & pnt, + double & func, + MbVector * der = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки поверхности, в которых выбранная кривизна принимает наибольшие по модулю значения. + \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] func - \ru Функция расчета кривизны в точке. + \en The function of calculating the curvature at a point. \~ + \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). + \en The largest in modulus value negative curvature (0, if there is no such). \~ + \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The point at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). + \en The greatest positive value of curvature (0, if there is no such). \~ + \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. + \en The point at which the curvature takes the most positive value. \~ + \param[in] method - \ru Алгоритм поиска экстремумов. + \en Extremum search algorithm. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) SurfaceMinMaxCurvature( const MbSurface & surface, + SurfaceFunction func, + double & maxNegCurv, + MbCartPoint & maxNegLoc, + double & maxPosCurv, + MbCartPoint & maxPosLoc, + MbeExtremsSearchingMethod method = esm_LineSegregation ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки оболочки, в которых выбранная кривизна принимает наибольшие по модулю значения. + \en Find the points of the shell at which the selected curvature takes the most modulo values. \~ + \details \ru Ищутся точки на оболочке, в которых выбранная кривизна принимают наибольшее положительное и наименьшее отрицательное значение. + \en Finds points on the shell at which the selected curvature takes the largest positive and lowest negative values. \~ + \param[in] faces - \ru Грани оболочки. + \en Faces of the shell. \~ + \param[in] func - \ru Функция расчета кривизны в точке. + \en The function of calculating the curvature at a point. \~ + \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). + \en The largest in modulus value negative curvature (0, if there is no such). \~ + \param[out] maxNegFace - \ru Грань, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The face at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The point at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). + \en The greatest positive value of curvature (0, if there is no such). \~ + \param[out] maxPosFace - \ru Грань, в которой кривизна принимает наибольшее положительное значение. + \en The face at which the curvature takes the most positive value. \~ + \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. + \en The point at which the curvature takes the most positive value. \~ + \param[in] borderControl - \ru Учитывать границы граней при поиске экстремумов. + \en Take into account the boundaries of the faces when searching for extrema. \~ + \param[in] method - \ru Алгоритм поиска экстремумов. + \en Extremum search algorithm. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, + SurfaceFunction func, + double & maxNegCurv, + MbFace *& maxNegFace, + MbCartPoint & maxNegLoc, + double & maxPosCurv, + MbFace *& maxPosFace, + MbCartPoint & maxPosLoc, + bool borderControl = false, + MbeExtremsSearchingMethod method = esm_LineSegregation ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки на поверхности, в которых главные нормальные кривизны принимают наибольшие по модулю значения. + \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[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). + \en The largest in modulus value negative curvature (0, if there is no such). \~ + \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The point at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). + \en The greatest positive value of curvature (0, if there is no such). \~ + \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. + \en The point at which the curvature takes the most positive value. \~ + \param[in] method - \ru Алгоритм поиска экстремумов. + \en Extremum search algorithm. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) SurfaceMinMaxCurvature( const MbSurface & surface, + double & maxNegCurv, + MbCartPoint & maxNegLoc, + double & maxPosCurv, + MbCartPoint & maxPosLoc, + MbeExtremsSearchingMethod method = esm_LineSegregation ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки на оболочке, в которых главные нормальные кривизны принимают наибольшие по модулю значения. + \en Find the points on the shell at which the major normal curvatures take the largest values in the module. \~ + \details \ru Ищутся точки на оболочке, в которых главные нормальные кривизны принимают наибольшее положительное и наименьшее отрицательное значение. + \en Looks for points on the shell at which the major normal curvatures take the largest positive and smallest negative values. \~ + \param[in] faces - \ru Грани оболочки. + \en Faces of the shell. \~ + \param[out] maxNegCurv - \ru Наибольшее по модулю отрицательное значение кривизны (0, если нет такого). + \en The largest in modulus value negative curvature (0, if there is no such). \~ + \param[out] maxNegFace - \ru Грань, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The face at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxNegLoc - \ru Точка, в которой кривизна принимает наибольшее по модулю отрицательное значение. + \en The point at which the curvature takes the largest in modulus negative value. \~ + \param[out] maxPosCurv - \ru Наибольшее положительное значение кривизны (0, если нет такого). + \en The greatest positive value of curvature (0, if there is no such). \~ + \param[out] maxPosFace - \ru Грань, в которой кривизна принимает наибольшее положительное значение. + \en The face at which the curvature takes the most positive value. \~ + \param[out] maxPosLoc - \ru Точка, в которой кривизна принимает наибольшее положительное значение. + \en The point at which the curvature takes the most positive value. \~ + \param[in] borderControl - \ru Учитывать границы граней при поиске экстремумов. + \en Take into account the boundaries of the faces when searching for extrema. \~ + \param[in] method - \ru Алгоритм поиска экстремумов. + \en Extremum search algorithm. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) FacesMinMaxCurvature( const RPArray & faces, + double & maxNegCurv, + MbFace *& maxNegFace, + MbCartPoint & maxNegLoc, + double & maxPosCurv, + MbFace *& maxPosFace, + MbCartPoint & maxPosLoc, + bool borderControl = false, + MbeExtremsSearchingMethod method = esm_LineSegregation ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Ориентированная кривизна для плоской кривой. + \en Oriented curvature for a plane curve. \~ + \details \ru Для плоской кривой функция возвращает кривизну в точке, ориентированную относительно нормали плоскости, + в которой она лежит. Для неплоской кривой функция просто возвращает кривизну в точке. + \en For a flat curve, the function returns the curvature at a point oriented relative to the normal to the plane, + in which she lies. For a non-flat curve, the function simply returns the curvature at the point. \~ + \param[in] curve - \ru Исследуемая кривая. + \en Test curve. \~ + \param[in] param - \ru Параметр на кривой. + \en Parameter on the curve. \~ + \param[in] planeNorm - \ru Нормаль плоскости, в которой лежит кривая. Если нормаль не передается в функцию, алгоритм самостоятельно + выполняет проверку, лежит ли кривая в плоскости, и вычисляет нормаль, если проверка выполняется. + \en The normal of the plane in which the curve lies. If the normal is not passed to the function, the algorithm itself + checks if the curve is in the plane and calculates normal if the test is being performed. \~ + \return \ru Возвращается значение ориентированной кривизны в точке. + \en The value of the oriented curvature at the point is returned. \~ + + \ingroup Algorithms_3D +*/ +MATH_FUNC( double ) CurveOrientedCurvature( const MbCurve3D & curve, + double & param, + const MbVector3D * planeNorm = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки на кривой, в которых кривизна принимает наибольшее и наименьшее значения. + \en Find the points on the curve at which the curvature takes the largest and smallest values. \~ + \details \ru Для плоской кривой наибольшее и наименьшее значение может уходить в отрицательную область. + Для неплоской кривой наибольшее и наименьшее значение всегда неотрицательны. + \en For a flat curve, the largest and smallest value may go into the negative region. + For a non-planar curve, the largest and smallest values are always non-negative. \~ + \param[in] curve - \ru Исследуемая кривая. + \en Test curve. \~ + \param[out] maxCurv - \ru Наибольшее значение кривизны. + \en The greatest value of curvature. \~ + \param[out] maxParam - \ru Точка, в которой кривизна принимает наибольшее значение. + \en The point at which the curvature takes the largest value. \~ + \param[out] minCurv - \ru Наименьшее значение кривизны. + \en The smallest value of curvature. \~ + \param[out] minParam - \ru Точка, в которой кривизна принимает наибольшее значение. + \en The point at which the curvature takes the smallest value. \~ + \param[out] bendPoints - \ru Mассив параметров точек перегиба. + \en Array of parameters of bend points. \~ + \param[out] maxPoints - \ru Mассив параметров, в которых достигается локальный максимум кривизны по модулю. + \en An array of parameters in which the local maximum curvature modulo is reached. \~ + \param[out] minPoints - \ru Mассив параметров, в которых достигается локальный минимум кривизны по модулю. + \en An array of parameters in which the local minimum curvature modulo is reached. \~ + \param[out] rapPoints - \ru Mассив параметров, в которых кривизна терпит разрыв. + Для каждого разрыва вставляются две точки, до и после. + \en Array of parameters in which curvature breaks. + For each break two points are inserted, before and after. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) CurveMinMaxCurvature( const MbCurve3D & curve, + double & maxCurv, + double & maxParam, + double & minCurv, + double & minParam, + c3d::DoubleVector * bendPoints = NULL, + c3d::DoubleVector * maxPoints = NULL, + c3d::DoubleVector * minPoints = NULL, + c3d::DoublePairsVector * rapPoints = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Направление максимальной нормальной кривизны поверхности. + \en The direction of the maximum normal surface curvature. \~ + \details \ru Вычисляется направление на поверхности, в котором нормальная кривизна поверхности принимает максимальное значение по модулю. + \en The direction on the surface is calculated in which the normal curvature of the surface takes a maximum absolute value. \~ + \param[in] surf - \ru Поверхность. + \en Surface. \~ + \param[in] pnt - \ru Точка расчета. + \en Point of calculation. \~ + \param[out] dir - \ru Рассчитываемое направление. + \en The calculated direction. \~ + \ingroup Algorithms_3D +*/ +MATH_FUNC( void ) SurfaceMaxCurvatureDirection( const MbSurface & surf, + const MbCartPoint & pnt, + MbVector & dir ); + +#endif // __ACTION_CURVATURE_ANALYSIS_H diff --git a/C3d/Include/action_b_shaper.h b/C3d/Include/action_b_shaper.h index 208f375..42be300 100644 --- a/C3d/Include/action_b_shaper.h +++ b/C3d/Include/action_b_shaper.h @@ -1,396 +1,457 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы преобразования полигональных геометрических объектов в объекты BRep. - \en Functions for conversion of the polygonal geometric object to BRep objects. \~ - \details \ru Методы преобразования полигональных геометрических объектов в объекты BRep. - \en Functions for conversion of the polygonal geometric object to BRep objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_B_SHAPER_H -#define __ACTION_B_SHAPER_H - - -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbMesh; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbFace; -class MATH_CLASS MbCollection; - - -//------------------------------------------------------------------------------ -/** \brief \ru Режим распознавания поверхностей. - \en Surface reconstruction mode. \~ - \details \ru Режим распознавания поверхностей. - \en Surface reconstruction mode. \~ - \ingroup Polygonal_Objects -*/ -// --- -enum MbeSurfReconstructMode -{ - srm_All = 0, ///< \ru Строить все поверхности. \en Build all surfaces. - srm_NoGrids = 1, ///< \ru Не строить поверхности на базе триангуляции. \en Not build surfaces based on triangulation. - srm_CanonicOnly = 2, ///< \ru Строить только элементарные поверхности. \en Build elementary surfaces only. - srm_Default = srm_NoGrids ///< \ru Режим по умолчанию. \en Default mode. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Параметры построения оболочки тела по полигональной сетке. - \en Parameters of BRep shell construction from polygonal mesh. \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbMeshProcessorValues { -public: - - /** \brief \ru Использовать относительную точность (true). - \en Use relative tolerance (true). \~ - \details \ru При использовании относительной точности отклонение граней тела от сетки проверяется относительно размера модели. - \en While use of relative tolerance distance from shell to mesh is checked relative to model size. \~ - */ - bool useRelativeTolerance; - - /** \brief \ru Точность. - \en Tolerance. \~ - \details \ru Точность работы метода: допустимое отклонение граней тела от вершин сетки. - \en Tolerance: maximum distance from BRep faces to mesh vertices. \~ - */ - double tolerance; - - /** \brief \ru Режим распознавания поверхностей. - \en Surface reconstruction mode. \~ - */ - MbeSurfReconstructMode surfReconstructMode; - - /// \ru Конструктор по умолчанию. \en Default constructor. - explicit MbMeshProcessorValues( bool useRelTol = true, double tol = 0.01, MbeSurfReconstructMode mode = srm_Default ) - : useRelativeTolerance( useRelTol ) - , tolerance ( tol ) - , surfReconstructMode ( mode ) - {} -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Класс для создания оболочки в граничном представлении по полигональной сетке. - \en Class for creating a BRep shell by polygonal mesh. \~ - \details \ru Предоставить интерфейс для управления преобразованием сетки в - оболочку в граничном представлении. \n - \en Provide an interface for managing of "Mesh to BRep" conversion. \n \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbMeshProcessor : public MbRefItem -{ -protected: - /// \ru Конструктор. \en Constructor. - MbMeshProcessor(); - -public: - /** \brief \ru Создать экземпляр процессора по коллекции. - \en Create mesh processor by collection. \~ - \details \ru Создать экземпляр процессора по коллекции. Пользователь должен сам удалить объект. - \en Create mesh processor by collection. User must delete created object. \~ - \param[in] collection - \ru Входная коллекция, содержащая треугольную сетку. \n - \en Input collection containing triangle mesh. \~ - \return \ru Возвращает указатель на созданный объект. - \en Returns pointer to created object. \~ - \ingroup Polygonal_Objects - */ - static MbMeshProcessor * Create( const MbCollection & collection ); - - /// \ru Деструктор. \en Destructor. - virtual ~MbMeshProcessor(); - - /** \brief \ru Установить относительную точность. - \en Set relative tolerance. \~ - \details \ru Установить относительную точность по габаритам текущей сетки. - \en Set relative tolerance by current mesh box. \~ - \param[in] tolerance - \ru Относительная точность. \n - \en Relative tolerance to set. \~ - \ingroup Polygonal_Objects - */ - virtual void SetRelativeTolerance( double tolerance ) = 0; - - /** \brief \ru Установить точность. - \en Set tolerance. \~ - \details \ru Установить точность распознавания поверхностей и расширения сегментов сетки. - Метод должен быть вызван перед вызовом SegmentMesh. - Точность по умолчанию равна 0.1. - \en Set tolerance of surface reconstruction and segments extension. - Method should be called before call to SegmentMesh. - Default tolerance is 0.1. \n \~ - \param[in] tolerance - \ru Точность. \n - \en Tolerance to set. \~ - \ingroup Polygonal_Objects - */ - virtual void SetTolerance( double tolerance ) = 0; - - /** \brief \ru Получить точность. - \en Get tolerance. \~ - \details \ru Получить текущую точность, используемую при распознавании поверхностей и расширения сегментов сетки. - \en Get current tolerance used in surface reconstruction and segments extension. \~ - \return \ru Возвращает абсолютную точность. - \en Returns absolute tolerance. \~ - \ingroup Polygonal_Objects - */ - virtual double GetTolerance() const = 0; - - //------------------------------------------------------------------------------ - /** \brief \ru Установить режим распознавания поверхностей. - \en Set the surfaces reconstruction mode. \~ - \details \ru Задать типы поверхностей, генерируемых на сегментах. Поверхности неподдерживаемых типов строиться не будут. \n - \en Set types of surfaces which will be generated on segments. The surfaces of unsupoprted type will not be built. \n \~ - \param[in] mode - \ru Режим распознавания поверхностей. - \en Surface reconstruction mode. - \ingroup Polygonal_Objects - */ - virtual void SetReconstructionMode( MbeSurfReconstructMode mode ) = 0; - - //------------------------------------------------------------------------------ - /** \brief \ru Установить флаг сглаживания входной сетки. - \en Set flag to use smoothing of input mesh. \~ - \details \ru Установить флаг сглаживания входной сетки. Если флаг установлен в true, - то перед запуском основного алгоритма сегментации будет выполнено сглаживание входной сетки. - Рекомендуется использовать сглаживание на неточных сетках, например, полученных методом сканирования. \n - \en Set flag to use smoothing of input mesh. If the flag set to true, then run smoothing of input mesh - before main segmentation algorithm start. - It is recommended to use mesh smoothing on inexact meshes, e.g. meshes obtained by scanning. \n \~ - \param[in] useSmoothing - \ru Флаг использования сглаживания входной сетки. По-умолчанию false. - \en The flag to use smoothing of input mesh. Default false. - \ingroup Polygonal_Objects - */ - // --- - virtual void SetUseMeshSmoothing( bool useSmoothing ) = 0; - - /** \brief \ru Получить исправленную (упрощенную) копию входной полигональной сетки. - \en Get fixed (simplified) copy of the input mesh. \~ - \details \ru Получить исправленную копию входной сетки, на которой выполняются операции MbMeshProcessor: - подсчет кривизн, сегментация, построение оболочки. Все индексы в выходных данных соответствуют - индексам вершин и треугольников упрощенной сетки, возвращаемой данным методом. \n - \en Get fixed copy of the input mesh. All further operations of MbMehsProcessor are - performed for simplified mesh: curvature calculation, segmentation, shell creation. - All indices in the output of these operations corresponds to indices of vertices and - triangles of the simplified mesh returned from this function. \n \~ - \return \ru Возвращает исправленную версию входной полигональной сетки. - \en Returns a fixed version of the input mesh. \~ - \ingroup Polygonal_Objects - */ - virtual const MbCollection & GetSimplifiedMesh() = 0; - - /** \brief \ru Получить сегментированную копию входной полигональной сетки. - \en Get segmented copy of the input mesh. \~ - \details \ru Получить сегменитрованную копию входной сетки, на которой выполняются операции MbMeshProcessor: - подсчет кривизн, сегментация, построение оболочки. - Сегментация доступна внутри коллекции. \n - \en Get segmented copy of the input mesh. All further operations of MbMehsProcessor are - performed for simplified mesh: curvature calculation, segmentation, shell creation. - Segmentation is stored inside collection. \n \~ - \return \ru Возвращает сегментированную версию входной полигональной сетки. - \en Returns a segmented version of the input mesh. \~ - \ingroup Polygonal_Objects - */ - virtual const MbCollection & GetSegmentedMesh() = 0; - - /** \brief \ru Рассчитать главные кривизны и главные направления изменения кривизн в точках сетки. - \en Calculate the principal curvatures and principal curvature directions at mesh points. \~ - \details \ru Рассчитать главные кривизны и главные направления изменения кривизн в точках сетки. \n - \en Calculate the principal curvatures and principal curvature directions at mesh points. \n \~ - \return \ru Возвращает главные кривизны и главные направления в точках сетки. - \en Returns principal curvatures and principal curvature directions at mesh points. \~ - \ingroup Polygonal_Objects - */ - virtual const std::vector & CalculateCurvatures() = 0; - - /** \brief \ru Сегментровать полигональную сетку. - \en Segment a polygonal mesh. \~ - \details \ru Выполнить сегментацию полигональной сетки. \n - \en Perform segmentation of a polygonal mesh. \n \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \param[in] createSurfaces - \ru Создавать ли поверхности на сегментах. - \en Create surfaces on segments or not. \~ - \ingroup Polygonal_Objects - */ - virtual MbResultType SegmentMesh( bool createSurfaces = true ) = 0; - - /** \brief \ru Создать оболочку. - \en Create shell. \~ - \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. - Используется текущая сегментация. - Если сегментация не была вычислена, но вычисляется автоматическая сегментация (с параметрами по умолчанию). \n - \en Create BRep shell that represents input mesh model. - Current segmentation is used. - If segmentation is not computed yet, then automatic segmentation is performed (with default paramters). \n \~ - \param[out] pShell - \ru Указатель на созданную оболочку. - \en The pointer to created shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects - */ - virtual MbResultType CreateBRepShell( MbFaceShell *& pShell ) = 0; - - /** \brief \ru Вписать поверхность. - \en Fit surface to segment . \~ - \details \ru Распознать поверхность по сегменту сетки с заданным индексом. - Распознанная поверхность может быть получена с помощью метода GetSegmentSurface. \n - \en Recognize surface for mesh segment with a given index. - Recognized surface is available through GetSegmentSurface method. \n \~ - \param[in] idxSegment - \ru Индекс сегмента полигональной сетки. - \en Index of a mesh segment. \~ - \ingroup Polygonal_Objects - */ - virtual void FitSurfaceToSegment( size_t idxSegment ) = 0; - - /** \brief \ru Вписать поверхность заданного типа. - \en Fit surface of a given type to a segment. \~ - \details \ru Построить поверхность заданного типа, аппроксимирующиую сегмент сетки с заданным индексом. - Распознанная поверхность может быть получена с помощью метода GetSegmentSurface. \n - \en Find surface of a given type approximating mesh segment with a given index. - Recognized surface is available through GetSegmentSurface method. \n \~ - \param[in] idxSegment - \ru Индекс сегмента полигональной сетки. - \en Index of a mesh segment. \~ - \param[in] surfaceType - \ru Тип вписываемой поверхности. - \en Type of fitted surface. \~ - \ingroup Polygonal_Objects - */ - virtual void FitSurfaceToSegment( size_t idxSegment, MbeSpaceType surfaceType ) = 0; - - /** \brief \ru Получить поверхность для сегмента. - \en Get surface of segment. \~ - \details \ru Получить поверхность, вписанную в сегмент. - Чтобы поверхность была определена предварительно должны быть вызваны методы - SegmentMesh или FitSurfaceToSegment. - Распознанная поверхность с помощью метода GetSegmentSurface. \n - \en Get surface that approximates segment. - 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. \~ - \ingroup Polygonal_Objects - */ - virtual const MbSurface * GetSegmentSurface( size_t idxSegment ) const = 0; - - /** \brief \ru Очистить сегментацию полигональной сетки. - \en Reset segmentation of the polygonal mesh. \~ - \details \ru Очистить сегментацию полигональной сетки, хранящуюся внутри MbMeshProcessor. \n - \en Reset segmentation of the polygonal mesh stored inside MbMeshProcessor. \n \~ - \ingroup Polygonal_Objects - */ - virtual void ResetSegmentation() = 0; - - /** \brief \ru Найти ближайший путь между двумя вершинами коллекции. - \en Find shortest path between two vertices. \~ - \details \ru Найти ближайший путь, проходящий по вершинам и ребрам коллекции, соединяющий две заданные вершины. \n - \en Find shortest path between two vertices. The path should pass through collection vertices and edges. \n \~ - \param[in] v1 - \ru Индекс первой вершины. - \en The index of first vertex. \~ - \param[in] v2 - \ru Индекс второй вершины. - \en The index of second vertex. \~ - \param[out] path - \ru Путь из первой вершины во вторую. - Массив содержит последовательные индексы всех вершин пути. - \en The path from the first vertex to the second one. - The array contains successive indices of path vertices. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects - */ - virtual bool FindShortestVertexPath( uint v1, uint v2, std::vector & path ) = 0; - -private: // UNDER DEVELOPMENT - /** \} */ - /** \ru \name Функции для работы с разбиением сетки на сегменты и распознаванием поверхностей для сегментов. - \en \name Functions for editting of mesh segmentation and reconstruction of surfaces for the segments. - \{ */ - - /** \brief \ru Объединить два сегмента в текущей сегментации. - \en Unite two segments in current segmentation. \~ - \details \ru Объединение сегментов в текущей сегментации. - Результат объединения доступен через коллекцию, возвращаемую методом GetSegmentedMesh. \n - \en Union of segments in current mesh segmentation. - Result segmentation is available through collection returned by GetSegmentedMesh. \n \~ - \param[in] firstSegmentIdx - \ru Индекс первого сегмента для объединения. \n - \en Index of the first segment for union. \~ - \param[in] secondSegmentIdx - \ru Индекс второго сегмента для объединения. \n - \en Index of the second segment for union. \~ - \ingroup Polygonal_Objects - */ - virtual void UniteSegments( size_t firstSegmentIdx, size_t secondSegmentIdx ) = 0; - - /** \brief \ru Сегментровать полигональную сетку по разделителям сегментов. - \en Segment a polygonal mesh by segment separators. \~ - \details \ru Выполнить сегментацию полигональной сетки по заданным разделителям сегментов. \n - \en Perform segmentation of a polygonal mesh by segment separators. \n \~ - \param[in] separators - \ru Массив разделителей. - Каждый разделитель содержит путь по вершинам сетки, ребра которого разделяют сегменты. - \en The array of segment separators. - Each separator contains a path by mesh vertices. Edges of that path split mesh to segments. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects - */ - virtual MbResultType SegmentMeshBySeparators( const std::vector> & separators ) = 0; - - OBVIOUS_PRIVATE_COPY( MbMeshProcessor ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать оболочку по полигональной сетке c автоматическим распознаванием поверхностей. - \en Create shell from mesh with automatic surface reconstruction. \~ - \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. - Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным - поверхностям (плоскость, цилиндр, сфера, конус, тор). \n - \en Create BRep shell that represents input mesh model. - Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ - \param[in] mesh - \ru Входная сетка. - \en The input mesh. \~ - \param[out] shell - \ru Указатель на созданную оболочку. - \en The pointer to created shell. \~ - \param[in] params - \ru Параметры построения оболочки тела. - \en Parameters of BRep shell construction. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC( MbResultType ) ConvertMeshToShell( MbMesh & mesh, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать оболочку по коллекции, содержащей полигональную сетку c автоматическим распознаванием поверхностей. - \en Create shell from collection with automatic surface reconstruction. \~ - \details \ru Создать оболочку в граничном представлении, соответствующую модели, заданной полигональной сеткой. - Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным - поверхностям (плоскость, цилиндр, сфера, конус, тор). \n - \en Create BRep shell that represents input mesh model from collection. - Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ - \param[in] collection - \ru Коллекция, содержащая входную сетку. - \en The input collection. \~ - \param[out] shell - \ru Указатель на созданную оболочку. - \en The pointer to created shell. \~ - \param[in] params - \ru Параметры построения оболочки тела. - \en Parameters of BRep shell construction. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC( MbResultType ) ConvertCollectionToShell( MbCollection & collection, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); - -#endif // __ACTION_B_SHAPER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы преобразования полигональных геометрических объектов в объекты BRep. + \en Functions for conversion of the polygonal geometric object to BRep objects. \~ + \details \ru Методы преобразования полигональных геометрических объектов в объекты BRep. + \en Functions for conversion of the polygonal geometric object to BRep objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_B_SHAPER_H +#define __ACTION_B_SHAPER_H + + +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbMesh; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFace; +class MATH_CLASS MbCollection; + + +//------------------------------------------------------------------------------ +/** \brief \ru Режим распознавания поверхностей. + \en Surface reconstruction mode. \~ + \details \ru Режим распознавания поверхностей. + \en Surface reconstruction mode. \~ + \ingroup Polygonal_Objects +*/ +// --- +enum MbeSurfReconstructMode +{ + srm_All = 0, ///< \ru Строить все поверхности. \en Build all surfaces. + srm_NoGrids = 1, ///< \ru Не строить поверхности на базе триангуляции. \en Not build surfaces based on triangulation. + srm_CanonicOnly = 2, ///< \ru Строить только элементарные поверхности. \en Build elementary surfaces only. + srm_Default = srm_NoGrids ///< \ru Режим по умолчанию. \en Default mode. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Режим построения модели BRep. + \en BRep creation mode. \~ + \details \ru Режим построения модели BRep. + \en BRep creation mode. \~ + \ingroup Polygonal_Objects +*/ +// --- +enum MbeCreateBRepMode +{ + cbm_Strict = 0, ///< \ru Соседние грани пересекаются по общей кривой. \en Adjancent faces have a common edge. + cbm_Weak = 1, ///< \ru Все ребра каждой из граней - граничные. \en All edges of each face are a boundary edges. + cbm_Default = cbm_Strict ///< \ru Режим по умолчанию. \en Default mode. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры построения оболочки тела по полигональной сетке. + \en Parameters of BRep shell construction from polygonal mesh. \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbMeshProcessorValues { +public: + + /** \brief \ru Использовать относительную точность (true). + \en Use relative tolerance (true). \~ + \details \ru При использовании относительной точности отклонение граней тела от сетки проверяется относительно размера модели. + \en While use of relative tolerance distance from shell to mesh is checked relative to model size. \~ + */ + bool useRelativeTolerance; + + /** \brief \ru Флаг сглаживания краевых ребер. + \en Smoothing flag of boundary edges. \~ + \details \ru Сглаживать краевые ребра результирующей оболочки или строить их кусочно-линейными. + \en Smooth boundary edges of the resultant shell or build them piecewise linear. \~ + */ + bool smoothBoundaryEdges; + + /** \brief \ru Предельное значение угла между соседними внешними ребрами сетки в радианах. + \en The treshold value of angle between two adjanced external edges of mesh (in radians). \~ + \details \ru Предельное значение угла между соседними ребрами сетки используется при построении граничных ребер оболочки: граничные ребра оболочки + будут разделяться в вершинах, где наименьший угол между соседними внешними ребрами сетки менее данного предельного. + \en The treshold value of angle between two adjanced edges of mesh is used for building boundary edges of the shell: + boundary edge will be divied at the vertices at which minimum angle between two adjanced edges of mesh is less + then a given treshold value. \~ + */ + double bAngle; + + /** \brief \ru Точность. + \en Tolerance. \~ + \details \ru Точность работы метода: допустимое отклонение граней тела от вершин сетки. + \en Tolerance: maximum distance from BRep faces to mesh vertices. \~ + */ + double tolerance; + + /** \brief \ru Режим распознавания поверхностей. + \en Surface reconstruction mode. \~ + */ + MbeSurfReconstructMode surfReconstructMode; + + /** \brief \ru Режим построения модели BRep. + \en BRep creation mode. \~ + */ + MbeCreateBRepMode brepCreationMode; + + /// \ru Конструктор по умолчанию. \en Default constructor. + explicit MbMeshProcessorValues( bool useRelTol = true, + bool smoothBoundary = true, + double tol = 0.01, + double angle = M_PI_2, + MbeSurfReconstructMode reconMode = srm_Default, + MbeCreateBRepMode bMode = cbm_Default ) + : useRelativeTolerance( useRelTol ) + , smoothBoundaryEdges ( smoothBoundary ) + , tolerance ( tol ) + , bAngle ( angle ) + , surfReconstructMode ( reconMode ) + , brepCreationMode ( bMode ) + {} +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Класс для создания оболочки в граничном представлении по полигональной сетке. + \en Class for creating a BRep shell by polygonal mesh. \~ + \details \ru Предоставить интерфейс для управления преобразованием сетки в + оболочку в граничном представлении. \n + \en Provide an interface for managing of "Mesh to BRep" conversion. \n \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbMeshProcessor : public MbRefItem +{ +protected: + /// \ru Конструктор. \en Constructor. + MbMeshProcessor(); + +public: + /** \brief \ru Создать экземпляр процессора по коллекции. + \en Create mesh processor by collection. \~ + \details \ru Создать экземпляр процессора по коллекции. Пользователь должен сам удалить объект. + \en Create mesh processor by collection. User must delete created object. \~ + \param[in] collection - \ru Входная коллекция, содержащая треугольную сетку. \n + \en Input collection containing triangle mesh. \~ + \return \ru Возвращает указатель на созданный объект. + \en Returns pointer to created object. \~ + \ingroup Polygonal_Objects + */ + static MbMeshProcessor * Create( const MbCollection & collection ); + + /// \ru Деструктор. \en Destructor. + virtual ~MbMeshProcessor(); + + /** \brief \ru Установить относительную точность. + \en Set relative tolerance. \~ + \details \ru Установить относительную точность по габаритам текущей сетки. + \en Set relative tolerance by current mesh box. \~ + \param[in] tolerance - \ru Относительная точность. \n + \en Relative tolerance to set. \~ + \ingroup Polygonal_Objects + */ + virtual void SetRelativeTolerance( double tolerance ) = 0; + + /** \brief \ru Установить точность. + \en Set tolerance. \~ + \details \ru Установить точность распознавания поверхностей и расширения сегментов сетки. + Метод должен быть вызван перед вызовом SegmentMesh. + Точность по умолчанию равна 0.1. + \en Set tolerance of surface reconstruction and segments extension. + Method should be called before call to SegmentMesh. + Default tolerance is 0.1. \n \~ + \param[in] tolerance - \ru Точность. \n + \en Tolerance to set. \~ + \ingroup Polygonal_Objects + */ + virtual void SetTolerance( double tolerance ) = 0; + + /** \brief \ru Получить точность. + \en Get tolerance. \~ + \details \ru Получить текущую точность, используемую при распознавании поверхностей и расширения сегментов сетки. + \en Get current tolerance used in surface reconstruction and segments extension. \~ + \return \ru Возвращает абсолютную точность. + \en Returns absolute tolerance. \~ + \ingroup Polygonal_Objects + */ + virtual double GetTolerance() const = 0; + + //------------------------------------------------------------------------------ + /** \brief \ru Установить режим распознавания поверхностей. + \en Set the surfaces reconstruction mode. \~ + \details \ru Задать типы поверхностей, генерируемых на сегментах. Поверхности неподдерживаемых типов строиться не будут. \n + \en Set types of surfaces which will be generated on segments. The surfaces of unsupoprted type will not be built. \n \~ + \param[in] mode - \ru Режим распознавания поверхностей. + \en Surface reconstruction mode. + \ingroup Polygonal_Objects + */ + virtual void SetReconstructionMode( MbeSurfReconstructMode mode ) = 0; + + + //------------------------------------------------------------------------------ + /** \brief \ru Установить режим построения модели BRep. + \en Set the BRep creation mode. \~ + \details \ru Задать степень связности граней в результирующей модели BRep. \n + \en Set connectivity type of faces of resultant BRep model. \n \~ + \param[in] mode - \ru Режим построения модели BRep. + \en BRep creation mode. + \ingroup Polygonal_Objects + */ + virtual void SetBrepCreationMode( MbeCreateBRepMode mode ) = 0; + + //------------------------------------------------------------------------------ + /** \brief \ru Установить флаг сглаживания входной сетки. + \en Set flag to use smoothing of input mesh. \~ + \details \ru Установить флаг сглаживания входной сетки. Если флаг установлен в true, + то перед запуском основного алгоритма сегментации будет выполнено сглаживание входной сетки. + Рекомендуется использовать сглаживание на неточных сетках, например, полученных методом сканирования. \n + \en Set flag to use smoothing of input mesh. If the flag set to true, then run smoothing of input mesh + before main segmentation algorithm start. + It is recommended to use mesh smoothing on inexact meshes, e.g. meshes obtained by scanning. \n \~ + \param[in] useSmoothing - \ru Флаг использования сглаживания входной сетки. По-умолчанию false. + \en The flag to use smoothing of input mesh. Default false. + \ingroup Polygonal_Objects + */ + // --- + virtual void SetUseMeshSmoothing( bool useSmoothing ) = 0; + + /** \brief \ru Получить исправленную (упрощенную) копию входной полигональной сетки. + \en Get fixed (simplified) copy of the input mesh. \~ + \details \ru Получить исправленную копию входной сетки, на которой выполняются операции MbMeshProcessor: + подсчет кривизн, сегментация, построение оболочки. Все индексы в выходных данных соответствуют + индексам вершин и треугольников упрощенной сетки, возвращаемой данным методом. \n + \en Get fixed copy of the input mesh. All further operations of MbMehsProcessor are + performed for simplified mesh: curvature calculation, segmentation, shell creation. + All indices in the output of these operations corresponds to indices of vertices and + triangles of the simplified mesh returned from this function. \n \~ + \return \ru Возвращает исправленную версию входной полигональной сетки. + \en Returns a fixed version of the input mesh. \~ + \ingroup Polygonal_Objects + */ + virtual const MbCollection & GetSimplifiedMesh() = 0; + + /** \brief \ru Получить сегментированную копию входной полигональной сетки. + \en Get segmented copy of the input mesh. \~ + \details \ru Получить сегменитрованную копию входной сетки, на которой выполняются операции MbMeshProcessor: + подсчет кривизн, сегментация, построение оболочки. + Сегментация доступна внутри коллекции. \n + \en Get segmented copy of the input mesh. All further operations of MbMehsProcessor are + performed for simplified mesh: curvature calculation, segmentation, shell creation. + Segmentation is stored inside collection. \n \~ + \return \ru Возвращает сегментированную версию входной полигональной сетки. + \en Returns a segmented version of the input mesh. \~ + \ingroup Polygonal_Objects + */ + virtual const MbCollection & GetSegmentedMesh() = 0; + + /** \brief \ru Рассчитать главные кривизны и главные направления изменения кривизн в точках сетки. + \en Calculate the principal curvatures and principal curvature directions at mesh points. \~ + \details \ru Рассчитать главные кривизны и главные направления изменения кривизн в точках сетки. \n + \en Calculate the principal curvatures and principal curvature directions at mesh points. \n \~ + \return \ru Возвращает главные кривизны и главные направления в точках сетки. + \en Returns principal curvatures and principal curvature directions at mesh points. \~ + \ingroup Polygonal_Objects + */ + virtual const std::vector & CalculateCurvatures() = 0; + + /** \brief \ru Сегментровать полигональную сетку. + \en Segment a polygonal mesh. \~ + \details \ru Выполнить сегментацию полигональной сетки. \n + \en Perform segmentation of a polygonal mesh. \n \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \param[in] createSurfaces - \ru Создавать ли поверхности на сегментах. + \en Create surfaces on segments or not. \~ + \ingroup Polygonal_Objects + */ + virtual MbResultType SegmentMesh( bool createSurfaces = true ) = 0; + + /** \brief \ru Создать оболочку. + \en Create shell. \~ + \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. + Используется текущая сегментация. + Если сегментация не была вычислена, то вычисляется автоматическая сегментация (с параметрами по умолчанию). \n + \en Create BRep shell that represents input mesh model. + Current segmentation is used. + If segmentation is not computed yet, then automatic segmentation is performed (with default paramters). \n \~ + \param[out] pShell - \ru Указатель на созданную оболочку. + \en The pointer to created shell. \~ + \param[in] smoothBoundaryEdges - \ru Флаг сглаживания краевых ребер. + \en Smoothing flag of boundary edges. \~ + \param[in] bondThresholdAngle - \ru Предельное значение угла между соседними внешними ребрами сетки в радианах. + \en The treshold value of angle between two adjanced external edges of mesh (in radians). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects + */ + virtual MbResultType CreateBRepShell( MbFaceShell *& pShell, bool smoothBoundaryEdges, double bondThresholdAngle ) = 0; + + /** \brief \ru Вписать поверхность. + \en Fit surface to segment . \~ + \details \ru Распознать поверхность по сегменту сетки с заданным индексом. + Распознанная поверхность может быть получена с помощью метода GetSegmentSurface. \n + \en Recognize surface for mesh segment with a given index. + Recognized surface is available through GetSegmentSurface method. \n \~ + \param[in] idxSegment - \ru Индекс сегмента полигональной сетки. + \en Index of a mesh segment. \~ + \ingroup Polygonal_Objects + */ + virtual void FitSurfaceToSegment( size_t idxSegment ) = 0; + + /** \brief \ru Вписать поверхность заданного типа. + \en Fit surface of a given type to a segment. \~ + \details \ru Построить поверхность заданного типа, аппроксимирующиую сегмент сетки с заданным индексом. + Распознанная поверхность может быть получена с помощью метода GetSegmentSurface. \n + \en Find surface of a given type approximating mesh segment with a given index. + Recognized surface is available through GetSegmentSurface method. \n \~ + \param[in] idxSegment - \ru Индекс сегмента полигональной сетки. + \en Index of a mesh segment. \~ + \param[in] surfaceType - \ru Тип вписываемой поверхности. + \en Type of fitted surface. \~ + \ingroup Polygonal_Objects + */ + virtual void FitSurfaceToSegment( size_t idxSegment, MbeSpaceType surfaceType ) = 0; + + /** \brief \ru Получить поверхность для сегмента. + \en Get surface of segment. \~ + \details \ru Получить поверхность, вписанную в сегмент. + Чтобы поверхность была определена предварительно должны быть вызваны методы + SegmentMesh или FitSurfaceToSegment. + Распознанная поверхность с помощью метода GetSegmentSurface. \n + \en Get surface that approximates segment. + 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. \~ + \ingroup Polygonal_Objects + */ + virtual const MbSurface * GetSegmentSurface( size_t idxSegment ) const = 0; + + /** \brief \ru Очистить сегментацию полигональной сетки. + \en Reset segmentation of the polygonal mesh. \~ + \details \ru Очистить сегментацию полигональной сетки, хранящуюся внутри MbMeshProcessor. \n + \en Reset segmentation of the polygonal mesh stored inside MbMeshProcessor. \n \~ + \ingroup Polygonal_Objects + */ + virtual void ResetSegmentation() = 0; + + /** \brief \ru Найти ближайший путь между двумя вершинами коллекции. + \en Find shortest path between two vertices. \~ + \details \ru Найти ближайший путь, проходящий по вершинам и ребрам коллекции, соединяющий две заданные вершины. \n + \en Find shortest path between two vertices. The path should pass through collection vertices and edges. \n \~ + \param[in] v1 - \ru Индекс первой вершины. + \en The index of first vertex. \~ + \param[in] v2 - \ru Индекс второй вершины. + \en The index of second vertex. \~ + \param[out] path - \ru Путь из первой вершины во вторую. + Массив содержит последовательные индексы всех вершин пути. + \en The path from the first vertex to the second one. + The array contains successive indices of path vertices. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects + */ + virtual bool FindShortestVertexPath( uint v1, uint v2, std::vector & path ) = 0; + +private: // UNDER DEVELOPMENT + /** \} */ + /** \ru \name Функции для работы с разбиением сетки на сегменты и распознаванием поверхностей для сегментов. + \en \name Functions for editting of mesh segmentation and reconstruction of surfaces for the segments. + \{ */ + + /** \brief \ru Объединить два сегмента в текущей сегментации. + \en Unite two segments in current segmentation. \~ + \details \ru Объединение сегментов в текущей сегментации. + Результат объединения доступен через коллекцию, возвращаемую методом GetSegmentedMesh. \n + \en Union of segments in current mesh segmentation. + Result segmentation is available through collection returned by GetSegmentedMesh. \n \~ + \param[in] firstSegmentIdx - \ru Индекс первого сегмента для объединения. \n + \en Index of the first segment for union. \~ + \param[in] secondSegmentIdx - \ru Индекс второго сегмента для объединения. \n + \en Index of the second segment for union. \~ + \ingroup Polygonal_Objects + */ + virtual void UniteSegments( size_t firstSegmentIdx, size_t secondSegmentIdx ) = 0; + + /** \brief \ru Сегментровать полигональную сетку по разделителям сегментов. + \en Segment a polygonal mesh by segment separators. \~ + \details \ru Выполнить сегментацию полигональной сетки по заданным разделителям сегментов. \n + \en Perform segmentation of a polygonal mesh by segment separators. \n \~ + \param[in] separators - \ru Массив разделителей. + Каждый разделитель содержит путь по вершинам сетки, ребра которого разделяют сегменты. + \en The array of segment separators. + Each separator contains a path by mesh vertices. Edges of that path split mesh to segments. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects + */ + virtual MbResultType SegmentMeshBySeparators( const std::vector> & separators ) = 0; + + OBVIOUS_PRIVATE_COPY( MbMeshProcessor ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать оболочку по полигональной сетке c автоматическим распознаванием поверхностей. + \en Create shell from mesh with automatic surface reconstruction. \~ + \details \ru Создать оболочку в граничном представлении, соответствующее модели, заданной полигональной сеткой. + Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным + поверхностям (плоскость, цилиндр, сфера, конус, тор). \n + \en Create BRep shell that represents input mesh model. + Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ + \param[in] mesh - \ru Входная сетка. + \en The input mesh. \~ + \param[out] shell - \ru Указатель на созданную оболочку. + \en The pointer to created shell. \~ + \param[in] params - \ru Параметры построения оболочки тела. + \en Parameters of BRep shell construction. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC( MbResultType ) ConvertMeshToShell( MbMesh & mesh, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать оболочку по коллекции, содержащей полигональную сетку c автоматическим распознаванием поверхностей. + \en Create shell from collection with automatic surface reconstruction. \~ + \details \ru Создать оболочку в граничном представлении, соответствующую модели, заданной полигональной сеткой. + Алгоритм в автоматическом режиме распознает и реконструирует грани, соответствующие элементарным + поверхностям (плоскость, цилиндр, сфера, конус, тор). \n + \en Create BRep shell that represents input mesh model from collection. + Algorithm automatically detect and reconstruct faces based on elementary surfaces (plane, cylinder, sphere, cone, torus). \n \~ + \param[in] collection - \ru Коллекция, содержащая входную сетку. + \en The input collection. \~ + \param[out] shell - \ru Указатель на созданную оболочку. + \en The pointer to created shell. \~ + \param[in] params - \ru Параметры построения оболочки тела. + \en Parameters of BRep shell construction. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC( MbResultType ) ConvertCollectionToShell( MbCollection & collection, MbFaceShell *& shell, const MbMeshProcessorValues & params = MbMeshProcessorValues() ); + +#endif // __ACTION_B_SHAPER_H diff --git a/C3d/Include/action_curve.h b/C3d/Include/action_curve.h index 8d4af22..312d158 100644 --- a/C3d/Include/action_curve.h +++ b/C3d/Include/action_curve.h @@ -1,757 +1,764 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения двумерных кривых. - \en Functions for two-dimensional curves construction. \~ - \details \ru Двумерные кривые могут быть построены с помощью аналитических функций, - по набору точек, на базе других двумерных кривых. - \en Two-dimensional curves can be constructed using analytical functions, - for a point set or on the basis of other two-dimensional curves. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_CURVE_H -#define __ACTION_CURVE_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbCurve; -class MATH_CLASS MbContour; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbFace; - - -//------------------------------------------------------------------------------ -/** \brief \ru Перечисление способов создания эллипса (окружности) или их дуг в двумерном пространстве. - \en Enumeration of ways to create an ellipse (circle) or their arcs in two-dimensional space. \~ -\ingroup Curve_Modeling -*/ -// --- -enum MbeArcCreateWay -{ - /** - \ru Окружность по центру и радиусу, задается 'center' и радиус в 'c'. - \en Circle by center and radius, set the 'center' and radius in 'c'. - */ - acw_CircleByCenterAndRadius, - - /** - \ru Дуга окружности по центру и двум точкам. - Задается: 'center', две точки в 'points', направление в 'option' (true - по часовой стрелке). - Возвращается: начальный угол дуги в 'а', конечный угол в 'b', радиус в 'c'. - \en Circular arc by center and two points. - Set: 'center', two points in 'points', direction in 'option' (true - clockwise direction). - Return: start angle in 'a', end in 'b', radius in 'c'. - */ - acw_ArcByCenterAnd2Points, - - /** - \ru Дуга окружности по центру и двум углам. - Задается: 'center', начальный угол в 'a', конечный в 'b', радиус в 'c', - направление в 'option' (true - по часовой стрелке). Углы задаются в радианах. - \en Circular arc by center and two angles, - Set: 'center', start angle in 'a', end in 'b', radius in 'c', - direction in 'option' (true - clockwise direction). The angles are given in radians. - */ - acw_ArcByCenterAnd2Angles, - /** - \ru Дуга окружности по трем точкам, заданным в 'points', точки points[0] и points[2] конечные. - Возвращается: начальный угол дуги в 'а', конечный угол в 'b', радиус в 'c'. - \en Circular arc by three points specified in 'points', points[0] and points[2] are the end point. - Return: start angle in 'a', end in 'b', radius in 'c'. - */ - acw_ArcBy3Points, - - /** - \ru Эллипс с заданными полуосями и углом наклона. - Задается 'center', X полуось в 'a', Y полуось в 'b', угол наклона в 'с'. Угол задается в радианах. - \en Ellipse by semiaxes and angle. - Set : 'center', X semiaxis in 'a', Y semiaxis in 'b', angle in 'c'. The angle are given in radians. - */ - acw_EllipseByCenterAndSemiaxis, - - /** - \ru Эллипс по центру и трем точкам на нем. - Задается 'center' и 3 точки в 'points'. - Возвращаются: X полуось в 'a', Y полуось в 'b', угол наклона в 'с'. Угол задается в радианах. - \en Ellipse by centre and three points on ellipse. - Set: 'center', 3 points in 'points'. - Return: X semiaxis in 'a', Y semiaxis in 'b', angle in 'c'. The angle are given in radians. - */ - acw_EllipseByCenterAnd3Points, - - /** - \ru Дуга эллипса, обрезанная двумя лучами из центра к заданным точкам. - Задается 'center' и 2 точки в 'points', X полуось в 'a', Y полуось в 'b', угол наклона в 'с', - направление в 'option' (true - по часовой стрелке). Угол задается в радианах. - \en Elliptical arc is trimmed by two rays, starting from the center and passing through points. - Set: 'center', 2 points in 'points', X semiaxis in 'a', Y semiaxis in 'b', angle in 'c', - direction in 'option' (true - clockwise direction). The angle are given in radians. - */ - acw_EArcByCenterAnd2Points -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Создать прямую. - \en Create a line. \~ - \details \ru Создать прямую по двум точкам. \n - \en Create a line given two points. \n \~ - \param[in] point1 - \ru Первая точка. - \en The first point. \~ - \param[in] point2 - \ru Вторая точка. - \en The second point. \~ - \param[out] result - \ru Прямая. - \en The line. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbResultType) Line( const MbCartPoint & point1, - const MbCartPoint & point2, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать отрезок прямой. - \en Create a line segment. \~ - \details \ru Создать отрезок прямой по двум точкам. \n - \en Create a line segment given two points. \n \~ - \param[in] point1 - \ru Первая точка. - \en The first point. \~ - \param[in] point2 - \ru Вторая точка. - \en The second point. \~ - \param[out] result - \ru Отрезок. - \en The segment. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbResultType) Segment( const MbCartPoint & point1, - const MbCartPoint & point2, - MbCurve *& result ); - - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эллипс (окружность) или его дугу указанным способом. - \en Create an ellipse (circle) or an elliptical (circular) arc in the specified way. \~ -\details \ru Создать эллипс (окружность) или его дугу указанным способом.\n Входные параметры интерпретируются в соответствии с выбранным путем создания. - \en Create an ellipse (circle) or an elliptical (circular) arc in the specified way. \n The input parameters are interpreted according to the selected create way. -\param[in] createWay - \ru Способ создания. Определяет как интерпретировать входные параметры. - \en Create way. Defines how to interpret the input parameters.\~ -\param[in] center - \ru Центр - \en Сenter. \~ -\param[in] points - \ru Конечные точки или точки через которые проходит кривая. - \en Endpoints or points through which the curve passes. \~ -\param[in,out] a - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay - \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ -\param[in,out] b - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay - \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ -\param[in,out] с - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay - \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ -\param[in] option - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay - \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ -\param[out] result - \ru Эллипс (окружность) или его дуга. - \en The ellipse (circle) or the elliptical (circular) arc. \~ -\return \ru Возвращает код результата операции. - \en Returns operation result code. \~ -\ingroup Curve_Modeling -*/ -//--- - -MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, - const MbCartPoint & center, - const std::vector & points, - double & a, double & b, double & c, - bool option, - MbCurve *& result ); - -//------------------------------------------------------------------------------ -/**\attention \ru Функция устарела. Вместо неё применять #Arc. - \en The function is deprecated. Use #Arc instead. \~ -\ingroup Curve_Modeling -*/ -// 2018 -//--- -MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, - const SArray & points, - bool curveClosed, double angle, - double & a, double & b, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую, проходящую по набору точек. - \en Create a curve passing through a set of points. \~ - \details \ru Создать кривую, проходящую по набору точек, следующего типа: \n - - curveType == pt_LineSegment - отрезок, \n - - curveType == pt_Arc - окружность или дуга, \n - - curveType == pt_Polyline - ломаная, \n - - curveType == pt_Bezier - кривая Безье, \n - - curveType == pt_CubicSpline - кубический сплайн, \n - - curveType == pt_Hermit - составной кубический сплайн Эрмита, \n - - curveType == pt_Nurbs - неоднородный рациональный B-сплайн четвертого порядка (кубический). \n - \en Create a curve passing through a set of points that has the following type: \n - - curveType == pt_LineSegment - a line segment, \n - - curveType == pt_Arc - a circle or an arc, \n - - curveType == pt_Polyline - a polyline, \n - - curveType == pt_Bezier - a Bezier curve, \n - - curveType == pt_CubicSpline - a cubic spline, \n - - curveType == pt_Hermit - a cubic Hermite spline, \n - - curveType == pt_Nurbs - a nonuniform rational B-spline of fourth order (cubic). \n \~ - \param[in] pointList - \ru Набор точек. - \en A point set. \~ - \param[in] curveClosed - \ru Замкнутость кривой. - \en A curve closedness. \~ - \param[in] curveType - \ru Тип кривой. - \en A curve type. \~ - \param[out] result - \ru Кривая. - \en The curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, - bool curveClosed, MbePlaneType curveType, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать NURBS-кривую. - \en Create a NURBS-curve. \~ - \details \ru Создать NURBS-кривую, построенную по набору контрольных точек. \n - Контейнер weightList может быть пустым. \n - Контейнер knotList может быть пустым. \n - \en Create a NURBS-curve given a sequence of control points. \n - Container 'weightList' can be empty. \n - Container 'knotList' can be empty. \n \~ - \param[in] pointList - \ru Множество точек. - \en An array of points. \~ - \param[in] weightList - \ru Множество весов. - \en An array of weights. \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline degree. \~ - \param[in] knotList - \ru Множество параметрических узлов (Узловой вектор). - \en An array of parametric knots (A knot vector). \~ - \param[in] curveClosed - \ru Замкнутость кривой. - \en A curve closedness. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, - const SArray & weightList, size_t degree, - const SArray & knotList, bool curveClosed, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать копию кривой в виде NURBS. - \en Create a copy of a curve as a NURBS-curve. \~ - \details \ru Создать копию кривой в виде NURBS. \n - \en Create a copy of a curve as a NURBS-curve. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] result - \ru Сплайновая копия кривой. - \en The spline copy of the curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) NurbsCopy( const MbCurve & curve, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать правильный многоугольник, вписанный в окружность или описанный вокруг окружности. - \en Create a regular polygon inscribed in a circle or circumscribed around a circle. \~ - \details \ru Создать правильный многоугольник, вписанный в окружность (describe == false) или - описанный вокруг окружности (describe == true) с центром centre, проходящей через point: \n - - при vertexCount == 0 строится окружность с центром centre, проходящая через point, \n - - при vertexCount == 1 строится отрезок c крайними точками centre и point, \n - - при vertexCount == 2 строится прямоугольник со сторонами, параллельными глобальным осям и противоположными вершинами в centre и point, \n - - при vertexCount >= 3 строится правильный многоугольник с заданным числом сторон, - вписанный в окружность (describe == false) или описанный вокруг окружности (describe == true) с центром centre, проходящей через point: \n - \en Create a regular polygon inscribed in a circle (describe == false) or - circumscribed around a circle (describe == true) with the specified centre and passing through the given point: \n - - if vertexCount == 0, a circle with center 'center' passing through 'point' is created, \n - - if vertexCount == 1, a line segment with end points at 'centre' and 'point' is created, \n - - if vertexCount, == 2 a rectangle aligned with the global axes with the opposite vertices at points 'centre' and 'point' is created, \n - - if vertexCount >= 3, a regular polygon is created with a given number of sides, - inscribed in a circle (describe == false) or circumscribed around a circle (describe == true) with the specified centre and passing through the given point: \n \~ - \param[in] centre - \ru Центр фигуры. - \en A figure centre. \~ - \param[in] point - \ru Точка для построения. - \en A point for the curve construction. \~ - \param[in] vertexCount - \ru Количество вершин правильного многоугольника. - \en The number of vertices of a regular polygon. \~ - \param[in] describe - \ru Флаг построения многоугольника: описать вокруг окружности (true), вписать в окружность (false). - \en A polygon construction flag: circumscribe the polygon around the circle, inscribe the polygon in the circle (false). \~ - \param[out] result - \ru Результат построения. - \en The curve creation result. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) RegularPolygon( const MbCartPoint & centre, - const MbCartPoint & point, - size_t vertexCount, - bool describe, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать косинусоиду. - \en Create a cosine curve. \~ - \details \ru Создать косинусоиду по точкам, фазе и длине волны. \n - \en Create a cosine curve given the points, phase and wave length. \n \~ - \param[in] point0 - \ru Начало локальной системы координат (ЛСК). - \en The origin of local coordinate system (LCS). \~ - \param[in] point1 - \ru Точка на оси X ЛСК. - \en A point on the X-axis of LCS. \~ - \param[in] point2 - \ru Точка на оси Y ЛСК. - \en A point on the Y-axis of LCS. \~ - \param[in] phase - \ru Фаза. - \en The phase. \~ - \param[in] waveLength - \ru Длина Волны. - \en The wave length. \~ - \param[out] result - \ru Косинусоида. - \en The cosine curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) Cosinusoid( const MbCartPoint & point0, - const MbCartPoint & point1, - const MbCartPoint & point2, - double phase, - double waveLength, - MbCurve *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Создать косинусоиду. - \en Create a cosine curve. \~ - \details \ru Создать косинусоиду по точкам, фазе и длине волны. \n - \en Create a cosine curve given the points, phase and wave length. \n \~ - \param[in] origin - \ru Начало локальной системы координат (ЛСК). - \en The origin of local coordinate system (LCS). \~ - \param[in] amplitude - \ru Амплитуда волны. - \en The amplitude of the wave. \~ - \param[in] waveLength - \ru Длина Волны. - \en The wave length. \~ - \param[in] wavesCount - \ru Количество волн. - \en The number of waves. \~ - \param[in] phase - \ru Фаза. - \en The phase. \~ - \param[out] result - \ru Косинусоида. - \en The cosine curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) Cosinusoid( const MbCartPoint & origin, - double amplitude, - double waveLength, - double wavesCount, - double phase, - MbCurve *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать составную кривую (контур). - \en Create a composite curve (contour). \~ - \details \ru Создать составную кривую (контур) на базе исходной кривой. \n - \en Create a composite curve (contour) on the basis of the given curve. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] result - \ru Контур на основе кривой. - \en The contour created on the basis of the curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) CreateContour( MbCurve & curve, - MbContour *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать копию кривой. - \en Create a copy of a curve. \~ - \details \ru Создать копию кривой с заменой некоторых кривых. \n - \en Create a copy of a curve with substitution of some curves. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \return \ru Возвращает модифицированную копию кривой, если получилось ее создать. - \en Returns a modified copy of the curve if it has been successfully created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать копию контура. - \en Create a copy of a contour. \~ - \details \ru Создать копию контура с заменой некоторых кривых и его модификацией по флагу. - Модификация - слияние подобных кривых и удаление вырожденных. \n - \en Create a copy of a contour with substitution of some curves and its modification according to the flag. - Modification is a merging of similar curves and deleting of degenerate ones. \n \~ - \param[in] cntr - \ru Исходный контур. - \en The initial contour. \~ - \param[in] modifySegments - \ru Флаг разрешения замены и слияния сегментов. - \en The flag determines whether segments can be replaced or merged. \~ - \param[in] names - \ru Именователь, синхронизированный с контуром. - \en An object defining the names synchronized with contour. \~ - \return \ru Возвращает модифицированнную копию контура, если получилось его создать. - \en Returns a modified copy of the contour if it has been successfully created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr, - bool modifySegments, - MbSNameMaker * names = NULL ); - - -//------------------------------------------------------------------------------ -// Создание эквидистантной кривой. -/** \brief \ru Создать эквидистантную кривую. - \en Create an offset curve. \~ - \details \ru Создать эквидистантную кривую по базовой кривой и смещению в крайних точках. \n - \en Create the offset curve for a given curve with offset in the begin and the end points. \n \~ - \param[in] curve - \ru Базовая кривая. - \en Base curve. \~ - \param[in] offset1 - \ru Смещение в точке Tmin базовой кривой. - \en Offset distance on point Tmin of base curve. \~ - \param[in] offset2 - \ru Смещение в точке Tmax базовой кривой. - \en Offset distance on point Tmax of base curve. \~ - \param[in] type - \ru Тип смещения точек: константный, линейный или кубический. - \en The offset type: constant, or linear, or cubic. \~ - \return \ru Возвращает эквидистантную кривую. - \en Returns the offset curve. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbCurve *) OffsetCurve( const MbCurve & curve, - double offset1, - double offset2, - MbeOffsetType type ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантный контур. - \en Create an offset contour. \~ - \details \ru Создать эквидистантный контур к исходному контуру. \n - \en Create the offset contour for a given contour. \n \~ - \param[in] cntr - \ru Исходный контур. - \en The initial contour. \~ - \param[in] rad - \ru Величина эквидистантного смещения. - \en The offset value. \~ - \param[in] xEpsilon - \ru Точность по x. - \en Tolerance in x direction. \~ - \param[in] yEpsilon - \ru Точность по y. - \en Tolerance in y direction. \~ - \param[in] modifySegments - \ru Флаг разрешения замены и слияния сегментов. - \en The flag determines whether segments can be replaced or merged. \~ - \param[in] version - \ru Версия исполнения. - \en The version. \~ - \return \ru Возвращает эквидистантный контур, если получилось его создать. - \en Returns the offset contour if it has been successfully created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbContour *) OffsetContour( const MbContour & cntr, - double rad, - double xEpsilon, - double yEpsilon, - bool modifySegments, - VERSION version = Math::DefaultMathVersion()/*BUG_61694*/ ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантный контур, начинающийся и оканчивающийся на оси вращения. - \en Create an offset contour with start and end points on the rotation axis. \~ - \details \ru Создать незамкнутый эквидистантный контур, начинающийся и оканчивающийся на оси вращения. \n - Cчитается, что, если контур замкнуть, то он будет ориентирован против движения часовой стрелки. \n - \en Create an open offset contour with start and end points on the rotation axis. \n - It is considered that if one closes the contour, it will be oriented counterclockwise. \n \~ - \param[in] cntr - \ru Исходный контур. - \en The initial contour. \~ - \param[in] q1 - \ru Начальная точка оси вращения. - \en The start point of the rotation axis. \~ - \param[in] q2 - \ru Конечная точка оси вращения. - \en The end point of the rotation axis. \~ - \param[in] rad - \ru Величина эквидистантного смещения. - \en The offset value. \~ - \param[in] xEpsilon - \ru Точность по x. - \en Tolerance in x direction. \~ - \param[in] yEpsilon - \ru Точность по y. - \en Tolerance in y direction. \~ - \return \ru Возвращает эквидистантный контур, если получилось его создать. - \en Returns the offset contour if it has been successfully created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbContour *) AxisOffsetOpenContour( const MbContour & cntr, - const MbCartPoint & q1, - const MbCartPoint & q2, - double rad, - double xEpsilon, - double yEpsilon ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Инициализировать кривую по новым параметрам. - \en Initialize a curve with new parameters. \~ - \details \ru Инициализировать кривую по новым параметрам. \n - \en Initialize a curve with new parameters. \n \~ - \param[in,out] curve - \ru Изменяемая кривая. - \en The curve to be modified. \~ - \param[in] t1 - \ru Новый начальный параметр. - \en A new start parameter. \~ - \param[in] t2 - \ru Новый конечный параметр. - \en A new end parameter. \~ - \param[in] eps - \ru Точность. - \en Tolerance. \~ - \return \ru Возвращает true, если получилось модифицировать кривую. - \en Returns 'true' if the curve has been successfully modified. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (bool) CurveTrim( MbCurve & curve, - double t1, - double t2, - double eps = METRIC_PRECISION ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить кривую в составную кривую (контур). - \en Add a curve to a composite curve (a contour). \~ - \details \ru Добавить кривую curve в составную кривую (контур) contour. \n - Если toEnd == true, то добавить в конец. \n - Если toEnd == false, то добавить в начало. \n - \en Add a curve to a composite curve (a contour) 'contour'. \n - If toEnd == true, the curve is to be added to the end. \n - If toEnd == true, the curve is to be added to the beginning. \n \~ - \param[in] curve - \ru Добавляемая кривая - \en A curve to be added. \~ - \param[in,out] contour - \ru Модифицируемый контур. - \en A contour to be modified. \~ - \param[in] toEnd - \ru Флаг места добавления кривой. - \en The flag determines the place of the curve in the contour. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) AddCurveToContour( MbCurve & curve, - MbContour & contour, - bool toEnd ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти пересечения кривой с плоскостью. - \en Calculate the intersections of a curve and a surface. \~ - \details \ru Найти пересечения кривой с плоскостью. \n - Результат - массив точек или массив двумерных кривых на плоскости. - \en Calculate the intersections of a curve and a surface. \n - The result is an array of points or an array of two-dimensional curves on the plane. \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in] place - \ru Система координат плоскости. - \en The plane coordinate system. \~ - \param[out] result - \ru Множество точек на плоскости. - \en The array of points on the plane. \~ - \param[out] resultCurve - \ru Множество кривых на плоскости. - \en The array of curves on the plane. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (void) CurveSection( const MbCurve3D & curve, - const MbPlacement3D & place, - SArray & result, - RPArray & resultCurve ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти пересечения поверхности с плоскостью. - \en Calculate the intersections of a surface and a plane. \~ - \details \ru Найти пересечения поверхности с плоскостью. \n - Результат - массив кривых на поверхности и двумерных кривых на плоскости. - \en Calculate the intersections of a surface and a plane. \n - The result is an array of curves on the surface and two-dimensional curves on the plane. \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] place - \ru Система координат плоскости. - \en The plane coordinate system. \~ - \param[out] result - \ru Множество кривых на плоскости. - \en The array of curves on the plane. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (void) SurfaceSection( const MbSurface & surface, - const MbPlacement3D & place, - RPArray & result, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать двумерный сегмент поверхности проецированием ориентированного ребра. - \en Create a two-dimensional segment on a surface by projection of an oriented edge. \~ - \details \ru Создать двумерный сегмент поверхности проецированием ориентированного ребра. \n - Результатом является двумерная кривая в параметрической области поверхности surface. - \en Create a two-dimensional segment on a surface by projection of an oriented edge. \n - The result is a two-dimensional curve in the parametric domain of the given surface. \~ - \param[in] face - \ru Грань поверхности. - \en A face defined on the surface. \~ - \param[in] loopInd - \ru Номер цикла в грани. - \en The number of a loop in the face. \~ - \param[in] edgeInd - \ru Номер проецируемого ребра в цикле. - \en Index of the edge in the loop to be projected. \~ - \param[in] surface - \ru Поверхность проецирования. - \en A surface to project on. \~ - \param[in] version - \ru Версия изготовления. - \en Version. \~ - \param[out] result - \ru Двумерная кривая. - \en A two-dimensional curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -//--- -MATH_FUNC (MbResultType) FaceBoundSegment( const MbFace & face, - size_t loopInd, - size_t edgeInd, // \ru Проецируемое ребро грани \en The edge of face to be pojected. - const MbSurface & surface, // \ru На поверхность \en On the surface - VERSION version, - MbCurve *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Создать двумерную границу поверхности проецированием пространственной кривой. - \en Create a two-dimension boundary of a surface by projection of a space curve. \~ - \details \ru Создать двумерную границу поверхности проецированием пространственной кривой \n - (предполагается, что пространственные граничные кривые лежат на поверхности). \n - \en Create a two-dimension boundary of a surface by projection of a space curve \n - (the boundary space curves are considered to belong to the surface) \n \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] spaceCurve - \ru Пространственная кривая. - \en A space curve. \~ - \param[in] version - \ru Версия изготовления. - \en Version. \~ - \param[out] result - \ru Двумерный контур на поверхности. - \en The two-dimensional contour on the surface. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SurfaceBoundContour( const MbSurface & surface, - const MbCurve3D & spaceCurve, - VERSION version, - MbContour *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скорректировать начальную точку. - \en Correct the start point. \~ - \details \ru Изменить начальную точку кривой на новую.\n - Меняет начальную точку у кривых типа:\n - pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, - pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n - или у контура pt_Contour, если первый его сегмент одного из перечисленных типов. - \en Change the start point of curve with a new one.\n - Changes the start point for curves of types:\n - pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, - pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n - 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. \~ - \ingroup Algorithms_2D -*/ -// --- -MATH_FUNC (bool) ChangeFirstPoint( MbCurve * segment, const MbCartPoint & p1 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скорректировать конечную точку. - \en Correct the last point. \~ - \details \ru Изменить конечную точку кривой на новую.\n - Меняет начальную точку у кривых типа:\n - pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, - pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n - или у контура pt_Contour, если последний его сегмент одного из перечисленных типов. - \en Change the end point of curve with a new one.\n - Changes the end point for curves of types:\n - pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, - pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n - 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. \~ - \ingroup Algorithms_2D -*/ -// --- -MATH_FUNC (bool) ChangeLastPoint( MbCurve * segment, const MbCartPoint & p2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Является ли кривая прямолинейной независимо от ее параметризации. - \en Whether the curve is like straight-line regardless of its parameterisation. \~ - \details \ru Является ли кривая прямолинейной независимо от ее параметризации.\n - \en Whether the curve is like straight-line regardless of its parameterisation. \~ - \param[in] curve - \ru Кривая. - \en Curve. \~ - \param[in] eps - \ru Точность. - \en Accuracy. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Удалить вырожденные сегменты из контура. - \en Delete degenerate segments from contour. \~ - \details \ru Удалить вырожденные сегменты из контура с заменой некоторых кривых и модификацией по флагу. \n - \en Delete degenerate segments from contour with substitution of some curves and its modification according to the flag. \n \~ - \param[in] cntr - \ru Исходный контур. - \en The initial contour. \~ - \param[in] modifySegments - \ru Флаг разрешения замены сегментов. - \en The flag determines whether segments can be replaced. \~ - \param[in] names - \ru Именователь, синхронизированный с контуром. - \en An object defining the names synchronized with contour. \~ - \return \ru Возвращает модифицированнную копию контура, если получилось его создать. - \en Returns a modified copy of the contour if it has been successfully created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC( MbContour * ) DeleteDegenerateSegments( const MbContour & cntr, - bool modifySegments, - MbSNameMaker * names = NULL ); - - -#endif // __ACTION_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы построения двумерных кривых. + \en Functions for two-dimensional curves construction. \~ + \details \ru Двумерные кривые могут быть построены с помощью аналитических функций, + по набору точек, на базе других двумерных кривых. + \en Two-dimensional curves can be constructed using analytical functions, + for a point set or on the basis of other two-dimensional curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_CURVE_H +#define __ACTION_CURVE_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbCurve; +class MATH_CLASS MbContour; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFace; + + +//------------------------------------------------------------------------------ +/** \brief \ru Перечисление способов создания эллипса (окружности) или их дуг в двумерном пространстве. + \en Enumeration of ways to create an ellipse (circle) or their arcs in two-dimensional space. \~ +\ingroup Curve_Modeling +*/ +// --- +enum MbeArcCreateWay +{ + /** + \ru Окружность по центру и радиусу, задается 'center' и радиус в 'c'. + \en Circle by center and radius, set the 'center' and radius in 'c'. + */ + acw_CircleByCenterAndRadius, + + /** + \ru Дуга окружности по центру и двум точкам. + Задается: 'center', две точки в 'points', направление в 'option' (true - по часовой стрелке). + Возвращается: начальный угол дуги в 'а', конечный угол в 'b', радиус в 'c'. + \en Circular arc by center and two points. + Set: 'center', two points in 'points', direction in 'option' (true - clockwise direction). + Return: start angle in 'a', end in 'b', radius in 'c'. + */ + acw_ArcByCenterAnd2Points, + + /** + \ru Дуга окружности по центру и двум углам. + Задается: 'center', начальный угол в 'a', конечный в 'b', радиус в 'c', + направление в 'option' (true - по часовой стрелке). Углы задаются в радианах. + \en Circular arc by center and two angles, + Set: 'center', start angle in 'a', end in 'b', radius in 'c', + direction in 'option' (true - clockwise direction). The angles are given in radians. + */ + acw_ArcByCenterAnd2Angles, + /** + \ru Дуга окружности по трем точкам, заданным в 'points', точки points[0] и points[2] конечные. + Возвращается: начальный угол дуги в 'а', конечный угол в 'b', радиус в 'c'. + \en Circular arc by three points specified in 'points', points[0] and points[2] are the end point. + Return: start angle in 'a', end in 'b', radius in 'c'. + */ + acw_ArcBy3Points, + + /** + \ru Эллипс с заданными полуосями и углом наклона. + Задается 'center', X полуось в 'a', Y полуось в 'b', угол наклона в 'с'. Угол задается в радианах. + \en Ellipse by semiaxes and angle. + Set : 'center', X semiaxis in 'a', Y semiaxis in 'b', angle in 'c'. The angle are given in radians. + */ + acw_EllipseByCenterAndSemiaxis, + + /** + \ru Эллипс по центру и трем точкам на нем. + Задается 'center' и 3 точки в 'points'. + Возвращаются: X полуось в 'a', Y полуось в 'b', угол наклона в 'с'. Угол задается в радианах. + \en Ellipse by centre and three points on ellipse. + Set: 'center', 3 points in 'points'. + Return: X semiaxis in 'a', Y semiaxis in 'b', angle in 'c'. The angle are given in radians. + */ + acw_EllipseByCenterAnd3Points, + + /** + \ru Дуга эллипса, обрезанная двумя лучами из центра к заданным точкам. + Задается 'center' и 2 точки в 'points', X полуось в 'a', Y полуось в 'b', угол наклона в 'с', + направление в 'option' (true - по часовой стрелке). Угол задается в радианах. + \en Elliptical arc is trimmed by two rays, starting from the center and passing through points. + Set: 'center', 2 points in 'points', X semiaxis in 'a', Y semiaxis in 'b', angle in 'c', + direction in 'option' (true - clockwise direction). The angle are given in radians. + */ + acw_EArcByCenterAnd2Points +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Создать прямую. + \en Create a line. \~ + \details \ru Создать прямую по двум точкам. \n + \en Create a line given two points. \n \~ + \param[in] point1 - \ru Первая точка. + \en The first point. \~ + \param[in] point2 - \ru Вторая точка. + \en The second point. \~ + \param[out] result - \ru Прямая. + \en The line. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbResultType) Line( const MbCartPoint & point1, + const MbCartPoint & point2, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать отрезок прямой. + \en Create a line segment. \~ + \details \ru Создать отрезок прямой по двум точкам. \n + \en Create a line segment given two points. \n \~ + \param[in] point1 - \ru Первая точка. + \en The first point. \~ + \param[in] point2 - \ru Вторая точка. + \en The second point. \~ + \param[out] result - \ru Отрезок. + \en The segment. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbResultType) Segment( const MbCartPoint & point1, + const MbCartPoint & point2, + MbCurve *& result ); + + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эллипс (окружность) или его дугу указанным способом. + \en Create an ellipse (circle) or an elliptical (circular) arc in the specified way. \~ +\details \ru Создать эллипс (окружность) или его дугу указанным способом.\n Входные параметры интерпретируются в соответствии с выбранным путем создания. + \en Create an ellipse (circle) or an elliptical (circular) arc in the specified way. \n The input parameters are interpreted according to the selected create way. +\param[in] createWay - \ru Способ создания. Определяет как интерпретировать входные параметры. + \en Create way. Defines how to interpret the input parameters.\~ +\param[in] center - \ru Центр + \en Сenter. \~ +\param[in] points - \ru Конечные точки или точки через которые проходит кривая. + \en Endpoints or points through which the curve passes. \~ +\param[in,out] a - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay + \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ +\param[in,out] b - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay + \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ +\param[in,out] с - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay + \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ +\param[in] option - \ru Интерпретация параметра зависит от способа создания дуги, см. enum #ArcCreateWay + \en Interpretation of parameter depends on a way of creation of an arc, see enum #ArcCreateWay. \~ +\param[out] result - \ru Эллипс (окружность) или его дуга. + \en The ellipse (circle) or the elliptical (circular) arc. \~ +\return \ru Возвращает код результата операции. + \en Returns operation result code. \~ +\ingroup Curve_Modeling +*/ +//--- + +MATH_FUNC( MbResultType ) Arc( MbeArcCreateWay createWay, + const MbCartPoint & center, + const std::vector & points, + double & a, double & b, double & c, + bool option, + MbCurve *& result ); + +//------------------------------------------------------------------------------ +/**\attention \ru Функция устарела. Вместо неё применять #Arc. + \en The function is deprecated. Use #Arc instead. \~ +\ingroup Curve_Modeling +*/ +// 2018 +//--- +MATH_FUNC( MbResultType ) Arc( const MbCartPoint & centre, + const SArray & points, + bool curveClosed, double angle, + double & a, double & b, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую, проходящую по набору точек. + \en Create a curve passing through a set of points. \~ + \details \ru Создать кривую, проходящую по набору точек, следующего типа: \n + - curveType == pt_LineSegment - отрезок, \n + - curveType == pt_Arc - окружность или дуга, \n + - curveType == pt_Polyline - ломаная, \n + - curveType == pt_Bezier - кривая Безье, \n + - curveType == pt_CubicSpline - кубический сплайн, \n + - curveType == pt_Hermit - составной кубический сплайн Эрмита, \n + - curveType == pt_Nurbs - неоднородный рациональный B-сплайн четвертого порядка (кубический). \n + \en Create a curve passing through a set of points that has the following type: \n + - curveType == pt_LineSegment - a line segment, \n + - curveType == pt_Arc - a circle or an arc, \n + - curveType == pt_Polyline - a polyline, \n + - curveType == pt_Bezier - a Bezier curve, \n + - curveType == pt_CubicSpline - a cubic spline, \n + - curveType == pt_Hermit - a cubic Hermite spline, \n + - curveType == pt_Nurbs - a nonuniform rational B-spline of fourth order (cubic). \n \~ + \param[in] pointList - \ru Набор точек. + \en A point set. \~ + \param[in] curveClosed - \ru Замкнутость кривой. + \en A curve closedness. \~ + \param[in] curveType - \ru Тип кривой. + \en A curve type. \~ + \param[out] result - \ru Кривая. + \en The curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, + bool curveClosed, MbePlaneType curveType, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать NURBS-кривую. + \en Create a NURBS-curve. \~ + \details \ru Создать NURBS-кривую, построенную по набору контрольных точек. \n + Контейнер weightList может быть пустым. \n + Контейнер knotList может быть пустым. \n + \en Create a NURBS-curve given a sequence of control points. \n + Container 'weightList' can be empty. \n + Container 'knotList' can be empty. \n \~ + \param[in] pointList - \ru Множество точек. + \en An array of points. \~ + \param[in] weightList - \ru Множество весов. + \en An array of weights. \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline degree. \~ + \param[in] knotList - \ru Множество параметрических узлов (Узловой вектор). + \en An array of parametric knots (A knot vector). \~ + \param[in] curveClosed - \ru Замкнутость кривой. + \en A curve closedness. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, + const SArray & weightList, size_t degree, + const SArray & knotList, bool curveClosed, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию кривой в виде NURBS. + \en Create a copy of a curve as a NURBS-curve. \~ + \details \ru Создать копию кривой в виде NURBS. \n + \en Create a copy of a curve as a NURBS-curve. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] result - \ru Сплайновая копия кривой. + \en The spline copy of the curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) NurbsCopy( const MbCurve & curve, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать правильный многоугольник, вписанный в окружность или описанный вокруг окружности. + \en Create a regular polygon inscribed in a circle or circumscribed around a circle. \~ + \details \ru Создать правильный многоугольник, вписанный в окружность (describe == false) или + описанный вокруг окружности (describe == true) с центром centre, проходящей через point: \n + - при vertexCount == 0 строится окружность с центром centre, проходящая через point, \n + - при vertexCount == 1 строится отрезок c крайними точками centre и point, \n + - при vertexCount == 2 строится прямоугольник со сторонами, параллельными глобальным осям и противоположными вершинами в centre и point, \n + - при vertexCount >= 3 строится правильный многоугольник с заданным числом сторон, + вписанный в окружность (describe == false) или описанный вокруг окружности (describe == true) с центром centre, проходящей через point: \n + \en Create a regular polygon inscribed in a circle (describe == false) or + circumscribed around a circle (describe == true) with the specified centre and passing through the given point: \n + - if vertexCount == 0, a circle with center 'center' passing through 'point' is created, \n + - if vertexCount == 1, a line segment with end points at 'centre' and 'point' is created, \n + - if vertexCount, == 2 a rectangle aligned with the global axes with the opposite vertices at points 'centre' and 'point' is created, \n + - if vertexCount >= 3, a regular polygon is created with a given number of sides, + inscribed in a circle (describe == false) or circumscribed around a circle (describe == true) with the specified centre and passing through the given point: \n \~ + \param[in] centre - \ru Центр фигуры. + \en A figure centre. \~ + \param[in] point - \ru Точка для построения. + \en A point for the curve construction. \~ + \param[in] vertexCount - \ru Количество вершин правильного многоугольника. + \en The number of vertices of a regular polygon. \~ + \param[in] describe - \ru Флаг построения многоугольника: описать вокруг окружности (true), вписать в окружность (false). + \en A polygon construction flag: circumscribe the polygon around the circle, inscribe the polygon in the circle (false). \~ + \param[out] result - \ru Результат построения. + \en The curve creation result. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) RegularPolygon( const MbCartPoint & centre, + const MbCartPoint & point, + size_t vertexCount, + bool describe, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать косинусоиду. + \en Create a cosine curve. \~ + \details \ru Создать косинусоиду по точкам, фазе и длине волны. \n + \en Create a cosine curve given the points, phase and wave length. \n \~ + \param[in] point0 - \ru Начало локальной системы координат (ЛСК). + \en The origin of local coordinate system (LCS). \~ + \param[in] point1 - \ru Точка на оси X ЛСК. + \en A point on the X-axis of LCS. \~ + \param[in] point2 - \ru Точка на оси Y ЛСК. + \en A point on the Y-axis of LCS. \~ + \param[in] phase - \ru Фаза. + \en The phase. \~ + \param[in] waveLength - \ru Длина Волны. + \en The wave length. \~ + \param[out] result - \ru Косинусоида. + \en The cosine curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) Cosinusoid( const MbCartPoint & point0, + const MbCartPoint & point1, + const MbCartPoint & point2, + double phase, + double waveLength, + MbCurve *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Создать косинусоиду. + \en Create a cosine curve. \~ + \details \ru Создать косинусоиду по точкам, фазе и длине волны. \n + \en Create a cosine curve given the points, phase and wave length. \n \~ + \param[in] origin - \ru Начало локальной системы координат (ЛСК). + \en The origin of local coordinate system (LCS). \~ + \param[in] amplitude - \ru Амплитуда волны. + \en The amplitude of the wave. \~ + \param[in] waveLength - \ru Длина Волны. + \en The wave length. \~ + \param[in] wavesCount - \ru Количество волн. + \en The number of waves. \~ + \param[in] phase - \ru Фаза. + \en The phase. \~ + \param[out] result - \ru Косинусоида. + \en The cosine curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) Cosinusoid( const MbCartPoint & origin, + double amplitude, + double waveLength, + double wavesCount, + double phase, + MbCurve *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать составную кривую (контур). + \en Create a composite curve (contour). \~ + \details \ru Создать составную кривую (контур) на базе исходной кривой. \n + \en Create a composite curve (contour) on the basis of the given curve. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] result - \ru Контур на основе кривой. + \en The contour created on the basis of the curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) CreateContour( MbCurve & curve, + MbContour *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию кривой. + \en Create a copy of a curve. \~ + \details \ru Создать копию кривой с заменой некоторых кривых. \n + \en Create a copy of a curve with substitution of some curves. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \return \ru Возвращает модифицированную копию кривой, если получилось ее создать. + \en Returns a modified copy of the curve if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbCurve *) DuplicateCurve( const MbCurve & curve ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию контура. + \en Create a copy of a contour. \~ + \details \ru Создать копию контура с заменой некоторых кривых и его модификацией по флагу. + Модификация - слияние подобных кривых и удаление вырожденных. \n + \en Create a copy of a contour with substitution of some curves and its modification according to the flag. + Modification is a merging of similar curves and deleting of degenerate ones. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] modifySegments - \ru Флаг разрешения замены и слияния сегментов. + \en The flag determines whether segments can be replaced or merged. \~ + \param[in] names - \ru Именователь, синхронизированный с контуром. + \en An object defining the names synchronized with contour. \~ + \return \ru Возвращает модифицированнную копию контура, если получилось его создать. + \en Returns a modified copy of the contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbContour *) DuplicateContour( const MbContour & cntr, + bool modifySegments, + MbSNameMaker * names = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную кривую. + \en Create an offset curve. \~ + \details \ru Создать эквидистантную кривую по базовой кривой и смещению в крайних точках. \n + \en Create the offset curve for a given curve with offset in the begin and the end points. \n \~ + \param[in] curve - \ru Базовая кривая. + \en Base curve. \~ + \param[in] offset1 - \ru Смещение в точке Tmin базовой кривой. + \en Offset distance on point Tmin of base curve. \~ + \param[in] offset2 - \ru Смещение в точке Tmax базовой кривой. + \en Offset distance on point Tmax of base curve. \~ + \param[in] type - \ru Тип смещения точек: константный, линейный или кубический. + \en The offset type: constant, or linear, or cubic. \~ + \return \ru Возвращает эквидистантную кривую. + \en Returns the offset curve. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbCurve *) OffsetCurve( const MbCurve & curve, + double offset1, + double offset2, + MbeOffsetType type ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантный контур. + \en Create an offset contour. \~ + \details \ru Создать эквидистантный контур к исходному контуру. \n + \en Create the offset contour for a given contour. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] rad - \ru Величина эквидистантного смещения. + \en The offset value. \~ + \param[in] xEpsilon - \ru Точность по x. + \en Tolerance in x direction. \~ + \param[in] yEpsilon - \ru Точность по y. + \en Tolerance in y direction. \~ + \param[in] modifySegments - \ru Флаг разрешения замены и слияния сегментов. + \en The flag determines whether segments can be replaced or merged. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \return \ru Возвращает эквидистантный контур, если получилось его создать. + \en Returns the offset contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbContour *) OffsetContour( const MbContour & cntr, + double rad, + double xEpsilon, + double yEpsilon, + bool modifySegments, + VERSION version = Math::DefaultMathVersion()/*BUG_61694*/ ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантный контур, начинающийся и оканчивающийся на оси вращения. + \en Create an offset contour with start and end points on the rotation axis. \~ + \details \ru Создать незамкнутый эквидистантный контур, начинающийся и оканчивающийся на оси вращения. \n + Cчитается, что, если контур замкнуть, то он будет ориентирован против движения часовой стрелки. \n + \en Create an open offset contour with start and end points on the rotation axis. \n + It is considered that if one closes the contour, it will be oriented counterclockwise. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] q1 - \ru Начальная точка оси вращения. + \en The start point of the rotation axis. \~ + \param[in] q2 - \ru Конечная точка оси вращения. + \en The end point of the rotation axis. \~ + \param[in] rad - \ru Величина эквидистантного смещения. + \en The offset value. \~ + \param[in] xEpsilon - \ru Точность по x. + \en Tolerance in x direction. \~ + \param[in] yEpsilon - \ru Точность по y. + \en Tolerance in y direction. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \return \ru Возвращает эквидистантный контур, если получилось его создать. + \en Returns the offset contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbContour *) AxisOffsetOpenContour( const MbContour & cntr, + const MbCartPoint & q1, + const MbCartPoint & q2, + double rad, + double xEpsilon, + double yEpsilon, + VERSION version );// = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Инициализировать кривую по новым параметрам. + \en Initialize a curve with new parameters. \~ + \details \ru Инициализировать кривую по новым параметрам. \n + \en Initialize a curve with new parameters. \n \~ + \param[in,out] curve - \ru Изменяемая кривая. + \en The curve to be modified. \~ + \param[in] t1 - \ru Новый начальный параметр. + \en A new start parameter. \~ + \param[in] t2 - \ru Новый конечный параметр. + \en A new end parameter. \~ + \param[in] eps - \ru Точность. + \en Tolerance. \~ + \return \ru Возвращает true, если получилось модифицировать кривую. + \en Returns 'true' if the curve has been successfully modified. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (bool) CurveTrim( MbCurve & curve, + double t1, + double t2, + double eps = METRIC_PRECISION ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить кривую в составную кривую (контур). + \en Add a curve to a composite curve (a contour). \~ + \details \ru Добавить кривую curve в составную кривую (контур) contour. \n + Если toEnd == true, то добавить в конец. \n + Если toEnd == false, то добавить в начало. \n + \en Add a curve to a composite curve (a contour) 'contour'. \n + If toEnd == true, the curve is to be added to the end. \n + If toEnd == true, the curve is to be added to the beginning. \n \~ + \param[in] curve - \ru Добавляемая кривая + \en A curve to be added. \~ + \param[in,out] contour - \ru Модифицируемый контур. + \en A contour to be modified. \~ + \param[in] toEnd - \ru Флаг места добавления кривой. + \en The flag determines the place of the curve in the contour. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) AddCurveToContour( MbCurve & curve, + MbContour & contour, + bool toEnd ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти пересечения кривой с плоскостью. + \en Calculate the intersections of a curve and a surface. \~ + \details \ru Найти пересечения кривой с плоскостью. \n + Результат - массив точек или массив двумерных кривых на плоскости. + \en Calculate the intersections of a curve and a surface. \n + The result is an array of points or an array of two-dimensional curves on the plane. \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] place - \ru Система координат плоскости. + \en The plane coordinate system. \~ + \param[out] result - \ru Множество точек на плоскости. + \en The array of points on the plane. \~ + \param[out] resultCurve - \ru Множество кривых на плоскости. + \en The array of curves on the plane. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (void) CurveSection( const MbCurve3D & curve, + const MbPlacement3D & place, + SArray & result, + RPArray & resultCurve, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти пересечения поверхности с плоскостью. + \en Calculate the intersections of a surface and a plane. \~ + \details \ru Найти пересечения поверхности с плоскостью. \n + Результат - массив кривых на поверхности и двумерных кривых на плоскости. + \en Calculate the intersections of a surface and a plane. \n + The result is an array of curves on the surface and two-dimensional curves on the plane. \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] place - \ru Система координат плоскости. + \en The plane coordinate system. \~ + \param[out] result - \ru Множество кривых на плоскости. + \en The array of curves on the plane. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (void) SurfaceSection( const MbSurface & surface, + const MbPlacement3D & place, + RPArray & result, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать двумерный сегмент поверхности проецированием ориентированного ребра. + \en Create a two-dimensional segment on a surface by projection of an oriented edge. \~ + \details \ru Создать двумерный сегмент поверхности проецированием ориентированного ребра. \n + Результатом является двумерная кривая в параметрической области поверхности surface. + \en Create a two-dimensional segment on a surface by projection of an oriented edge. \n + The result is a two-dimensional curve in the parametric domain of the given surface. \~ + \param[in] face - \ru Грань поверхности. + \en A face defined on the surface. \~ + \param[in] loopInd - \ru Номер цикла в грани. + \en The number of a loop in the face. \~ + \param[in] edgeInd - \ru Номер проецируемого ребра в цикле. + \en Index of the edge in the loop to be projected. \~ + \param[in] surface - \ru Поверхность проецирования. + \en A surface to project on. \~ + \param[in] version - \ru Версия изготовления. + \en Version. \~ + \param[out] result - \ru Двумерная кривая. + \en A two-dimensional curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +//--- +MATH_FUNC (MbResultType) FaceBoundSegment( const MbFace & face, + size_t loopInd, + size_t edgeInd, // \ru Проецируемое ребро грани \en The edge of face to be pojected. + const MbSurface & surface, // \ru На поверхность \en On the surface + VERSION version, + MbCurve *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Создать двумерную границу поверхности проецированием пространственной кривой. + \en Create a two-dimension boundary of a surface by projection of a space curve. \~ + \details \ru Создать двумерную границу поверхности проецированием пространственной кривой \n + (предполагается, что пространственные граничные кривые лежат на поверхности). \n + \en Create a two-dimension boundary of a surface by projection of a space curve \n + (the boundary space curves are considered to belong to the surface) \n \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] spaceCurve - \ru Пространственная кривая. + \en A space curve. \~ + \param[in] version - \ru Версия изготовления. + \en Version. \~ + \param[out] result - \ru Двумерный контур на поверхности. + \en The two-dimensional contour on the surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SurfaceBoundContour( const MbSurface & surface, + const MbCurve3D & spaceCurve, + VERSION version, + MbContour *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скорректировать начальную точку. + \en Correct the start point. \~ + \details \ru Изменить начальную точку кривой на новую.\n + Меняет начальную точку у кривых типа:\n + pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, + pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n + или у контура pt_Contour, если первый его сегмент одного из перечисленных типов. + \en Change the start point of curve with a new one.\n + Changes the start point for curves of types:\n + pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, + pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n + 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. \~ + \ingroup Algorithms_2D +*/ +// --- +MATH_FUNC (bool) ChangeFirstPoint( MbCurve * segment, const MbCartPoint & p1 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скорректировать конечную точку. + \en Correct the last point. \~ + \details \ru Изменить конечную точку кривой на новую.\n + Меняет начальную точку у кривых типа:\n + pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, + pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n + или у контура pt_Contour, если последний его сегмент одного из перечисленных типов. + \en Change the end point of curve with a new one.\n + Changes the end point for curves of types:\n + pt_Nurbs, pt_Hermit, pt_Polyline, pt_Bezier, + pt_CubicSpline, pt_LineSegment, pt_ReparamCurve,\n + 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. \~ + \ingroup Algorithms_2D +*/ +// --- +MATH_FUNC (bool) ChangeLastPoint( MbCurve * segment, const MbCartPoint & p2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Является ли кривая прямолинейной независимо от ее параметризации. + \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \details \ru Является ли кривая прямолинейной независимо от ее параметризации.\n + \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \param[in] curve - \ru Кривая. + \en Curve. \~ + \param[in] eps - \ru Точность. + \en Accuracy. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Удалить вырожденные сегменты из контура. + \en Delete degenerate segments from contour. \~ + \details \ru Удалить вырожденные сегменты из контура с заменой некоторых кривых и модификацией по флагу. \n + \en Delete degenerate segments from contour with substitution of some curves and its modification according to the flag. \n \~ + \param[in] cntr - \ru Исходный контур. + \en The initial contour. \~ + \param[in] modifySegments - \ru Флаг разрешения замены сегментов. + \en The flag determines whether segments can be replaced. \~ + \param[in] names - \ru Именователь, синхронизированный с контуром. + \en An object defining the names synchronized with contour. \~ + \return \ru Возвращает модифицированнную копию контура, если получилось его создать. + \en Returns a modified copy of the contour if it has been successfully created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC( MbContour * ) DeleteDegenerateSegments( const MbContour & cntr, + bool modifySegments, + MbSNameMaker * names = NULL ); + + +#endif // __ACTION_CURVE_H diff --git a/C3d/Include/action_curve3d.h b/C3d/Include/action_curve3d.h index e0201a0..dd300ff 100644 --- a/C3d/Include/action_curve3d.h +++ b/C3d/Include/action_curve3d.h @@ -1,1226 +1,1269 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения трехмерных кривых. - \en Functions for three-dimensional curves construction. \~ - \details \ru На базе кривых строятся рёбра. Рёбра используются в твёрдотельной и каркасной модели. - Кроме того, кривые используются для построения поверхностей, а также могут служить - вспомогательными элементами модели. - \en Edges are created on the basis of curves. Edges are used in solid and wireframe model. - In addition curves are used for construction of surfaces as well as can be used - as auxiliary elements of a model. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_CURVE3D_H -#define __ACTION_CURVE3D_H - - -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbNurbs3D; -class MATH_CLASS MbContour3D; -class MATH_CLASS MbFace; -class MATH_CLASS MbSurface; -class MATH_CLASS MbWireFrame; -class MATH_CLASS MbItem; -class MATH_CLASS MbName; -class MATH_CLASS MbSweptData; -struct MATH_CLASS EvolutionValues; - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать прямую. - \en Create a line. \~ - \details \ru Создать прямую по двум точкам. \n - \en Create a line given two points. \n \~ - \param[in] point1 - \ru Первая точка. - \en The first point. \~ - \param[in] point2 - \ru Вторая точка. - \en The second point. \~ - \param[out] result - \ru Прямая. - \en The line. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) Line( const MbCartPoint3D & point1, - const MbCartPoint3D & point2, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать отрезок прямой. - \en Create a line segment. \~ - \details \ru Создать отрезок прямой по двум точкам. \n - \en Create a line segment given two points. \n \~ - \param[in] point1 - \ru Первая точка. - \en The first point. \~ - \param[in] point2 - \ru Вторая точка. - \en The second point. \~ - \param[out] result - \ru Отрезок. - \en The segment. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) Segment( const MbCartPoint3D & point1, - const MbCartPoint3D & point2, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эллипс (окружность) или его дугу. - \en Create an ellipse (circle) or an elliptical (circular) arc. \~ - \details \ru Создать эллипс (окружность) или его дугу. \n - Контейнер points может содержать 0, 2 элементов. \n - \en Create an ellipse (circle) or an elliptical (circular) arc. \n - The container 'points' should contain 0 or 2 elements. \n \~ - \param[in] centre - \ru Центр эллипса (окружности) - \en The center of an ellipse (circle). \~ - \param[in] points - \ru Точки дуги. - \en Points on the arc. \~ - \param[in] curveClosed - \ru Замкнутость дуги. - \en The closedness of the arc. \~ - \param[in] angle - \ru Угол наклона. - \en The inclination angle. \~ - \param[in,out] a - \ru Длина большой полуоси. - \en The major axis length. \~ - \param[in,out] b - \ru Длина малой полуоси. - \en The minor axis length. \~ - \param[out] result - \ru Эллипс (окружность) или его дуга. - \en The ellipse (circle) or the elliptical (circular) arc. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) Arc( const MbCartPoint3D & centre, - const SArray & points, - bool curveClosed, double angle, - double & a, double & b, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую, проходящую по набору точек. - \en Create a curve passing through a set of points. \~ - \details \ru Создать кривую, проходящую по набору точек, следующего типа: \n - curveType == st_LineSegment3D - отрезок, \n - curveType == st_Arc3D - окружность или дуга, \n - curveType == st_Polyline3D - ломаная, \n - curveType == st_Bezier3D - кривая Безье, \n - curveType == st_CubicSpline3D - кубический сплайн, \n - curveType == st_Hermit3D - составной кубический сплайн Эрмита, \n - curveType == st_Nurbs3D - неоднородный рациональный B-сплайн четвертого порядка (кубический). \n - \en Create a curve passing through a set of points that has the following type: \n - curveType == st_LineSegment3D - a line segment, \n - curveType == st_Arc3D - a circle or an arc, \n - curveType == st_Polyline3D - a polyline, \n - curveType == st_Bezier3D - a Bezier curve, \n - curveType == st_CubicSpline3D - a cubic spline, \n - curveType == st_Hermit3D - a cubic Hermite spline, \n - curveType == st_Nurbs3D - a nonuniform rational B-spline of fourth order (cubic). \n \~ - \param[in] pointList - \ru Набор точек. - \en A point set. \~ - \param[in] curveClosed - \ru Замкнутость кривой. - \en A curve closedness. \~ - \param[in] curveType - \ru Тип кривой. - \en A curve type. \~ - \param[out] result - \ru Кривая. - \en The curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, - bool curveClosed, - MbeSpaceType curveType, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать NURBS-кривую. - \en Create a NURBS-curve. \~ - \details \ru Создать NURBS-кривую, построенную по набору контрольных точек. \n - Контейнер weightList может быть пустым. \n - Контейнер knotList может быть пустым. \n - \en Create a NURBS-curve given a sequence of control points. \n - Container 'weightList' can be empty. \n - Container 'knotList' can be empty. \n \~ - \param[in] pointList - \ru Множество точек. - \en An array of points. \~ - \param[in] weightList - \ru Множество весов. - \en An array of weights. \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline degree. \~ - \param[in] knotList - \ru Множество параметрических узлов (Узловой вектор). - \en An array of parametric knots (A knot vector). \~ - \param[in] curveClosed - \ru Замкнутость кривой. - \en A curve closedness. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, - const SArray & weightList, size_t degree, - const SArray & knotList, bool curveClosed, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать копию кривой в виде NURBS. - \en Create a copy of a curve as a NURBS-curve. \~ - \details \ru Создать копию кривой в виде NURBS. \n - \en Create a copy of a curve as a NURBS-curve. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] result - \ru Сплайновая копия кривой. - \en The spline copy of the curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) NurbsCopy( const MbCurve3D & curve, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать правильный многоугольник, вписанный в окружность. - \en Create a regular polygon inscribed in a circle. \~ - \details \ru Создать правильный многоугольник, вписанный в окружность \n - (при describe == true описанного вокруг окружности) с центром centre и проходящей через point: \n - - при vertexCount <= 1 строится окружность с центром centre и проходящая через point, \n - - при vertexCount == 2 строится прямоугольник со сторонами, параллельными глобальным осям - и противоположными вершинами в centre и point. \n - \en Create a regular polygon inscribed in a circle \n - (if 'describe' == true circumscribed around a circle) with the specified centre and passing through the given point: \n - - if vertexCount <= 1, a circle with center 'center' passing through 'point' is created, \n - - if vertexCount == 2, a rectangle aligned with the global axes - with the opposite vertices at points 'centre' and 'point' is created. \n \~ - \param[in] centre - \ru Центр. - \en The center. \~ - \param[in] point - \ru Точка. - \en A point. \~ - \param[in] axisZ - \ru Ось Z для создания ЛСК кривой. - \en Z-axis for curve LCS creation. \~ - \param[in] vertexCount - \ru Количество вершин. - \en Number of vertices. \~ - \param[in] describe - \ru Описанный вокруг окружности. - \en Circumscribing around the circle. \~ - \param[out] result - \ru Правильный многоугольник. - \en The regular polygon. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) RegularPolygon( const MbCartPoint3D & centre, - const MbCartPoint3D & point, - const MbVector3D & axisZ, - size_t vertexCount, - bool describe, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать спираль. - \en Create a spiral. \~ - \details \ru Создать спираль. \n - Если spiralAxis == true, то lawCurve - определяет плоскую ось спирали. \n - Если spiralAxis == false, то lawCurve - определяет закон изменения радиуса спирали. \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 \~ - \param[in] place - \ru Локальная система координат. - \en A local coordinate system. \~ - \param[in] radius - \ru Радиус спирали. - \en A spiral radius. \~ - \param[in] step - \ru Шаг спирали. - \en A pitch. \~ - \param[in] lawCurve - \ru Формообразующая кривая. - \en A guide curve. \~ - \param[in] spiralAxis - \ru Выбор режима формообразования - \en A spiral construction mode. \~ - \param[out] result - \ru Спиральная кривая. - \en The spiral curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SpiralCurve( const MbPlacement3D & place, - double radius, - double step, - MbCurve & lawCurve, - bool spiralAxis, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать спираль. - \en Create a spiral. \~ - \details \ru Создать спираль. \n - Если spiralAxis == true, то lawCurve - определяет плоскую ось спирали. \n - Если spiralAxis == false, то lawCurve - определяет закон изменения радиуса спирали. \n - Если lawCurve == 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 \~ - \param[in] point0 - \ru Начало локальной системы координат (ЛСК). - \en The origin of local coordinate system (LCS). \~ - \param[in] point1 - \ru Точка на оси Z ЛСК. - \en A point on Z-axis of LCS. \~ - \param[in] point2 - \ru Точка на оси X ЛСК. - \en A point on the X-axis of LCS. \~ - \param[in] radius - \ru Радиус спирали. - \en A spiral radius. \~ - \param[in] step - \ru Шаг спирали. - \en A pitch. \~ - \param[in] angle - \ru Угол коничности спирали. - \en A taper angle. \~ - \param[in] lawCurve - \ru Формообразующая кривая. - \en A guide curve. \~ - \param[in] spiralAxis - \ru Выбор режима формообразования - \en A spiral construction mode. \~ - \param[out] result - \ru Спиральная кривая. - \en The spiral curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SpiralCurve( const MbCartPoint3D & point0, - const MbCartPoint3D & point1, - const MbCartPoint3D & point2, - double radius, - double step, - double angle, - MbCurve * lawCurve, - bool spiralAxis, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать составную кривую (контур). - \en Create a composite curve (contour). \~ - \details \ru Создать составную кривую (контур) на базе исходной кривой. \n - \en Create a composite curve (contour) on the basis of the given curve. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] result - \ru Контур на основе кривой. - \en The contour created on the basis of the curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) CreateContour( MbCurve3D & curve, - MbContour3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать копию кривой. - \en Create a copy of a curve. \~ - \details \ru Создать копию кривой с разбивкой ломаной линии и заменой некоторых кривых. \n - \en Create a copy of a curve with splitting of a polyline and replacement of some curves. \n \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[in] version - \ru Версия исполнения. - \en The version. \~ - \return \ru Возвращает модифицированную копию кривой, если получилось ее создать. - \en Returns a modified copy of the curve if it has been successfully created. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCurve3D *) DuplicateCurve( const MbCurve3D & curve, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить кривую в составную кривую (контур). - \en Add a curve to a composite curve (a contour). \~ - \details \ru Добавить кривую curve в составную кривую (контур) contour. \n - Если toEnd == true, то добавить в конец. \n - Если toEnd == false, то добавить в начало. \n - \en Add a curve to a composite curve (a contour) 'contour'. \n - If toEnd == true, the curve is to be added to the end. \n - If toEnd == true, the curve is to be added to the beginning. \n \~ - \param[in] curve - \ru Добавляемая кривая - \en A curve to be added. \~ - \param[in,out] contour - \ru Модифицируемый контур. - \en A contour to be modified. \~ - \param[in] toEnd - \ru Флаг места добавления кривой. - \en The flag determines the place of the curve in the contour. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) AddCurveToContour( MbCurve3D & curve, - MbCurve3D & contour, - bool toEnd ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить кривую в пространстве по двумерной кривой. - \en Create a space curve from a two-dimensional curve. \~ - \details \ru Построить кривую в пространстве по двумерной кривой сurve на плоскости place. \n - Построение выполняется на оригинале кривой. - \en Create a space curve from a two-dimensional curve 'curve' lying on plane 'place'. \n - The construction is performed on the source curve. \~ - \param[in] place - \ru Система координат плоскости. - \en The plane coordinate system. \~ - \param[in] curve - \ru Двумерная кривая - \en A two-dimensional curve \~ - \param[out] result - \ru Плоская кривая. - \en The planar curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) PlaneCurve( const MbPlacement3D & place, - const MbCurve & curve, - MbCurve3D *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Построить кривую на поверхности по двумерной кривой. - \en Create a curve on a surface given a two-dimensional curve. \~ - \details \ru Построить кривую на поверхности surface по двумерной кривой сurve. \n - Построение выполняется на оригиналах кривой и поверхности. - \en Create a curve on a surface 'surface' given a two-dimensional curve 'curve'. \n - The construction is performed on the original curve and surface. \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] curve - \ru Двумерная кривая - \en A two-dimensional curve \~ - \param[out] result - \ru Поверхностная кривая. - \en The curve on the specified surface. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SurfaceCurve( const MbSurface & surface, - const MbCurve & curve, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхностную кривую, если пространственная кривая лежит на поверхности. - \en Create a curve on a surface from a space curve lying on the surface. \~ - \details \ru Создать поверхностную кривую, если пространственная кривая лежит на поверхности. \n - Разбираются частные случае точной принадлежности кривой выбранной поверхности. - В общем случае пространственная кривая считается принадлежащей поверхности, если группа точек, - полученная шаганием по параметру кривой по угловому отклонению, принадлежит поверхности. - В этом случае создается двумерная проекционная кривая этой кривой на поверхности. \n - \en Create a curve on a surface from a space curve lying on the surface. \n - The special cases of curves exactly lying on the specified surfaces are treated. - In the general case a space curve is considered to lie on the surface if a group of points - obtained by sampling the curve with the given turning angle belongs to the surface. - In this case a two-dimensional curve is created as the projection of the curve on the surface. \n \~ - \param[in] curve - \ru Пространственная кривая. - \en A space curve. \~ - \param[in] surf - \ru Поверхность. - \en A surface. \~ - \param[in] sameSurf - \ru Использовать оригинал поверхности. - \en Whether to use the source surface. \~ - \param[in] extSurf - \ru Искать на расширенной поверхности. - \en Whether to use the extended surface. \~ - \param[in] strictOnSurface - \ru Все точки кривой лежат на поверхности (true) или часть точек лежит на поверхности (false). - \en All the points of the curve belong to the surface (true) or a part of the points belong to the surface (false). \~ - \param[out] result - \ru Поверхностная кривая. - \en The curve on the specified surface. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) CurveOnSurface( const MbCurve3D & curve, - const MbSurface & surf, - bool sameSurf, bool extSurf, - MbCurve3D *& result, - bool strictOnSurface = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Лежит ли кривая на поверхности. - \en Determine whether the curve lies on the surface. \~ - \details \ru Проверить, лежит ли кривая полностью на поверхности. \n - \en Determine whether the curve entirely lies on the surface. \n \~ - \param[in] curve - \ru Пространственная кривая. - \en A space curve. \~ - \param[in] surf - \ru Поверхность. - \en A surface. \~ - \param[in] ext - \ru Искать на расширенной поверхности. - \en Whether to use the extended surface. \~ - \param[in] strictOnSurface - \ru Все точки кривой лежат на поверхности (true) или часть точек лежит на поверхности (false). - \en All the points of the curve belong to the surface (true) or a part of the points belong to the surface (false). \~ - \return \ru Возвращает true, если кривая лежит на поверхности. - \en Returns true if the curve lies on the surface. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (bool) IsCurveOnSurface( const MbCurve3D & curve, - const MbSurface & surf, bool ext, - bool strictOnSurface = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив контуров по массиву кривых. - \en Create an array of contours given an array of curves. \~ - \details \ru Создать массив контуров по массиву кривых (на оригиналах кривых). \n - \en Create an array of contours given an array of curves (using the original curves). \n \~ - \param[in] curves - \ru Множество кривых. - \en An array of curves. \~ - \param[in] metricEps - \ru Радиус захвата для стыковки кривых. - \en The radius for curves joining. \~ - \param[out] result - \ru Множество контуров. - \en The array of contours. \~ - \param[in] onlySmoothConnected - \ru Добавлять в контур только гладко стыкующиеся сегменты. - \en Whether to add only smoothly connected segments. \~ - \param[in] version - \ru Версия исполнения. - \en Version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateContours( RPArray & curves, - double metricEps, - RPArray & result, - bool onlySmoothConnected = false, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать контуры по набору кривых с удалением вырожденных. - \en Create contours given a set of curves with elimination of degenerate ones. \~ - \details \ru Создать контуры по набору кривых с удалением вырожденных (на оригиналах кривых). \n - \en Create contours given a set of curves with elimination of degenerate ones (the original curves are used). \n \~ - \param[in, out] curves - \ru Множество кривых. - \en An array of curves. \~ - \param[in] metricAcc - \ru Радиус захвата для стыковки кривых. - \en The radius for curves joining. \~ - \param[in] onlySmoothConnected - \ru Добавлять в контур только гладко стыкующиеся сегменты. - \en Whether to add only smoothly connected segments. \~ - \param[in] version - \ru Версия исполнения. - \en Version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) CreateContours( RPArray & curves, - double metricAcc, - bool onlySmoothConnected = false, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать именованный трехмерный каркас. - \en Create a named three-dimensional wireframe. \~ - \details \ru Создать именованный трехмерный каркас по кривой. \n - \en Create a named three-dimensional wireframe from a curve. \n \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in] curveName - \ru Имя кривой. - \en The curve name. \~ - \param[in] mainName - \ru Главное имя операции. - \en The operation main name. \~ - \param[out] result - \ru Каркас. - \en The wireframe. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) WireFrame( const MbCurve3D & curve, - const MbName & curveName, - SimpleName mainName, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать именованный трехмерный каркас. - \en Create a named three-dimensional wireframe. \~ - \details \ru Создать именованный трехмерный каркас по массиву кривых. \n - \en Create a named three-dimensional wireframe from a given array of curves. \n \~ - \param[in] curves - \ru Множество кривых. - \en An array of curves. \~ - \param[in] curveNames - \ru Множество имен кривых. - \en An array of the curves names. \~ - \param[in] mainName - \ru Главное имя операции. - \en The operation main name. \~ - \param[out] result - \ru Каркас. - \en The wireframe. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) WireFrame( const RPArray & curves, - const RPArray & curveNames, - SimpleName mainName, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Аппроксимировать контур дугами и отрезками. - \en Approximate a contour with arcs and line segments. \~ - \details \ru Аппроксимировать контур дугами и отрезками. \n - Производится аппроксимация каждого из сегментов контура. \n - \en Approximate a contour with arcs and line segments. \n - The approximation is performed for each segment of the contour. \n \~ - \param[in] curve - \ru Кривая или контур, которую надо аппроксимировать. - \en A curve or a contour to approximate. \~ - \param[out] result - \ru Результат аппроксимации. - \en The approximation result. \~ - \param[in] eps - \ru Ошибка аппроксимации. - \en The approximation precision. \~ - \param[in] minRad - \ru Минимально допустимый радиус окружностей, используемых для аппроксимации. - \en The minimal acceptable radius of the circles used for the approximation. \~ - \param[in] maxRad - \ru Максимально допустимый радиус окружностей, используемых для аппроксимации. - \en The maximal acceptable radius of the circles used for the approximation. \~ - \return \ru - Возращает код результата операции. - \en - Returns operation result code. \~ -\ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreatePolyArcCurve3D( const MbCurve3D & curve, - MbCurve3D *& result, - double & eps, - double minRad = Math::minRadius, - double maxRad = Math::maxRadius ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить или создать пространственную кривую. - \en Get or create a space curve. \~ - \details \ru Получить или создать пространственную кривую из данных модельного объекта - c опциональным сохранением несущей плоскости в случае плоского объекта. \n - Двумерный контур на плоскости преобразуется не в контур на плоскости, - а в пространственный контур. \n - \en Get or create a space curve from a model object data. - with optional keeping of supporting plane in the case of a planar object. \n - A two-dimensional contour is to be converted not to a contour on a plane - but to a three-dimensional contour. \n \~ - \param[in] item - \ru Модельный объект. - \en A model object. \~ - \param[in] keepPlacement - \ru Сохранять несущую плоскость. - \en Whether to keep the supporting plane. \~ - \param[out] curve0 - \ru Пространственная кривая. - \en A space curve. \~ - \param[out] curves - \ru Дополнительные пространственные кривые (могут быть в объекте MbPlaneInstance). - \en Additional space curve (It's possible if a object "MbItem" is the object "MbPlaneInstance"). \~ - \return \ru - Возвращает успешность результата операции. - \en - Returns whether the result is successful. \~ -\ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (bool) GetSpaceCurve( const MbItem & item, - bool keepPlacement, - SPtr & curve0, - std::vector< SPtr > * curves = NULL ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Построить развертку кривой/контура на плоскость. - \en Construct a unwrapping curve/contour. \~ - \details \ru Построение развертки кривой/контура на плоскость. Контур разворачивается посегментно, функцией UnwrapCurve. - Первым разворачивается сегмент, который лежит в плоскости и находиться ближе всех к точке, - если лежащих в плоскости нет, то ближащий к точке из тех что пересекают контур, если и таких нет то просто ближайший к точке. - Первый сегмент разворачивается так, чтобы точка пересечения или ближайшей проекции была неподвижной. \n - \en Construction unwrapping of the curve/contour on a plane. Each segment of the contour is unwrapped by the function UnwrapCurve. - Unwrapping starting with a segment which lies in the plane or crosses the plane and which is closest to the given point. - Unwrapping of the first segment is constructed in the manner, that cross point or closest projection of the segment on the plane were stationary. \n \~ - \param[in] curve - \ru Разворачиваемая кривая/контур. - \en Original curve/contour. \~ - \param[in] placement - \ru Локальная система координат плоскости. - \en The placement of the plane. \~ - \param[in] point - \ru Точка для определения первого сегмента. - \en The point for determine first segment. \~ - \param[in] deviationAngle - \ru Параметру точности. - \en The parameter of accuracy. \~ - \return \ru Возвращает указатель на построенную кривую с нулевум счетчиком ссылок \n - или 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 -\ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCurve3D *) UnwrapCurve( const MbCurve3D & curve, - const MbPlacement3D & placement, - const MbCartPoint3D & point, - double deviationAngle = DEVIATION_SAG); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать сечение кинематического тела для заданного параметра на направляющей. - \en Create a section of evolution solid for defined parameter on the guide curve. \~ - \details \ru Создать сечение кинематического тела для заданного параметра на направляющей. - Если направляющая является контуром, то стыки между сегментами контура должны быть гладкими. \n - \en Create a section of evolution solid (sweep solid with guide curve) for defined parameter on guide curve. - If the guide curve is a contour, then this contour have to be smooth. \n \~ - \param[in] generCurves - \ru Множество плоских образующих. - \en An array of forming curves. \~ - \param[in] guideCurve - \ru Направляющая кривая (или контур). - \en An guide curve (or contour). \~ - \param[in] guideParam - \ru Параметр, заданный на направляющей кривой. - \en A parameter on the guide curve. \~ - \param[in] angleEpsilon - \ru Желаемая угловая точность параллельности касательных в точке стыка сегментов контура. - \en The desired angular precision parallel to the tangent at the point of junction path segments. \~ - \param[out] result - \ru Кривые сечения кинематического тела. - \en Curves of evolution solid section. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) EvolutionSection( const MbSweptData & generCurves, - const MbCurve3D & guideCurve, - double guideParam, - const EvolutionValues & params, - MbSweptData & result, - VERSION version = Math::DefaultMathVersion(), - double angleEpsilon = ANGLE_EPSILON ); - - -//------------------------------------------------------------------------------ -// Является ли кривая прямолинейной независимо от ее параметризации. -/** \brief \ru Является ли кривая прямолинейной независимо от ее параметризации. - \en Whether the curve is like straight-line regardless of its parameterisation. \~ - \details \ru Является ли кривая прямолинейной независимо от ее параметризации.\n - \en Whether the curve is like straight-line regardless of its parameterisation. \~ - \param[in] curve - \ru Кривая. - \en Curve. \~ - \param[in] eps - \ru Точность. - \en Accuracy. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (bool) IsLikeStraightLine( const MbCurve & curve, double eps ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать осевые (центральные) линии для грани оболочки. - \en Create center lines of shell face. \~ - \details \ru Создать осевые (центральные) линии для грани оболочки. \n - \en Create center lines of shell face. \n \~ - \param[in] face - \ru Исходная грань. - \en The initial face. \~ - \param[out] clCurves - \ru Набор построенных осевых линий. - \en The set of created center lines. \~ - \return \ru Возвращает true, если осевые кривые удалось создать. - \en Returns true if the center lines was created. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC( bool ) CreateCenterLineCurves( const MbFace & face, - std::vector & clCurves ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную B-сплайновую кривую на опорной ломаной. - \en Create a fair B-spline on base polyline. \~ - \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать B-сплайновой кривой. - Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. - Для гармоничного перераспределения точек значение переменной arrange == 1. В противном сучае == 0. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, - 1 - как направление касательного вектора). \n - \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. - The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. - For harmonious redistribution of points, the value of the variable arrange == 1. Otherwise, == 0. - To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). - The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, - 1 - as the direction of the tangent vector). \n \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateFairBSplineCurveOnBasePolyline( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную B-сплайновую кривую на касательной ломаной. - \en Create a fair B-spline on tangent polyline. \~ - \details \ru Создать плавную V-кривую на касательной ломаной и аппроксимировать B-сплайновой кривой. - Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. - Для уплотнения кривой устанавливается значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - Направление вектора в точках перегиба кривой совпадает с направлением звена перегиба касательной ломаной. \n - \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. - The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. - To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). - The direction of the tangent vector at the inflection points coincides with the direction of the inflection segment of tangent polyline). \n \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateFairBSplineCurveOnTangentPolyline( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную кривую Безье на опорной ломаной. - \en Create a fair Bezier curve on base polyline. \~ - \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать рациональной кубической кривой Безье. - Для гармоничного перераспределения точек значение переменной arrange == 1. В противном сучае == 0. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного).\n - \en Create a smooth V-curve on the reference polyline and approximate a rational cubic Bezier curve. - For harmonious redistribution of points, the value of the variable arrange == 1. Otherwise, == 0. - To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). \n \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) CreateFairBezierCurveOnBasePolyline( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную кривую Безье на касательной ломаной. - \en Create a fair Bezier curve on tangent polyline. \~ - \details \ru Создать плавную V-кривую на касательной ломаной и аппроксимировать рациональной кубической кривой Безье. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). \n - \en Create a smooth V-curve on a tangent polyline and approximate a rational cubic Bezier curve. - To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). \n \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number.from the message list of the MessageError method. \~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateFairBezierCurveOnTangentPolyline( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать ГО Эрмита на кривой Безье. - \en Create Hermite GD on a Bezier curve. \~ - \details \ru Создать геометрический определитель Эрмита в виде ломаной линии на рациональной сплайновой кривой Безье. \n - На кривой определяется опорная ломаная, вершины которой принадлежат узловым точкам сплайна. - Определяются векторы касательных и векторы кривизны. Вектор касательной может иметь произвольную длину. - Вектор кривизны должет иметь длину, равную значению кривизны в данной вершине опорной ломаной. - Если значение кривизны равно нулю в точке перегиба, то вектор кривизны откладывается по направлению касательного вектора в данной вершине - и имеет произвольную ненулевую длину, не превышающую длину касательного вектора. - Направленная ломаная ГО Эрмита последовательно обходит вершины опорной ломаной, концы касательных векторов и концы векторов кривизны. - Обход происходит следующим образом: от вершины опорной к концу касательного вектора, затем возврат к вершине опорной ломаной, - переход к концу вектора кривизны, возврат к вершине опорной ломаной, затем переход к следующей вершине опорной ломаной и т.д. - Вершина с номером 1 и вершины с номерами через 5 (1, 6, 11, ... ) принадлежат концам касательных векторов. - Вершина с номером 3 и вершины с номерами через 5 (3, 8, 13, ... ) принадлежат концам векторов кривизны. - \en Create a Hermite geometric determinant in the form of a polyline on a rational Bezier spline curve. \n - A base polyline is defined on the curve, the vertices of which belong to the nodal points of the spline. - The tangent vectors and the curvature vectors are determined. The tangent vector can be of arbitrary length. - The curvature vector must have a length equal to the value of curvature at a given vertex of the base polyline. - If the curvature value is zero at the inflection point, then the curvature vector is set in the direction of the tangent vector at the given vertex - and has an arbitrary nonzero length not exceeding the length of the tangent vector. \ n - A directional polyline of Hermite GD sequentially bypasses the vertices of the base polyline, the ends of the tangent vectors and the ends of the curvature vectors. - Bypass occurs as follows: from the vertex of the base polyline to the end of the tangent vector, then return to the vertex of the base polyline, - transition to the end of the curvature vector, return to the vertex of the base polyline, then transition to the next vertex of the base polyline, etc. - The vertex with number 1 and the vertices with numbers in 5 (1, 6, 11, ...) belong to the ends of the tangent vectors. - The vertex with number 3 and the vertices with numbers in 5 (3, 8, 13, ...) belong to the ends of the curvature vectors. \~ - \param[in] curve - \ru Исходная кривая. - \en An initial curve. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] polyline - \ru 3D ломаная ГО Эрмита. - \en 3D polyline of Hermite GD. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) KernelCreateHermiteGDOnBezierCurve( MbNurbs3D * curve, - MbFairCurveData & data, - MbCurve3D *& polyline ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать кривую Безье на ГО Эрмита. - \en Create a Bezier on Hermite GD. \~ - \details \ru Изогеометрически построить рациональную кубическую кривую Безье на ГО Эрмита второго порядка фиксации. - Используются все параметры ГО Эрмита второго порядка фиксации: точки, касательные векторы и значения кривизны. - \en Isogeometrically create a cubic rational Bezier curve on a Hermite GD of second-order fixation. - Used all params of Hermite GD of second-order fixation: points, tangent vectors and values of curvature. \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateBezierCurveOnHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать B-сплайновую кривую на ГО Эрмита. - \en Create a B-spline on Hermite GD. \~ - \details \ru Создать B-сплайную кривую на ГО Эрмита первого порядка фиксации. \n - Направления касательных векторов ГО Эрмита определяют направления звеньев S-полигона. - Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, \n - 1 - как направление касательного вектора). \n - Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). - \en Create a B-spline curve on Hermite's GD of first-order fixation. \ n -               The directions of the tangent vectors of the Hermite GD determine the directions of the S-polygon segmentss. \n -               The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, -               1 - as the direction of the tangent vector). \n -               The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) CreateBSplineCurveOnHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную кривую Безье на опорной ломаной ГО Эрмита. - \en Create a fair Bezier curve on base polyline of Hermite GD. \~ - \details \ru Создать плавную V-кривую на опорной ломаной ГО Эрмита и аппроксимировать рациональной кубической кривой Безье. \n - Учитываются концевые значения кривизны и направления касательных в точках перегиба ГО Эрмита. - Для гармоничного перераспределения точек значение переменной arrange == 1. В противном сучае == 0. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - \en Create a fair V-curve on the base polyline and approximate by a rational cubic Bezier curve. \ n - The end values of the curvature and directions of the tangents at the inflection points of the Hermite GO are taken into account. - For harmonious redistribution of points, the value of the variable arrange == 1. Otherwise, == 0. - To subdivide a curve, the value of the variable subdivision> 0 (1 for a single subdivision, 2 for a double subdivision).\~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) CreateFairBezierCurveOnBasePolylineOfHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную кривую Безье на касательных прямых ГО Эрмита. - \en Create a fair Bezier curve on tangent lines of Hermite GD. \~ - \details \ru Создать плавную V-кривую на касательных прямых ГО Эрмита и аппроксимировать рациональной кубической кривой Безье. \n - Учитываются концевые значения кривизны и положения точек перегиба ГО Эрмита. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - \en Create a fair V-curve on the base polyline and approximate by a rational cubic Bezier curve. \ n -  The end values of the curvature and directions of the tangents at the inflection points of the Hermite GO are taken into account. - To subdivide a curve, set the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision).\~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке \n - из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number \ n -              from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateFairBezierCurveOnTangentsOfHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную B-сплайновую кривую на опорной ломаной ГО Эрмита. - \en Create a fair B-spline curve on base polyline of Hermite GD. \~ - \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать B-сплайновой кривой. \n - Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. - Для гармоничного перераспределения точек значение переменной arrange == 1. В противном сучае == 0. - Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, - 1 - как направление касательного вектора). \n - Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). - \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. \ n - The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. - For harmonious redistribution of points, the value of the variable arrange == 1. Otherwise, == 0. - To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). - The directions of the tangent vectors of the Hermite GD determine the directions of the S-polygon segmentss. \n - The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, \ n - 1 - as the direction of the tangent vector). \n - The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC (MbResultType) CreateFairBSplineCurveOnBasePolylineOfHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать плавную B-сплайновую кривую на касательных прямых ГО Эрмита. - \en Create a fair B-spline curve on tangent lines of Hermite GD. \~ - \details \ru Создать плавную V-кривую на касательных прямых ГО Эрмита и аппроксимировать B-сплайновой кривой. \n - Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. - Для гармоничного перераспределения точек значение переменной arrange == 1. В противном сучае == 0. - Для уплотнения кривой установите значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). - Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). - \en Create a fair V-curve on the base polyline of Hermite GD and approximate by a B-spline curve. \ n - The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degree. - For harmonious redistribution of points, the value of the variable arrange == 1. Otherwise, == 0. - To subdivide a curve, set the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). - The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. - \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) CreateFairBSplineCurveOnTangentsOfHermiteGD( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать клотоиду. - \en Create a clothoid. \~ - \details \ru Создать начальный участок клотоиды. \n - В переменных data задаются параметры построения клотоиды. Максимальная длина начального участка клотоиды в переменной - clothoidMax и минимальный радиус на конце участка в переменной clothoidRMin. В переменной clothoidSegms задается количество - сегментов аппроксимирующей клотоиду сплайновой кривой Безье. - \en Create the starting part of the clothoid. \ n -             The parameters to create the clothoid are set in the data. The maximum length of the initial section of the clothoid in the variable clothoidMax and the minimum radius at the end of the section in the variable clothoidRMin. - The variable clothoidSegms sets the number of segments of the Bezier spline curve approximating the clothoid .\~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. - \en Returns operation result value. - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) KernelCreateClothoid( MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Создать сектрису. - \en Create a sectrix. \~ - \details \ru Создать сектрису Маклорена. \n - На касательной ломаной из двух звеньев генерируются точки сектрисы Маклорена - кривой с монотонным изменением кривизны. - Сектриса Маклорена изогеометрически с сохранением монотонности аппроксимируется сплайновой кривой Безье. - \en Create a sectrix of Maclourin. - On a tangent polyline of two links, points of the Maclaurin sectrix — a curve with a monotonic change in curvature — are generated. -             The Maclaurin sectrix is isometrically approximated with the preservation of monotony by the Bezier spline curve.\~ -            - \param[in] polyline - \ru Исходная ломаная. - \en An initial polyline. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. - \en Returns operation result value. - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) KernelCreateSectrix( MbCurve3D * polyline, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Увеличить степень NURBzS кривой. - \en Elevate the degree of the NURBzS curve. \~ - \details \ru Увеличить степень NURBzS кривой. \n - Степень кубической кривой увеличивается до шестой степени. - Степени больше 6 увеличиваются на единцу. Максимальная степень - 10. - \en The increasing the degree of the NURBzS curve. \n - The degree of the cubic curve increases to the sixth degree. -             Degrees greater than 6 increase by one. The maximum degree is 10.\~ - \param[in] curve - \ru Исходная кривая. - \en An initial curve. \~ - \param[in] data - \ru Данные построения кривой. - \en The curve construction data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. - \en Returns operation result value. - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) ElevateDegreeNurbzs( MbNurbs3D * curve, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Уплотнить NURBS кривую. - \en Subdivide the NURBS curve. \~ - \details \ru Однократно уплотнить NURBS кривую. \n - \en Single subdivision of NURBS curve. \~ - \param[in] curve - \ru Исходная кривая. - \en An initial curve. \~ - \param[in] data - \ru Данные построения и преобразования кривой. - \en Curve construction and transformation data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. - \en Returns operation result value. - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) SubdivideNurbs( MbNurbs3D * curve, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Выделить участок NURBS кривой / изменить формат NURBS кривой. - \en To extrct part of NURBS curve / change the format of the NURBS curve. \~ - \details \ru Выделить участок NURBS кривой / изменить формат NURBS кривой. \n - В data устанавливаются переменые преобразований. Выделямый участок определяется номером начального сегмента в переменной numSegment - и количеством сегментов в переменной numSegments. Выходной формат сплайна определяется в переменной outFormat. - При значении 2 - NURBS кривая с управляющим S-полигоном. При значении 3 - рациональная кривая Безье - с управляющим GB-полигоном. - \en To extrct part of NURBS curve / change the format of the NURBS curve. \n - Transformation variables are set in data. The extracting part is determined by the number of the starting segment in the variable numSegment and the number of segments in the variable numSegments. - The output spline format is defined in the outFormat variable.    If the value is 2 - NURBS curve with control S-polygon. If the value is 3 - rational Bezier curve with GB-control polygon.\~ - \param[in] curve - \ru Исходная кривая. - \en An initial curve. \~ - \param[in] data - \ru Данные построения и преобразования кривой. - \en Curve construction and transformation data. \~ - \param[out] result - \ru Сплайновая кривая. - \en The spline curve. \~ - \return \ru Возвращает значение результата операции. - \en Returns operation result value. - \ingroup Curve3D_Modeling - */ -// --- -MATH_FUNC(MbResultType) ExtractChangeNurbs( MbNurbs3D * curve, - MbFairCurveData & data, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ - /** \brief \ru Вставить узел в NURBS. - \en Insert node in NURBS. \~ - \details \ru Вставить узел в NURBS. \n - В data устанавливаются переменые преобразований. Место вставки узла определяется переменными nSegment и tParam. - В переменной nSegment устанавливается номер сегмента, в переменной tParam (0.1 < tParam < 0.9) задается значение внутреннего параметра на сегменте сплайна. - \en Insert node in NURBS. Transformation variables are set in data. The insertion positon of the node is determined by the variables nSegment and tParam. -             The nSegment variable sets the segment number, the tParam variable (0.1 +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbNurbs3D; +class MATH_CLASS MbContour3D; +class MATH_CLASS MbFace; +class MATH_CLASS MbSurface; +class MATH_CLASS MbWireFrame; +class MATH_CLASS MbItem; +class MATH_CLASS MbName; +class MATH_CLASS MbSweptData; +struct MATH_CLASS EvolutionValues; + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать прямую. + \en Create a line. \~ + \details \ru Создать прямую по двум точкам. \n + \en Create a line given two points. \n \~ + \param[in] point1 - \ru Первая точка. + \en The first point. \~ + \param[in] point2 - \ru Вторая точка. + \en The second point. \~ + \param[out] result - \ru Прямая. + \en The line. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) Line( const MbCartPoint3D & point1, + const MbCartPoint3D & point2, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать отрезок прямой. + \en Create a line segment. \~ + \details \ru Создать отрезок прямой по двум точкам. \n + \en Create a line segment given two points. \n \~ + \param[in] point1 - \ru Первая точка. + \en The first point. \~ + \param[in] point2 - \ru Вторая точка. + \en The second point. \~ + \param[out] result - \ru Отрезок. + \en The segment. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) Segment( const MbCartPoint3D & point1, + const MbCartPoint3D & point2, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эллипс (окружность) или его дугу. + \en Create an ellipse (circle) or an elliptical (circular) arc. \~ + \details \ru Создать эллипс (окружность) или его дугу. \n + Контейнер points может содержать 0, 2 элементов. \n + \en Create an ellipse (circle) or an elliptical (circular) arc. \n + The container 'points' should contain 0 or 2 elements. \n \~ + \param[in] centre - \ru Центр эллипса (окружности) + \en The center of an ellipse (circle). \~ + \param[in] points - \ru Точки дуги. + \en Points on the arc. \~ + \param[in] curveClosed - \ru Замкнутость дуги. + \en The closedness of the arc. \~ + \param[in] angle - \ru Угол наклона. + \en The inclination angle. \~ + \param[in,out] a - \ru Длина большой полуоси. + \en The major axis length. \~ + \param[in,out] b - \ru Длина малой полуоси. + \en The minor axis length. \~ + \param[out] result - \ru Эллипс (окружность) или его дуга. + \en The ellipse (circle) or the elliptical (circular) arc. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) Arc( const MbCartPoint3D & centre, + const SArray & points, + bool curveClosed, double angle, + double & a, double & b, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую, проходящую по набору точек. + \en Create a curve passing through a set of points. \~ + \details \ru Создать кривую, проходящую по набору точек, следующего типа: \n + curveType == st_LineSegment3D - отрезок, \n + curveType == st_Arc3D - окружность или дуга, \n + curveType == st_Polyline3D - ломаная, \n + curveType == st_Bezier3D - кривая Безье, \n + curveType == st_CubicSpline3D - кубический сплайн, \n + curveType == st_Hermit3D - составной кубический сплайн Эрмита, \n + curveType == st_Nurbs3D - неоднородный рациональный B-сплайн четвертого порядка (кубический). \n + \en Create a curve passing through a set of points that has the following type: \n + curveType == st_LineSegment3D - a line segment, \n + curveType == st_Arc3D - a circle or an arc, \n + curveType == st_Polyline3D - a polyline, \n + curveType == st_Bezier3D - a Bezier curve, \n + curveType == st_CubicSpline3D - a cubic spline, \n + curveType == st_Hermit3D - a cubic Hermite spline, \n + curveType == st_Nurbs3D - a nonuniform rational B-spline of fourth order (cubic). \n \~ + \param[in] pointList - \ru Набор точек. + \en A point set. \~ + \param[in] curveClosed - \ru Замкнутость кривой. + \en A curve closedness. \~ + \param[in] curveType - \ru Тип кривой. + \en A curve type. \~ + \param[out] result - \ru Кривая. + \en The curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplineCurve( const SArray & pointList, + bool curveClosed, + MbeSpaceType curveType, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать NURBS-кривую. + \en Create a NURBS-curve. \~ + \details \ru Создать NURBS-кривую, построенную по набору контрольных точек. \n + Контейнер weightList может быть пустым. \n + Контейнер knotList может быть пустым. \n + \en Create a NURBS-curve given a sequence of control points. \n + Container 'weightList' can be empty. \n + Container 'knotList' can be empty. \n \~ + \param[in] pointList - \ru Множество точек. + \en An array of points. \~ + \param[in] weightList - \ru Множество весов. + \en An array of weights. \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline degree. \~ + \param[in] knotList - \ru Множество параметрических узлов (Узловой вектор). + \en An array of parametric knots (A knot vector). \~ + \param[in] curveClosed - \ru Замкнутость кривой. + \en A curve closedness. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) NurbsCurve( const SArray & pointList, + const SArray & weightList, size_t degree, + const SArray & knotList, bool curveClosed, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию кривой в виде NURBS. + \en Create a copy of a curve as a NURBS-curve. \~ + \details \ru Создать копию кривой в виде NURBS. \n + \en Create a copy of a curve as a NURBS-curve. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] result - \ru Сплайновая копия кривой. + \en The spline copy of the curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) NurbsCopy( const MbCurve3D & curve, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать правильный многоугольник, вписанный в окружность. + \en Create a regular polygon inscribed in a circle. \~ + \details \ru Создать правильный многоугольник, вписанный в окружность \n + (при describe == true описанного вокруг окружности) с центром centre и проходящей через point: \n + - при vertexCount <= 1 строится окружность с центром centre и проходящая через point, \n + - при vertexCount == 2 строится прямоугольник со сторонами, параллельными глобальным осям + и противоположными вершинами в centre и point. \n + \en Create a regular polygon inscribed in a circle \n + (if 'describe' == true circumscribed around a circle) with the specified centre and passing through the given point: \n + - if vertexCount <= 1, a circle with center 'center' passing through 'point' is created, \n + - if vertexCount == 2, a rectangle aligned with the global axes + with the opposite vertices at points 'centre' and 'point' is created. \n \~ + \param[in] centre - \ru Центр. + \en The center. \~ + \param[in] point - \ru Точка. + \en A point. \~ + \param[in] axisZ - \ru Ось Z для создания ЛСК кривой. + \en Z-axis for curve LCS creation. \~ + \param[in] vertexCount - \ru Количество вершин. + \en Number of vertices. \~ + \param[in] describe - \ru Описанный вокруг окружности. + \en Circumscribing around the circle. \~ + \param[out] result - \ru Правильный многоугольник. + \en The regular polygon. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) RegularPolygon( const MbCartPoint3D & centre, + const MbCartPoint3D & point, + const MbVector3D & axisZ, + size_t vertexCount, + bool describe, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать спираль. + \en Create a spiral. \~ + \details \ru Создать спираль. \n + Если spiralAxis == true, то lawCurve - определяет плоскую ось спирали. \n + Если spiralAxis == false, то lawCurve - определяет закон изменения радиуса спирали. \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 \~ + \param[in] place - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] radius - \ru Радиус спирали. + \en A spiral radius. \~ + \param[in] step - \ru Шаг спирали. + \en A pitch. \~ + \param[in] lawCurve - \ru Формообразующая кривая. + \en A guide curve. \~ + \param[in] spiralAxis - \ru Выбор режима формообразования + \en A spiral construction mode. \~ + \param[out] result - \ru Спиральная кривая. + \en The spiral curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SpiralCurve( const MbPlacement3D & place, + double radius, + double step, + MbCurve & lawCurve, + bool spiralAxis, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать спираль. + \en Create a spiral. \~ + \details \ru Создать спираль. \n + Если spiralAxis == true, то lawCurve - определяет плоскую ось спирали. \n + Если spiralAxis == false, то lawCurve - определяет закон изменения радиуса спирали. \n + Если lawCurve == 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 \~ + \param[in] point0 - \ru Начало локальной системы координат (ЛСК). + \en The origin of local coordinate system (LCS). \~ + \param[in] point1 - \ru Точка на оси Z ЛСК. + \en A point on Z-axis of LCS. \~ + \param[in] point2 - \ru Точка на оси X ЛСК. + \en A point on the X-axis of LCS. \~ + \param[in] radius - \ru Радиус спирали. + \en A spiral radius. \~ + \param[in] step - \ru Шаг спирали. + \en A pitch. \~ + \param[in] angle - \ru Угол коничности спирали. + \en A taper angle. \~ + \param[in] lawCurve - \ru Формообразующая кривая. + \en A guide curve. \~ + \param[in] spiralAxis - \ru Выбор режима формообразования + \en A spiral construction mode. \~ + \param[out] result - \ru Спиральная кривая. + \en The spiral curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SpiralCurve( const MbCartPoint3D & point0, + const MbCartPoint3D & point1, + const MbCartPoint3D & point2, + double radius, + double step, + double angle, + MbCurve * lawCurve, + bool spiralAxis, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать составную кривую (контур). + \en Create a composite curve (contour). \~ + \details \ru Создать составную кривую (контур) на базе исходной кривой. \n + \en Create a composite curve (contour) on the basis of the given curve. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] result - \ru Контур на основе кривой. + \en The contour created on the basis of the curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) CreateContour( MbCurve3D & curve, + MbContour3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать копию кривой. + \en Create a copy of a curve. \~ + \details \ru Создать копию кривой с разбивкой ломаной линии и заменой некоторых кривых. \n + \en Create a copy of a curve with splitting of a polyline and replacement of some curves. \n \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \return \ru Возвращает модифицированную копию кривой, если получилось ее создать. + \en Returns a modified copy of the curve if it has been successfully created. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCurve3D *) DuplicateCurve( const MbCurve3D & curve, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить кривую в составную кривую (контур). + \en Add a curve to a composite curve (a contour). \~ + \details \ru Добавить кривую curve в составную кривую (контур) contour. \n + Если toEnd == true, то добавить в конец. \n + Если toEnd == false, то добавить в начало. \n + \en Add a curve to a composite curve (a contour) 'contour'. \n + If toEnd == true, the curve is to be added to the end. \n + If toEnd == true, the curve is to be added to the beginning. \n \~ + \param[in] curve - \ru Добавляемая кривая + \en A curve to be added. \~ + \param[in,out] contour - \ru Модифицируемый контур. + \en A contour to be modified. \~ + \param[in] toEnd - \ru Флаг места добавления кривой. + \en The flag determines the place of the curve in the contour. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) AddCurveToContour( MbCurve3D & curve, + MbCurve3D & contour, + bool toEnd ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить кривую в пространстве по двумерной кривой. + \en Create a space curve from a two-dimensional curve. \~ + \details \ru Построить кривую в пространстве по двумерной кривой сurve на плоскости place. \n + Построение выполняется на оригинале кривой. + \en Create a space curve from a two-dimensional curve 'curve' lying on plane 'place'. \n + The construction is performed on the source curve. \~ + \param[in] place - \ru Система координат плоскости. + \en The plane coordinate system. \~ + \param[in] curve - \ru Двумерная кривая + \en A two-dimensional curve \~ + \param[out] result - \ru Плоская кривая. + \en The planar curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) PlaneCurve( const MbPlacement3D & place, + const MbCurve & curve, + MbCurve3D *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Построить кривую на поверхности по двумерной кривой. + \en Create a curve on a surface given a two-dimensional curve. \~ + \details \ru Построить кривую на поверхности surface по двумерной кривой сurve. \n + Построение выполняется на оригиналах кривой и поверхности. + \en Create a curve on a surface 'surface' given a two-dimensional curve 'curve'. \n + The construction is performed on the original curve and surface. \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] curve - \ru Двумерная кривая + \en A two-dimensional curve \~ + \param[out] result - \ru Поверхностная кривая. + \en The curve on the specified surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SurfaceCurve( const MbSurface & surface, + const MbCurve & curve, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхностную кривую, если пространственная кривая лежит на поверхности. + \en Create a curve on a surface from a space curve lying on the surface. \~ + \details \ru Создать поверхностную кривую, если пространственная кривая лежит на поверхности. \n + Разбираются частные случае точной принадлежности кривой выбранной поверхности. + В общем случае пространственная кривая считается принадлежащей поверхности, если группа точек, + полученная шаганием по параметру кривой по угловому отклонению, принадлежит поверхности. + В этом случае создается двумерная проекционная кривая этой кривой на поверхности. \n + \en Create a curve on a surface from a space curve lying on the surface. \n + The special cases of curves exactly lying on the specified surfaces are treated. + In the general case a space curve is considered to lie on the surface if a group of points + obtained by sampling the curve with the given turning angle belongs to the surface. + In this case a two-dimensional curve is created as the projection of the curve on the surface. \n \~ + \param[in] curve - \ru Пространственная кривая. + \en A space curve. \~ + \param[in] surf - \ru Поверхность. + \en A surface. \~ + \param[in] sameSurf - \ru Использовать оригинал поверхности. + \en Whether to use the source surface. \~ + \param[in] extSurf - \ru Искать на расширенной поверхности. + \en Whether to use the extended surface. \~ + \param[in] strictOnSurface - \ru Все точки кривой лежат на поверхности (true) или часть точек лежит на поверхности (false). + \en All the points of the curve belong to the surface (true) or a part of the points belong to the surface (false). \~ + \param[out] result - \ru Поверхностная кривая. + \en The curve on the specified surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) CurveOnSurface( const MbCurve3D & curve, + const MbSurface & surf, + bool sameSurf, bool extSurf, + MbCurve3D *& result, + bool strictOnSurface = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Лежит ли кривая на поверхности. + \en Determine whether the curve lies on the surface. \~ + \details \ru Проверить, лежит ли кривая полностью на поверхности. \n + \en Determine whether the curve entirely lies on the surface. \n \~ + \param[in] curve - \ru Пространственная кривая. + \en A space curve. \~ + \param[in] surf - \ru Поверхность. + \en A surface. \~ + \param[in] ext - \ru Искать на расширенной поверхности. + \en Whether to use the extended surface. \~ + \param[in] strictOnSurface - \ru Все точки кривой лежат на поверхности (true) или часть точек лежит на поверхности (false). + \en All the points of the curve belong to the surface (true) or a part of the points belong to the surface (false). \~ + \return \ru Возвращает true, если кривая лежит на поверхности. + \en Returns true if the curve lies on the surface. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (bool) IsCurveOnSurface( const MbCurve3D & curve, + const MbSurface & surf, bool ext, + bool strictOnSurface, // = false + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив контуров по массиву кривых. + \en Create an array of contours given an array of curves. \~ + \details \ru Создать массив контуров по массиву кривых (на оригиналах кривых). \n + \en Create an array of contours given an array of curves (using the original curves). \n \~ + \param[in] curves - \ru Множество кривых. + \en An array of curves. \~ + \param[in] metricEps - \ru Радиус захвата для стыковки кривых. + \en The radius for curves joining. \~ + \param[out] result - \ru Множество контуров. + \en The array of contours. \~ + \param[in] onlySmoothConnected - \ru Добавлять в контур только гладко стыкующиеся сегменты. + \en Whether to add only smoothly connected segments. \~ + \param[in] version - \ru Версия исполнения. + \en Version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateContours( RPArray & curves, + double metricEps, + RPArray & result, + bool onlySmoothConnected = false, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать контуры по набору кривых с удалением вырожденных. + \en Create contours given a set of curves with elimination of degenerate ones. \~ + \details \ru Создать контуры по набору кривых с удалением вырожденных (на оригиналах кривых). \n + \en Create contours given a set of curves with elimination of degenerate ones (the original curves are used). \n \~ + \param[in, out] curves - \ru Множество кривых. + \en An array of curves. \~ + \param[in] metricAcc - \ru Радиус захвата для стыковки кривых. + \en The radius for curves joining. \~ + \param[in] onlySmoothConnected - \ru Добавлять в контур только гладко стыкующиеся сегменты. + \en Whether to add only smoothly connected segments. \~ + \param[in] version - \ru Версия исполнения. + \en Version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) CreateContours( RPArray & curves, + double metricAcc, + bool onlySmoothConnected = false, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать именованный трехмерный каркас. + \en Create a named three-dimensional wireframe. \~ + \details \ru Создать именованный трехмерный каркас по кривой. \n + \en Create a named three-dimensional wireframe from a curve. \n \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] curveName - \ru Имя кривой. + \en The curve name. \~ + \param[in] mainName - \ru Главное имя операции. + \en The operation main name. \~ + \param[out] result - \ru Каркас. + \en The wireframe. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) WireFrame( const MbCurve3D & curve, + const MbName & curveName, + SimpleName mainName, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать именованный трехмерный каркас. + \en Create a named three-dimensional wireframe. \~ + \details \ru Создать именованный трехмерный каркас по массиву кривых. \n + \en Create a named three-dimensional wireframe from a given array of curves. \n \~ + \param[in] curves - \ru Множество кривых. + \en An array of curves. \~ + \param[in] curveNames - \ru Множество имен кривых. + \en An array of the curves names. \~ + \param[in] mainName - \ru Главное имя операции. + \en The operation main name. \~ + \param[out] result - \ru Каркас. + \en The wireframe. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) WireFrame( const RPArray & curves, + const RPArray & curveNames, + SimpleName mainName, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Аппроксимировать контур дугами и отрезками. + \en Approximate a contour with arcs and line segments. \~ + \details \ru Аппроксимировать контур дугами и отрезками. \n + Производится аппроксимация каждого из сегментов контура. \n + \en Approximate a contour with arcs and line segments. \n + The approximation is performed for each segment of the contour. \n \~ + \param[in] curve - \ru Кривая или контур, которую надо аппроксимировать. + \en A curve or a contour to approximate. \~ + \param[out] result - \ru Результат аппроксимации. + \en The approximation result. \~ + \param[in] eps - \ru Ошибка аппроксимации. + \en The approximation precision. \~ + \param[in] minRad - \ru Минимально допустимый радиус окружностей, используемых для аппроксимации. + \en The minimal acceptable radius of the circles used for the approximation. \~ + \param[in] maxRad - \ru Максимально допустимый радиус окружностей, используемых для аппроксимации. + \en The maximal acceptable radius of the circles used for the approximation. \~ + \return \ru - Возращает код результата операции. + \en - Returns operation result code. \~ +\ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreatePolyArcCurve3D( const MbCurve3D & curve, + MbCurve3D *& result, + double & eps, + double minRad = Math::minRadius, + double maxRad = Math::maxRadius ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить или создать пространственную кривую. + \en Get or create a space curve. \~ + \details \ru Получить или создать пространственную кривую из данных модельного объекта + c опциональным сохранением несущей плоскости в случае плоского объекта. \n + Двумерный контур на плоскости преобразуется не в контур на плоскости, + а в пространственный контур. \n + \en Get or create a space curve from a model object data. + with optional keeping of supporting plane in the case of a planar object. \n + A two-dimensional contour is to be converted not to a contour on a plane + but to a three-dimensional contour. \n \~ + \param[in] item - \ru Модельный объект. + \en A model object. \~ + \param[in] keepPlacement - \ru Сохранять несущую плоскость. + \en Whether to keep the supporting plane. \~ + \param[out] curve0 - \ru Пространственная кривая. + \en A space curve. \~ + \param[out] curves - \ru Дополнительные пространственные кривые (могут быть в объекте MbPlaneInstance). + \en Additional space curve (It's possible if a object "MbItem" is the object "MbPlaneInstance"). \~ + \return \ru - Возвращает успешность результата операции. + \en - Returns whether the result is successful. \~ +\ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (bool) GetSpaceCurve( const MbItem & item, + bool keepPlacement, + SPtr & curve0, + std::vector< SPtr > * curves = NULL ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Построить развертку кривой/контура на плоскость. + \en Construct a unwrapping curve/contour. \~ + \details \ru Построение развертки кривой/контура на плоскость. Контур разворачивается посегментно, функцией UnwrapCurve. + Первым разворачивается сегмент, который лежит в плоскости и находиться ближе всех к точке, + если лежащих в плоскости нет, то ближащий к точке из тех что пересекают контур, если и таких нет то просто ближайший к точке. + Первый сегмент разворачивается так, чтобы точка пересечения или ближайшей проекции была неподвижной. \n + \en Construction unwrapping of the curve/contour on a plane. Each segment of the contour is unwrapped by the function UnwrapCurve. + Unwrapping starting with a segment which lies in the plane or crosses the plane and which is closest to the given point. + Unwrapping of the first segment is constructed in the manner, that cross point or closest projection of the segment on the plane were stationary. \n \~ + \param[in] curve - \ru Разворачиваемая кривая/контур. + \en Original curve/contour. \~ + \param[in] placement - \ru Локальная система координат плоскости. + \en The placement of the plane. \~ + \param[in] point - \ru Точка для определения первого сегмента. + \en The point for determine first segment. \~ + \param[in] deviationAngle - \ru Параметру точности. + \en The parameter of accuracy. \~ + \return \ru Возвращает указатель на построенную кривую с нулевум счетчиком ссылок \n + или 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 +\ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCurve3D *) UnwrapCurve( const MbCurve3D & curve, + const MbPlacement3D & placement, + const MbCartPoint3D & point, + double deviationAngle = DEVIATION_SAG); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать сечение кинематического тела для заданного параметра на направляющей. + \en Create a section of evolution solid for defined parameter on the guide curve. \~ + \details \ru Создать сечение кинематического тела для заданного параметра на направляющей. + Если направляющая является контуром, то стыки между сегментами контура должны быть гладкими. \n + \en Create a section of evolution solid (sweep solid with guide curve) for defined parameter on guide curve. + If the guide curve is a contour, then this contour have to be smooth. \n \~ + \param[in] generCurves - \ru Множество плоских образующих. + \en An array of forming curves. \~ + \param[in] guideCurve - \ru Направляющая кривая (или контур). + \en An guide curve (or contour). \~ + \param[in] guideParam - \ru Параметр, заданный на направляющей кривой. + \en A parameter on the guide curve. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[out] result - \ru Кривые сечения кинематического тела. + \en Curves of evolution solid section. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[in] angleEpsilon - \ru Желаемая угловая точность параллельности касательных в точке стыка сегментов контура. + \en The desired angular precision parallel to the tangent at the point of junction path segments. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) EvolutionSection( const MbSweptData & generCurves, + const MbCurve3D & guideCurve, + double guideParam, + const EvolutionValues & params, + MbSweptData & result, + VERSION version = Math::DefaultMathVersion(), + double angleEpsilon = ANGLE_EPSILON ); + + +//------------------------------------------------------------------------------ +// Является ли кривая прямолинейной независимо от ее параметризации. +/** \brief \ru Является ли кривая прямолинейной независимо от ее параметризации. + \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \details \ru Является ли кривая прямолинейной независимо от ее параметризации.\n + \en Whether the curve is like straight-line regardless of its parameterisation. \~ + \param[in] curve - \ru Кривая. + \en Curve. \~ + \param[in] eps - \ru Точность. + \en Accuracy. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (bool) IsLikeStraightLine( const MbCurve3D & curve, double eps ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать осевые (центральные) линии для грани оболочки. + \en Create center lines of shell face. \~ + \details \ru Создать осевые (центральные) линии для грани оболочки. \n + \en Create center lines of shell face. \n \~ + \param[in] face - \ru Исходная грань. + \en The initial face. \~ + \param[out] clCurves - \ru Набор построенных осевых линий. + \en The set of created center lines. \~ + \return \ru Возвращает true, если осевые кривые удалось создать. + \en Returns true if the center lines was created. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC( bool ) CreateCenterLineCurves( const MbFace & face, + std::vector & clCurves ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную B-сплайновую кривую на опорной ломаной. + \en Create a fair B-spline on base polyline. \~ + \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать B-сплайновой кривой. + Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, + 1 - как направление касательного вектора). \n + \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. + The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). + The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, + 1 - as the direction of the tangent vector). \n \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateFairBSplineCurveOnBasePolyline( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную B-сплайновую кривую на касательной ломаной. + \en Create a fair B-spline on tangent polyline. \~ + \details \ru Создать плавную V-кривую на касательной ломаной и аппроксимировать B-сплайновой кривой. + Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. + Для уплотнения кривой устанавливается значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + Направление вектора в точках перегиба кривой совпадает с направлением звена перегиба касательной ломаной. \n + \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. + The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). + The direction of the tangent vector at the inflection points coincides with the direction of the inflection segment of tangent polyline). \n \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateFairBSplineCurveOnTangentPolyline( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную кривую Безье на опорной ломаной. + \en Create a fair Bezier curve on base polyline. \~ + \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать рациональной кубической кривой Безье. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного).\n + \en Create a smooth V-curve on the reference polyline and approximate a rational cubic Bezier curve. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). \n \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) CreateFairBezierCurveOnBasePolyline( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную кривую Безье на касательной ломаной. + \en Create a fair Bezier curve on tangent polyline. \~ + \details \ru Создать плавную V-кривую на касательной ломаной и аппроксимировать рациональной кубической кривой Безье. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). \n + \en Create a smooth V-curve on a tangent polyline and approximate a rational cubic Bezier curve. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). \n \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number.from the message list of the MessageError method. \~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateFairBezierCurveOnTangentPolyline( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать ГО Эрмита на кривой Безье. + \en Create Hermite GD on a Bezier curve. \~ + \details \ru Создать геометрический определитель Эрмита в виде ломаной линии на рациональной сплайновой кривой Безье. \n + На кривой определяется опорная ломаная, вершины которой принадлежат узловым точкам сплайна. + Определяются векторы касательных и векторы кривизны. Вектор касательной может иметь произвольную длину. + Вектор кривизны должет иметь длину, равную значению кривизны в данной вершине опорной ломаной. + Если значение кривизны равно нулю в точке перегиба, то вектор кривизны откладывается по направлению касательного вектора в данной вершине + и имеет произвольную ненулевую длину, не превышающую длину касательного вектора. + Направленная ломаная ГО Эрмита последовательно обходит вершины опорной ломаной, концы касательных векторов и концы векторов кривизны. + Обход происходит следующим образом: от вершины опорной к концу касательного вектора, затем возврат к вершине опорной ломаной, + переход к концу вектора кривизны, возврат к вершине опорной ломаной, затем переход к следующей вершине опорной ломаной и т.д. + Вершина с номером 1 и вершины с номерами через 5 (1, 6, 11, ... ) принадлежат концам касательных векторов. + Вершина с номером 3 и вершины с номерами через 5 (3, 8, 13, ... ) принадлежат концам векторов кривизны. + \en Create a Hermite geometric determinant in the form of a polyline on a rational Bezier spline curve. \n + A base polyline is defined on the curve, the vertices of which belong to the nodal points of the spline. + The tangent vectors and the curvature vectors are determined. The tangent vector can be of arbitrary length. + The curvature vector must have a length equal to the value of curvature at a given vertex of the base polyline. + If the curvature value is zero at the inflection point, then the curvature vector is set in the direction of the tangent vector at the given vertex + and has an arbitrary nonzero length not exceeding the length of the tangent vector. \ n + A directional polyline of Hermite GD sequentially bypasses the vertices of the base polyline, the ends of the tangent vectors and the ends of the curvature vectors. + Bypass occurs as follows: from the vertex of the base polyline to the end of the tangent vector, then return to the vertex of the base polyline, + transition to the end of the curvature vector, return to the vertex of the base polyline, then transition to the next vertex of the base polyline, etc. + The vertex with number 1 and the vertices with numbers in 5 (1, 6, 11, ...) belong to the ends of the tangent vectors. + The vertex with number 3 and the vertices with numbers in 5 (3, 8, 13, ...) belong to the ends of the curvature vectors. \~ + \param[in] curve - \ru Исходная кривая. + \en An initial curve. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] polyline - \ru 3D ломаная ГО Эрмита. + \en 3D polyline of Hermite GD. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) KernelCreateHermiteGDOnBezierCurve( MbNurbs3D * curve, + MbFairCurveData & data, + MbCurve3D *& polyline ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать кривую Безье на ГО Эрмита. + \en Create a Bezier on Hermite GD. \~ + \details \ru Изогеометрически построить рациональную кубическую кривую Безье на ГО Эрмита второго порядка фиксации. + Используются все параметры ГО Эрмита второго порядка фиксации: точки, касательные векторы и значения кривизны. + \en Isogeometrically create a cubic rational Bezier curve on a Hermite GD of second-order fixation. + Used all params of Hermite GD of second-order fixation: points, tangent vectors and values of curvature. \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateBezierCurveOnHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать B-сплайновую кривую на ГО Эрмита. + \en Create a B-spline on Hermite GD. \~ + \details \ru Создать B-сплайную кривую на ГО Эрмита первого порядка фиксации. \n + Направления касательных векторов ГО Эрмита определяют направления звеньев S-полигона. + Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, \n + 1 - как направление касательного вектора). \n + Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). + \en Create a B-spline curve on Hermite's GD of first-order fixation. \ n +               The directions of the tangent vectors of the Hermite GD determine the directions of the S-polygon segmentss. \n +               The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, +               1 - as the direction of the tangent vector). \n +               The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) CreateBSplineCurveOnHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную кривую Безье на опорной ломаной ГО Эрмита. + \en Create a fair Bezier curve on base polyline of Hermite GD. \~ + \details \ru Создать плавную V-кривую на опорной ломаной ГО Эрмита и аппроксимировать рациональной кубической кривой Безье. \n + Учитываются концевые значения кривизны и направления касательных в точках перегиба ГО Эрмита. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + \en Create a fair V-curve on the base polyline and approximate by a rational cubic Bezier curve. \ n + The end values of the curvature and directions of the tangents at the inflection points of the Hermite GO are taken into account. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, the value of the variable subdivision> 0 (1 for a single subdivision, 2 for a double subdivision).\~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) CreateFairBezierCurveOnBasePolylineOfHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную кривую Безье на касательных прямых ГО Эрмита. + \en Create a fair Bezier curve on tangent lines of Hermite GD. \~ + \details \ru Создать плавную V-кривую на касательных прямых ГО Эрмита и аппроксимировать рациональной кубической кривой Безье. \n + Учитываются концевые значения кривизны и положения точек перегиба ГО Эрмита. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + \en Create a fair V-curve on the base polyline and approximate by a rational cubic Bezier curve. \ n +  The end values of the curvature and directions of the tangents at the inflection points of the Hermite GO are taken into account. + To subdivide a curve, set the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision).\~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке \n + из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number \ n +              from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateFairBezierCurveOnTangentsOfHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную B-сплайновую кривую на опорной ломаной ГО Эрмита. + \en Create a fair B-spline curve on base polyline of Hermite GD. \~ + \details \ru Создать плавную V-кривую на опорной ломаной и аппроксимировать B-сплайновой кривой. \n + Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + Направление вектора в точках перегиба учитывается по значению переменной accountInflexVector (0 - как направление звена S-полигона, + 1 - как направление касательного вектора). \n + Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). + \en Create a fair V-curve on the base polyline and approximate by a B-spline curve. \ n + The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degreeBSpline. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). + The directions of the tangent vectors of the Hermite GD determine the directions of the S-polygon segmentss. \n + The direction of the vector at the inflection points is taken into account by the value of the variable InflexVector (0 - as the direction of the S-polygon segment, \ n + 1 - as the direction of the tangent vector). \n + The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC (MbResultType) CreateFairBSplineCurveOnBasePolylineOfHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать плавную B-сплайновую кривую на касательных прямых ГО Эрмита. + \en Create a fair B-spline curve on tangent lines of Hermite GD. \~ + \details \ru Создать плавную V-кривую на касательных прямых ГО Эрмита и аппроксимировать B-сплайновой кривой. \n + Степень сплайна m, (m = 3, 4, ... , 9, 10) устанавливается в переменной degreeBSpline. + Для гармоничного перераспределения точек значение переменной arrange == true. В противном случае == false. + Для уплотнения кривой установите значение переменной subdivision > 0 (1 - для однократного уплотнения, 2 - для двукратного). + Кривизна в концевых точках учитывается по значению accountCurvature (0 - не учитывается, 1 - в начальной точке, 2 - в конечной точке, 3 - учитываются на обоих концах). + \en Create a fair V-curve on the base polyline of Hermite GD and approximate by a B-spline curve. \ n + The degree of spline m, (m = 3, 4, ... , 9, 10) is set by variable degree. + For harmonious redistribution of points, the value of the variable arrange == true. Otherwise, == false. + To subdivide a curve, set the value of the variable subdivision > 0 (1 for a single subdivision, 2 for a double subdivision). + The curvature at the end points is taken into account by the value of accountCurvature (0 - not taken into account, 1 - at the start point, 2 - at the end point, 3 - are taken into account at both ends). \~ + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. 0 - при успешном построении кривой. При > 0 значение равно номеру сообщения об ошибке из списка сообщений метода MessageError. + \en Returns operation result value. 0 - upon successful creation of the curve. If > 0, the value is equal to the error message number from the message list of the MessageError method.\~ + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) CreateFairBSplineCurveOnTangentsOfHermiteGD( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать клотоиду. + \en Create a clothoid. \~ + \details \ru Создать начальный участок клотоиды. \n + В переменных data задаются параметры построения клотоиды. Максимальная длина начального участка клотоиды в переменной + clothoidMax и минимальный радиус на конце участка в переменной clothoidRMin. В переменной clothoidSegms задается количество + сегментов аппроксимирующей клотоиду сплайновой кривой Безье. + \en Create the starting part of the clothoid. \ n +             The parameters to create the clothoid are set in the data. The maximum length of the initial section of the clothoid in the variable clothoidMax and the minimum radius at the end of the section in the variable clothoidRMin. + The variable clothoidSegms sets the number of segments of the Bezier spline curve approximating the clothoid .\~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) KernelCreateClothoid( MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Создать сектрису. + \en Create a sectrix. \~ + \details \ru Создать сектрису Маклорена. \n + На касательной ломаной из двух звеньев генерируются точки сектрисы Маклорена - кривой с монотонным изменением кривизны. + Сектриса Маклорена изогеометрически с сохранением монотонности аппроксимируется сплайновой кривой Безье. + \en Create a sectrix of Maclourin. + On a tangent polyline of two links, points of the Maclaurin sectrix — a curve with a monotonic change in curvature — are generated. +             The Maclaurin sectrix is isometrically approximated with the preservation of monotony by the Bezier spline curve.\~ +            + \param[in] polyline - \ru Исходная ломаная. + \en An initial polyline. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) KernelCreateSectrix( MbCurve3D * polyline, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Увеличить степень NURBzS кривой. + \en Elevate the degree of the NURBzS curve. \~ + \details \ru Увеличить степень NURBzS кривой. \n + Степень кубической кривой увеличивается до шестой степени. + Степени больше 6 увеличиваются на единцу. Максимальная степень - 10. + \en The increasing the degree of the NURBzS curve. \n + The degree of the cubic curve increases to the sixth degree. +             Degrees greater than 6 increase by one. The maximum degree is 10.\~ + \param[in] curve - \ru Исходная кривая. + \en An initial curve. \~ + \param[in] data - \ru Данные построения кривой. + \en The curve construction data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) ElevateDegreeNurbzs( MbNurbs3D * curve, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Уплотнить NURBS кривую. + \en Subdivide the NURBS curve. \~ + \details \ru Однократно уплотнить NURBS кривую. \n + \en Single subdivision of NURBS curve. \~ + \param[in] curve - \ru Исходная кривая. + \en An initial curve. \~ + \param[in] data - \ru Данные построения и преобразования кривой. + \en Curve construction and transformation data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) SubdivideNurbs( MbNurbs3D * curve, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Выделить участок NURBS кривой / изменить формат NURBS кривой. + \en To extrct part of NURBS curve / change the format of the NURBS curve. \~ + \details \ru Выделить участок NURBS кривой / изменить формат NURBS кривой. \n + В data устанавливаются переменые преобразований. Выделямый участок определяется номером начального сегмента в переменной numSegment + и количеством сегментов в переменной numSegments. Выходной формат сплайна определяется в переменной outFormat. + При значении 2 - NURBS кривая с управляющим S-полигоном. При значении 3 - рациональная кривая Безье + с управляющим GB-полигоном. + \en To extract part of NURBS curve / change the format of the NURBS curve. \n + Transformation variables are set in data. The extracting part is determined by the number of the starting segment in the variable numSegment and the number of segments in the variable numSegments. + The output spline format is defined in the outFormat variable.    If the value is 2 - NURBS curve with control S-polygon. If the value is 3 - rational Bezier curve with GB-control polygon.\~ + \param[in] curve - \ru Исходная кривая. + \en An initial curve. \~ + \param[in] data - \ru Данные построения и преобразования кривой. + \en Curve construction and transformation data. \~ + \param[out] result - \ru Сплайновая кривая. + \en The spline curve. \~ + \return \ru Возвращает значение результата операции. + \en Returns operation result value. + \ingroup Curve3D_Modeling + */ +// --- +MATH_FUNC(MbResultType) ExtractChangeNurbs( MbNurbs3D * curve, + MbFairCurveData & data, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ + /** \brief \ru Вставить узел в NURBS. + \en Insert node in NURBS. \~ + \details \ru Вставить узел в NURBS. \n + В data устанавливаются переменые преобразований. Место вставки узла определяется переменными nSegment и tParam. + В переменной nSegment устанавливается номер сегмента, в переменной tParam (0.1 < tParam < 0.9) задается значение внутреннего параметра на сегменте сплайна. + \en Insert node in NURBS. Transformation variables are set in data. The insertion positon of the node is determined by the variables nSegment and tParam. +             The nSegment variable sets the segment number, the tParam variable (0.1 -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbSplineSurface; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbSNameMaker; - - -//------------------------------------------------------------------------------ -/** \brief \ru Модифицировать тело по матрице. - \en Modify a solid by the matrix. \~ - \details \ru Выполнить трансформацию копии исходного тела по матрице, рассчитанной по габаритному кубу. \n - \en Transform a copy of the solid using the matrix calculated by bounding box of solid. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] p - \ru Параметры трансформации. - \en The transformation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) TransformedSolid( MbSolid & solid, - MbeCopyMode sameShell, - const TransformValues & p, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Собрать грани оболочки для методов прямого моделирования. - \en Modify a shell by the methods of direct modeling. \~ - \details \ru Функция собирает грани оболочки для методов прямого моделирования: \n - удаление из тела выбранных граней с окружением (way==dmt_Remove), \n - удаление выбранных граней скругления тела (way==dmt_Purify). \n - Для удаления граней собираются замкнутые цилиндрические, конические, тороидальные, сферические грани тела, - а также грани вращения, радиус которых не превосходит указанный радиус. - Для удаления граней скругления собираются незамкнутые цилиндрические, тороидальные, сферические грани, - а также грани скругления, радиус которых не превосходит указанный радиус. \n - \en The method collects the faces of the shell for direct modeling methods: \n - removal of the faces from a shell (way==dmt_Remove), \n - removal of the fillet faces from a shell (way==dmt_Purify). \n - The cylindrical, conical, toroidal, spherical, and revolution periodic faces are collect to remove way. - The cylindrical, toroidal, spherical non-periodic, and fillet faces are collect to purify way. \n \~ - \param[in] shell - \ru Исходная оболочка тела. - \en The initial faces set. \~ - \param[in] way - \ru Способ модификации. - \en Way of the modification. \~ - \param[in] radius - \ru Радиус собираемых граней. - \en Radius of collected faces. \~ - \param[in] faces - \ru Найденные грани для дальнейшей модификации. - \en Found faces to be modified. \~ - \return \ru Возвращает код результата действий. - \en Returns action result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CollectFacesForModification( MbFaceShell * shell, - MbeModifyingType way, - double radius, - RPArray & faces ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Модифицировать или построить тело методами прямого моделирования. - \en Modify a solid by the methods of direct modeling. \~ - \details \ru В зависимости от параметров модификации метод выполняет одно из следующих действий: \n - 1. Удаление из тела выбранных граней с окружением (param.way==dmt_Remove). \n - 2. Создание тела из выбранных граней с окружением (param.way==dmt_Create). \n - 3. Перемещение выбранных граней с окружением относительно оставшихся граней тела (param.way==dmt_Action). \n - 4. Замена выбранных граней тела эквидистантными гранями (param.way==dmt_Offset). \n - 5. Изменение радиуса выбранных граней скругления (param.way==dmt_Fillet). \n - 6. Замена выбранных граней тела деформируемыми гранями для редактирования (param.way==dmt_Supple). \n - 7. Удаление выбранных граней скругления тела (param.way==dmt_Purify). - \en The method is for one of listed actions below depends of parameters: \n - 1. Removal of the specified faces with the neighborhood from a solid (param.way==dmt_Remove). \n - 2. Creation of a solid from the specified faces with the neighborhood (param.way==dmt_Create). \n - 3. Translation of the specified faces with neighborhood relative to the other faces of the solid (param.way==dmt_Action). \n - 4. Replacement of the specified faces of a solid with the offset faces (param.way==dmt_Offset). \n - 5. Changing of the radius of the specified fillet faces (param.way==dmt_Fillet). \n - 6. Replacement of the specified faces of a solid with a deformable faces for editing (param.way==dmt_Supple). \n - 7. Removal of the specified fillet faces from a solid (param.way==dmt_Purify). \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] params - \ru Параметры модификации. - \en Parameters of the modification. \~ - \param[in] faces - \ru Изменяемые грани тела. - \en Faces to be modified. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FaceModifiedSolid( MbSolid & solid, - MbeCopyMode sameShell, - const ModifyValues & params, - const RPArray & faces, - const MbSNameMaker & names, - MbSolid *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Модифицировать или построить тело методами прямого моделирования. - \en Modify a solid by the methods of direct modeling. \~ - \details \ru Метод выполняет удаление указанных рёбер, слияние их вершин и модификацию окружающих граней (param.way==dmt_Merger). - По направлению вектора "param.direction" определяется: начальная ли вершина ребра будет слита с конечной вершиной, или конечная вершина ребра будет слита с начальной вершиной. \n - \en The method performs the deletion of selectsd edges, merging their vertices and modification of surrounding faces (param.way==dmt_Merger). - The direction of the vector "params.direction" determines whether the start vertex of an edge is merged with the end vertex, or whether the end vertex of an edge is merged with the start vertex. \n - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] params - \ru Параметры модификации, способ должен быть равен param.way==dmt_Merger. - \en Parameters of the modification, the way must be equal to param.way==dmt_Merger. \~ - \param[in] edges - \ru Удаляемые рёьра тела. - \en Edges to be removed. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- - -MATH_FUNC (MbResultType) EdgeModifiedSolid( MbSolid & solid, - MbeCopyMode sameShell, - const ModifyValues & params, - const RPArray & edges, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Заменить выбранные грани тела деформируемыми гранями. - \en Replace the specified faces of solid with deformable faces. \~ - \details \ru Заменить выбранные грани тела деформируемыми гранями (превращение в NURBS для редактирования). \n - \en Replace the specified faces of the solid with deformable faces (conversion to NURBS for editing). \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] p - \ru Параметры преобразования. - \en The transformation parameters. \~ - \param[in] faces - \ru Заменяемые грани тела. - \en Faces to replace. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ModifiedNurbsItem( MbSolid & solid, - MbeCopyMode sameShell, - const NurbsValues & p, - const RPArray & faces, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Заменить выбранную грань тела деформируемой гранью. - \en Replace the specified face of the solid by a deformable face. \~ - \details \ru Заменить выбранную грань тела деформируемой гранью (превращение в NURBS для редактирования). \n - \en Replace the specified face of the solid by a deformable face (conversion to NURBS for editing). \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] p - \ru Параметры преобразования. - \en The transformation parameters. \~ - \param[in] face - \ru Заменяемая грань тела. - \en A face to replace. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ModifiedNurbsItem( MbSolid & solid, - MbeCopyMode sameShell, - const NurbsValues & p, - const MbFace & face, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить NURBS-поверхности грани. - \en Get the NURBS-surfaces of a face. \~ - \details \ru Выполнить построение деформируемой поверхности для исходной грани. \n - \en Create a deformable surface for the initial face. \n \~ - \param[in] face - \ru Исходная грань. - \en The initial face. \~ - \return \ru Возвращает NURBS-поверхности грани. - \en Returns NURBS-surfaces of the face. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbSurface *) GetControlSurface( const MbFace & face ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить контрольные точки NURBS-поверхности грани. - \en Get the control points of the NURBS-surface of a face. \~ - \details \ru Получить множество контрольных точек NURBS-поверхности грани и множества их весов. \n - \en Get a set of the control points of a NURBS-surface of a face and a set of their weights. \n \~ - \param[in] face - \ru Исходная грань. - \en The initial face. \~ - \param[out] controlPoints - \ru Контрольные точки NURBS-поверхности грани. - \en The control points of the NURBS-surface of the face. \~ - \param[out] result - \ru Веса контрольных точек. - \en The weights of the control points. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FaceControlPoints( const MbFace & face, - Array2 & controlPoints, - Array2 & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Деформировать грань тела. - \en Deform a face of a solid. \~ - \details \ru Деформировать грань тела путём подстановки присланных контрольных точек NURBS-поверхности грани. \n - \en Deform a face of a solid by substitution the control points of NURBS-surface of the face with the given control points. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] face - \ru Изменяемая грань тела. - \en A face of a solid to be modified. \~ - \param[in] faceSurface - \ru Новая NURBS-поверхность для грани. - \en The new NURBS-surface of the face. \~ - \param[in] fixedPoints - \ru Неподвижные узлы. - \en The fixed points. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsModification( MbSolid & solid, - MbeCopyMode sameShell, - MbFace * face, - MbSurface & faceSurface, - Array2 & fixedPoints, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Деформировать грань тела. - \en Deform a face of a solid. \~ - \details \ru Деформировать грань тела путём подстановки присланных контрольных точек NURBS-поверхности грани. \n - \en Deform a face of a solid by substitution the control points of NURBS-surface of the face with the given control points. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the initial solid. \~ - \param[in] face - \ru Изменяемая грань тела. - \en A face of a solid to be modified. \~ - \param[in] controlPoints - \ru Контрольные точки NURBS-поверхности грани. - \en The control points of the NURBS-surface of the face. \~ - \param[in] weights - \ru Веса контрольных точек. - \en The weights of the control points. \~ - \param[in] fixedPoints - \ru Неподвижные узлы. - \en The fixed points. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Модифицированное тело. - \en The modified solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsModification( MbSolid & solid, - MbeCopyMode sameShell, - MbFace * face, - const Array2 & controlPoints, - const Array2 & weights, - Array2 * fixedPoints, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить деформируемую призму. - \en Create a deformable prism. \~ - \details \ru Построить тело в форме прямого параллелепипеда с деформируемыми гранями. \n - \en Create a solid as a right parallelepiped with deformable faces. \n \~ - \param[in] place - \ru Локальная система координат. - \en A local coordinate system. \~ - \param[in] ax - \ru Размер по X. - \en The size in X-direction. \~ - \param[in] ay - \ru Размер по Y. - \en The size in Y-direction. \~ - \param[in] az - \ru Размер по Z. - \en The size in Z-direction. \~ - \param[in] outDir - \ru Ориентация нормалей наружу. - \en An outer orientation of the normals. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] name - \ru Главное имя. - \en The main name. \~ - \param[in] param - \ru Параметры NURBS-поверхностей граней параллелепипеда. - \en The parameters of NURBS-surfaces of the parallelepiped faces. \~ - \param[out] result - \ru Тело из NURBS-поверхностей. - \en The solid constructed from the NU|RBS-surfaces. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsBlockSolid( const MbPlacement3D & place, - double ax, - double ay, - double az, - bool outDir, - const MbSNameMaker & names, - SimpleName name, - NurbsBlockValues & param, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить согласованную поверхность. - \en Create a matched surface. \~ - \details \ru Для исходной поверхности выполнить построение изменённой поверхности - путем выставления сопряжения вдоль кривой. \n - \en Create a modified surface for the initial surface - by specifying the conjugation along the curve. \n \~ - \param[in] curve - \ru Кривая пересечения поверхностей ребра. - \en The intersection curve of the edge surfaces. \~ - \param[in] sences - \ru Ориентация кривой ребра в цикле. - \en The edge curve sense in the loop. \~ - \param[in] faceSences - \ru Ориентация нормали на смежной грани. - \en The adjacent face normal orientation. \~ - \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. - \en The initial spline surface of the face to be modified. \~ - \param[in] tension - \ru Натяжение. - \en The tension. \~ - \param[in] conType - \ru Тип сопряжения. - \en The conjugation type. \~ - \param[in] insertNum - \ru Вставляемый ряд. - \en The row number. \~ - \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. - \en The NURBS-surface obtained as a result of the modifications. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsFaceConjugation( const MbSurfaceIntersectionCurve & curve, - bool sences, - bool faceSences, - const MbSplineSurface & surface, - double tension, - MbeConjugationType conType, - size_t insertNum, - MbSplineSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить подобную поверхность. - \en Create a similar surface. \~ - \details \ru Для исходной поверхности выполнить построение подобной поверхности - по указанной поверхности-образцу. \n - \en Create a surface similar to the initial one - given the pattern surface. \n \~ - \param[in] originSurface - \ru Поверхность-образец. - \en A pattern surface. \~ - \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. - \en The initial spline surface of the face to be modified. \~ - \param[in] uToU - \ru Флаг сохранения параметрического направления как у поверхности-образца. - \en Whether to keep the parametric direction of the pattern surface. \~ - \param[in] normSence - \ru Флаг сохранения направления нормали поверхности-образца. - \en Whether to keep the normal direction of the pattern surface. \~ - \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. - \en The NURBS-surface obtained as a result of the modifications. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsFaceSimilarity( const MbSurface & originSurface, - const MbSplineSurface & surface, - bool uToU, - bool normSence, - MbSplineSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить сглаженную поверхность. - \en Create a smoothed surface. \~ - \details \ru Выполнить сглаживание копии исходной поверхности не изменяя ее порядок и количество контрольных точек. \n - \en Perform smoothing of a copy of the initial surface without changing its order and the number of control points. \n \~ - \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. - \en The initial spline surface of the face to be modified. \~ - \param[in] udegree - \ru Параметр сглаживания по первому параметру поверхности. - \en The smoothing surface degree for direction of first parameter of surface. \~ - \param[in] vdegree - \ru Параметр сглаживания по второму параметру поверхности. - \en The smoothing surface degree for direction of second parameter of surface. \~ - \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. - \en The NURBS-surface obtained as a result of the modifications. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Direct_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplineSurfaceSmoothing( const MbSplineSurface & surface, - size_t udegree, - size_t vdegree, - MbSplineSurface *& result ); - - -#endif // __ACTION_DIRECT_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы прямого редактирования тел. + \en Functions for direct editing of solids. \~ + \details \ru Прямое моделирование позволяет редактировать и создавать подобные тела + путём непосредственной модификации элементов уже построенных тел. \n + Представленные ниже функции пока не доведены до коммерческого состояния + и позволяют лишь познакомиться с будущими возможностями геометрического ядра. + \en The direct modeling allows to edit and to create similar solids + by direct modification of elements of already constructed solids. \n + The following functions do not conform to the state of a commercial product yet + and allows just to acquaint oneself with the future features of the geometrical kernel. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_DIRECT_H +#define __ACTION_DIRECT_H + + +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbSplineSurface; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbSNameMaker; + + +//------------------------------------------------------------------------------ +/** \brief \ru Модифицировать тело по матрице. + \en Modify a solid by the matrix. \~ + \details \ru Выполнить трансформацию копии исходного тела по матрице, рассчитанной по габаритному кубу. \n + \en Transform a copy of the solid using the matrix calculated by bounding box of solid. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] p - \ru Параметры трансформации. + \en The transformation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) TransformedSolid( MbSolid & solid, + MbeCopyMode sameShell, + const TransformValues & p, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Собрать грани оболочки для методов прямого моделирования. + \en Modify a shell by the methods of direct modeling. \~ + \details \ru Функция собирает грани оболочки для методов прямого моделирования: \n + удаление из тела выбранных граней с окружением (way==dmt_Remove), \n + удаление выбранных граней скругления тела (way==dmt_Purify). \n + Для удаления граней собираются замкнутые цилиндрические, конические, тороидальные, сферические грани тела, + а также грани вращения, радиус которых не превосходит указанный радиус. + Для удаления граней скругления собираются незамкнутые цилиндрические, тороидальные, сферические грани, + а также грани скругления, радиус которых не превосходит указанный радиус. \n + \en The method collects the faces of the shell for direct modeling methods: \n + removal of the faces from a shell (way==dmt_Remove), \n + removal of the fillet faces from a shell (way==dmt_Purify). \n + The cylindrical, conical, toroidal, spherical, and revolution periodic faces are collect to remove way. + The cylindrical, toroidal, spherical non-periodic, and fillet faces are collect to purify way. \n \~ + \param[in] shell - \ru Исходная оболочка тела. + \en The initial faces set. \~ + \param[in] way - \ru Способ модификации. + \en Way of the modification. \~ + \param[in] radius - \ru Радиус собираемых граней. + \en Radius of collected faces. \~ + \param[in] faces - \ru Найденные грани для дальнейшей модификации. + \en Found faces to be modified. \~ + \return \ru Возвращает код результата действий. + \en Returns action result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CollectFacesForModification( MbFaceShell * shell, + MbeModifyingType way, + double radius, + RPArray & faces ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Модифицировать или построить тело методами прямого моделирования. + \en Modify a solid by the methods of direct modeling. \~ + \details \ru В зависимости от параметров модификации метод выполняет одно из следующих действий: \n + 1. Удаление из тела выбранных граней с окружением (param.way==dmt_Remove). \n + 2. Создание тела из выбранных граней с окружением (param.way==dmt_Create). \n + 3. Перемещение выбранных граней с окружением относительно оставшихся граней тела (param.way==dmt_Action). \n + 4. Замена выбранных граней тела эквидистантными гранями (param.way==dmt_Offset). \n + 5. Изменение радиуса выбранных граней скругления (param.way==dmt_Fillet). \n + 6. Замена выбранных граней тела деформируемыми гранями для редактирования (param.way==dmt_Supple). \n + 7. Удаление выбранных граней скругления тела (param.way==dmt_Purify). + \en The method is for one of listed actions below depends of parameters: \n + 1. Removal of the specified faces with the neighborhood from a solid (param.way==dmt_Remove). \n + 2. Creation of a solid from the specified faces with the neighborhood (param.way==dmt_Create). \n + 3. Translation of the specified faces with neighborhood relative to the other faces of the solid (param.way==dmt_Action). \n + 4. Replacement of the specified faces of a solid with the offset faces (param.way==dmt_Offset). \n + 5. Changing of the radius of the specified fillet faces (param.way==dmt_Fillet). \n + 6. Replacement of the specified faces of a solid with a deformable faces for editing (param.way==dmt_Supple). \n + 7. Removal of the specified fillet faces from a solid (param.way==dmt_Purify). \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] params - \ru Параметры модификации. + \en Parameters of the modification. \~ + \param[in] faces - \ru Изменяемые грани тела. + \en Faces to be modified. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FaceModifiedSolid( MbSolid & solid, + MbeCopyMode sameShell, + const ModifyValues & params, + const RPArray & faces, + const MbSNameMaker & names, + MbSolid *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Модифицировать или построить тело методами прямого моделирования. + \en Modify a solid by the methods of direct modeling. \~ + \details \ru Метод выполняет удаление указанных рёбер, слияние их вершин и модификацию окружающих граней (param.way==dmt_Merger). + По направлению вектора "param.direction" определяется: начальная ли вершина ребра будет слита с конечной вершиной, или конечная вершина ребра будет слита с начальной вершиной. \n + \en The method performs the deletion of selectsd edges, merging their vertices and modification of surrounding faces (param.way==dmt_Merger). + The direction of the vector "params.direction" determines whether the start vertex of an edge is merged with the end vertex, or whether the end vertex of an edge is merged with the start vertex. \n + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] params - \ru Параметры модификации, способ должен быть равен param.way==dmt_Merger. + \en Parameters of the modification, the way must be equal to param.way==dmt_Merger. \~ + \param[in] edges - \ru Удаляемые рёьра тела. + \en Edges to be removed. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- + +MATH_FUNC (MbResultType) EdgeModifiedSolid( MbSolid & solid, + MbeCopyMode sameShell, + const ModifyValues & params, + const RPArray & edges, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Заменить выбранные грани тела деформируемыми гранями. + \en Replace the specified faces of solid with deformable faces. \~ + \details \ru Заменить выбранные грани тела деформируемыми гранями (превращение в NURBS для редактирования). \n + \en Replace the specified faces of the solid with deformable faces (conversion to NURBS for editing). \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] p - \ru Параметры преобразования. + \en The transformation parameters. \~ + \param[in] faces - \ru Заменяемые грани тела. + \en Faces to replace. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ModifiedNurbsItem( MbSolid & solid, + MbeCopyMode sameShell, + const NurbsValues & p, + const RPArray & faces, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Заменить выбранную грань тела деформируемой гранью. + \en Replace the specified face of the solid by a deformable face. \~ + \details \ru Заменить выбранную грань тела деформируемой гранью (превращение в NURBS для редактирования). \n + \en Replace the specified face of the solid by a deformable face (conversion to NURBS for editing). \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] p - \ru Параметры преобразования. + \en The transformation parameters. \~ + \param[in] face - \ru Заменяемая грань тела. + \en A face to replace. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ModifiedNurbsItem( MbSolid & solid, + MbeCopyMode sameShell, + const NurbsValues & p, + const MbFace & face, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить NURBS-поверхности грани. + \en Get the NURBS-surfaces of a face. \~ + \details \ru Выполнить построение деформируемой поверхности для исходной грани. \n + \en Create a deformable surface for the initial face. \n \~ + \param[in] face - \ru Исходная грань. + \en The initial face. \~ + \return \ru Возвращает NURBS-поверхности грани. + \en Returns NURBS-surfaces of the face. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbSurface *) GetControlSurface( const MbFace & face ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить контрольные точки NURBS-поверхности грани. + \en Get the control points of the NURBS-surface of a face. \~ + \details \ru Получить множество контрольных точек NURBS-поверхности грани и множества их весов. \n + \en Get a set of the control points of a NURBS-surface of a face and a set of their weights. \n \~ + \param[in] face - \ru Исходная грань. + \en The initial face. \~ + \param[out] controlPoints - \ru Контрольные точки NURBS-поверхности грани. + \en The control points of the NURBS-surface of the face. \~ + \param[out] result - \ru Веса контрольных точек. + \en The weights of the control points. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FaceControlPoints( const MbFace & face, + Array2 & controlPoints, + Array2 & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Деформировать грань тела. + \en Deform a face of a solid. \~ + \details \ru Деформировать грань тела путём подстановки присланных контрольных точек NURBS-поверхности грани. \n + \en Deform a face of a solid by substitution the control points of NURBS-surface of the face with the given control points. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] face - \ru Изменяемая грань тела. + \en A face of a solid to be modified. \~ + \param[in] faceSurface - \ru Новая NURBS-поверхность для грани. + \en The new NURBS-surface of the face. \~ + \param[in] fixedPoints - \ru Неподвижные узлы. + \en The fixed points. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsModification( MbSolid & solid, + MbeCopyMode sameShell, + MbFace * face, + MbSurface & faceSurface, + Array2 & fixedPoints, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Деформировать грань тела. + \en Deform a face of a solid. \~ + \details \ru Деформировать грань тела путём подстановки присланных контрольных точек NURBS-поверхности грани. \n + \en Deform a face of a solid by substitution the control points of NURBS-surface of the face with the given control points. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the initial solid. \~ + \param[in] face - \ru Изменяемая грань тела. + \en A face of a solid to be modified. \~ + \param[in] controlPoints - \ru Контрольные точки NURBS-поверхности грани. + \en The control points of the NURBS-surface of the face. \~ + \param[in] weights - \ru Веса контрольных точек. + \en The weights of the control points. \~ + \param[in] fixedPoints - \ru Неподвижные узлы. + \en The fixed points. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Модифицированное тело. + \en The modified solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsModification( MbSolid & solid, + MbeCopyMode sameShell, + MbFace * face, + const Array2 & controlPoints, + const Array2 & weights, + Array2 * fixedPoints, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить деформируемую призму. + \en Create a deformable prism. \~ + \details \ru Построить тело в форме прямого параллелепипеда с деформируемыми гранями. \n + \en Create a solid as a right parallelepiped with deformable faces. \n \~ + \param[in] place - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] ax - \ru Размер по X. + \en The size in X-direction. \~ + \param[in] ay - \ru Размер по Y. + \en The size in Y-direction. \~ + \param[in] az - \ru Размер по Z. + \en The size in Z-direction. \~ + \param[in] outDir - \ru Ориентация нормалей наружу. + \en An outer orientation of the normals. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] name - \ru Главное имя. + \en The main name. \~ + \param[in] param - \ru Параметры NURBS-поверхностей граней параллелепипеда. + \en The parameters of NURBS-surfaces of the parallelepiped faces. \~ + \param[out] result - \ru Тело из NURBS-поверхностей. + \en The solid constructed from the NU|RBS-surfaces. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsBlockSolid( const MbPlacement3D & place, + double ax, + double ay, + double az, + bool outDir, + const MbSNameMaker & names, + SimpleName name, + NurbsBlockValues & param, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить согласованную поверхность. + \en Create a matched surface. \~ + \details \ru Для исходной поверхности выполнить построение изменённой поверхности + путем выставления сопряжения вдоль кривой. \n + \en Create a modified surface for the initial surface + by specifying the conjugation along the curve. \n \~ + \param[in] curve - \ru Кривая пересечения поверхностей ребра. + \en The intersection curve of the edge surfaces. \~ + \param[in] sences - \ru Ориентация кривой ребра в цикле. + \en The edge curve sense in the loop. \~ + \param[in] faceSences - \ru Ориентация нормали на смежной грани. + \en The adjacent face normal orientation. \~ + \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. + \en The initial spline surface of the face to be modified. \~ + \param[in] tension - \ru Натяжение. + \en The tension. \~ + \param[in] conType - \ru Тип сопряжения. + \en The conjugation type. \~ + \param[in] insertNum - \ru Вставляемый ряд. + \en The row number. \~ + \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. + \en The NURBS-surface obtained as a result of the modifications. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsFaceConjugation( const MbSurfaceIntersectionCurve & curve, + bool sences, + bool faceSences, + const MbSplineSurface & surface, + double tension, + MbeConjugationType conType, + size_t insertNum, + MbSplineSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить подобную поверхность. + \en Create a similar surface. \~ + \details \ru Для исходной поверхности выполнить построение подобной поверхности + по указанной поверхности-образцу. \n + \en Create a surface similar to the initial one + given the pattern surface. \n \~ + \param[in] originSurface - \ru Поверхность-образец. + \en A pattern surface. \~ + \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. + \en The initial spline surface of the face to be modified. \~ + \param[in] uToU - \ru Флаг сохранения параметрического направления как у поверхности-образца. + \en Whether to keep the parametric direction of the pattern surface. \~ + \param[in] normSence - \ru Флаг сохранения направления нормали поверхности-образца. + \en Whether to keep the normal direction of the pattern surface. \~ + \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. + \en The NURBS-surface obtained as a result of the modifications. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsFaceSimilarity( const MbSurface & originSurface, + const MbSplineSurface & surface, + bool uToU, + bool normSence, + MbSplineSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить сглаженную поверхность. + \en Create a smoothed surface. \~ + \details \ru Выполнить сглаживание копии исходной поверхности не изменяя ее порядок и количество контрольных точек. \n + \en Perform smoothing of a copy of the initial surface without changing its order and the number of control points. \n \~ + \param[in] surface - \ru Исходная сплайновая поверхность для изменяемой грани. + \en The initial spline surface of the face to be modified. \~ + \param[in] udegree - \ru Параметр сглаживания по первому параметру поверхности. + \en The smoothing surface degree for direction of first parameter of surface. \~ + \param[in] vdegree - \ru Параметр сглаживания по второму параметру поверхности. + \en The smoothing surface degree for direction of second parameter of surface. \~ + \param[out] result - \ru NURBS-поверхность, полученная в результате преобразований. + \en The NURBS-surface obtained as a result of the modifications. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Direct_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplineSurfaceSmoothing( const MbSplineSurface & surface, + size_t udegree, + size_t vdegree, + MbSplineSurface *& result ); + + +#endif // __ACTION_DIRECT_H diff --git a/C3d/Include/action_mesh.h b/C3d/Include/action_mesh.h index 5d03edb..e4b16d6 100644 --- a/C3d/Include/action_mesh.h +++ b/C3d/Include/action_mesh.h @@ -1,279 +1,318 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения полигональных геометрических объектов. - \en Functions for construction of the polygonal geometric object. \~ - \details \ru Полигональные геометрические объекты могут быть построены по набору точек или на базе других объектов. - \en Polygonal geometric objects can be constructed using a set of point or on the basis of other objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_MESH_H -#define __ACTION_MESH_H - - -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbMesh; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbSolid; -class MATH_CLASS MbPlaneItem; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbFace; -class MATH_CLASS MbCollection; - - -//------------------------------------------------------------------------------ - /** \brief \ru Расчет полигона кривой. - \en Calculation of polygon of curve. \~ - \details \ru Расчет трехмерного полигона двумерной кривой в плоскости XOY локальная системы координат. - \en Calculation of three-dimensional polygon of two-dimensional curve located in the XOY-plane of a local coordinate system. \~ - \param[in] curve - \ru Двумерная кривая. - \en A two-dimensional curve. \~ - \param[in] plane - \ru Локальная система координат. - \en Local coordinate system. \~ - \param[in] sag - \ru Максимальное допустимое отклонение полигона от оригинала по прогибу или по углу между соседними элементами. - \en Maximum allowable deviation of polygon from the original by sag or by angle between neighboring elements. \~ - \param[out] polygon - \ru Рассчитанный полигон. - \en Calculated polygon. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, - const MbPlacement3D & plane, - double sag, - MbPolygon3D & polygon ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить полигональный двухмерный объект. - \en Create a polygonal two-dimensional object. \~ - \details \ru Построить полигональный объект для двумерного объекта в плоскости XOY - локальной системы координат. - \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] plane - \ru Локальная система координат. - \en A local coordinate system. \~ - \param[in] sag - \ru Максимальное отклонение полигонального объекта от оригинала по прогибу. - \en The maximum deviation of polygonal object from the original object by sag. \~ - \param[out] mesh - \ru Полигональный объект. - \en Polygonal object. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (void) CalculateWire( const MbPlaneItem & obj, - const MbPlacement3D & plane, - double sag, - MbMesh & mesh ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить икосаэдр в виде полигональной модели. - \en Construct an icosahedron mesh. \~ - \details \ru Построить икосаэдр в виде полигональной модели. \n - \en Construct an icosahedron mesh. \n \~ - \param[in] place - \ru Местная система координат. - \en Local placement. \~ - \param[in] radius - \ru Радиус описанной сферы. - \en The radius of the sphere. \~ - \param[in] fn - \ru Способ построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \param[out] result - \ru Результат построения. - \en The resulting mesh. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CreateIcosahedron( const MbPlacement3D & place, - double radius, - const MbFormNote & fn, - MbMesh *& result ); - - -//------------------------------------------------------------------------------ -// . -/** \brief \ru Построить полигональную сферу. - \en Construct an spherical mesh. \~ - \details \ru Построить аппроксимацию сферы выпуклым многогранником. \n - \en Construct an approximation of the sphere by a convex polyhedron. \n \~ - \param[in] place - \ru Местная система координат. - \en Local placement. \~ - \param[in] radius - \ru Радиус сферы. - \en The radius of the sphere. \~ - \param[in] epsilon - \ru Параметр аппроксимации сферы. - \en The approximation parameter. \~ - \param[out] result - \ru Результат построения. - \en The resulting mesh. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CreateSpherePolyhedron( const MbPlacement3D & place, - double radius, - double & epsilon, - MbMesh *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить выпуклую оболочку для множества точек. - \en Calculate a convex hull of a point set. \~ - \details \ru Вычислить сетку, представляющую выпуклой оболочку для множества точек. - \en Calculate mesh being a convex hull of a point set. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CreateConvexPolyhedron( const SArray & points, - MbMesh *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить выпуклую оболочку для триангуляционной сетки. - \en Construct the convex hull of triangulation grid. \~ - \details \ru Построить сетку, представляющую собой выпуклую оболочку для тела, - заданного его триангуляционной сеткой. По заданному объекту MbMesh - строится охватывающая его вершины выпуклая триангуляционная сетка. - Расстояние offset задает смещение точек результирующей сетки относительно - заданной вдоль нормалей к её граням. Если offset = 0, то результирующая сетка - будет в точности охватывать все вершины заданной. Смещение по нормали может - быть как положительным, так и отрицательным (внутрь сетки). Используется для - определения пересечения с некоторым допуском (offset). \n - \en Construct the convex hull of triangulation grid. \n \~ - \param[in] mesh - \ru Исходная триангуляционная сетка. - \en Initial triangulated mesh. \~ - \param[in] offset - \ru Отступ по нормали для результирующей сетки. - \en The offset along a normal for the resulting grid. \~ - \param[out] resMesh - \ru Результирующая выпуклая триангуляционная сетка. - \en The resulting triangulation convex grid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CreateConvexPolyhedron( const MbMesh & mesh, - double offset, - MbMesh *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить, пересекаются ли данные выпуклые сетки. - \en Whether there is intersection of convex grids. \~ - \details \ru Определить, пересекаются ли данные выпуклые оболочки, заданные - триангуляционными сетками. Пересечение определяется по алгоритму - Гильберта-Джонсона-Керти (Gilbert-Johnson-Keerthi). Заданные сетки - равноправны, их последовательность в алгоритме не важна. Сложность - алгоритма линейная, зависит от количества вершин сеток. \n - \en Whether there is intersection of convex grids. \n \~ - \param[in] mesh1 - \ru Первая выпуклая триангуляционная сетка. - \en The first convex grid. \~ - \param[in] mesh2 - \ru Вторая выпуклая триангуляционная сетка. - \en The second convex grid. \~ - \return \ru true - Выпуклые триангуляционные сетки пересекаются. - false - Выпуклые триангуляционные сетки не пересекаются. - \en true - true - there is an intersection, - false - there are no intersections. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (bool) AreIntersectConvexPolyhedrons( const MbMesh & mesh1, - const MbMesh & mesh2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отрезать часть полигонального объекта плоскостью. - \en Cut a part of a polygonal object by a plane. \~ - \details \ru Отрезать часть полигонального объекта плоскостью XY локальной системы координат. \n - part = 1 - оставляем часть объекта, расположенную сверху плоскости XY локальной системы координат, \n - part = -1 - оставляем часть объекта, расположенную снизу плоскости XY локальной системы координат. \n - \en Cut a part of a polygonal object off by a plane XY of local coordinate system. \n - part = 1 - a part of polygonal object above the XY plane is to be retained. \n - part = -1 - a part of polygonal object below the XY plane is to be retained. \n \~ - \param[in] mesh - \ru Исходный полигональный объект. - \en The source polygonal object. \~ - \param[in] sameShell - \ru Режим копирования исходного объекта. - \en The mode of copying of the source polygonal object. \~ - \param[in] place - \ru Секущая плоскость. - \en A cutting plane. \~ - \param[in] part - \ru Направление отсечения. - \en The direction of cutting off. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] onlySection - \ru Флаг режима отсечения: false - сечем как тело, true - сечем как оболочку. - \en The flag of the cutting off mode: false - cut as a solid, true - cut as a shell. \~ - \param[out] result - \ru Построенный полигональный объект. - \en The resultant polygonal object. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) MeshCutting( MbMesh & mesh, - MbeCopyMode sameShell, - const MbPlacement3D & place, - int part, - const MbSNameMaker & names, - bool onlySection, - MbMesh *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить контур сечения полигонального объекта плоскостью. - \en Create a section contour of a polygon figure. \~ - \details \ru Построить контур сечения присланного объекта плоскостью XY локальной системы координат. \n - \en Construct curves of the section of the mesh object lying on the XY plane of the local coordinate system. \n - \param[in] mesh - \ru Исходный полигональный объект. - \en The source polygonal object. \~ - \param[in] place - \ru Секущая плоскость. - \en A cutting plane. \~ - \param[out] polylines - \ru Построенные ломагные контура сечения объекта. - \en The resultant contours. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) MeshSection( const MbMesh & mesh, - const MbPlacement3D & place, - RPArray & polylines ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить триангуляцию по облаку точек на основе алгоритма поворотного шара. - \en Build a triangulation by point cloud with Ball Pivoting algorithm. \~ - \param[in] collection - \ru Коллекция трехмерных элементов. - \en Collection of 3d elements. \~ - \param[in] radius - \ru Радиус поворотного шара, если radius==0 будет предпринята попытка его автоопределения. - \en Radius of the pivoting ball, if radius==0 an autoguess for the ball pivoting radius is attempted \~ - \param[in] radiusMin - \ru Радиус кластеризации ( в % от радиуса поворотного шара ). - \en Clusterization radius ( % from radius value). \~ - \param[in] angle - \ru Максимальный угол между двумя соседними элементами сетки. - \en Max angle between two mesh faces \~ - \param[out] result - \ru Построенный полигональный объект. - \en The resultant polygonal object. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (MbResultType) CalculateBallPivotingGrid( const MbCollection & collection, - double radius, - double radiusMin, - double angle, - MbMesh *& result ); - - -#endif // __ACTION_MESH_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы построения полигональных геометрических объектов. + \en Functions for construction of the polygonal geometric object. \~ + \details \ru Полигональные геометрические объекты могут быть построены по набору точек или на базе других объектов. + \en Polygonal geometric objects can be constructed using a set of point or on the basis of other objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_MESH_H +#define __ACTION_MESH_H + + +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbMesh; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbSolid; +class MATH_CLASS MbPlaneItem; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFace; +class MATH_CLASS MbCollection; + + +//------------------------------------------------------------------------------ + /** \brief \ru Расчет полигона кривой. + \en Calculation of polygon of curve. \~ + \details \ru Расчет трехмерного полигона двумерной кривой в плоскости XOY локальная системы координат. + \en Calculation of three-dimensional polygon of two-dimensional curve located in the XOY-plane of a local coordinate system. \~ + \param[in] curve - \ru Двумерная кривая. + \en A two-dimensional curve. \~ + \param[in] plane - \ru Локальная система координат. + \en Local coordinate system. \~ + \param[in] sag - \ru Максимальное допустимое отклонение полигона от оригинала по прогибу или по углу между соседними элементами. + \en Maximum allowable deviation of polygon from the original by sag or by angle between neighboring elements. \~ + \param[out] polygon - \ru Рассчитанный полигон. + \en Calculated polygon. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) CalculatePolygon( const MbCurve & curve, + const MbPlacement3D & plane, + double sag, + MbPolygon3D & polygon ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить полигональный двухмерный объект. + \en Create a polygonal two-dimensional object. \~ + \details \ru Построить полигональный объект для двумерного объекта в плоскости XOY + локальной системы координат. + \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] plane - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] sag - \ru Максимальное отклонение полигонального объекта от оригинала по прогибу. + \en The maximum deviation of polygonal object from the original object by sag. \~ + \param[out] mesh - \ru Полигональный объект. + \en Polygonal object. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (void) CalculateWire( const MbPlaneItem & obj, + const MbPlacement3D & plane, + double sag, + MbMesh & mesh ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить икосаэдр в виде полигональной модели. + \en Construct an icosahedron mesh. \~ + \details \ru Построить икосаэдр в виде полигональной модели. \n + \en Construct an icosahedron mesh. \n \~ + \param[in] place - \ru Местная система координат. + \en Local placement. \~ + \param[in] radius - \ru Радиус описанной сферы. + \en The radius of the sphere. \~ + \param[in] fn - \ru Способ построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \param[out] result - \ru Результат построения. + \en The resulting mesh. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CreateIcosahedron( const MbPlacement3D & place, + double radius, + const MbFormNote & fn, + MbMesh *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Построить параллелепипед в виде полигональной модели. + \en Construct a parallepiped mesh. \~ + \details \ru Построить ориентированный параллелепипед в виде полигональной модели. + Если матрица 'trans' единичная, то результатом вызова будет кубик + единичного объема. В общем случае матрица содержит смещение и ротацию, + позиционирующую куб относительно начала координат. Размеры параллелепипеда + определяются коэффициентами масштабирования по собственным осям ЛСК + параллелепипеда, содержащимися в матрице. + \en Construct an oriented box in the mesh representation. If the matrix 'trans' + is identity then the result of the call will be an unit cube. In general, + the matrix contains a translation and rotation that positions the cube + relative to the origin. The sizes of the parallelepiped are specified + by the scaling factors of the matrix along the eigen axes of the LCS of + the parallelepiped. \~ + \note \ru У матрицы должна быть ротационная часть ортогональной и не вырожденной. + Масштабирующая часть определяет размеры параллелепипеда. + \en The rotational componet of the matrix should be nondegenerate and ortogonal. + The scaling component specifies the box sizes. + \param[in] trans - \ru Матрица, задающая позицию, ориентацию и размеры сторон параллелепипеда. + \en The matrix specifying a postion, orientation and sizes of the box sides. \~ + \param[out] result - \ru Результат построения. + \en The resulting mesh. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CreateBoxMesh( const MbMatrix3D & trans, SPtr & result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Построить параллелепипед в виде проволочной модели. + \en Construct an parallepiped wireframe. + \details \ru Функция конструирует проволочный каркас параллелепипеда по тем же правилам, что и #CreateBoxMesh. + \en The function makes the wireframe of the oriented box by the same rules as #CreateBoxMesh. + \ingroup Polygonal_Objects +*/ +//--- +MATH_FUNC (MbResultType) CreateBoxWire( const MbMatrix3D & trans, SPtr & result ); + +//------------------------------------------------------------------------------ +// . +/** \brief \ru Построить полигональную сферу. + \en Construct an spherical mesh. \~ + \details \ru Построить аппроксимацию сферы выпуклым многогранником. \n + \en Construct an approximation of the sphere by a convex polyhedron. \n \~ + \param[in] place - \ru Местная система координат. + \en Local placement. \~ + \param[in] radius - \ru Радиус сферы. + \en The radius of the sphere. \~ + \param[in] epsilon - \ru Параметр аппроксимации сферы. + \en The approximation parameter. \~ + \param[out] result - \ru Результат построения. + \en The resulting mesh. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CreateSpherePolyhedron( const MbPlacement3D & place, + double radius, + double & epsilon, + MbMesh *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить выпуклую оболочку для множества точек. + \en Calculate a convex hull of a point set. \~ + \details \ru Вычислить сетку, представляющую выпуклой оболочку для множества точек. + \en Calculate mesh being a convex hull of a point set. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CreateConvexPolyhedron( const SArray & points, + MbMesh *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить выпуклую оболочку для триангуляционной сетки. + \en Construct the convex hull of triangulation grid. \~ + \details \ru Построить сетку, представляющую собой выпуклую оболочку для тела, + заданного его триангуляционной сеткой. По заданному объекту MbMesh + строится охватывающая его вершины выпуклая триангуляционная сетка. + Расстояние offset задает смещение точек результирующей сетки относительно + заданной вдоль нормалей к её граням. Если offset = 0, то результирующая сетка + будет в точности охватывать все вершины заданной. Смещение по нормали может + быть как положительным, так и отрицательным (внутрь сетки). Используется для + определения пересечения с некоторым допуском (offset). \n + \en Construct the convex hull of triangulation grid. \n \~ + \param[in] mesh - \ru Исходная триангуляционная сетка. + \en Initial triangulated mesh. \~ + \param[in] offset - \ru Отступ по нормали для результирующей сетки. + \en The offset along a normal for the resulting grid. \~ + \param[out] resMesh - \ru Результирующая выпуклая триангуляционная сетка. + \en The resulting triangulation convex grid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CreateConvexPolyhedron( const MbMesh & mesh, + double offset, + MbMesh *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить, пересекаются ли данные выпуклые сетки. + \en Whether there is intersection of convex grids. \~ + \details \ru Определить, пересекаются ли данные выпуклые оболочки, заданные + триангуляционными сетками. Пересечение определяется по алгоритму + Гильберта-Джонсона-Керти (Gilbert-Johnson-Keerthi). Заданные сетки + равноправны, их последовательность в алгоритме не важна. Сложность + алгоритма линейная, зависит от количества вершин сеток. \n + \en Whether there is intersection of convex grids. \n \~ + \param[in] mesh1 - \ru Первая выпуклая триангуляционная сетка. + \en The first convex grid. \~ + \param[in] mesh2 - \ru Вторая выпуклая триангуляционная сетка. + \en The second convex grid. \~ + \return \ru true - Выпуклые триангуляционные сетки пересекаются. + false - Выпуклые триангуляционные сетки не пересекаются. + \en true - true - there is an intersection, + false - there are no intersections. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (bool) AreIntersectConvexPolyhedrons( const MbMesh & mesh1, + const MbMesh & mesh2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отрезать часть полигонального объекта плоскостью. + \en Cut a part of a polygonal object by a plane. \~ + \details \ru Отрезать часть полигонального объекта плоскостью XY локальной системы координат. \n + part = 1 - оставляем часть объекта, расположенную сверху плоскости XY локальной системы координат, \n + part = -1 - оставляем часть объекта, расположенную снизу плоскости XY локальной системы координат. \n + \en Cut a part of a polygonal object off by a plane XY of local coordinate system. \n + part = 1 - a part of polygonal object above the XY plane is to be retained. \n + part = -1 - a part of polygonal object below the XY plane is to be retained. \n \~ + \param[in] mesh - \ru Исходный полигональный объект. + \en The source polygonal object. \~ + \param[in] sameShell - \ru Режим копирования исходного объекта. + \en The mode of copying of the source polygonal object. \~ + \param[in] place - \ru Секущая плоскость. + \en A cutting plane. \~ + \param[in] part - \ru Направление отсечения. + \en The direction of cutting off. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] onlySection - \ru Флаг режима отсечения: false - сечем как тело, true - сечем как оболочку. + \en The flag of the cutting off mode: false - cut as a solid, true - cut as a shell. \~ + \param[out] result - \ru Построенный полигональный объект. + \en The resultant polygonal object. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) MeshCutting( MbMesh & mesh, + MbeCopyMode sameShell, + const MbPlacement3D & place, + int part, + const MbSNameMaker & names, + bool onlySection, + MbMesh *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить контур сечения полигонального объекта плоскостью. + \en Create a section contour of a polygon figure. \~ + \details \ru Построить контур сечения присланного объекта плоскостью XY локальной системы координат. \n + \en Construct curves of the section of the mesh object lying on the XY plane of the local coordinate system. \n + \param[in] mesh - \ru Исходный полигональный объект. + \en The source polygonal object. \~ + \param[in] place - \ru Секущая плоскость. + \en A cutting plane. \~ + \param[out] polylines - \ru Построенные ломагные контура сечения объекта. + \en The resultant contours. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) MeshSection( const MbMesh & mesh, + const MbPlacement3D & place, + RPArray & polylines ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить триангуляцию по облаку точек на основе алгоритма поворотного шара. + \en Build a triangulation by point cloud with Ball Pivoting algorithm. \~ + \param[in] collection - \ru Коллекция трехмерных элементов. + \en Collection of 3d elements. \~ + \param[in] radius - \ru Радиус поворотного шара, если radius==0 будет предпринята попытка его автоопределения. + \en Radius of the pivoting ball, if radius==0 an autoguess for the ball pivoting radius is attempted \~ + \param[in] radiusMin - \ru Радиус кластеризации ( в % от радиуса поворотного шара ). + \en Clusterization radius ( % from radius value). \~ + \param[in] angle - \ru Максимальный угол между двумя соседними элементами сетки. + \en Max angle between two mesh faces \~ + \param[out] result - \ru Построенный полигональный объект. + \en The resultant polygonal object. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (MbResultType) CalculateBallPivotingGrid( const MbCollection & collection, + double radius, + double radiusMin, + double angle, + MbMesh *& result ); + + +#endif // __ACTION_MESH_H diff --git a/C3d/Include/action_phantom.h b/C3d/Include/action_phantom.h index bd26ea5..c26309b 100644 --- a/C3d/Include/action_phantom.h +++ b/C3d/Include/action_phantom.h @@ -1,299 +1,317 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение фантомов операций. - \en Creation of phantom operations. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_PHANTOM_H -#define __ACTION_PHANTOM_H - - -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbSNameMaker; - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить фантомные поверхности скругления/фаски. - \en Create phantom surfaces of fillet/chamfer. \~ - \details \ru Построить фантомные поверхности скругления/фаски и сложить в контейнер surfaces. \n - По окончании работ поверхности можно и нужно удалить. \n - \en Create phantom surfaces of fillet/chamfer and store them in the container 'surfaces'. \n - After finish working with the surfaces they should be deleted. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. - \en An array of edges for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[out] result - \ru Поверхности скругления/фаски. - \en The fillet/chamfer surfaces. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) SmoothPhantom( const MbSolid & solid, - RPArray & edges, - const SmoothValues & params, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить фантомные поверхности скругления/фаски. - \en Create phantom surfaces of fillet/chamfer.\~ - \details \ru Построить фантомные поверхности скругления/фаски и сложить в контейнер surfaces. \n - По окончании работ поверхности можно и нужно удалить. - \en Create phantom surfaces of fillet/chamfer and store them in the container 'surfaces'. \n - After finish working with the surfaces they should be deleted. \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер и функций изменения радиуса для скругления/фаски. - \en An array of edges and radius laws for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[out] result - \ru Поверхности скругления/фаски. - \en The fillet/chamfer surfaces. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) SmoothPhantom( const MbSolid & solid, - SArray & edges, - const SmoothValues & params, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить последовательности гладко стыкующихся рёбер. - \en \~ - \details \ru Построить последовательности гладко стыкующихся рёбер, скругляемых одновременно, - а также поверхности скругления/фаски (массив surfaces). \n - По окончании работ поверхности можно и нужно удалить. - \en \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. - \en An array of edges for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[in] createSurfaces - \ru Создавать ли поверхности скругления/фаски для фантома? - \en Create a fillet/chamfer surfaces for phantom. \~ - \param[out] sequences - \ru Последовательность гладко стыкующихся рёбер. - \en Sequence of smooth mating edges. \~ - \param[out] result - \ru Поверхности скругления/фаски. - \en The fillet/chamfer surfaces. \~ - \return \ru Возвращает код результата построения. - \en \~ - \ingroup Algorithms_3D -*/ - -// --- -MATH_FUNC (MbResultType) SmoothSequence( const MbSolid & solid, - RPArray & edges, - const SmoothValues & params, - bool createSurfaces, - RPArray & sequences, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить последовательности гладко стыкующихся рёбер. - \en \~ - \details \ru Построить последовательности гладко стыкующихся рёбер, скругляемых одновременно, - а также поверхности скругления/фаски (массив surfaces). \n - По окончании работ поверхности можно и нужно удалить. - \en \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер и функций изменения радиуса для скругления/фаски. - \en An array of edges and radius laws for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[in] createSurfaces - \ru Создавать ли поверхности скругления/фаски для фантома? - \en Create a fillet/chamfer surfaces for phantom. \~ - \param[out] sequences - \ru Последовательность гладко стыкующихся рёбер. - \en Sequence of smooth mating edges. \~ - \param[out] result - \ru Поверхности скругления/фаски. - \en The fillet/chamfer surfaces. \~ - \return \ru Возвращает код результата построения. - \en \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) SmoothSequence( const MbSolid & solid, - SArray & edges, - const SmoothValues & params, - bool createSurfaces, - RPArray & sequences, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить фантомные эквидистантные поверхности для граней оболочки. - \en Create phantom offset surfaces for faces of a shell. \~ - \details \ru Построить фантомные эквидистантные поверхности для граней оболочки, \n - кроме имеющих перечислены кроме имеющих перечисленные индексы, и сложить в массив surfaces. \n - По окончании работ поверхности можно и нужно удалить. - \en Create phantom offset surfaces for faces of a shell, \n - except the faces with specified indices and store them in array 'surfaces'. \n - After finish working with the surfaces they should be deleted. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] outFaces - \ru Множество вскрываемых граней тела. - \en An array of shelling faces of the solid. \~ - \param[in] offFaces - \ru Множество граней, для которых заданы индивидуальные значения толщин. - \en An array of faces for which the individual values of thickness are specified. \~ - \param[in] offDists - \ru Множество индивидуальных значений толщин (должен быть синхронизирован с массивом offFaces). - \en An array of individual values of thickness (must be synchronized with the array 'offFaces'). \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результат операции. - \en The operation result. \~ - \param[out] hpShellFaceInd - \ru Номер грани в исходной оболочки для построения хот-точки. - \en The face number in the initial shell for a hot-point creation. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetPhantom( const MbSolid & solid, - RPArray & outFaces, - RPArray & offFaces, - SArray & offDists, - 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); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить фантом габаритного куба в локальной системе координат. - \en Create a phantom of a bounding box in local coordinate system. \~ - \details \ru Построить фантом габаритного куба в локальной системе координат. \n - \en Create a phantom of a bounding box in local coordinate system. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] place - \ru Локальная система координат (ЛСК). - \en A local coordinate system (LCS). \~ - \param[in] bScale - \ru Является ли ЛСК масштабирующей. - \en Whether the LCS is scaling. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Фантом локального куба. - \en The phantom of the local bounding box. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LocalCubePhantom( const MbSolid & solid, - const MbPlacement3D & place, - bool bScale, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить фантомное направление усечения. - \en Determine a phantom direction of truncation. \~ - \details \ru Определить фантомное направление усечения по усеченной грани исходного тела. \n - \en Determine a phantom direction of truncation given the truncated face of the initial solid. \n \~ - \param[in] truncatingEdge - \ru Ребро усеченной грани исходного тела. - \en An edge of truncated face of the initial solid. \~ - \param[in] dirPlace - \ru Система координат направления усечения (Ось Z - направление усечения). - \en A coordinate system of truncation direction (Z-axis is a truncation direction). \~ - \return \ru Возвращает true, если получилось определить направление. - \en Returns true if the direction has been successfully determined. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) TruncatDirection( const MbCurveEdge & truncatingEdge, - MbPlacement3D & dirPlace ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить опорные точки размеров операции скругления/фаски. - \en Create support points of fillet/chamfer operation sizes. \~ - \details \ru Построить опорные точки размеров операции скругления/фаски и сложить в контейнер data. \n - Первые две точки лежат на краях поверхности скругления/фаски. - \en Create support points of fillet/chamfer operation sizes and store them in container 'data'. \n - The first two points lie on the fillet/chamfer surface boundary. \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. - \en An array of edges for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[out] result - \ru Опорные точки размеров операции скругления/фаски. - \en Support points of the fillet/chamfer operation sizes. \~ - \param[in] edgeParam - \ru Параметр точки на ребре (0 <= edgeParam <= 1). - \en The parameter of a point on the edge (0 <= edgeParam <= 1). \~ - \param[in] dimensionEdge - \ru Ребро, на котором дать опорные точки. - \en The edge on which the support points are to be created. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & solid, - RPArray & edges, - const SmoothValues & params, - RPArray & result, - double edgeParam = 0.5, - const MbCurveEdge * dimensionEdge = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить опорные точки размеров операции скругления/фаски. - \en Create support points of fillet/chamfer operation sizes. \~ - \details \ru Построить опорные точки размеров операции скругления/фаски и сложить в контейнер data. \n - Первые две точки лежат на краях поверхности скругления/фаски. - \en Create support points of fillet/chamfer operation sizes and store them in container 'data'. \n - The first two points lie on the fillet/chamfer surface boundary. \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] edges - \ru Множество выбранных ребер для скругления/фаски и функций изменения радиуса для скругления/фаски. - \en The array of specified edges for fillet/chamfer and radius laws for fillet/chamfer. \~ - \param[in] params - \ru Параметры операции скругления/фаски. - \en Parameters of the fillet/chamfer operation. \~ - \param[out] result - \ru Опорные точки размеров операции скругления/фаски. - \en Support points of the fillet/chamfer operation sizes. \~ - \param[in] edgeParam - \ru Параметр точки на ребре (0 <= edgeParam <= 1). - \en The parameter of a point on the edge (0 <= edgeParam <= 1). \~ - \param[in] dimensionEdge - \ru Ребро, на котором дать опорные точки. - \en The edge on which the support points are to be created. \~ - \return \ru Возвращает код результата построения. - \en Returns the creation result code. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & solid, - SArray & edges, - const SmoothValues & params, - RPArray & result, - double edgeParam = 0.5, - const MbCurveEdge * dimensionEdge = NULL ); - - -#endif // __ACTION_PHANTOM_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение фантомов операций. + \en Creation of phantom operations. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_PHANTOM_H +#define __ACTION_PHANTOM_H + + +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbSNameMaker; + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить фантомные поверхности скругления/фаски. + \en Create phantom surfaces of fillet/chamfer. \~ + \details \ru Построить фантомные поверхности скругления/фаски и сложить в контейнер surfaces. \n + По окончании работ поверхности можно и нужно удалить. \n + \en Create phantom surfaces of fillet/chamfer and store them in the container 'surfaces'. \n + After finish working with the surfaces they should be deleted. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. + \en An array of edges for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[out] result - \ru Поверхности скругления/фаски. + \en The fillet/chamfer surfaces. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SmoothPhantom( const MbSolid & solid, + RPArray & edges, + const SmoothValues & params, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить фантомные поверхности скругления/фаски. + \en Create phantom surfaces of fillet/chamfer.\~ + \details \ru Построить фантомные поверхности скругления/фаски и сложить в контейнер surfaces. \n + По окончании работ поверхности можно и нужно удалить. + \en Create phantom surfaces of fillet/chamfer and store them in the container 'surfaces'. \n + After finish working with the surfaces they should be deleted. \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер и функций изменения радиуса для скругления/фаски. + \en An array of edges and radius laws for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[out] result - \ru Поверхности скругления/фаски. + \en The fillet/chamfer surfaces. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SmoothPhantom( const MbSolid & solid, + SArray & edges, + const SmoothValues & params, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить последовательности гладко стыкующихся рёбер. + \en \~ + \details \ru Построить последовательности гладко стыкующихся рёбер, скругляемых одновременно, + а также поверхности скругления/фаски (массив surfaces). \n + По окончании работ поверхности можно и нужно удалить. + \en \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. + \en An array of edges for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[in] createSurfaces - \ru Создавать ли поверхности скругления/фаски для фантома? + \en Create a fillet/chamfer surfaces for phantom. \~ + \param[out] sequences - \ru Последовательность гладко стыкующихся рёбер. + \en Sequence of smooth mating edges. \~ + \param[out] result - \ru Поверхности скругления/фаски. + \en The fillet/chamfer surfaces. \~ + \return \ru Возвращает код результата построения. + \en \~ + \ingroup Algorithms_3D +*/ + +// --- +MATH_FUNC (MbResultType) SmoothSequence( const MbSolid & solid, + RPArray & edges, + const SmoothValues & params, + bool createSurfaces, + RPArray & sequences, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить последовательности гладко стыкующихся рёбер. + \en \~ + \details \ru Построить последовательности гладко стыкующихся рёбер, скругляемых одновременно, + а также поверхности скругления/фаски (массив surfaces). \n + По окончании работ поверхности можно и нужно удалить. + \en \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер и функций изменения радиуса для скругления/фаски. + \en An array of edges and radius laws for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[in] createSurfaces - \ru Создавать ли поверхности скругления/фаски для фантома? + \en Create a fillet/chamfer surfaces for phantom. \~ + \param[out] sequences - \ru Последовательность гладко стыкующихся рёбер. + \en Sequence of smooth mating edges. \~ + \param[out] result - \ru Поверхности скругления/фаски. + \en The fillet/chamfer surfaces. \~ + \return \ru Возвращает код результата построения. + \en \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SmoothSequence( const MbSolid & solid, + SArray & edges, + const SmoothValues & params, + bool createSurfaces, + RPArray & sequences, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить фантомные эквидистантные поверхности для граней оболочки. + \en Create phantom offset surfaces for faces of a shell. \~ + \details \ru Построить фантомные эквидистантные поверхности для граней оболочки, \n + кроме имеющих перечислены кроме имеющих перечисленные индексы, и сложить в массив surfaces. \n + По окончании работ поверхности можно и нужно удалить. + \en Create phantom offset surfaces for faces of a shell, \n + except the faces with specified indices and store them in array 'surfaces'. \n + After finish working with the surfaces they should be deleted. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] outFaces - \ru Множество вскрываемых граней тела. + \en An array of shelling faces of the solid. \~ + \param[in] offFaces - \ru Множество граней, для которых заданы индивидуальные значения толщин. + \en An array of faces for which the individual values of thickness are specified. \~ + \param[in] offDists - \ru Множество индивидуальных значений толщин (должен быть синхронизирован с массивом offFaces). + \en An array of individual values of thickness (must be synchronized with the array 'offFaces'). \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результат операции. + \en The operation result. \~ + \param[out] hpShellFaceInd - \ru Номер грани в исходной оболочки для построения хот-точки. + \en The face number in the initial shell for a hot-point creation. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetPhantom( const MbSolid & solid, + RPArray & outFaces, + RPArray & offFaces, + SArray & offDists, + 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); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить фантом габаритного куба в локальной системе координат. + \en Create a phantom of a bounding box in local coordinate system. \~ + \details \ru Построить фантом габаритного куба в локальной системе координат. \n + \en Create a phantom of a bounding box in local coordinate system. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] place - \ru Локальная система координат (ЛСК). + \en A local coordinate system (LCS). \~ + \param[in] bScale - \ru Является ли ЛСК масштабирующей. + \en Whether the LCS is scaling. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Фантом локального куба. + \en The phantom of the local bounding box. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LocalCubePhantom( const MbSolid & solid, + const MbPlacement3D & place, + bool bScale, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить фантомное направление усечения. + \en Determine a phantom direction of truncation. \~ + \details \ru Определить фантомное направление усечения по усеченной грани исходного тела. \n + \en Determine a phantom direction of truncation given the truncated face of the initial solid. \n \~ + \param[in] truncatingEdge - \ru Ребро усеченной грани исходного тела. + \en An edge of truncated face of the initial solid. \~ + \param[in] dirPlace - \ru Система координат направления усечения (Ось Z - направление усечения). + \en A coordinate system of truncation direction (Z-axis is a truncation direction). \~ + \return \ru Возвращает true, если получилось определить направление. + \en Returns true if the direction has been successfully determined. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) TruncatDirection( const MbCurveEdge & truncatingEdge, + MbPlacement3D & dirPlace ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить опорные точки размеров операции скругления/фаски. + \en Create support points of fillet/chamfer operation sizes. \~ + \details \ru Построить опорные точки размеров операции скругления/фаски и сложить в контейнер data. \n + Первые две точки лежат на краях поверхности скругления/фаски. + \en Create support points of fillet/chamfer operation sizes and store them in container 'data'. \n + The first two points lie on the fillet/chamfer surface boundary. \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер для скругления/фаски. + \en An array of edges for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[out] result - \ru Опорные точки размеров операции скругления/фаски. + \en Support points of the fillet/chamfer operation sizes. \~ + \param[in] edgeParam - \ru Параметр точки на ребре (0 <= edgeParam <= 1). + \en The parameter of a point on the edge (0 <= edgeParam <= 1). \~ + \param[in] dimensionEdge - \ru Ребро, на котором дать опорные точки. + \en The edge on which the support points are to be created. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & solid, + RPArray & edges, + const SmoothValues & params, + RPArray & result, + double edgeParam = 0.5, + const MbCurveEdge * dimensionEdge = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить опорные точки размеров операции скругления/фаски. + \en Create support points of fillet/chamfer operation sizes. \~ + \details \ru Построить опорные точки размеров операции скругления/фаски и сложить в контейнер data. \n + Первые две точки лежат на краях поверхности скругления/фаски. + \en Create support points of fillet/chamfer operation sizes and store them in container 'data'. \n + The first two points lie on the fillet/chamfer surface boundary. \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] edges - \ru Множество выбранных ребер для скругления/фаски и функций изменения радиуса для скругления/фаски. + \en The array of specified edges for fillet/chamfer and radius laws for fillet/chamfer. \~ + \param[in] params - \ru Параметры операции скругления/фаски. + \en Parameters of the fillet/chamfer operation. \~ + \param[out] result - \ru Опорные точки размеров операции скругления/фаски. + \en Support points of the fillet/chamfer operation sizes. \~ + \param[in] edgeParam - \ru Параметр точки на ребре (0 <= edgeParam <= 1). + \en The parameter of a point on the edge (0 <= edgeParam <= 1). \~ + \param[in] dimensionEdge - \ru Ребро, на котором дать опорные точки. + \en The edge on which the support points are to be created. \~ + \return \ru Возвращает код результата построения. + \en Returns the creation result code. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbResultType) SmoothPositionData( const MbSolid & solid, + SArray & edges, + const SmoothValues & params, + RPArray & result, + double edgeParam = 0.5, + const MbCurveEdge * dimensionEdge = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение функции изменения указанной координаты кривой. + \en Create a function by one of three coordinates of curve. \~ + \details \ru Для указанной координаты кривой построить склярную функцию её изменения, зависящую от параметра кривой. \n + \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. \~ + \return \ru Возвращает построенную функцию. + \en Returns the created function. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbFunction *) CreateFunction( const MbCurve3D & curve, + size_t coordinate ); + + +#endif // __ACTION_PHANTOM_H diff --git a/C3d/Include/action_point.h b/C3d/Include/action_point.h index 304621b..706e36d 100644 --- a/C3d/Include/action_point.h +++ b/C3d/Include/action_point.h @@ -1,820 +1,852 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Функции создания точек. - \en Functions for points creation. \~ - \details \ru Функции, использующие в качестве выходных параметров точки или массивы точек. - \en Functions that take points or arrays of points as input parameters. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_POINT_H -#define __ACTION_POINT_H - - -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbLineSegment; -class MATH_CLASS MbLine3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив. - \en Create an array. \~ - \details \ru Создать массив с контролем выделения памяти. \n - \en Create an array with memory allocation control. \n \~ - \param[in] cnt - \ru Количество элементов массива. - \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. \~ - \ingroup Algorithms_3D -*/ -// --- -template -inline SArray * CreateArray( size_t cnt, MbResultType & res ) -{ - SArray * arr = new SArray ( cnt, 1 ); - if ( arr != NULL && arr->GetAddr() == NULL ) { - delete arr; - arr = NULL; - } - if ( arr == NULL ) - res = rt_TooManyPoints; - - return arr; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выделить в массиве память под n элементов. - \en Allocate memory in the array for n elements. \~ - \details \ru Выделить в массиве память под n элементов с контролем выделения памяти. \n - \en Allocate memory in the array for n elements with memory allocation control. \n \~ - \param[in, out] arr - \ru Массив. - \en An array. \~ - \param[in] n - \ru Количество элементов, под которые нужно выделить память. - \en Number of elements for allocation. \~ - \param[out] res - \ru Результат операции. - \en The operation result. \~ - \return \ru Возвращает true в случае успешного выделения памяти. - \en Returns true if the memory has been successfully allocated. \~ - \ingroup Algorithms_3D -*/ -// --- -template -inline bool ReserveArray( SArray & arr, size_t n, MbResultType & res ) -{ - arr.Reserve( n ); - if ( arr.GetAddr() == NULL ) { - res = rt_TooManyPoints; - return false; - } - return true; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить в массив элемент. - \en Add an element to the array. \~ - \details \ru Добавить в массив элемент с контролем выделения памяти. \n - \en Add an element to the array with memory allocation control. \n \~ - \param[in, out] arr - \ru Массив. - \en An array. \~ - \param[in] item - \ru Элемент, который нужно добавить. - \en The element to add. \~ - \param[out] res - \ru Результат операции. - \en The operation result. \~ - \return \ru Возвращает true в случае успешного добавления. - \en Returns true if the element has been successfully added. \~ - \ingroup Algorithms_3D -*/ -// --- -template -inline bool AddItem( SArray & arr, const Type & item, MbResultType & res ) -{ - arr.Add( item ); - if ( arr.GetAddr() == NULL ) { - res = rt_TooManyPoints; - return false; - } - return true; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Пространственно-параметрическая точка. - \en A space-parametric point. \~ - \details \ru Пространственно-параметрическая точка. \n - Содержит в себе трехмерную и двумерную точки. - \en A space-parametric point. \n - Contains a three-dimensional point and a two-dimensional point. \~ - \ingroup Point_Modeling -*/ -// --- -class MATH_CLASS MbSpaceParamPnt { -protected: - MbCartPoint3D spacePnt; ///< \ru Пространственная точка. \en A spatial point. - MbCartPoint paramPnt; ///< \ru Параметрическая точка. \en A parametric point. - -public: // \ru Конструкторы \en Constructors - /// \ru Конструктор по пространственной точке. \en A constructor that takes a space point. - explicit MbSpaceParamPnt( const MbCartPoint3D & sp ) : spacePnt( sp ), paramPnt( UNDEFINED_DBL, 0.0 ) {} - /// \ru Конструктор по пространственной и параметрической точкам. \en A constructor that takes a space point and a parametric point. - explicit MbSpaceParamPnt( const MbCartPoint3D & sp, const MbCartPoint & pp ) : spacePnt( sp ), paramPnt( pp ) {} - /// \ru Конструктор по пространственно-параметрической точке. \en A constructor that takes a space-parametric point. - explicit MbSpaceParamPnt( const MbSpaceParamPnt & cp ) : spacePnt( cp.spacePnt ), paramPnt( cp.paramPnt ) {} - ~MbSpaceParamPnt() {} - -public: // \ru Инициализация \en The initialization - /// \ru Инициализация по пространственно-параметрической точке. \en Initialization with a space-parametric point. - void Init( const MbSpaceParamPnt & cp ) { spacePnt = cp.spacePnt; paramPnt = cp.paramPnt; } - /// \ru Инициализация по пространственной и параметрической точкам. \en Initialization with a space point and a parametric point. - void Init( const MbCartPoint3D & sp, const MbCartPoint & pp ) { spacePnt = sp; paramPnt = pp; } -public: // \ru Функции \en Functions - /// \ru Установлена ли параметрическая точка? \en Whether the parametric point is speified. - bool IsParamPnt() const { return (paramPnt.x != UNDEFINED_DBL); } //-V550 - /// \ru Перевести параметрическую точку в неустановленное состояние. \en Reset a parametric point. - void ResetParamPnt() { paramPnt.x = UNDEFINED_DBL; } - /// \ru Проверка на равенство параметрических точек по X с заданной погрешностью. \en Check if parametric points are equal by X component with the specified tolerance. - bool IsParamEqualX( const MbSpaceParamPnt & cp, double eps ) const { return (::fabs(paramPnt.x - cp.paramPnt.x) < eps); } - /// \ru Проверка на равенство параметрических точек по Y с заданной погрешностью. \en Check if parametric points are equal by Y component with the specified tolerance. - bool IsParamEqualY( const MbSpaceParamPnt & cp, double eps ) const { return (::fabs(paramPnt.y - cp.paramPnt.y) < eps); } - - /// \ru Получить ссылку на пространственную точку. \en Get a reference to the space point. - const MbCartPoint3D & GetSpacePnt() const { return spacePnt; } - /// \ru Получить ссылку на параметрическую точку. \en Get a reference to the parametric point. - const MbCartPoint & GetParamPnt() const { return paramPnt; } - -private: // \ru Нереализованные \en Not implemented - MbSpaceParamPnt(); - MbSpaceParamPnt( const MbCartPoint & ); - void operator = ( const MbCartPoint3D & ); - void operator = ( const MbCartPoint & ); - void operator = ( const MbSpaceParamPnt & ); - bool operator == ( const MbSpaceParamPnt & ) const; -}; - - -typedef std::pair MbLocPnt; ///< \ru Пространственно-параметрическая точка с индексированным положением. \en A space-parametric point with indexed position. - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать точки на поверхности. - \en Create points on a surface. \~ - \details \ru Создать группу точек на поверхности. \n - \en Create a group of points on a surface. \n \~ - \param[in] surface - \ru Поверхность-источник. - \en The source surface. \~ - \param[in] stepType - \ru Тип шага по поверхности. - \en Type of spacing on a surface. \~ - \param[in] uValue - \ru Величина шага по u или количество точек по u при шаге по параметру - \en U-spacing value or number of points in u-direction while sampling by parameter \~ - \param[in] vValue - \ru Величина шага по v или количество точек по v при шаге по параметру. - \en V-spacing value or number of points in v-direction while sampling by parameter. \~ - \param[in] truncateByBounds - \ru Усечь границами поверхности. - \en Whether to truncate by surface boundary. \~ - \param[out] result - \ru Индексированные пространственно-параметрические точки. - \en Indexed space-parametric points. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (MbResultType) PointsOnSurface( const MbSurface & surface, - MbeStepType stepType, - double uValue, - double vValue, - bool truncateByBounds, - RPArray< SArray > & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать точки на поверхности. - \en Create points on a surface. \~ - \details \ru Создать группу точек на поверхности. \n - \en Create a group of points on a surface. \n \~ - \param[in] surface - \ru Поверхность-источник. - \en The source surface. \~ - \param[in] gridType - \ru Тип cетки на поверхности. - \en A type of a grid on a surface. \~ - \param[in] uv0 - \ru Центральная точка сетки - \en The central point of the grid. \~ - \param[in] angle - \ru Угол поворота сетки относительно направления U (в радианах) - \en Rotaion angle of the grid relative to U direction (in radians). \~ - \param[in] stepType - \ru Тип шага по поверхности. - \en Type of spacing on a surface. \~ - \param[in] step1 - \ru Величина шага по первому направлению - \en A spacing value in the first direction \~ - \param[in] step2 - \ru Величина шага по второму направлению - \en A spacing value in the second direction \~ - \param[in] truncateByBounds - \ru Усечь границами поверхности. - \en Whether to truncate by surface boundary. \~ - \param[out] result - \ru Индексированные пространственно-параметрические точки. - \en Indexed space-parametric points. \~ - \param[in] maxPntsCnt - \ru Максимально допустимое количество точек. - \en The maximal acceptable number of points. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (MbResultType) PointsOnSurface( const MbSurface & surface, - MbeItemGridType & gridType, - const MbCartPoint & uv0, - double angle, - MbeStepType stepType, - double step1, - double step2, - bool truncateByBounds, - RPArray< SArray > & result, - size_t maxPntsCnt = c3d::ARRAY_MAX_COUNT ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить умолчательную разбивку поверхности. - \en Define the default sampling of a surface. \~ - \details \ru Определить умолчательную разбивку поверхности \n - (вспомогательная функция для функции PointsOnSurface). - \en Define the default sampling of a surface \n - (an auxillary function for function PointsOnSurface). \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[out] uPntsCnt - \ru Количество разбиений по u. - \en The points number in U direction. \~ - \param[out] vPntsCnt - \ru Количество разбиений по v. - \en The points number in V direction. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (void) DefinePointsOnSurfaceCounts( const MbSurface & surface, - size_t & uPntsCnt, - size_t & vPntsCnt ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точку пересечения трех поверхностей. - \en Calculate the intersection point of three surfaces. \~ - \details \ru Найти точку пересечения трех поверхностей по начальным приближениям. \n - \en Calculate the intersection point of three surfaces given the initial estimates. \n \~ - \param[in] surf0 - \ru Первая поверхность. - \en The first surface. \~ - \param[in] ext0 - \ru Флаг поиска на продолжении первой поверхности. - \en Whether to use the extension of the first surface. \~ - \param[in] surf1 - \ru Вторая поверхность. - \en The second surface. \~ - \param[in] ext1 - \ru Флаг поиска на продолжении второй поверхности. - \en Whether to use the extension of the second surface. \~ - \param[in] surf2 - \ru Третья поверхность. - \en The third surface. \~ - \param[in] ext2 - \ru Флаг поиска на продолжении третьей поверхности. - \en Whether to use the extension of the third surface. \~ - \param[in,out] uv0 - \ru Началальное приближение и результат на поверхности surf0. - \en The initial approximation and the result on surface surf0. \~ - \param[in,out] uv1 - \ru Началальное приближение и результат на поверхности surf1. - \en The initial approximation and the result on surface surf1. \~ - \param[in,out] uv2 - \ru Началальное приближение и результат на поверхности surf2. - \en The initial approximation and the result on surface surf2. \~ - \return \ru Возвращает код результата итерационного поиска точки пересечения. - \en Returns the result code of the intersection point iterative search. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (MbeNewtonResult) IntersectionPoint( const MbSurface & surf0, bool ext0, - const MbSurface & surf1, bool ext1, - const MbSurface & surf2, bool ext2, - MbCartPoint & uv0, - MbCartPoint & uv1, - MbCartPoint & uv2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти все точки пересечения поверхности и кривой. - \en Calculate all the points of intersection of a surface and a curve. \~ - \details \ru Найти все точки пересечения поверхности и кривой. \n - \en Calculate all the points of intersection of a surface and a curve. \n \~ - \param[in] surf - \ru Поверхность. - \en A surface. \~ - \param[in] surfExt - \ru Искать на продолжении поверхности. - \en Use the surface extension. \~ - \param[in] curv - \ru Кривая. - \en The curve. \~ - \param[in] curveExt - \ru Искать на продолжении кривой. - \en Use the curve extension. \~ - \param[out] uv - \ru Параметры точек пересечения на поверхности. - \en Parameters of the intersection points on the surface. \~ - \param[out] tt - \ru Параметры точек пересечения на кривой. - \en Parameters of the intersection points on the curve. \~ - \param[in] touchInclude - \ru Считать касания пересечениями. - \en Consider tangencies as intersections. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (void) IntersectionPoints( const MbSurface & surf, bool surfExt, - const MbCurve3D & curv, bool curveExt, - SArray & uv, - SArray & tt, - bool touchInclude = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить параметры ближайших точек прямых. - \en Determine the parameters of the nearest points of lines. \~ - \details \ru Определить параметры ближайших точек прямых, заданных точкой и вектором направления. - \en Determine the parameters of the nearest points of lines which are defined by the given point and direction vector. \~ - \param[in] origin1, direction1 - \ru Точка и направление первой прямой. - \en A point and direction of the first line. \~ - \param[in] origin2, direction2 - \ru Точка и направление второй прямой. - \en A point and direction of the second line. \~ - \param[out] t1 - \ru Параметр на первой прямой. - \en Parameter on the first line. \~ - \param[out] t2 - \ru Параметр на второй прямой. - \en Parameter on the second line. \~ - \return \ru Возвращает true, если есть прямые не параллельны. \n - \en Returns true, if lines are not parallel. \n \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) LineLineNearestParams( const MbCartPoint3D & origin1, const MbVector3D & direction1, - const MbCartPoint3D & origin2, const MbVector3D & direction2, - double & t1, double & t2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определение расстояния между ближайшими точками p1 и p2 прямых line1 и line2 - \en Determination of the distance between the nearest points p1 and p2 of lines line1 and line2 \~ - \details \ru Определение расстояния между ближайшими точками p1 и p2 прямых line1 и line2 - \en Determination of the distance between the nearest points p1 and p2 of lines line1 and line2 \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (double) LineLineNearestPoints( const MbLine3D & line1, const MbLine3D & line2, - MbCartPoint3D & p1, MbCartPoint3D & p2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить параметры ближайших точек прямых. - \en Determine the parameters of the nearest points of lines. \~ - \details \ru Определить параметры ближайших точек прямых, заданных точкой и вектором направления. - \en Determine the parameters of the nearest points of lines which are defined by the given point and direction vector. \~ - \param[in] origin1, direction1 - \ru Точка и направление первой прямой. - \en A point and direction of the first line. \~ - \param[in] origin2, direction2 - \ru Точка и направление второй прямой. - \en A point and direction of the second line. \~ - \param[out] t1 - \ru Параметр на первой прямой. - \en Parameter on the first line. \~ - \param[out] t2 - \ru Параметр на второй прямой. - \en Parameter on the second line. \~ - \return \ru Возвращает true, если есть прямые не параллельны. \n - \en Returns true, if lines are not parallel. \n \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) LineLineNearestParams( const MbCartPoint & origin1, const MbVector & direction1, - const MbCartPoint & origin2, const MbVector & direction2, - double & t1, double & t2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точку пересечения двух прямых. - \en Calculate the point of two lines intersection. \~ - \details \ru Найти точку пересечения двух точно пересекающихся прямых без проверки параллельности. \n - \en Calculate the intersection point of two exactly intersecting lines without check. \n \~ - \param[in] line1 - \ru Первая прямая. - \en The first line. \~ - \param[in] line2 - \ru Вторая прямая. - \en The second line. \~ - \param[out] result - \ru Точка пересечения. - \en The intersection point. \~ - \ingroup Point_Modeling -*/ -// --- -inline void FastLineLine( const MbLine & line1, - const MbLine & line2, - MbCartPoint & result ) -{ - const MbDirection & dir1 = line1.GetDirection(); - const MbDirection & dir2 = line2.GetDirection(); - const MbCartPoint & pnt1 = line1.GetOrigin(); - const MbCartPoint & pnt2 = line2.GetOrigin(); - - double t = ( dir1.ax * (pnt2.y - pnt1.y) - dir1.ay * (pnt2.x - pnt1.x )) / - ( dir1.ay * dir2.ax - dir1.ax * dir2.ay ); - - result.x = pnt2.x + dir2.ax * t; - result.y = pnt2.y + dir2.ay * t; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точку пересечения двух прямых. - \en Calculate the point of two lines intersection. \~ - \details \ru Найти точку пересечения двух прямых. \n - Прямые могут быть параллельны или совпадать. \n - \en Calculate the point of two lines intersection. \n - The curves can be parallel or coincident. \n \~ - \param[in] line1 - \ru Первая прямая. - \en The first line. \~ - \param[in] line2 - \ru Вторая прямая. - \en The second line. \~ - \param[out] result - \ru Точка пересечения. - \en The intersection point. \~ - \return \ru Возвращает результат пересечения: \n - 1 - Прямые пересекаются. \n - 0 - Прямые параллельны или совпадают. - \en Returns the result of intersection: \n - 1 - The lines intersect at a point. \n - 0 - The lines are parallel or coincident. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (int) LineLine( const MbLine & line1, - const MbLine & line2, - MbCartPoint & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точку пересечения двух прямых. - \en Calculate the point of two lines intersection. \~ - \details \ru Найти точку пересечения двух прямых. \n - Прямые могут быть параллельны или совпадать. \n - \en Calculate the point of two lines intersection. \n - The curves can be parallel or coincident. \n \~ - \param[in] line1 - \ru Первая прямая. - \en The first line. \~ - \param[in] line2 - \ru Вторая прямая. - \en The second line. \~ - \param[out] result - \ru Точка пересечения. - \en The intersection point. \~ - \return \ru Возвращает результат пересечения: \n - 1 : прямые пересекаются; \n - 0 : прямые параллельны; \n - 1 : прямые совпадают - касательная точка пересечения. - \en Returns the result of intersection: \n 1 : the curves intersect at a point; \n 0 : the curves are parallel; \n 1 : the curves are coincident - the tangent intersection point. \~\ingroup Point_Modeling -*/ -// --- -MATH_FUNC (int) LineLine( const MbLine & line1, - const MbLine & line2, - MbCrossPoint & result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точку пересечения прямой и отрезка. - \en Calculate the intersection point of a line and a line segment. \~ - \details \ru Найти точку пересечения прямой и отрезка. \n - Отрезок может быть параллелен прямой или лежать на ней. \n - \en Calculate the intersection point of a line and a line segment. \n - The line segment can be parallel to the curve or lie on it. \n \~ - \param[in] line - \ru Прямая. - \en The line. \~ - \param[in] lseg - \ru Отрезок. - \en The segment. \~ - \param[out] result - \ru Точка пересечения. - \en The intersection point. \~ - \return \ru Возвращает результат пересечения: \n - 1 : прямая и отрезок пересекаются; \n - 0 : прямая и отрезок параллельны; \n - 1 : отрезок лежит на прямой - касательная точка пересечения. - \en Returns the result of intersection: \n 1 : the line and the line segment intersect at a point; \n 0 : the line and a line segment are parallel; \n 1 : the segment lies on the curve - a tangent intersection point. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (int) LineLineSeg( const MbLine & line, - const MbLineSegment & lseg, - MbCrossPoint & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки пересечения прямой и окружности. - \en Calculate intersection points of a line and a circle. \~ - \details \ru Найти параметры точек пересечения прямой и окружности. \n - \en Calculate the parameters of intersection points of a line and a circle. \n \~ - \param[in] line - \ru Прямая. - \en The line. \~ - \param[in] centre - \ru Центр окружности. - \en The circle center. \~ - \param[in] radius - \ru Радиус окружности. - \en The circle radius. \~ - \param[out] result - \ru Точки пересечения (указатель на массив из двух(!) элементов). - \en The intersection points (a pointer to the array of two (!) elements). \~ - \return \ru Возвращает количество найденных пересечений. - \en Returns the number of intersections. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (int) LineCircle( const MbLine & line, - const MbCartPoint & centre, - double radius, - MbCrossPoint * result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки пересечения двух кривых. - \en Calculate intersection points of two curves. \~ - \details \ru Найти параметры точек пересечения двух произвольных кривых. \n - Общий метод вызывается, если нет частной функции пересечения. \n - \en Calculate the parameters of intersection points of two arbitrary curves. \n - The general method is used if there is no special function for intersection. \n \~ - \param[in] pCurve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] pCurve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] result - \ru Множество точек пересечения. - \en The array of intersection points. \~ - \param[in] touchInclude - \ru Считать касания пересечениями. - \en Consider tangencies as intersections. \~ - \param[in] epsilon - \ru Точность совпадения точек пересечения кривых. - \en The accuracy of coincidence points of intersection. \~ - \param[in] allowInaccuracy - \ru Разрешить понижать входную точность. - \en Allow lowering input accuracy. \~ - \return \ru Количество найденных пересечений. - \en The number of intersections. \~ - \warning \ru Применяется для двумерных построений, аналог CurveCurveIntersection. - \en Used for two-dimensional constructions, the analogue of CurveCurveIntersection. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (ptrdiff_t) IntersectTwoCurves( const MbCurve & pCurve1, - const MbCurve & pCurve2, - SArray & result, - bool touchInclude = true, - double epsilon = Math::LengthEps*c3d::METRIC_DELTA, - bool allowInaccuracy = true ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки пересечения двух кривых. - \en Calculate intersection points of two curves. \~ - \details \ru Найти параметры точек пересечения двух произвольных кривых. \n - Общий метод вызывается, если нет частной функции пересечения. \n - \en Calculate the parameters of intersection points of two arbitrary curves. \n - The general method is used if there is no special function for intersection. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] result1 - \ru Параметры пересечений первой кривой. - \en The parameters of intersections for the first curve. \~ - \param[out] result2 - \ru Параметры пересечений второй кривой. - \en The parameters of intersections for the second curve. \~ - \param[in] xEpsilon - \ru Точность по x. - \en Tolerance in x direction. \~ - \param[in] yEpsilon - \ru Точность по y. - \en Tolerance in y direction. \~ - \param[in] touchInclude - \ru Считать касания пересечениями. - \en Consider tangencies as intersections. \~ - \param[in] allowInaccuracy - \ru Разрешить нахождение решения с меньшей точностью при невозможности удовлетворить указанной. - \en Allow to find a solution with less precision when we can't get a solution with given precision. \~ - \return \ru Количество найденных пересечений. - \en The number of intersections. \~ - \warning \ru Применяется для трехмерных построений, аналог IntersectTwoCurves. - \en Used for three-dimensional constructions, the analogue of IntersectTwoCurves. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (ptrdiff_t) CurveCurveIntersection( const MbCurve & curve1, - const MbCurve & curve2, - SArray & result1, - SArray & result2, - double xEpsilon, - double yEpsilon, - bool touchInclude, bool allowInaccuracy = true ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки самопересечения кривой. - \en Calculate the points of curve self-intersection. \~ - \details \ru Найти параметры точек самопересечения кривой с заданной точностью. \n - \en Calculate the self-intersection points parameters with the given tolerance. \n \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in] xEpsilon - \ru Точность по x. - \en Tolerance in x direction. \~ - \param[in] yEpsilon - \ru Точность по y. - \en Tolerance in y direction. \~ - \param[out] result1 - \ru Множество параметров самопересечения. - \en The self-intersection parameters array. \~ - \param[out] result2 - \ru Множество параметров самопересечения. - \en The self-intersection parameters array. \~ - \param[in] version - \ru Версия операции. - \en The version of the operation. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (void) CurveSelfIntersect( const MbCurve & curve, - double xEpsilon, - double yEpsilon, - SArray & result1, - SArray & result2, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Удалить точки касания. - \en Remove touch points. \~ - \details \ru Удалить все точки касания кривых вне зависимости от положения параметра на кривой - (внутри области определения или на границах кривой). - \en Remove all curves touch points regardless the position on the curve - (in the domain or on the borders). \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[in, out] result - \ru Множество точек пересечения. - \en The array of intersection points. \~ - \param[in] eps - \ru Погрешность для функции проверки параллельности касательных RoundColinear. - \en Accuracy for the function RoundColinear of testing the parallelism of tangents. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (void) RemoveAllTouchParams( const MbCurve & curve1, - const MbCurve & curve2, - SArray & result, - double eps = PARAM_NEAR ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки пересечения двух кривых. - \en Calculate intersection points of two curves. \~ - \details \ru Найти параметры точек пересечения двух произвольных кривых. \n - \en Calculate the parameters of intersection points of two arbitrary curves. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] result1 - \ru Параметры точек пересечения для первой кривой. - \en The intersection points parameters for the first curve. \~ - \param[out] result2 - \ru Параметры точек пересечения для второй кривой. - \en The intersection points parameters for the second curve. \~ - \param[in] mEps - \ru Возможная максимальная погрешность найденных пересечений. - \en The intersection tolerance. \~ - \return \ru Количество найденных пересечений. - \en The number of intersections. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (ptrdiff_t) CurveCurveIntersection( const MbCurve3D & curve1, - const MbCurve3D & curve2, - SArray & result1, - SArray & result2, - double mEps = Math::metricRegion ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить кривую на самопересечение. - \en Determine if the curve has self-intersections. \~ - \details \ru Проверить заданную кривую на самопересечение. \n - \en Determine if the given curve has self-intersections. \n \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in] mEps - \ru Возможная максимальная погрешность найденных самопересечений. - \en The tolerance of self-intersections. \~ - \return \ru Возвращает true, если кривая самопересекается. - \en Returns true if the curve has self-intersections. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (bool) IsSelfIntersect( const MbCurve3D & curve, - double mEps = Math::metricRegion ); - - - -//------------------------------------------------------------------------------ -/** \brief \ru Убрать касательные точки пересечения. - \en Remove the tangent intersection points. \~ - \details \ru Убрать параметры касательных точек пересечения внутри областей определения кривых. \n - \en Remove the tangent intersection points parameters inside the domains of curves. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] result1 - \ru Параметры точек пересечения для первой кривой. - \en The intersection points parameters for the first curve. \~ - \param[out] result2 - \ru Параметры точек пересечения для второй кривой. - \en The intersection points parameters for the second curve. \~ - \param[in] mEps - \ru Возможная максимальная погрешность найденных пересечений. - \en The intersection tolerance. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (void) FilterTouchParams( const MbCurve3D & curve1, - const MbCurve3D & curve2, - SArray & result1, - SArray & result2, - double mEps = Math::metricRegion ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки скрещения двух кривых. - \en Calculate the points of two curves crossing. \~ - \details \ru Найти параметры точек скрещения двух кривых. \n - \en Calculate parameters of the points of two curves crossing. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] result1 - \ru Параметры точек скрещения для первой кривой. - \en Parameters of the points of crossing for the first curve. \~ - \param[out] result2 - \ru Параметры точек скрещения для второй кривой. - \en Parameters of the points of crossing for the second curve. \~ - \return \ru Количество найденных скрещений. - \en The points of crossing number. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (ptrdiff_t) CurveCurveCrossing( const MbCurve3D & curve1, - const MbCurve3D & curve2, - SArray & result1, - SArray & result2, - double epsilon = Math::metricRegion ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти проекцию точки на поверхность относительно внешнего контура поверхности. - \en Find the projection of a point on a surface relative to the outer contour of the surface. \~ - \details \ru Найти проекцию пространственной точки на поверхность в виде двумерной точки на поверхности - относительно внешнего контура поверхности. \n - \en Calculate the projection of a space point on a surface as a two-dimensional point on the surface. - relative to the outer contour of the surface. \n \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] pnt - \ru Пространственная точка. - \en A space point. \~ - \param[in] byOuterRectOnly - \ru Классифицировать проекцию только относительно внешнего габаритного прямоугольника. - \en Whether to classify the projection relative to the outer bounding box only. \~ - \param[out] result - \ru Двумерная параметрическая точка на поверхности. - \en A two-dimensional parametric point on the surface. \~ - \return \ru Возвращает true, если найдена нормальная проекция точки на поверхность. - \en Returns true if a normal projection of the point on the surface has been calculated. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (bool) PointProjectionRelativeOuterLoop( const MbSurface & surface, - const MbCartPoint3D & pnt, - bool byOuterRectOnly, - MbCartPoint & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Является ли проекция точки точно неоднозначной. - \en Determine whether the point projection is multiple-valued. \~ - \details \ru Является ли проекция точки неоднозначной при проецировании - в области определения поверхности. \n - \en Determine whether the point projection is multiple-valued while projecting - inside the surface domain. \n \~ - \param[in] surface - \ru Поверхность. - \en A surface. \~ - \param[in] result - \ru Пространственная точка. - \en A space point. \~ - \return \ru Возвращает true, если проекция точки является неоднозначной. - \en Returns true if the point projection is multiple-valued \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC (bool) IsMultipleProjection( const MbSurface & surface, - const MbCartPoint3D & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти точки касания двух поверхностей. - \en Calculate the touch points of two surfaces. \~ - \details \ru Найти параметры точек касания двух поверхностей. \n - \en Calculate the parameters of touch points of two surfaces. \n \~ - \param[in] surf1 - \ru Первая поверхность. - \en A first surface. \~ - \param[in] ext1 - \ru Искать на продолжении первой поверхности. - \en Use the first surface extension. \~ - \param[in] surf2 - \ru Вторая поверхность. - \en A second surface. \~ - \param[in] ext2 - \ru Искать на продолжении второй поверхности. - \en Use the second surface extension. \~ - \param[in] uv1arr - \ru Параметры точек касания первой поверхности. - \en Parameters of touch points of first surface. \~ - \param[in] uv2arr - \ru Параметры точек касания второй поверхности. - \en Parameters of touch points of second surface. \~ - \return \ru Возвращает true, если найдены точки касания. - \en Returns true if the touch points has be calculate. \~ - \warning \ru В разработке. - \en Under development. \~ - \ingroup Point_Modeling -*/ -// --- -MATH_FUNC ( bool) TouchIntersectionPoints( const MbSurface & surf1, bool ext1, - const MbSurface & surf2, bool ext2, - std::vector & uv1arr, - std::vector & uv2arr ); - - -#endif // __ACTION_POINT_H - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Функции создания точек. + \en Functions for points creation. \~ + \details \ru Функции, использующие в качестве выходных параметров точки или массивы точек. + \en Functions that take points or arrays of points as input parameters. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_POINT_H +#define __ACTION_POINT_H + + +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbLineSegment; +class MATH_CLASS MbLine3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbFaceShell; + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив. + \en Create an array. \~ + \details \ru Создать массив с контролем выделения памяти. \n + \en Create an array with memory allocation control. \n \~ + \param[in] cnt - \ru Количество элементов массива. + \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. \~ + \ingroup Algorithms_3D +*/ +// --- +template +inline SArray * CreateArray( size_t cnt, MbResultType & res ) +{ + SArray * arr = new SArray ( cnt, 1 ); + if ( arr != NULL && arr->GetAddr() == NULL ) { + delete arr; + arr = NULL; + } + if ( arr == NULL ) + res = rt_TooManyPoints; + + return arr; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выделить в массиве память под n элементов. + \en Allocate memory in the array for n elements. \~ + \details \ru Выделить в массиве память под n элементов с контролем выделения памяти. \n + \en Allocate memory in the array for n elements with memory allocation control. \n \~ + \param[in, out] arr - \ru Массив. + \en An array. \~ + \param[in] n - \ru Количество элементов, под которые нужно выделить память. + \en Number of elements for allocation. \~ + \param[out] res - \ru Результат операции. + \en The operation result. \~ + \return \ru Возвращает true в случае успешного выделения памяти. + \en Returns true if the memory has been successfully allocated. \~ + \ingroup Algorithms_3D +*/ +// --- +template +inline bool ReserveArray( SArray & arr, size_t n, MbResultType & res ) +{ + arr.Reserve( n ); + if ( arr.GetAddr() == NULL ) { + res = rt_TooManyPoints; + return false; + } + return true; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить в массив элемент. + \en Add an element to the array. \~ + \details \ru Добавить в массив элемент с контролем выделения памяти. \n + \en Add an element to the array with memory allocation control. \n \~ + \param[in, out] arr - \ru Массив. + \en An array. \~ + \param[in] item - \ru Элемент, который нужно добавить. + \en The element to add. \~ + \param[out] res - \ru Результат операции. + \en The operation result. \~ + \return \ru Возвращает true в случае успешного добавления. + \en Returns true if the element has been successfully added. \~ + \ingroup Algorithms_3D +*/ +// --- +template +inline bool AddItem( SArray & arr, const Type & item, MbResultType & res ) +{ + arr.Add( item ); + if ( arr.GetAddr() == NULL ) { + res = rt_TooManyPoints; + return false; + } + return true; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Пространственно-параметрическая точка. + \en A space-parametric point. \~ + \details \ru Пространственно-параметрическая точка. \n + Содержит в себе трехмерную и двумерную точки. + \en A space-parametric point. \n + Contains a three-dimensional point and a two-dimensional point. \~ + \ingroup Point_Modeling +*/ +// --- +class MATH_CLASS MbSpaceParamPnt { +protected: + MbCartPoint3D spacePnt; ///< \ru Пространственная точка. \en A spatial point. + MbCartPoint paramPnt; ///< \ru Параметрическая точка. \en A parametric point. + +public: // \ru Конструкторы \en Constructors + /// \ru Конструктор по пространственной точке. \en A constructor that takes a space point. + explicit MbSpaceParamPnt( const MbCartPoint3D & sp ) : spacePnt( sp ), paramPnt( UNDEFINED_DBL, 0.0 ) {} + /// \ru Конструктор по пространственной и параметрической точкам. \en A constructor that takes a space point and a parametric point. + explicit MbSpaceParamPnt( const MbCartPoint3D & sp, const MbCartPoint & pp ) : spacePnt( sp ), paramPnt( pp ) {} + /// \ru Конструктор по пространственно-параметрической точке. \en A constructor that takes a space-parametric point. + explicit MbSpaceParamPnt( const MbSpaceParamPnt & cp ) : spacePnt( cp.spacePnt ), paramPnt( cp.paramPnt ) {} + ~MbSpaceParamPnt() {} + +public: // \ru Инициализация \en The initialization + /// \ru Инициализация по пространственно-параметрической точке. \en Initialization with a space-parametric point. + void Init( const MbSpaceParamPnt & cp ) { spacePnt = cp.spacePnt; paramPnt = cp.paramPnt; } + /// \ru Инициализация по пространственной и параметрической точкам. \en Initialization with a space point and a parametric point. + void Init( const MbCartPoint3D & sp, const MbCartPoint & pp ) { spacePnt = sp; paramPnt = pp; } +public: // \ru Функции \en Functions + /// \ru Установлена ли параметрическая точка? \en Whether the parametric point is specified. + bool IsParamPnt() const { return (paramPnt.x != UNDEFINED_DBL); } //-V550 + /// \ru Перевести параметрическую точку в неустановленное состояние. \en Reset a parametric point. + void ResetParamPnt() { paramPnt.x = UNDEFINED_DBL; } + /// \ru Проверка на равенство параметрических точек по X с заданной погрешностью. \en Check if parametric points are equal by X component with the specified tolerance. + bool IsParamEqualX( const MbSpaceParamPnt & cp, double eps ) const { return (::fabs(paramPnt.x - cp.paramPnt.x) < eps); } + /// \ru Проверка на равенство параметрических точек по Y с заданной погрешностью. \en Check if parametric points are equal by Y component with the specified tolerance. + bool IsParamEqualY( const MbSpaceParamPnt & cp, double eps ) const { return (::fabs(paramPnt.y - cp.paramPnt.y) < eps); } + + /// \ru Получить ссылку на пространственную точку. \en Get a reference to the space point. + const MbCartPoint3D & GetSpacePnt() const { return spacePnt; } + /// \ru Получить ссылку на параметрическую точку. \en Get a reference to the parametric point. + const MbCartPoint & GetParamPnt() const { return paramPnt; } + +private: // \ru Нереализованные \en Not implemented + MbSpaceParamPnt(); + MbSpaceParamPnt( const MbCartPoint & ); + void operator = ( const MbCartPoint3D & ); + void operator = ( const MbCartPoint & ); + void operator = ( const MbSpaceParamPnt & ); + bool operator == ( const MbSpaceParamPnt & ) const; +}; + + +typedef std::pair MbLocPnt; ///< \ru Пространственно-параметрическая точка с индексированным положением. \en A space-parametric point with indexed position. + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать точки на поверхности. + \en Create points on a surface. \~ + \details \ru Создать группу точек на поверхности. \n + \en Create a group of points on a surface. \n \~ + \param[in] surface - \ru Поверхность-источник. + \en The source surface. \~ + \param[in] stepType - \ru Тип шага по поверхности. + \en Type of spacing on a surface. \~ + \param[in] uValue - \ru Величина шага по u или количество точек по u при шаге по параметру + \en U-spacing value or number of points in u-direction while sampling by parameter \~ + \param[in] vValue - \ru Величина шага по v или количество точек по v при шаге по параметру. + \en V-spacing value or number of points in v-direction while sampling by parameter. \~ + \param[in] truncateByBounds - \ru Усечь границами поверхности. + \en Whether to truncate by surface boundary. \~ + \param[out] result - \ru Индексированные пространственно-параметрические точки. + \en Indexed space-parametric points. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (MbResultType) PointsOnSurface( const MbSurface & surface, + MbeStepType stepType, + double uValue, + double vValue, + bool truncateByBounds, + RPArray< SArray > & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать точки на поверхности. + \en Create points on a surface. \~ + \details \ru Создать группу точек на поверхности. \n + \en Create a group of points on a surface. \n \~ + \param[in] surface - \ru Поверхность-источник. + \en The source surface. \~ + \param[in] gridType - \ru Тип сетки на поверхности. + \en A type of a grid on a surface. \~ + \param[in] uv0 - \ru Центральная точка сетки + \en The central point of the grid. \~ + \param[in] angle - \ru Угол поворота сетки относительно направления U (в радианах) + \en Rotation angle of the grid relative to U direction (in radians). \~ + \param[in] stepType - \ru Тип шага по поверхности. + \en Type of spacing on a surface. \~ + \param[in] step1 - \ru Величина шага по первому направлению + \en A spacing value in the first direction \~ + \param[in] step2 - \ru Величина шага по второму направлению + \en A spacing value in the second direction \~ + \param[in] truncateByBounds - \ru Усечь границами поверхности. + \en Whether to truncate by surface boundary. \~ + \param[out] result - \ru Индексированные пространственно-параметрические точки. + \en Indexed space-parametric points. \~ + \param[in] maxPntsCnt - \ru Максимально допустимое количество точек. + \en The maximal acceptable number of points. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (MbResultType) PointsOnSurface( const MbSurface & surface, + MbeItemGridType & gridType, + const MbCartPoint & uv0, + double angle, + MbeStepType stepType, + double step1, + double step2, + bool truncateByBounds, + RPArray< SArray > & result, + size_t maxPntsCnt = c3d::ARRAY_MAX_COUNT ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить разбивку поверхности по умолчанию. + \en Define the default sampling of a surface. \~ + \details \ru Определить разбивку поверхности по умолчанию \n + (вспомогательная функция для функции PointsOnSurface). + \en Define the default sampling of a surface \n + (an auxiliary function for function PointsOnSurface). \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[out] uPntsCnt - \ru Количество разбиений по u. + \en The points number in U direction. \~ + \param[out] vPntsCnt - \ru Количество разбиений по v. + \en The points number in V direction. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (void) DefinePointsOnSurfaceCounts( const MbSurface & surface, + size_t & uPntsCnt, + size_t & vPntsCnt ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точку пересечения трех поверхностей. + \en Calculate the intersection point of three surfaces. \~ + \details \ru Найти точку пересечения трех поверхностей по начальным приближениям. \n + \en Calculate the intersection point of three surfaces given the initial estimates. \n \~ + \param[in] surf0 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] ext0 - \ru Флаг поиска на продолжении первой поверхности. + \en Whether to use the extension of the first surface. \~ + \param[in] surf1 - \ru Вторая поверхность. + \en The second surface. \~ + \param[in] ext1 - \ru Флаг поиска на продолжении второй поверхности. + \en Whether to use the extension of the second surface. \~ + \param[in] surf2 - \ru Третья поверхность. + \en The third surface. \~ + \param[in] ext2 - \ru Флаг поиска на продолжении третьей поверхности. + \en Whether to use the extension of the third surface. \~ + \param[in,out] uv0 - \ru Начальное приближение и результат на поверхности surf0. + \en The initial approximation and the result on surface surf0. \~ + \param[in,out] uv1 - \ru Начальное приближение и результат на поверхности surf1. + \en The initial approximation and the result on surface surf1. \~ + \param[in,out] uv2 - \ru Начальное приближение и результат на поверхности surf2. + \en The initial approximation and the result on surface surf2. \~ + \return \ru Возвращает код результата итерационного поиска точки пересечения. + \en Returns the result code of the intersection point iterative search. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (MbeNewtonResult) IntersectionPoint( const MbSurface & surf0, bool ext0, + const MbSurface & surf1, bool ext1, + const MbSurface & surf2, bool ext2, + MbCartPoint & uv0, + MbCartPoint & uv1, + MbCartPoint & uv2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти все точки пересечения поверхности и кривой. + \en Calculate all the points of intersection of a surface and a curve. \~ + \details \ru Найти все точки пересечения поверхности и кривой. \n + \en Calculate all the points of intersection of a surface and a curve. \n \~ + \param[in] surf - \ru Поверхность. + \en A surface. \~ + \param[in] surfExt - \ru Искать на продолжении поверхности. + \en Use the surface extension. \~ + \param[in] curv - \ru Кривая. + \en The curve. \~ + \param[in] curveExt - \ru Искать на продолжении кривой. + \en Use the curve extension. \~ + \param[out] uv - \ru Параметры точек пересечения на поверхности. + \en Parameters of the intersection points on the surface. \~ + \param[out] tt - \ru Параметры точек пересечения на кривой. + \en Parameters of the intersection points on the curve. \~ + \param[in] touchInclude - \ru Считать касания пересечениями. + \en Consider tangencies as intersections. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (void) IntersectionPoints( const MbSurface & surf, + bool surfExt, + const MbCurve3D & curv, + bool curveExt, + SArray & uv, + SArray & tt, + bool touchInclude = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить параметры ближайших точек прямых. + \en Determine the parameters of the nearest points of lines. \~ + \details \ru Определить параметры ближайших точек прямых, заданных точкой и вектором направления. + \en Determine the parameters of the nearest points of lines which are defined by the given point and direction vector. \~ + \param[in] origin1, direction1 - \ru Точка и направление первой прямой. + \en A point and direction of the first line. \~ + \param[in] origin2, direction2 - \ru Точка и направление второй прямой. + \en A point and direction of the second line. \~ + \param[out] t1 - \ru Параметр на первой прямой. + \en Parameter on the first line. \~ + \param[out] t2 - \ru Параметр на второй прямой. + \en Parameter on the second line. \~ + \return \ru Возвращает true, если есть прямые не параллельны. \n + \en Returns true, if lines are not parallel. \n \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) LineLineNearestParams( const MbCartPoint3D & origin1, + const MbVector3D & direction1, + const MbCartPoint3D & origin2, + const MbVector3D & direction2, + double & t1, + double & t2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определение расстояния между ближайшими точками p1 и p2 прямых line1 и line2 + \en Determination of the distance between the nearest points p1 and p2 of lines line1 and line2 \~ + \details \ru Определение расстояния между ближайшими точками p1 и p2 прямых line1 и line2 + \en Determination of the distance between the nearest points p1 and p2 of lines line1 and line2 \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (double) LineLineNearestPoints( const MbLine3D & line1, + const MbLine3D & line2, + MbCartPoint3D & p1, + MbCartPoint3D & p2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить параметры ближайших точек прямых. + \en Determine the parameters of the nearest points of lines. \~ + \details \ru Определить параметры ближайших точек прямых, заданных точкой и вектором направления. + \en Determine the parameters of the nearest points of lines which are defined by the given point and direction vector. \~ + \param[in] origin1, direction1 - \ru Точка и направление первой прямой. + \en A point and direction of the first line. \~ + \param[in] origin2, direction2 - \ru Точка и направление второй прямой. + \en A point and direction of the second line. \~ + \param[out] t1 - \ru Параметр на первой прямой. + \en Parameter on the first line. \~ + \param[out] t2 - \ru Параметр на второй прямой. + \en Parameter on the second line. \~ + \return \ru Возвращает true, если есть прямые не параллельны. \n + \en Returns true, if lines are not parallel. \n \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) LineLineNearestParams( const MbCartPoint & origin1, const MbVector & direction1, + const MbCartPoint & origin2, const MbVector & direction2, + double & t1, double & t2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точку пересечения двух прямых. + \en Calculate the point of two lines intersection. \~ + \details \ru Найти точку пересечения двух точно пересекающихся прямых без проверки параллельности. \n + \en Calculate the intersection point of two exactly intersecting lines without check. \n \~ + \param[in] line1 - \ru Первая прямая. + \en The first line. \~ + \param[in] line2 - \ru Вторая прямая. + \en The second line. \~ + \param[out] result - \ru Точка пересечения. + \en The intersection point. \~ + \ingroup Point_Modeling +*/ +// --- +inline +void FastLineLine( const MbLine & line1, + const MbLine & line2, + MbCartPoint & result ) +{ + const MbDirection & dir1 = line1.GetDirection(); + const MbDirection & dir2 = line2.GetDirection(); + const MbCartPoint & pnt1 = line1.GetOrigin(); + const MbCartPoint & pnt2 = line2.GetOrigin(); + + double t = ( dir1.ax * (pnt2.y - pnt1.y) - dir1.ay * (pnt2.x - pnt1.x )) / + ( dir1.ay * dir2.ax - dir1.ax * dir2.ay ); + + result.x = pnt2.x + dir2.ax * t; + result.y = pnt2.y + dir2.ay * t; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точку пересечения двух прямых. + \en Calculate the point of two lines intersection. \~ + \details \ru Найти точку пересечения двух прямых. \n + Прямые могут быть параллельны или совпадать. \n + \en Calculate the point of two lines intersection. \n + The curves can be parallel or coincident. \n \~ + \param[in] line1 - \ru Первая прямая. + \en The first line. \~ + \param[in] line2 - \ru Вторая прямая. + \en The second line. \~ + \param[out] result - \ru Точка пересечения. + \en The intersection point. \~ + \return \ru Возвращает результат пересечения: \n + 1 - Прямые пересекаются. \n + 0 - Прямые параллельны или совпадают. + \en Returns the result of intersection: \n + 1 - The lines intersect at a point. \n + 0 - The lines are parallel or coincident. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (int) LineLine( const MbLine & line1, + const MbLine & line2, + MbCartPoint & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точку пересечения двух прямых. + \en Calculate the point of two lines intersection. \~ + \details \ru Найти точку пересечения двух прямых. \n + Прямые могут быть параллельны или совпадать. \n + \en Calculate the point of two lines intersection. \n + The curves can be parallel or coincident. \n \~ + \param[in] line1 - \ru Первая прямая. + \en The first line. \~ + \param[in] line2 - \ru Вторая прямая. + \en The second line. \~ + \param[out] result - \ru Точка пересечения. + \en The intersection point. \~ + \return \ru Возвращает результат пересечения: \n + 1 : прямые пересекаются; \n + 0 : прямые параллельны; \n + 1 : прямые совпадают - касательная точка пересечения. + \en Returns the result of intersection: \n 1 : the curves intersect at a point; \n 0 : the curves are parallel; \n 1 : the curves are coincident - the tangent intersection point. \~\ingroup Point_Modeling +*/ +// --- +MATH_FUNC (int) LineLine( const MbLine & line1, + const MbLine & line2, + MbCrossPoint & result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точку пересечения прямой и отрезка. + \en Calculate the intersection point of a line and a line segment. \~ + \details \ru Найти точку пересечения прямой и отрезка. \n + Отрезок может быть параллелен прямой или лежать на ней. \n + \en Calculate the intersection point of a line and a line segment. \n + The line segment can be parallel to the curve or lie on it. \n \~ + \param[in] line - \ru Прямая. + \en The line. \~ + \param[in] lseg - \ru Отрезок. + \en The segment. \~ + \param[out] result - \ru Точка пересечения. + \en The intersection point. \~ + \return \ru Возвращает результат пересечения: \n + 1 : прямая и отрезок пересекаются; \n + 0 : прямая и отрезок параллельны; \n + 1 : отрезок лежит на прямой - касательная точка пересечения. + \en Returns the result of intersection: \n 1 : the line and the line segment intersect at a point; \n 0 : the line and a line segment are parallel; \n 1 : the segment lies on the curve - a tangent intersection point. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (int) LineLineSeg( const MbLine & line, + const MbLineSegment & lseg, + MbCrossPoint & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки пересечения прямой и окружности. + \en Calculate intersection points of a line and a circle. \~ + \details \ru Найти параметры точек пересечения прямой и окружности. \n + \en Calculate the parameters of intersection points of a line and a circle. \n \~ + \param[in] line - \ru Прямая. + \en The line. \~ + \param[in] centre - \ru Центр окружности. + \en The circle center. \~ + \param[in] radius - \ru Радиус окружности. + \en The circle radius. \~ + \param[out] result - \ru Точки пересечения (указатель на массив из двух(!) элементов). + \en The intersection points (a pointer to the array of two (!) elements). \~ + \return \ru Возвращает количество найденных пересечений. + \en Returns the number of intersections. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (int) LineCircle( const MbLine & line, + const MbCartPoint & centre, + double radius, + MbCrossPoint * result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки пересечения двух кривых. + \en Calculate intersection points of two curves. \~ + \details \ru Найти параметры точек пересечения двух произвольных кривых. \n + Общий метод вызывается, если нет частной функции пересечения. \n + \en Calculate the parameters of intersection points of two arbitrary curves. \n + The general method is used if there is no special function for intersection. \n \~ + \param[in] pCurve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] pCurve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] result - \ru Множество точек пересечения. + \en The array of intersection points. \~ + \param[in] touchInclude - \ru Считать касания пересечениями. + \en Consider tangencies as intersections. \~ + \param[in] epsilon - \ru Точность совпадения точек пересечения кривых. + \en The accuracy of coincidence points of intersection. \~ + \param[in] allowInaccuracy - \ru Разрешить понижать входную точность. + \en Allow lowering input accuracy. \~ + \return \ru Количество найденных пересечений. + \en The number of intersections. \~ + \warning \ru Применяется для двумерных построений, аналог CurveCurveIntersection. + \en Used for two-dimensional constructions, the analogue of CurveCurveIntersection. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (ptrdiff_t) IntersectTwoCurves( const MbCurve & pCurve1, + const MbCurve & pCurve2, + SArray & result, + bool touchInclude, // = true, + double epsilon = Math::LengthEps*c3d::METRIC_DELTA, + bool allowInaccuracy = true ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки пересечения двух кривых. + \en Calculate intersection points of two curves. \~ + \details \ru Найти параметры точек пересечения двух произвольных кривых. \n + Общий метод вызывается, если нет частной функции пересечения. \n + \en Calculate the parameters of intersection points of two arbitrary curves. \n + The general method is used if there is no special function for intersection. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] result1 - \ru Параметры пересечений первой кривой. + \en The parameters of intersections for the first curve. \~ + \param[out] result2 - \ru Параметры пересечений второй кривой. + \en The parameters of intersections for the second curve. \~ + \param[in] xEpsilon - \ru Точность по x. + \en Tolerance in x direction. \~ + \param[in] yEpsilon - \ru Точность по y. + \en Tolerance in y direction. \~ + \param[in] touchInclude - \ru Считать касания пересечениями. + \en Consider tangencies as intersections. \~ + \param[in] allowInaccuracy - \ru Разрешить нахождение решения с меньшей точностью при невозможности удовлетворить указанной. + \en Allow to find a solution with less precision when we can't get a solution with given precision. \~ + \return \ru Количество найденных пересечений. + \en The number of intersections. \~ + \warning \ru Применяется для трехмерных построений, аналог IntersectTwoCurves. + \en Used for three-dimensional constructions, the analogue of IntersectTwoCurves. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (ptrdiff_t) CurveCurveIntersection( const MbCurve & curve1, + const MbCurve & curve2, + SArray & result1, + SArray & result2, + double xEpsilon, + double yEpsilon, + bool touchInclude, + bool allowInaccuracy = true ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки самопересечения кривой. + \en Calculate the points of curve self-intersection. \~ + \details \ru Найти параметры точек самопересечения кривой с заданной точностью. \n + \en Calculate the self-intersection points parameters with the given tolerance. \n \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] xEpsilon - \ru Точность по x. + \en Tolerance in x direction. \~ + \param[in] yEpsilon - \ru Точность по y. + \en Tolerance in y direction. \~ + \param[out] result1 - \ru Множество параметров самопересечения. + \en The self-intersection parameters array. \~ + \param[out] result2 - \ru Множество параметров самопересечения. + \en The self-intersection parameters array. \~ + \param[in] version - \ru Версия операции. + \en The version of the operation. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (void) CurveSelfIntersect( const MbCurve & curve, + double xEpsilon, + double yEpsilon, + SArray & result1, + SArray & result2, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Удалить точки касания. + \en Remove touch points. \~ + \details \ru Удалить все точки касания кривых вне зависимости от положения параметра на кривой + (внутри области определения или на границах кривой). + \en Remove all curves touch points regardless the position on the curve + (in the domain or on the borders). \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[in, out] result - \ru Множество точек пересечения. + \en The array of intersection points. \~ + \param[in] eps - \ru Погрешность для функции проверки параллельности касательных RoundColinear. + \en Accuracy for the function RoundColinear of testing the parallelism of tangents. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (void) RemoveAllTouchParams( const MbCurve & curve1, + const MbCurve & curve2, + SArray & result, + double eps = PARAM_NEAR ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки пересечения двух кривых. + \en Calculate intersection points of two curves. \~ + \details \ru Найти параметры точек пересечения двух произвольных кривых. \n + \en Calculate the parameters of intersection points of two arbitrary curves. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] result1 - \ru Параметры точек пересечения для первой кривой. + \en The intersection points parameters for the first curve. \~ + \param[out] result2 - \ru Параметры точек пересечения для второй кривой. + \en The intersection points parameters for the second curve. \~ + \param[in] mEps - \ru Возможная максимальная погрешность найденных пересечений. + \en The intersection tolerance. \~ + \return \ru Количество найденных пересечений. + \en The number of intersections. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (ptrdiff_t) CurveCurveIntersection( const MbCurve3D & curve1, + const MbCurve3D & curve2, + SArray & result1, + SArray & result2, + double mEps, // = Math::metricRegion ); + VERSION version ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить кривую на самопересечение. + \en Determine if the curve has self-intersections. \~ + \details \ru Проверить заданную кривую на самопересечение. \n + \en Determine if the given curve has self-intersections. \n \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] mEps - \ru Возможная максимальная погрешность найденных самопересечений. + \en The tolerance of self-intersections. \~ + \return \ru Возвращает true, если кривая самопересекается. + \en Returns true if the curve has self-intersections. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (bool) IsSelfIntersect( const MbCurve3D & curve, double mEps = Math::metricRegion ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Убрать касательные точки пересечения. + \en Remove the tangent intersection points. \~ + \details \ru Убрать параметры касательных точек пересечения внутри областей определения кривых. \n + \en Remove the tangent intersection points parameters inside the domains of curves. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] result1 - \ru Параметры точек пересечения для первой кривой. + \en The intersection points parameters for the first curve. \~ + \param[out] result2 - \ru Параметры точек пересечения для второй кривой. + \en The intersection points parameters for the second curve. \~ + \param[in] mEps - \ru Возможная максимальная погрешность найденных пересечений. + \en The intersection tolerance. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (void) FilterTouchParams( const MbCurve3D & curve1, + const MbCurve3D & curve2, + SArray & result1, + SArray & result2, + double mEps = Math::metricRegion ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки скрещения двух кривых. + \en Calculate the points of two curves crossing. \~ + \details \ru Найти параметры точек скрещения двух кривых. \n + \en Calculate parameters of the points of two curves crossing. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] result1 - \ru Параметры точек скрещения для первой кривой. + \en Parameters of the points of crossing for the first curve. \~ + \param[out] result2 - \ru Параметры точек скрещения для второй кривой. + \en Parameters of the points of crossing for the second curve. \~ + \return \ru Количество найденных скрещений. + \en The points of crossing number. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (ptrdiff_t) CurveCurveCrossing( const MbCurve3D & curve1, + const MbCurve3D & curve2, + SArray & result1, + SArray & result2, + double epsilon = Math::metricRegion ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти проекцию точки на поверхность относительно внешнего контура поверхности. + \en Find the projection of a point on a surface relative to the outer contour of the surface. \~ + \details \ru Найти проекцию пространственной точки на поверхность в виде двумерной точки на поверхности + относительно внешнего контура поверхности. \n + \en Calculate the projection of a space point on a surface as a two-dimensional point on the surface. + relative to the outer contour of the surface. \n \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] pnt - \ru Пространственная точка. + \en A space point. \~ + \param[in] byOuterRectOnly - \ru Классифицировать проекцию только относительно внешнего габаритного прямоугольника. + \en Whether to classify the projection relative to the outer bounding box only. \~ + \param[out] result - \ru Двумерная параметрическая точка на поверхности. + \en A two-dimensional parametric point on the surface. \~ + \return \ru Возвращает true, если найдена нормальная проекция точки на поверхность. + \en Returns true if a normal projection of the point on the surface has been calculated. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (bool) PointProjectionRelativeOuterLoop( const MbSurface & surface, + const MbCartPoint3D & pnt, + bool byOuterRectOnly, + MbCartPoint & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Является ли проекция точки точно неоднозначной. + \en Determine whether the point projection is multiple-valued. \~ + \details \ru Является ли проекция точки неоднозначной при проецировании + в области определения поверхности. \n + \en Determine whether the point projection is multiple-valued while projecting + inside the surface domain. \n \~ + \param[in] surface - \ru Поверхность. + \en A surface. \~ + \param[in] result - \ru Пространственная точка. + \en A space point. \~ + \return \ru Возвращает true, если проекция точки является неоднозначной. + \en Returns true if the point projection is multiple-valued \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (bool) IsMultipleProjection( const MbSurface & surface, + const MbCartPoint3D & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти точки касания двух поверхностей. + \en Calculate the touch points of two surfaces. \~ + \details \ru Найти параметры точек касания двух поверхностей. \n + \en Calculate the parameters of touch points of two surfaces. \n \~ + \param[in] surf1 - \ru Первая поверхность. + \en A first surface. \~ + \param[in] ext1 - \ru Искать на продолжении первой поверхности. + \en Use the first surface extension. \~ + \param[in] surf2 - \ru Вторая поверхность. + \en A second surface. \~ + \param[in] ext2 - \ru Искать на продолжении второй поверхности. + \en Use the second surface extension. \~ + \param[in] uv1arr - \ru Параметры точек касания первой поверхности. + \en Parameters of touch points of first surface. \~ + \param[in] uv2arr - \ru Параметры точек касания второй поверхности. + \en Parameters of touch points of second surface. \~ + \return \ru Возвращает true, если найдены точки касания. + \en Returns true if the touch points has be calculate. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC ( bool) TouchIntersectionPoints( const MbSurface & surf1, + bool ext1, + const MbSurface & surf2, + bool ext2, + std::vector & uv1arr, + std::vector & uv2arr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить положение точек относительно оболочки. + \en Determine the position of points relative to the shell. \~ + \details \ru Определить положение точек относительно оболочки. \n + \en Determine the position of points relative to the shell. \n \~ + \param[in] points - \ru Точки. + \en Points. \~ + \param[in] shell - \ru Оболочка. + \en Shell. \~ + \param[out] pLocs - \ru Положение точек относительно оболочки. + \en The position of points relative to the shell. \~ + \return \ru Возвращает false, если хотя бы одно положение точки не определено, иначе true. + \en Returns false if at least one point position is not defined, otherwise true. \~ + \ingroup Point_Modeling +*/ +// --- +MATH_FUNC (bool) PointsRelativeShell( const std::vector & points, + const MbFaceShell & shell, + std::vector & pLocs ); + + +#endif // __ACTION_POINT_H + diff --git a/C3d/Include/action_sheet.h b/C3d/Include/action_sheet.h index 1c59799..8b5ba24 100644 --- a/C3d/Include/action_sheet.h +++ b/C3d/Include/action_sheet.h @@ -876,7 +876,7 @@ MATH_FUNC (MbResultType) CloseCorner( MbSolid & solid, //------------------------------------------------------------------------------ /** \brief \ru Подрезка массива тела solidArray контурами плоских листовых граней тела sheetSolid. \en Cutting the solidArray with contours of plane sheet faces of sheetSolid. \~ - \details \ru Для подрезания используются только грани, компланарые хотя бы одной ЛСК из массива placements. + \details \ru Для подрезания используются только грани, компланарные хотя бы одной ЛСК из массива placements. Контурные тела граней строятся выдавливанием ограничивающих контуров в обе стороны на величину depth.\n \en For cutting are used only those faces whose placements are complanar to the ones from placements array. The faces contours solids is built by extrusion of bounding contours of the faces in both directions on "depth" value.\n \~ @@ -1002,11 +1002,11 @@ MATH_FUNC (MbResultType) Stamp( MbSolid & solid, //------------------------------------------------------------------------------ /** \brief \ru Штамповка телом-инструментом (пуансоном или матрицей). - \en Stamping by tool solid (punch or die). \~ + \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 \~ + Штамповка подрезается границами листовой грани, которую пересекает тело.\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 Флаг удаления оболочки исходного тела. @@ -1032,16 +1032,16 @@ MATH_FUNC (MbResultType) Stamp( MbSolid & solid, \ingroup Sheet_Metal_Modeling */ // --- -MATH_FUNC( MbResultType ) StampBySolid( MbSolid & solid, - MbeCopyMode sameShell, - const MbFace & targetFace, - MbSolid & toolSolid, - MbeCopyMode sameShellTool, - bool punch, - const RPArray & openingFaces, - const MbUserStampingValues & params, - const MbSNameMaker & names, - MbSolid *& result ); +MATH_FUNC( MbResultType ) StampWithToolSolid( MbSolid & solid, + MbeCopyMode sameShell, + const MbFace & targetFace, + MbSolid & toolSolid, + MbeCopyMode sameShellTool, + bool punch, + const RPArray & pierceFaces, + const MbToolStampingValues & params, + const MbSNameMaker & nameMaker, + MbSolid *& result ); //------------------------------------------------------------------------------ @@ -1892,16 +1892,24 @@ MATH_FUNC (MbResultType) SplitContourIntoSegments( const MbCurve & curve, \en Split a part of a contours (an arc) into segments. \~ \details \ru Аппроксимировать участки контуров (дуги) ломаной.\n \en Split a part of a contours (an arc) into segments.\n \~ - \param[in] contour1 - \ru Первый контур. - \en First contour.\~ - \param[in] breaks1 - \ru Массив параметров разбиения первого контура. - \en Parameters of a partition of the first contour. \~ - \param[in] contour2 - \ru Второй контур. - \en Second contour.\~ - \param[in] breaks2 - \ru Массив параметров разбиения второго контура. - \en Parameters of a partition of the second contour. \~ - \param[in] segmNumber - \ru Количество сегментов аппроксимации. - \en Number of segments after splitting.\~ + \param[in,out] contour1 - \ru Первый контур. + \en First contour.\~ + \param[in,out] breaks1 - \ru Массив параметров разбиения первого контура. + \en Parameters of a partition of the first contour. \~ + \param[in,out] contour2 - \ru Второй контур. + \en Second contour.\~ + \param[in,out] breaks2 - \ru Массив параметров разбиения второго контура. + \en Parameters of a partition of the second contour. \~ + \param[in,out] names - \ru Именователь. + \en Name maker. + \param[in] segmNumbers1 - \ru Количество сегментов аппроксимации для каждого сегмента обечайки после применения разбиения по breaks1. + \en Number of the linear segments for each segment of the lofted bend after splitting by breaks1. + \param[in] segmNumbers2 - \ru Количество сегментов аппроксимации для каждого сегмента обечайки после применения разбиения по breaks2. + \en Number of the linear segments for each segment of the lofted bend after splitting by breaks2. + \param[in] defSegmNumb - \ru Количество сегментов аппроксимации, если не задано в segmNumbers1 и segmNumbers2. + \en Number of segments after splitting, if not defined in segmNumbers1 и segmNumbers2.\~ + \param[in] gapValue - \ru Ширина зазора. + \en The gap width. \result \ru - Код результата операции. \en - The operation result code. \~ \ingroup Sheet_Metal_Modeling @@ -2347,6 +2355,42 @@ MATH_FUNC (MbResultType) RemoveOperationResult( MbSolid & solid, MbSolid *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Преобразовать тело в листовой металл. + \en Construct sheet metal solid based on an arbitary solid. \~ + \details \ru Операция строит листовое тело на базе произвольного тела.\n + \en The operation builds a sheet metal solid based on an arbitrary solid.\n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Флаг удаления оболочки исходного тела. + \en Whether to delete the shell of the source solid. \~ + \param[in] initFace - \ru Исходная грань для построения листового тела. + \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] parameters - \ru Параметры операции. + \en Operation parameters. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующее тело. + \en The resultant solid. \~ + \result \ru - Код результата операции. + \en - The operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Sheet_Metal_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ConvertSolidToSheetMetal( MbSolid & solid, + const MbeCopyMode sameShell, + const MbFace & initFace, + bool sence, + const MbSolidToSheetMetalValues & parameters, + MbSNameMaker & nameMaker, + MbSolid *& result ); + + #endif // __ACTION_SHEET_H diff --git a/C3d/Include/action_shell.h b/C3d/Include/action_shell.h index 6633933..9c6487a 100644 --- a/C3d/Include/action_shell.h +++ b/C3d/Include/action_shell.h @@ -1,842 +1,906 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения незамкнутых тел. - \en Functions for open solids construction. \~ - \details \ru Геометрическое ядро C3D поддерживает поверхностное моделирование. - Результатом поверхностного моделирования являются элементы геометрической модели, - которые будем называть незамкнутыми телами. Незамкнутые тела характерны тем, - что они описывают не всю поверхность моделируемого объекта, а только часть её. - Часто незамкнутое тело состоит из одной грани. В незамкнутом теле всегда присутствуют - краевые рёбра. Незамкнутое тело описывает множество точек, принадлежащих только граням - этого тела, тогда как замкнутое тело описывает множество точек, располагающихся - на поверхности моделируемого объекта и внутри него. - \en The geometric kernel C3D supports the surface modeling. - The result of surface modeling are elements of geometric model - which are called open solids here. Open solids - describe not the whole surface of an object of modeling but only a part of it. - An open solid often consists of one face. An open solid always contains - boundary edges. An open solid describes a point set that belong to faces of the solid only, - whereas a closed solid describes a point set - on the surface of the modeled object and inside it. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_SHELL_H -#define __ACTION_SHELL_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbPatchCurve; -class IProgressIndicator; - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить заплатку. - \en Create a patch. \~ - \details \ru Построить заплатку по выбранным ребрам. \n - \en Create a patch from the specified edges. \n \~ - \param[in] initEdges - \ru Набор ребер. - \en A set of edges. \~ - \param[in] p - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] n - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная заплатка. - \en The required patch. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) PatchShell( const RPArray & initEdges, - const PatchValues & p, - const MbSNameMaker & n, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить заплатку. - \en Create a patch. \~ - \details \ru Построить заплатку по выбранным кривым. \n - \en Create a patch from the specified curves. \n \~ - \param[in] initCurves - \ru Набор кривых. - \en A set of curves. \~ - \param[in] p - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] n - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная заплатка. - \en The required patch. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) PatchShell( const RPArray & initCurves, - const PatchValues & p, - const MbSNameMaker & n, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить незамкнутое тело по множеству групп точек. - \en Create an open solid given a set of point groups. \~ - \details \ru Построить незамкнутое тело по сечениям, образованным сплайнами, построенными по группе контрольных точек. \n - \en Create an open lofted solid whose profiles are defined by splines created from the specified groups of points. \n \~ - \param[in] points - \ru Набор точек. - \en A point set. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] name - \ru Идентификатор. - \en An identifier. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedShell( const RPArray< SArray > & points, - const MbSNameMaker & names, - SimpleName name, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить незамкнутое тело по множеству кривых. - \en Create an open solid from a set of curves. \~ - \details \ru Построить незамкнутое тело по сечениям, образованным кривыми. \n - \en Create an open lofted solids whose profiles are defined by the curves. \n \~ - \param[in] curves - \ru Набор кривых. - \en A set of curves. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] name - \ru Идентификатор. - \en An identifier. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedShell( const RPArray & curves, - const MbSNameMaker & names, - SimpleName name, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить незамкнутое эквидистантное тело. - \en Create an open offset solid. \~ - \details \ru Построить незамкнутое эквидистантное тело на базе указанных в initFaces граней. \n - \en Create an open offset solid on the basis of the faces 'initFaces'. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] initFaces - \ru Грани исходного тела для построения. - \en Faces of the initial solid for construction. \~ - \param[in] checkFacesConnection - \ru Необходимость проверки связности выбранных граней. - \en Whether to check connectivity of the specified faces. \~ - \param[in] p - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. - \en Copy attributes of initial faces to offset faces. \~ - \param[out] result - \ru Эквидистантная оболочка. - \en The offset shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetShell( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & initFaces, - bool checkFacesConnection, - SweptValues & p, - const MbSNameMaker & operNames, - bool copyFaceAttrs, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить незамкнутое тело по множеству точек. - \en Create an open solid from a point set. \~ - \details \ru Построить незамкнутое тело по множеству точек, заданных в параметрах построения. \n - \en Create an open solid from a point set specified in parameters. \n \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] isPhantom - \ru Режим создания фантома. - \en Create in the phantom mode. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \param[in,out] progBar - \ru Индикатор прогресса выполнения операции. - \en A progress indicator of the operation. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsSurfacesShell( NurbsSurfaceValues & params, - const MbSNameMaker & operNames, - bool isPhantom, - MbSolid *& result, - IProgressIndicator * progBar ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить незамкнутое тело по сети кривых. - \en Create an open solid from a set of curves. \~ - \details \ru Построить незамкнутое тело по сети кривых, заданных в параметрах построения. \n - \en Create an open solid from a set of curves specified in the parameters. \n \~ - \param[in] pars - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] isPhantom - \ru Режим создания фантома. - \en Create in the phantom mode. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) MeshShell( MeshSurfaceValues & pars, - const MbSNameMaker & operNames, - bool isPhantom, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Усечь (обрезать) незамкнутое тело. - \en Truncate an open solid. \~ - \details \ru Выполнить построение незамкнутого тела путём усечения исходного тела. \n - \en Create an open solid by truncation the initial solid. \n \~ - \param[in] initSolid - \ru Исходная оболочка. - \en The initial shell. \~ - \param[in] selIndices - \ru Номера выбранных граней (если массив пуст, то вся оболочка). - \en The numbers of selected faces (if the array is empty, the whole shell is selected). \~ - \param[in] initCopyMode - \ru Режим копирования исходных оболочек. - \en Whether to copy the initial shells. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] truncatingItems - \ru Усекающие объекты. - \en Truncating objects. \~ - \param[in] truncatingOrients - \ru Ориентация усекающих объектов. - \en The truncating objects orientation. \~ - \param[in] truncatingSplitMode - \ru Кривые используются как линии разъема. - \en The curves are used as parting lines. \~ - \param[in] truncatingCopyMode - \ru Режим копирования усекающих оболочек. - \en Whether to copy the truncating shells. \~ - \param[in] mergeFlags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] result - \ru Усеченная оболочка. - \en The truncated shell. \~ - \param[out] resultPlace - \ru Фантомное направление усечения. - \en A phantom direction of truncation. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) TruncateShell( MbSolid & initSolid, - SArray & selIndices, - MbeCopyMode initCopyMode, - const MbSNameMaker & operNames, - RPArray & truncatingItems, - SArray & truncatingOrients, - bool truncatingSplitMode, - MbeCopyMode truncatingCopyMode, - const MbMergingFlags & mergeFlags, - MbSolid *& result, - MbPlacement3D *& resultPlace ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить линейчатое незамкнутое тело. - \en Create an open ruled solid. \~ - \details \ru Построить линейчатое незамкнутое тело по двум кривым, заданным в параметрах. \n - \en Create an open ruled solid from two curves specified in parameters. \n \~ - \param[in] pars - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] isPhantom - \ru Режим создания фантома. - \en Create in the phantom mode. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RuledShell( RuledSurfaceValues & pars, - const MbSNameMaker & operNames, - bool isPhantom, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить кривую для построения линейчатого тела. - \en Check the curve for a ruled solid creation. \~ - \details \ru Проверить вторую кривую на согласованность с первой кривой для построения - линейчатого незамкнутого тела и выполнить необходимую модификацию второй кривой. \n - \en Check the second curve for consistency with the first curve for creation - of the open ruled solid and make the necessary modification of the second curve. \n \~ - \param[in] curve0 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve1 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] isInverted1 - \ru Была ли вторая кривая инвертирована. - \en Whether the second curve was inverted. \~ - \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. - \en Whether the beginning of the first curve was shifted. \~ - \param[in] version - \ru Версия операции. - \en The version of the operation. \~ - \warning \ru Вспомогательная функция операции RuledShell. - \en An auxiliary function of operation 'RuledShell'. \~ - \ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (void) CheckRuledCurve( const MbCurve3D & curve0, - const MbCurve3D & curve1, - bool & isInverted1, - bool & isShifted1, - VERSION version ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры кривой для построения линейчатого тела. - \en Check the curve parameters for creation of a ruled solid. \~ - \details \ru Проверить параметры кривой и выполнить нормализацию параметров замкнутой кривой. \n - \en Check the curve parameters and perform the normalization of a closed curve parameters. \n \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in,out] params - \ru Множество параметров кривой. - \en An array of the curve parameters. \~ - \param[in] isAscending - \ru Будет ли порядок параметров возрастающим. - \en Whether the parameters are specified in the ascending order. \~ - \return \ru Возвращает true, если удалось нормализовать массив параметров. - \en Returns true if the parameter array has been successfully normalized. \~ - \warning \ru Вспомогательная функция операции RuledShell. - \en An auxiliary function of operation 'RuledShell'. \~ - \ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (bool) CheckRuledParams( const MbCurve3D & curve, - SArray & params, - bool isAscending ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить продолжение незамкнутого тела выдавливанием. - \en Create an extension of an open solid by extrusion. \~ - \details \ru Построить продолжение незамкнутого тела путём выдавливания указанных краевых рёбер заданной грани тела. \n - \en Create an extension of an open solid by extrusion of specified boundary edges of the given face of the solid. \n \~ - \param[in] solid - \ru Исходная оболочка. - \en The initial shell. \~ - \param[in] sameShell - \ru Режим копирования оболочки. - \en Whether to copy the shell. \~ - \param[in] face - \ru Продляемая грань в исходной оболочке. - \en A face of the initial shell to be extended. \~ - \param[in] edges - \ru Множество ребер продляемой грани, через которые выполняется продление. - \en An array of edges through which to extend the face. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtensionShell( MbSolid & solid, - MbeCopyMode sameShell, - MbFace & face, - const RPArray & edges, - const ExtensionValues & params, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить тело соединения по двум кривым. - \en Create a joint solid from two curves. \~ - \details \ru Построить незамкнутое тело соединения по двум кривым на поверхности. \n - \en Create an open joint solid from two curves on a surface. \n \~ - \param[in] curve1 - \ru Первая поверхностная кривая. - \en The first curve on a surface. \~ - \param[in] curve2 - \ru Вторая поверхностная кривая. - \en The second curve on a surface. \~ - \param[in] parameters - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (MbResultType) JoinShell( MbSurfaceCurve & curve1, - MbSurfaceCurve & curve2, - JoinSurfaceValues & parameters, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить тело соединения по двум множествам рёбер. - \en Create a joint solid from two sets of edges. \~ - \details \ru Построить незамкнутое тело соединения по двум множествам ребер. \n - \en Create an open joint solid from two sets of edges. \n \~ - \param[in] edges1 - \ru Первая группа ребер. - \en The first group of edges. \~ - \param[in] orients1 - \ru Ориентации ребер в первой группе. - \en The edges senses in the first group. \~ - \param[in] edges2 - \ru Вторая группа ребер. - \en The second group of edges. \~ - \param[in] orients2 - \ru Ориентация ребер во второй группе. - \en The edges senses in the second group. \~ - \param[in] matr1 - \ru Матрица преобразования первой группы ребер в единую систему координат. - \en The matrix of transformation of the first group of edges to the common coordinate system. \~ - \param[in] matr2 - \ru Матрица преобразования второй группы ребер в единую систему координат. - \en The matrix of transformation of the second group of edges to the common coordinate system. \~ - \param[in] parameters - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \param[in] isPhantom - \ru Режим фантома операции. - \en The operation phantom mode. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (MbResultType) JoinShell( const RPArray & edges1, - const SArray & orients1, - const RPArray & edges2, - const SArray & orients2, - const MbMatrix3D & matr1, - const MbMatrix3D & matr2, - JoinSurfaceValues & parameters, - const MbSNameMaker & operNames, - MbSolid *& result, - bool isPhantom = false ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разделить оболочку на части по заданному набору ребер. - \en Divide a shell into parts using a given set of edges. \~ - \details \ru Разделить оболочку на части по заданному набору ребер. \n - \en Divide shell into parts using a given set of edges. \n \~ - \param[in] solid - \ru Оболочка. - \en A shell. \~ - \param[in] sameShell - \ru Режим копирования оболочки. - \en Whether to copy the shell. \~ - \param[in] edges - \ru Набор ребер. - \en Set of edges. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ -\ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (MbResultType) DivideShell( MbSolid & solid, - MbeCopyMode sameShell, - const RPArray & edges, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить кривую для построения тела соединения. - \en Check a curve for creation a joint solid. \~ - \details \ru Проверить вторую кривую на согласованность с первой кривой для построения - незамкнутого тела соединения и выполнить необходимую модификацию второй кривой. \n - \en Check the second curve for consistency with the first curve for creation - of the open joint solid and make the necessary modification of the second curve. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] isInverted1 - \ru Была ли вторая кривая инвертирована. - \en Whether the second curve was inverted. \~ - \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. - \en Whether the beginning of the first curve was shifted. \~ - \param[in] version - \ru Версия операции. - \en The version of the operation. \~ - \warning \ru Вспомогательная функция операции JoinShell. - \en An auxiliary function of operation JoinShell. \~ - \ingroup Shell_Modeling -*/ -//--- -MATH_FUNC (void) CheckJoinedCurve( const MbCurve3D & curve1, - const MbCurve3D & curve2, - bool & isInverted1, - bool & isShifted1, - VERSION version ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры кривой для построения тела соединения. - \en Check the curve parameters for creation of a joint solid. \~ - \details \ru Проверить параметры кривой и нормализовать параметры замкнутой кривой. \n - \en Check the curve parameters and normalize a closed curve parameters. \n \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in,out] params - \ru Множество параметров кривой. - \en An array of the curve parameters. \~ - \param[in] isAscending - \ru Будет ли порядок параметров возрастающим. - \en Whether the parameters are specified in the ascending order. \~ - \return \ru Возвращает true, если удалось нормализовать массив параметров. - \en Returns true if the parameter array has been successfully normalized. \~ - \warning \ru Вспомогательная функция операции JoinShell. - \en An auxiliary function of operation JoinShell. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (bool) CheckJoinedParams( const MbCurve3D & curve, - SArray & params, - bool isAscending ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить кривую по множеству рёбер. - \en Create a curve from a set of edges. \~ - \details \ru Создать кривую для поверхности соединения по списку ребер. \n - \en Create a curve for a surface of the joint from a list of edges. \n \~ - \param[in] edges - \ru Набор ребер. - \en A set of edges. \~ - \param[in] orients - \ru Ориентации ребер. - \en Edges senses. \~ - \param[in] matr - \ru Матрица преобразования ребер. - \en Edges transformation matrix. \~ - \param[out] res - \ru Результат операции. - \en The operation result. \~ - \return \ru Возвращает указатель на кривую, если ее получилось создать, - иначе возвращает ноль. - \en Returns a pointer to the curve if it has been successfully created, - otherwise it returns null. \~ - \warning \ru Вспомогательная функция операции JoinShell. - \en An auxiliary function of operation JoinShell. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbCurve3D *) CreateJoinedCurve( const RPArray & edges, - const SArray & orients, - const MbMatrix3D & matr, - MbResultType & res ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить тело сопряжения несвязанных граней. - \en Create a solid of two non-connected faces. \~ - \details \ru Построить незамкнутое тело, состоящее из грани скругления между двумя несвязанными гранями. \n - \en Create an open solid that consists of a fillet face between two non-connected faces. \n \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] face1 - \ru Сопрягаемая грань первого тела. - \en The first solid face to fillet. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] face2 - \ru Сопрягаемая грань второго тела. - \en The second solid face to fillet. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FacesFillet( const MbSolid & solid1, - const MbFace & face1, - const MbSolid & solid2, - const MbFace & face2, - const SmoothValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить тело на базе элементарной поверхности. - \en Create a solid given an elementary surface. \~ - \details \ru Построить тело, состоящее из одной грани, на базе исходной элементарной поверхности. \n - \en Create a solid which consists of a face with the specified underlying elementary surface. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка. - \en The resultant shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ElementaryShell( const MbSurface & surface, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить тело на базе поверхности. - \en Create a solid given a surface. \~ - \details \ru Построить тело, состоящее из одной грани, на базе исходной поверхности. - Поверхность должна быть без самопересечений, с корректной ориентацией - ограничивающих кривых в случае поверхности MbCurveBoundedSurface. \n - \en Create a solid which consists of a face with the specified underlying surface. - The surface should have no self-intersections, - the bounding curves should be correctly oriented in case of surface MbCurveBoundedSurface. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка. - \en The resultant shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SurfaceShell( const MbSurface & surface, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \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\~ - \param[in] sameShell - \ru Способ передачи данных при копировании оболочек. - \en Methods of transferring data while copying shells \~ - \param[in] eye - \ru Направление взгляда. - \en Eye's direction. \~ - \param[out] outlineCurves - \ru Кривые, входящие в силуэтный контур. - - \en Curves of the silhouette contour. \~ - \param[out] result - \ru Тела, полученные в результате применения операции. - - \en The resultant solids.\~ - \return \ru Возвращает код результата операции.\~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CutShellSilhouetteContour( MbSolid & solid, - MbeCopyMode sameShell, - const MbVector3D & eye, - const VERSION version, - RPArray & outlineCurves, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Сшить грани нескольких тел в одно тело. - \en Stitch faces of several solids into single solid. \~ - \details \ru Сшить стыкующиеся друг с другом грани нескольких тел в одно тело. Ориентация граней может быть изменена. \n - \en Stitch faces of several solids with coincident edges into single solid. The faces orientation can be changed. \n \~ - \param[in] initialSolids - \ru Множество тел для сшивки. - \en An array of solids for stitching. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] formSolidBody - \ru Флаг формирования твердого тела из результирующей оболочки. - \en Whether to form a solid solid from the resultant shell. \~ - \param[in] stitchPrecision - \ru Точность сшивки. - \en Stitching accuracy. \~ - \param[out] resultSolid - \ru Результирующая оболочка или тело (в зависимости от флага). - \en The resultant shell or solid (depends on the flag). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbeStitchResType) StitchToOneSheetSolid( const RPArray & initialSolids, - const MbSNameMaker & operNames, - bool formSolidBody, - double stitchPrecision, - MbSolid *& resultSolid ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определение оси токарного сечения и построение кривых сечения для тела. - \en Search for lathe axis and construction of lathe elements for the solid. \~ - \details \ru Функция выполняет поиск токарной оси граней вращения и строит токарное сечение в некоторой плоскости. \n - \en The function searches for lathe axis of rotation faces and builds the curves of lathe-section in a plane. \n \~ - \param[in] solid - \ru Тело. \en Solid. \~ - \param[in] axis - \ru Ось токарного сечения может быть нуль). \en Lathe axis, may be null. \~ - \param[in] angle - \ru Угол, управляющий построением перпендикулярных оси сечения отрезками, рекомендуется M_PI_4-M_PI. \en The angle, managing the construction of segments which perpendicular to the axis, recomended M_PI_4-M_PI. \~ - \param[out] position - \ru Плоскость, в плоскости XY которой лежат кривые сечения, а ось X является осью токарного сечения. \en Plane position of section, axis X is a axis of section. \~ - \param[out] curves - \ru Кривые токарного сечения располагаются в плоскости XY position. \en The curves of section located on plane XY of position. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LatheCurves( const MbSolid & solid, - const MbAxis3D * axis, - double angle, - MbPlacement3D & position, - RPArray & curves ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построение следа кривой при её вращении вокруг оси токарного сечения. - \en Building of curves for lathe section for given curve. \~ - \details \ru Функция выполняет построение следа ребра в плоскости XY локальной системы координат при его вращении вокруг оси X. \n - \en The function builds the generatrix track in the XY plane of the local coordinate system as it rotates around the axis X. \n \~ - \param[in] generatrix - \ru Кривая. \en Curve \~ - \param[in] position - \ru Плоскость, ось X которой является осью токарного сечения. \en Plane position of section, axis X is a axis of section. \~ - \param[out] curves - \ru Контейр кривых, в который будет добавлен след в плоскости XY position от вращения кривой generatrix вокруг оси X. \en The curve on plane XY of position will be added to contaner curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LatheCurve( const MbCurve3D & generatrix, - const MbPlacement3D & position, - RPArray & curves ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить срединную оболочку по граням тела, основанным на - эквидистантных поверхностях. - \en Create a median shell by solid faces, based on equidistant - surfaces. \~ - \details \ru Построить срединную оболочку по парам граней тела, основанным на - эквидистантных поверхностях. Пары граней либо выбираются пользователем, - либо находятся автоматически по заданному расстоянию между гранями. - Грани должны принадлежать одному и тому же телу.\n - \en Construct a median shell between pair of faces, based on equidistant - surfaces. Pair of faces are selected by user or are found by given distance - between faces. The faces must belong to the same body. \n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] faceIndexes - \ru Выбранные пары граней. - \en Selected face pairs. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующая оболочка. - \en The required shell. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC( MbResultType ) MedianShell( MbSolid & solid, - MbeCopyMode sameShell, - const c3d::IndicesPairsVector & faceIndexes, - const MedianShellValues & params, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построение развёртки грани на плоскость. - \en Construction of a face sweep on a plane. \~ - \details \ru Построение развёртки грани на плоскость.\n - \en Construction of a face sweep on a plane.\n \~ - \param[in] face - \ru Исходная грань. - \en The initial face. \~ - \param[in] values - \ru Параметры построения: локальная система координат развернутой поверхности грани, данные для вычисления шага при триангуляции, коэффициент Пуассона материала грани. - \en The parameters: Local coordinate system for result surface, Data for step calculation during triangulation, the Poisson's ratio of face material. \~ - \param[out] result - \ru Тело - плоская развертка исходной грани. - \en The built solid unbend face on plane. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \warning \ru В разработке. - \en Under development. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RectifyFace( const MbFace & face, - const RectifyValues values, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать решетчатую оболочку. - \en Create a lattice shell. \~ - \details \ru Создать решетчатую оболочку по трем управляющим точкам, параметрам решетки и количеству элементов. \n - \en Create a lattice shell on the three control points of the lattice parameters and the number of elements. \~ - \param[in] point0 - \ru Точка, определяющая начало локальной системы координат поверхности. - \en The origin of the surface local coordinate system. \~ - \param[in] point1 - \ru Точка, определяющая направление оси X локальной системы и размер элемента. - \en A point specifying the direction of X-axis of the local system and the size of element. \~ - \param[in] point2 - \ru Точка, определяющая направление оси Y локальной системы. - \en A point specifying the direction of Y-axis of the local system. \~ - \param[in] xRadius - \ru Шаг вдоль первой оси локальной системы координат. - \en The step along the first axis of the local coordinate system. \~ - \param[in] yRadius - \ru Шаг вдоль второй оси локальной системы координат. - \en The step along the second axis of the local coordinate system. \~ - \param[in] zRadius - \ru Шаг вдоль третьей оси локальной системы координат. - \en The step along the third axis of the local coordinate system. \~ - \param[in] xCount - \ru Количество ячеек вдоль первой оси локальной системы координат. - \en The number of cells along a first axis of the local coordinate system. \~ - \param[in] yCount - \ru Количество ячеек вдоль второй оси локальной системы координат. - \en The number of cells along a second axis of the local coordinate system. \~ - \param[in] zCount - \ru Количество ячеек вдоль третьей оси локальной системы координат. - \en The number of cells along a third axis of the local coordinate system. \~ - \param[out] result - \ru Построенная тело. - \en The constructed solid. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OctaLattice( const MbCartPoint3D & point_0, - const MbCartPoint3D & point_1, - const MbCartPoint3D & point_2, - double xRadius, - double yRadius, - double zRadius, - size_t xCount, - size_t yCount, - size_t zCount, - const MbSNameMaker & names, - MbSolid *& result ); - - -#endif // __ACTION_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы построения незамкнутых тел. + \en Functions for open solids construction. \~ + \details \ru Геометрическое ядро C3D поддерживает поверхностное моделирование. + Результатом поверхностного моделирования являются элементы геометрической модели, + которые будем называть незамкнутыми телами. Незамкнутые тела характерны тем, + что они описывают не всю поверхность моделируемого объекта, а только часть её. + Часто незамкнутое тело состоит из одной грани. В незамкнутом теле всегда присутствуют + краевые рёбра. Незамкнутое тело описывает множество точек, принадлежащих только граням + этого тела, тогда как замкнутое тело описывает множество точек, располагающихся + на поверхности моделируемого объекта и внутри него. + \en The geometric kernel C3D supports the surface modeling. + The result of surface modeling are elements of geometric model + which are called open solids here. Open solids + describe not the whole surface of an object of modeling but only a part of it. + An open solid often consists of one face. An open solid always contains + boundary edges. An open solid describes a point set that belong to faces of the solid only, + whereas a closed solid describes a point set + on the surface of the modeled object and inside it. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_SHELL_H +#define __ACTION_SHELL_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbPatchCurve; +class IProgressIndicator; + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить заплатку. + \en Create a patch. \~ + \details \ru Построить заплатку по выбранным ребрам. \n + \en Create a patch from the specified edges. \n \~ + \param[in] initEdges - \ru Набор ребер. + \en A set of edges. \~ + \param[in] p - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] n - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная заплатка. + \en The required patch. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) PatchShell( const RPArray & initEdges, + const PatchValues & p, + const MbSNameMaker & n, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить заплатку. + \en Create a patch. \~ + \details \ru Построить заплатку по выбранным кривым. \n + \en Create a patch from the specified curves. \n \~ + \param[in] initCurves - \ru Набор кривых. + \en A set of curves. \~ + \param[in] p - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] n - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная заплатка. + \en The required patch. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) PatchShell( const RPArray & initCurves, + const PatchValues & p, + const MbSNameMaker & n, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить незамкнутое тело по множеству групп точек. + \en Create an open solid given a set of point groups. \~ + \details \ru Построить незамкнутое тело по сечениям, образованным сплайнами, построенными по группе контрольных точек. \n + \en Create an open lofted solid whose profiles are defined by splines created from the specified groups of points. \n \~ + \param[in] points - \ru Набор точек. + \en A point set. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] name - \ru Идентификатор. + \en An identifier. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedShell( const RPArray< SArray > & points, + const MbSNameMaker & names, + SimpleName name, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить незамкнутое тело по множеству кривых. + \en Create an open solid from a set of curves. \~ + \details \ru Построить незамкнутое тело по сечениям, образованным кривыми. \n + \en Create an open lofted solids whose profiles are defined by the curves. \n \~ + \param[in] curves - \ru Набор кривых. + \en A set of curves. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] name - \ru Идентификатор. + \en An identifier. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedShell( const RPArray & curves, + const MbSNameMaker & names, + SimpleName name, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить незамкнутое эквидистантное тело. + \en Create an open offset solid. \~ + \details \ru Построить незамкнутое эквидистантное тело на базе указанных в initFaces граней. \n + \en Create an open offset solid on the basis of the faces 'initFaces'. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] initFaces - \ru Грани исходного тела для построения. + \en Faces of the initial solid for construction. \~ + \param[in] checkFacesConnection - \ru Необходимость проверки связности выбранных граней. + \en Whether to check connectivity of the specified faces. \~ + \param[in] p - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. + \en Copy attributes of initial faces to offset faces. \~ + \param[out] result - \ru Эквидистантная оболочка. + \en The offset shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetShell( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & initFaces, + bool checkFacesConnection, + SweptValues & p, + const MbSNameMaker & operNames, + bool copyFaceAttrs, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить незамкнутое тело по множеству точек. + \en Create an open solid from a point set. \~ + \details \ru Построить незамкнутое тело по множеству точек, заданных в параметрах построения. \n + \en Create an open solid from a point set specified in parameters. \n \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] isPhantom - \ru Режим создания фантома. + \en Create in the phantom mode. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \param[in,out] progBar - \ru Индикатор прогресса выполнения операции. + \en A progress indicator of the operation. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsSurfacesShell( NurbsSurfaceValues & params, + const MbSNameMaker & operNames, + bool isPhantom, + MbSolid *& result, + IProgressIndicator * progBar ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить незамкнутое тело по сети кривых. + \en Create an open solid from a set of curves. \~ + \details \ru Построить незамкнутое тело по сети кривых, заданных в параметрах построения. \n + \en Create an open solid from a set of curves specified in the parameters. \n \~ + \param[in] pars - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] isPhantom - \ru Режим создания фантома. + \en Create in the phantom mode. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) MeshShell( MeshSurfaceValues & pars, + const MbSNameMaker & operNames, + bool isPhantom, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Усечь (обрезать) незамкнутое тело. + \en Truncate an open solid. \~ + \details \ru Выполнить построение незамкнутого тела путём усечения исходного тела. \n + \en Create an open solid by truncation the initial solid. \n \~ + \param[in] initSolid - \ru Исходная оболочка. + \en The initial shell. \~ + \param[in] selIndices - \ru Номера выбранных граней (если массив пуст, то вся оболочка). + \en The numbers of selected faces (if the array is empty, the whole shell is selected). \~ + \param[in] initCopyMode - \ru Режим копирования исходных оболочек. + \en Whether to copy the initial shells. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] truncatingItems - \ru Усекающие объекты. + \en Truncating objects. \~ + \param[in] truncatingOrients - \ru Ориентация усекающих объектов. + \en The truncating objects orientation. \~ + \param[in] truncatingSplitMode - \ru Кривые используются как линии разъема. + \en The curves are used as parting lines. \~ + \param[in] truncatingCopyMode - \ru Режим копирования усекающих оболочек. + \en Whether to copy the truncating shells. \~ + \param[in] mergeFlags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] result - \ru Усеченная оболочка. + \en The truncated shell. \~ + \param[out] resultPlace - \ru Фантомное направление усечения. + \en A phantom direction of truncation. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) TruncateShell( MbSolid & initSolid, + SArray & selIndices, + MbeCopyMode initCopyMode, + const MbSNameMaker & operNames, + RPArray & truncatingItems, + SArray & truncatingOrients, + bool truncatingSplitMode, + MbeCopyMode truncatingCopyMode, + const MbMergingFlags & mergeFlags, + MbSolid *& result, + MbPlacement3D *& resultPlace ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить линейчатое незамкнутое тело. + \en Create an open ruled solid. \~ + \details \ru Построить линейчатое незамкнутое тело по двум кривым, заданным в параметрах. \n + \en Create an open ruled solid from two curves specified in parameters. \n \~ + \param[in] pars - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] isPhantom - \ru Режим создания фантома. + \en Create in the phantom mode. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RuledShell( RuledSurfaceValues & pars, + const MbSNameMaker & operNames, + bool isPhantom, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить кривую для построения линейчатого тела. + \en Check the curve for a ruled solid creation. \~ + \details \ru Проверить вторую кривую на согласованность с первой кривой для построения + линейчатого незамкнутого тела и выполнить необходимую модификацию второй кривой. \n + \en Check the second curve for consistency with the first curve for creation + of the open ruled solid and make the necessary modification of the second curve. \n \~ + \param[in] curve0 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve1 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] isInverted1 - \ru Была ли вторая кривая инвертирована. + \en Whether the second curve was inverted. \~ + \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. + \en Whether the beginning of the first curve was shifted. \~ + \param[in] version - \ru Версия операции. + \en The version of the operation. \~ + \warning \ru Вспомогательная функция операции RuledShell. + \en An auxiliary function of operation 'RuledShell'. \~ + \ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (void) CheckRuledCurve( const MbCurve3D & curve0, + const MbCurve3D & curve1, + bool & isInverted1, + bool & isShifted1, + VERSION version ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры кривой для построения линейчатого тела. + \en Check the curve parameters for creation of a ruled solid. \~ + \details \ru Проверить параметры кривой и выполнить нормализацию параметров замкнутой кривой. \n + \en Check the curve parameters and perform the normalization of a closed curve parameters. \n \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in,out] params - \ru Множество параметров кривой. + \en An array of the curve parameters. \~ + \param[in] isAscending - \ru Будет ли порядок параметров возрастающим. + \en Whether the parameters are specified in the ascending order. \~ + \return \ru Возвращает true, если удалось нормализовать массив параметров. + \en Returns true if the parameter array has been successfully normalized. \~ + \warning \ru Вспомогательная функция операции RuledShell. + \en An auxiliary function of operation 'RuledShell'. \~ + \ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (bool) CheckRuledParams( const MbCurve3D & curve, + SArray & params, + bool isAscending ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить продолжение незамкнутого тела выдавливанием. + \en Create an extension of an open solid by extrusion. \~ + \details \ru Построить продолжение незамкнутого тела путём продления указанных краевых рёбер тела. \n + Продление может быть выполнено следующими способами. + Может быть удлинена на заданное расстояние указанная грань. + К указанной грани может быть добавлена гладко стыкующаяся с ней грань. + К указанной грани может быть добавлена грань, полученная выдавливанием крайнего ребра в заданном направлении. + \en Create an extension of an open solid by extension of specified boundary edges of the solid. \n \~ + An extension can be performed in the following ways: + The specified faces can be extended on the given distance. + A smoothly connected face can be added to the given face. + A face obtained by extrusion of a boundary edge in the given direction can be added to the specified face. + \param[in] solid - \ru Исходная оболочка. + \en The initial shell. \~ + \param[in] sameShell - \ru Режим копирования оболочки. + \en Whether to copy the shell. \~ + \param[in] face - \ru Одна из продляемых граней в исходной оболочке. + \en One of the face of the initial shell to be extended. \~ + \param[in] edges - \ru Множество краевых ребер, через которые выполняется продление. + \en An array of boundary edges through which to extend the face. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtensionShell( MbSolid & solid, + MbeCopyMode sameShell, + MbFace & face, + const RPArray & edges, + const ExtensionValues & params, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить тело соединения по двум кривым. + \en Create a joint solid from two curves. \~ + \details \ru Построить незамкнутое тело соединения по двум кривым на поверхности. \n + \en Create an open joint solid from two curves on a surface. \n \~ + \param[in] curve1 - \ru Первая поверхностная кривая. + \en The first curve on a surface. \~ + \param[in] curve2 - \ru Вторая поверхностная кривая. + \en The second curve on a surface. \~ + \param[in] parameters - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (MbResultType) JoinShell( MbSurfaceCurve & curve1, + MbSurfaceCurve & curve2, + JoinSurfaceValues & parameters, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить тело соединения по двум множествам рёбер. + \en Create a joint solid from two sets of edges. \~ + \details \ru Построить незамкнутое тело соединения по двум множествам ребер. \n + \en Create an open joint solid from two sets of edges. \n \~ + \param[in] edges1 - \ru Первая группа ребер. + \en The first group of edges. \~ + \param[in] orients1 - \ru Ориентации ребер в первой группе. + \en The edges senses in the first group. \~ + \param[in] edges2 - \ru Вторая группа ребер. + \en The second group of edges. \~ + \param[in] orients2 - \ru Ориентация ребер во второй группе. + \en The edges senses in the second group. \~ + \param[in] matr1 - \ru Матрица преобразования первой группы ребер в единую систему координат. + \en The matrix of transformation of the first group of edges to the common coordinate system. \~ + \param[in] matr2 - \ru Матрица преобразования второй группы ребер в единую систему координат. + \en The matrix of transformation of the second group of edges to the common coordinate system. \~ + \param[in] parameters - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \param[in] isPhantom - \ru Режим фантома операции. + \en The operation phantom mode. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (MbResultType) JoinShell( const RPArray & edges1, + const SArray & orients1, + const RPArray & edges2, + const SArray & orients2, + const MbMatrix3D & matr1, + const MbMatrix3D & matr2, + JoinSurfaceValues & parameters, + const MbSNameMaker & operNames, + MbSolid *& result, + bool isPhantom = false ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разделить оболочку на части по заданному набору ребер. + \en Divide a shell into parts using a given set of edges. \~ + \details \ru Разделить оболочку на части по заданному набору ребер. \n + \en Divide shell into parts using a given set of edges. \n \~ + \param[in] solid - \ru Оболочка. + \en A shell. \~ + \param[in] sameShell - \ru Режим копирования оболочки. + \en Whether to copy the shell. \~ + \param[in] edges - \ru Набор ребер. + \en Set of edges. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ +\ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (MbResultType) DivideShell( MbSolid & solid, + MbeCopyMode sameShell, + const RPArray & edges, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить кривую для построения тела соединения. + \en Check a curve for creation a joint solid. \~ + \details \ru Проверить вторую кривую на согласованность с первой кривой для построения + незамкнутого тела соединения и выполнить необходимую модификацию второй кривой. \n + \en Check the second curve for consistency with the first curve for creation + of the open joint solid and make the necessary modification of the second curve. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] isInverted1 - \ru Была ли вторая кривая инвертирована. + \en Whether the second curve was inverted. \~ + \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. + \en Whether the beginning of the first curve was shifted. \~ + \param[in] version - \ru Версия операции. + \en The version of the operation. \~ + \warning \ru Вспомогательная функция операции JoinShell. + \en An auxiliary function of operation JoinShell. \~ + \ingroup Shell_Modeling +*/ +//--- +MATH_FUNC (void) CheckJoinedCurve( const MbCurve3D & curve1, + const MbCurve3D & curve2, + bool & isInverted1, + bool & isShifted1, + VERSION version ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры кривой для построения тела соединения. + \en Check the curve parameters for creation of a joint solid. \~ + \details \ru Проверить параметры кривой и нормализовать параметры замкнутой кривой. \n + \en Check the curve parameters and normalize a closed curve parameters. \n \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in,out] params - \ru Множество параметров кривой. + \en An array of the curve parameters. \~ + \param[in] isAscending - \ru Будет ли порядок параметров возрастающим. + \en Whether the parameters are specified in the ascending order. \~ + \return \ru Возвращает true, если удалось нормализовать массив параметров. + \en Returns true if the parameter array has been successfully normalized. \~ + \warning \ru Вспомогательная функция операции JoinShell. + \en An auxiliary function of operation JoinShell. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (bool) CheckJoinedParams( const MbCurve3D & curve, + SArray & params, + bool isAscending ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить кривую по множеству рёбер. + \en Create a curve from a set of edges. \~ + \details \ru Создать кривую для поверхности соединения по списку ребер. \n + \en Create a curve for a surface of the joint from a list of edges. \n \~ + \param[in] edges - \ru Набор ребер. + \en A set of edges. \~ + \param[in] orients - \ru Ориентации ребер. + \en Edges senses. \~ + \param[in] matr - \ru Матрица преобразования ребер. + \en Edges transformation matrix. \~ + \param[out] res - \ru Результат операции. + \en The operation result. \~ + \return \ru Возвращает указатель на кривую, если ее получилось создать, + иначе возвращает ноль. + \en Returns a pointer to the curve if it has been successfully created, + otherwise it returns null. \~ + \warning \ru Вспомогательная функция операции JoinShell. + \en An auxiliary function of operation JoinShell. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbCurve3D *) CreateJoinedCurve( const RPArray & edges, + const SArray & orients, + const MbMatrix3D & matr, + MbResultType & res ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить тело сопряжения несвязанных граней. + \en Create a solid of two non-connected faces. \~ + \details \ru Построить незамкнутое тело, состоящее из грани скругления между двумя несвязанными гранями. \n + \en Create an open solid that consists of a fillet face between two non-connected faces. \n \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] face1 - \ru Сопрягаемая грань первого тела. + \en The first solid face to fillet. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] face2 - \ru Сопрягаемая грань второго тела. + \en The second solid face to fillet. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FacesFillet( const MbSolid & solid1, + const MbFace & face1, + const MbSolid & solid2, + const MbFace & face2, + const SmoothValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить тело на базе элементарной поверхности. + \en Create a solid given an elementary surface. \~ + \details \ru Построить тело, состоящее из одной грани, на базе исходной элементарной поверхности. \n + \en Create a solid which consists of a face with the specified underlying elementary surface. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка. + \en The resultant shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ElementaryShell( const MbSurface & surface, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить тело на базе поверхности. + \en Create a solid given a surface. \~ + \details \ru Построить тело, состоящее из одной грани, на базе исходной поверхности. + Поверхность должна быть без самопересечений, с корректной ориентацией + ограничивающих кривых в случае поверхности MbCurveBoundedSurface. \n + \en Create a solid which consists of a face with the specified underlying surface. + The surface should have no self-intersections, + the bounding curves should be correctly oriented in case of surface MbCurveBoundedSurface. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка. + \en The resultant shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SurfaceShell( const MbSurface & surface, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \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\~ + \param[in] sameShell - \ru Способ передачи данных при копировании оболочек. + \en Methods of transferring data while copying shells \~ + \param[in] eye - \ru Направление взгляда. + \en Eye's direction. \~ + \param[in] operNames - \ru Именователь с версией. + \en An object defining the names with the version. \~ + \param[out] outlineCurves - \ru Кривые, входящие в силуэтный контур. + - \en Curves of the silhouette contour. \~ + \param[out] cutSolids - \ru Тела, полученные в результате применения операции. + - \en The resultant solids.\~ + \return \ru Возвращает код результата операции.\~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CutShellSilhouetteContour( MbSolid & solid, + MbeCopyMode sameShell, + const MbVector3D & eye, + const MbSNameMaker & operNames, + c3d::SpaceCurvesSPtrVector & outlineCurves, + RPArray & cutSolids ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Сшить грани нескольких тел в одно тело. + \en Stitch faces of several solids into single solid. \~ + \details \ru Сшить стыкующиеся друг с другом грани нескольких тел в одно тело. Ориентация граней может быть изменена. \n + \en Stitch faces of several solids with coincident edges into single solid. The faces orientation can be changed. \n \~ + \param[in] initialSolids - \ru Множество тел для сшивки. + \en An array of solids for stitching. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] formSolidBody - \ru Флаг формирования твердого тела из результирующей оболочки. + \en Whether to form a solid solid from the resultant shell. \~ + \param[in] stitchPrecision - \ru Точность сшивки. + \en Stitching accuracy. \~ + \param[out] resultSolid - \ru Результирующая оболочка или тело (в зависимости от флага). + \en The resultant shell or solid (depends on the flag). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling + \warning \ru Операция устарела! + \en The operation is deprecated! \~ +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC (MbeStitchResType) StitchToOneSheetSolid( const RPArray & initialSolids, + const MbSNameMaker & operNames, + bool formSolidBody, + double stitchPrecision, + MbSolid *& resultSolid ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Сшить грани нескольких тел в одно тело. + \en Stitch faces of several solids into single solid. \~ + \details \ru Сшить стыкующиеся друг с другом грани нескольких тел в одно тело. Ориентация граней может быть изменена. \n + \en Stitch faces of several solids with coincident edges into single solid. The faces orientation can be changed. \n \~ + \param[in] initialSolids - \ru Множество тел для сшивки. + \en An array of solids for stitching. \~ + \param[in] stitchParams - \ru Параметры сшивки оболочек. + \en Shells stitch parameters. \~ + \param[out] resultSolid - \ru Результирующая оболочка или тело (в зависимости от флага). + \en The resultant shell or solid (depends on the flag). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbeStitchResType) StitchShells( const c3d::SolidsSPtrVector & initialSolids, + const MbShellStitchParams & stitchParams, + MbSolid *& resultSolid ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определение оси токарного сечения и построение кривых сечения для тела. + \en Search for lathe axis and construction of lathe elements for the solid. \~ + \details \ru Функция выполняет поиск токарной оси граней вращения и строит токарное сечение в некоторой плоскости. \n + \en The function searches for lathe axis of rotation faces and builds the curves of lathe-section in a plane. \n \~ + \param[in] solid - \ru Тело. \en Solid. \~ + \param[in] axis - \ru Ось токарного сечения может быть нуль). \en Lathe axis, may be null. \~ + \param[in] angle - \ru Угол, управляющий построением перпендикулярных оси сечения отрезками, рекомендуется M_PI_4-M_PI. \en The angle, managing the construction of segments which perpendicular to the axis, recomended M_PI_4-M_PI. \~ + \param[out] position - \ru Плоскость, в плоскости XY которой лежат кривые сечения, а ось X является осью токарного сечения. \en Plane position of section, axis X is a axis of section. \~ + \param[out] curves - \ru Кривые токарного сечения располагаются в плоскости XY position. \en The curves of section located on plane XY of position. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LatheCurves( const MbSolid & solid, + const MbAxis3D * axis, + double angle, + MbPlacement3D & position, + RPArray & curves ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение следа кривой при её вращении вокруг оси токарного сечения. + \en Building of curves for lathe section for given curve. \~ + \details \ru Функция выполняет построение следа ребра в плоскости XY локальной системы координат при его вращении вокруг оси X. \n + \en The function builds the generatrix track in the XY plane of the local coordinate system as it rotates around the axis X. \n \~ + \param[in] generatrix - \ru Кривая. \en Curve \~ + \param[in] position - \ru Плоскость, ось X которой является осью токарного сечения. \en Plane position of section, axis X is a axis of section. \~ + \param[out] curves - \ru Контейр кривых, в который будет добавлен след в плоскости XY position от вращения кривой generatrix вокруг оси X. \en The curve on plane XY of position will be added to contaner curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LatheCurve( const MbCurve3D & generatrix, + const MbPlacement3D & position, + RPArray & curves ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить срединную оболочку по граням тела, основанным на эквидистантных поверхностях. + \en Create a median shell by solid faces, based on equidistant surfaces. \~ + \details \ru Построить срединную оболочку по парам граней тела, основанным на + эквидистантных поверхностях. Пары граней либо выбираются пользователем, + либо находятся автоматически по заданному расстоянию между гранями. + Грани должны принадлежать одному и тому же телу.\n + \en Construct a median shell between pair of faces, based on equidistant + surfaces. Pair of faces are selected by user or are found by given distance + between faces. The faces must belong to the same body. \n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] faceIndexes - \ru Выбранные пары граней. + \en Selected face pairs. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] medianFaces - \ru Множество граней для создания срединной оболочки. + \en Set of faces for build a median shell. \~ + \param[out] result - \ru Результирующая оболочка. + \en The required shell. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC( MbResultType ) MedianShell( MbSolid & solid, + MbeCopyMode sameShell, + const c3d::IndicesPairsVector & faceIndexes, + const MedianShellValues & params, + const MbSNameMaker & operNames, + MedianShellFaces & medianFaces, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение развёртки грани на плоскость. + \en Construction of a face sweep on a plane. \~ + \details \ru Построение развёртки грани на плоскость.\n + \en Construction of a face sweep on a plane.\n \~ + \param[in] face - \ru Исходная грань. + \en The initial face. \~ + \param[in] values - \ru Параметры построения: локальная система координат развернутой поверхности грани, данные для вычисления шага при триангуляции, коэффициент Пуассона материала грани. + \en The parameters: Local coordinate system for result surface, Data for step calculation during triangulation, the Poisson's ratio of face material. \~ + \param[out] result - \ru Тело - плоская развертка исходной грани. + \en The built solid unbend face on plane. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RectifyFace( const MbFace & face, + const RectifyValues values, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать решетчатую оболочку. + \en Create a lattice shell. \~ + \details \ru Создать решетчатую оболочку по трем управляющим точкам, параметрам решетки и количеству элементов. \n + \en Create a lattice shell on the three control points of the lattice parameters and the number of elements. \~ + \param[in] point0 - \ru Точка, определяющая начало локальной системы координат поверхности. + \en The origin of the surface local coordinate system. \~ + \param[in] point1 - \ru Точка, определяющая направление оси X локальной системы и размер элемента. + \en A point specifying the direction of X-axis of the local system and the size of element. \~ + \param[in] point2 - \ru Точка, определяющая направление оси Y локальной системы. + \en A point specifying the direction of Y-axis of the local system. \~ + \param[in] xRadius - \ru Шаг вдоль первой оси локальной системы координат. + \en The step along the first axis of the local coordinate system. \~ + \param[in] yRadius - \ru Шаг вдоль второй оси локальной системы координат. + \en The step along the second axis of the local coordinate system. \~ + \param[in] zRadius - \ru Шаг вдоль третьей оси локальной системы координат. + \en The step along the third axis of the local coordinate system. \~ + \param[in] xCount - \ru Количество ячеек вдоль первой оси локальной системы координат. + \en The number of cells along a first axis of the local coordinate system. \~ + \param[in] yCount - \ru Количество ячеек вдоль второй оси локальной системы координат. + \en The number of cells along a second axis of the local coordinate system. \~ + \param[in] zCount - \ru Количество ячеек вдоль третьей оси локальной системы координат. + \en The number of cells along a third axis of the local coordinate system. \~ + \param[out] result - \ru Построенное тело. + \en The constructed solid. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OctaLattice( const MbCartPoint3D & point_0, + const MbCartPoint3D & point_1, + const MbCartPoint3D & point_2, + double xRadius, + double yRadius, + double zRadius, + size_t xCount, + size_t yCount, + size_t zCount, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить обологчку на поверхности переменного сечения. + \en Create a shell on swept mutable section surface. \~ + \details \ru Построить грань тела путём движения образующей кривой по направляющей кривой + и выполнить булеву операцию с оболочкой, если последняя задана. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Create a face of shell by moving the generating curve along the spine curve + and perform the Boolean operation with the shell if it is specified. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] solid - \ru Обологчка, к которой дополняется построение. + \en The shell the construction is complemented with respect to. \~ + \param[in] sameShell - \ru Способ копирования граней обологчки. + \en The method of copying faces of shell. \~ + \param[in] data - \ru Данные о поверхности переменного сечения. + \en Data about swept mutable section surface. \~ + \param[in] operNames - \ru Именователь новой грани оболочки. + \en Generating face names. \~ + \param[out] result - \ru Построенная обологчка. + \en The constructed shell. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC( MbResultType ) SectionShell( MbSolid * solid, + MbeCopyMode sameShell, + const MbSectionData & data, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +#endif // __ACTION_SHELL_H diff --git a/C3d/Include/action_solid.h b/C3d/Include/action_solid.h index 4394a2c..b915c26 100644 --- a/C3d/Include/action_solid.h +++ b/C3d/Include/action_solid.h @@ -1,2239 +1,2237 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Функции создания тел, операции с телами. - \en Functions for creation of solids, operations on solids. \~ - \details \ru Процесс построения тел в геометрическом моделировании похож на процесс - изготовления моделируемого объекта. Сначала создаются тела простой формы, а далее - выполняется набор действий, позволяющих из тел простой формы получить более сложные тела. - При необходимости создаются вспомогательные объекты. Редактировать и создавать подобные - тела можно путём изменения параметров с последующим повторением процесса построения тел.\n - Все функции создания тел содержат в качестве входного параметр MbSNameMaker, - обеспечивающий именование граней, рёбер и вершин. - Первым параметром конструктора генератора имён MbSNameMaker служит главное имя операции. - По главному имени можно определить, в какой функции рождена та или иная грань, ребро, вершина. - Главное имя выдаёт метод GetMainName().\n - \en The process of solids creation in geometric modeling is similar to the process - of the modeled object manufacturing. Firstly solids of a simple form are created, and then - a set of operations are performed to obtain a more complex solids from solids of a simple form. - Auxiliary objects are created if necessary. The similar solids can be edited and created - by modifying of the parameters and further repeating the process of the solids creation.\n - All of the function contain input parameter MbSNameMaker, - providing the naming of faces, edges and vertices. - The first parameter to the constructor MbSNameMaker is the main name of the function. - You can determine which function is born one or the other face, edge, vertex by main name. - GetMainName() gives the main name of the function (face.GetMainName(), edge.GetMainName(), vertex.GetMainName()).\~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_SOLID_H -#define __ACTION_SOLID_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbItem; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbPartSolidIndices; -class MATH_CLASS MbSpine; -class MATH_CLASS MbMesh; -class MATH_CLASS MbGrid; -class MATH_CLASS MbCollection; -class MATH_CLASS IProgressIndicator; - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать элементарное тело. - \en Create an elementary solid. \~ - \details \ru Создать одно из элементарных тел по заданным точкам и типу: \n - solidType = et_Sphere - шар (3 точки), \n - solidType = et_Torus - тор (3 точки), \n - solidType = et_Cylinder - цилиндр (3 точки), \n - solidType = et_Cone - конус (3 точки), \n - solidType = et_Block - блок (4 точки), \n - solidType = et_Wedge - клин (4 точки), \n - solidType = et_Prism - призма (количество вершин основания+1 точка), \n - solidType = et_Pyramid - пирамида (количество вершин основания+1 точка), \n - solidType = et_Plate - плита (4 точки), - solidType = et_Icosahedron - икосаэдр (3 точки), \n - solidType = et_Polyhedron - многогранник (3 точки), \n - solidType = et_Tetrapipe - тетра-труба (3 точки), \n - solidType = et_Octapipe - окта-труба (3 точки). \n - \en Create one of elementary solids from the specified points and type: \n - solidType = et_Sphere - a sphere (3 points), \n - solidType = et_Torus - a torus (3 points), \n - solidType = et_Cylinder - a cylinder (3 points), \n - solidType = et_Cone - a cone (3 points), \n - solidType = et_Block - a block (4 points), \n - solidType = et_Wedge - a wedge (4 points), \n - solidType = et_Prism - a prism (points count is equal to the base vertices count + 1), \n - solidType = et_Pyramid - a pyramid (points count is equal to the base vertices count + 1), \n - solidType = et_Plate - a plate (4 points), \n - solidType = et_Icosahedron - an icosahedron (3 points), \n - solidType = et_Polyhedron - a polyhedron (3 points), \n - solidType = et_Tetrapipe - a tetra-pipe (3 points), \n - solidType = et_Octapipe - an octa-pipe (3 points). \n \~ - \param[in] points - \ru Набор точек. \n - points[0] определяет начало локальной системы координат. \n - Для сферы, тора, цилиндра и конуса: \n - points[1] определяет направление оси Z локальной системы. \n - points[2] определяет направление оси X локальной системы. \n - Для блока, клина и плиты: \n - points[1] определяет направление оси X локальной системы. \n - points[2] определяет направление оси Y локальной системы. \n - Кроме того, \n - points[1] определяет высоту цилиндра, высоту конуса, - большой радиус тора, длину блока, длину клина. \n - points[2] определяет радиус цилиндра, угол конуса как угол между векторами v1(points[0],points[1]) и v2(points[0],points[2]), - радиус сферы, малый радиус тора, ширину блока, ширину клина. \n - В случае конуса вектора v1(points[0],points[1]) и v2(points[0],points[2]) не должны быть параллельны или перпендикулярны друг другу. \n - Последняя точка определяет высоту блока, клина, плиты, вершину пирамиды. - \en A point set. \n - points[0] determines a local coordinate system origin. \n - For a sphere, a torus, a cylinder or a cone: \n - points[1] determines the direction of Z-axis of a local coordinate system. \n - points[2] determines the direction of X-axis of a local coordinate system. \n - For a block, a plate or a wedge: \n - points[1] determines the direction of X-axis of a local coordinate system. \n - points[2] determines the direction of Y-axis of a local coordinate system. \n - Also, \n - points[1] determines the height of a cylinder or a cone, - the major radius of a torus, the length of a block or a wedge. \n - points[2] determines the radius of a cylinder, cone angle as angle between vectors v1(points[0],points[1]) and v2(points[0],points[2]), - radius of a sphere, the minor radius of a torus, the width of a block or a wedge. \n - In the case of the cone of the vector v1(points [0], points [1]) and v2(points [0], points [2]) must not be parallel or perpendicular to each other. \n - The last point determines the height of a block, a wedge or a plate, the vertex of a pyramid. \~ - \param[in] solidType - \ru Тип создаваемого тела. - \en The solid type. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ElementarySolid( const SArray & points, - ElementaryShellType solidType, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по поверхности. - \en Create a solid from a surface. \~ - \details \ru Создать тело по элементарной поверхности. \n - Допускается только тип поверхности - цилиндр, конус, сфера, тор. - \en Create a solid from an elementary surface. \n - The only acceptable surface types are cylinder, cone, sphere, torus. \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ElementarySolid( const MbSurface & surface, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело на основе полигональной модели. - \en Create a solid on the basis of a polygonal geometric object. \~ - \details \ru Создать тело #MbSolid на основе полигональной модели #MbMesh. \n - \en Create a solid #MbSolid on the basis of a polygonal geometric object #MbMesh. \n \~ - \param[in] mesh - \ru Полигональная модель. - \en The polygonal geometric object. \~ - \param[in] params - \ru Параметры операции. - \en Operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) MeshSolid( const MbMesh & mesh, - const GridsToShellValues & params, - const MbSNameMaker & names, - MbSolid *& result, - IProgressIndicator * prog = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело на основе триангуляции. - \en Create a solid on the basis of a triangulation. \~ - \details \ru Создать тело #MbSolid на основе триангуляции #MbGrid. \n - \en Create a solid #MbSolid on the basis of a triangulation #MbGrid. \n \~ - \param[in] grid - \ru Полигональная модель. - \en The polygonal geometric object. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, - const MbSNameMaker & names, - MbSolid *& result, - IProgressIndicator * prog = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело на основе коллекции элементов. - \en Create a solid on the basis of elements. \~ - \details \ru Создать тело #MbSolid на основе коллекции элементов #MbCollection. \n - \en Create a solid #MbSolid on the basis of elements #MbCollection. \n \~ - \param[in] grid - \ru Коллекция элементов. - \en The elements collection. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CollectionSolid( const MbCollection & grid, - const MbSNameMaker & names, - MbSolid *& result, - IProgressIndicator * progBar = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело c заданной оболочкой. - \en Create a solid with a given shell. \~ - \details \ru Создать тело без истории построения с заданной оболочкой. \n - \en Create a solid with a given shell without a history. \n \~ - \param[in] shell - \ru Оболочка. - \en A shell. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \return \ru Возвращает тело без истории. - \en Returns a solid without the history. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbSolid *) CreateSolid( MbFaceShell & shell, - const MbSNameMaker & names ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Рассчитать глубину выдавливания или угол вращения. - \en Compute the extrusion depth or the rotation angle. \~ - \details \ru Рассчитать value - глубину выдавливания или угол вращения (0.0 : M_PI2) - для последующего построения тела путем выдавливания или вращения образующей кривой. \n - \en Compute 'value' - the extrusion depth or the rotation angle (0.0 : M_PI2) - for the further construction of a solid by extrusion or revolution of the generating curve. \n \~ - \param[in] sweptData - \ru Данные об образующей. - \en The generating curve data. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] rotation - \ru Вращение или выдавливание. - \en Rotation or extrusion. \~ - \param[in] operationDirection - \ru Вперед\назад. - \en Forward or backward direction. \~ - \param[in] point - \ru Точка, до которой требуется вращать или выдавливать поверхность. - \en The point to rotate or extrude the surface up to. \~ - \param[out] value - \ru Глубина выдавливания или угол вращения. - \en The extrusion depth or the rotation angle. \~ - \return \ru Возвращает true, если расчет выполнен успешно. - \en Returns true if the value has been successfully calculated. \~ - \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. - \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (bool) GetSweptValue( const MbSweptData & sweptData, - const MbAxis3D & axis, - const MbVector3D & direction, - const bool rotation, - const bool operationDirection, - const MbCartPoint3D & point, - double & value ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить начальное приближение для нахождения образа при вращении/выдавливании. - \en Get the initial approximation for image calculation while rotating/extruding. \~ - \details \ru Вычислить положение образа точки образующей кривой на поверхности для последующего - построения тела путем выдавливания или вращения образующей кривой до заданной поверхности. \n - \en Compute the position of a generating curve point image on a surface for further - solid construction by extrusion or revolution of the generating curve up to the specified surface. \n \~ - \param[in] generatrix - \ru Кривая. - \en The curve. \~ - \param[in] surface - \ru Поверхность, до которой строим операцию. - \en The surface to construct up to. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] rotation - \ru Вращение (true) или выдавливание (false) - \en Rotation (true) or extrusion (false) \~ - \param[out] imagePosition - \ru Точка образа на поверхности. - \en The image point on the surface. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. - \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (void) GetSweptImagePosition( const MbCurve3D & generatrix, - const MbSurface & surface, - const MbVector3D & direction, - const MbAxis3D & axis, - const bool rotation, - MbCartPoint & imagePosition, - MbResultType & resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти расстояния/углы от образующей до поверхности при вращении/выдавливании. - \en Calculate the distances/angles from generating curve to the surface while rotating/extruding. \~ - \details \ru Вычислить глубины выдавливания в прямом и обратном направлениях или углы вращения - в прямом и обратном направлениях для последующего построения тела путем выдавливания или вращения - образующей кривой до заданной поверхности, а также и габарит образа кривой. \n - \en Calculate the extrusion depths in forward and backward directions or the rotating angles - in forward and backward directions for further solid construction by extrusion or revolution - of the generating curve up to the specified surface; and also calculate the bounding box of the curve image. \n \~ - \param[in] surface - \ru Поверхность, до которой строим операцию. - \en The surface to construct up to. \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] rotation - \ru Вращение (true) или выдавливание (false). - \en Revolution (true) or extrusion (false). \~ - \param[in] operationDirection - \ru Направление движения: вперед (true) или назад (false). - \en The motion direction: forward (true) or backward (false). \~ - \param[out] imagePosition - \ru Точка на части поверхности, в которой лежит образ. - \en A point on a surface part that contains the image. \~ - \param[out] range - \ru Расстояния до поверхности в обратном и прямом направлениях. - \en The distance to surface in the backward and the forward directions. \~ - \param[out] rectOnSurface - \ru Габарит образа на поверхности. - \en The bounding box of image on the surface. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. - \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (void) GetRangeToSurface( const MbSurface & surface, - const MbCurve3D & curve, - const MbVector3D & direction, - const MbAxis3D & axis, - const bool rotation, - const bool operationDirection, - const MbCartPoint & imagePosition, - double range[2], - MbRect & rectOnSurface, - MbResultType & resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить площадь проекции кривой на виртуальную координатную плоскость. - \en Compute the area of a curve projection onto a virtual coordinate plane. \~ - \details \ru Вычислить площадь проекции кривой на виртуальную координатную плоскость \n - для определения ориентации образующей кривой в оболочке выдавливания и вращения. \n - Параметры direction и axis определяют направление выдавливания и ось вращения, - а параметр rotation определяет тип операции: \n - - выдавливание, вычисляется площадь проекции на плоскость XOY, \n - - вращение, вычисляется площадь "проекции" на "плоскость" ROZ. - Для незамкнутой кривой в расчет добавляется "замыкание отрезком". - \en Compute the area of a curve projection onto a virtual coordinate plane \n - to determine the generating curve orientation in the shell of extrusion and revolution. \n - Parameters 'direction' and 'axis' determine the extrusion direction and the rotation axis, - and parameter 'rotation' determines the operation type: \n - - extrusion, the area of projection onto the plane XOY is computed, \n - - revolution, the area of "projection" to the "plane" ROZ is computed. - For an open curve "enclosure by a segment" is considered. \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] rotation - \ru Вращение (true) или выдавливание (false). - \en Revolution (true) or extrusion (false). \~ - \return \ru Возвращает площадь проекции. - \en Returns the projection area. \~ - \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. - \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (double) AreaSign( const MbCurve3D & curve, - const MbAxis3D & axis, - const MbVector3D & direction, - bool rotation ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить ориентацию секущей грани относительно тела выдавливания/вращения. - \en Determine the orientation of a cutting surface relative to the extrusion/revolution solid. \~ - \details \ru Определить ориентацию секущей поверхности относительно тела, которое будет строиться - путём выдавливания или вращения образующей кривой до заданной поверхности. \n - \en Determine the orientation of a cutting surface relative to the solid which is to be constructed - by extrusion or revolution the generation curve up to the specified surface. \n \~ - \param[in] cuttingSurface - \ru Поверхность для анализа. - \en A surface to analyze. \~ - \param[in] imagePosition - \ru Место образа на поверхности. - \en An image location on the surface. \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in] rotation - \ru Вращение (true) или выдавливание (false). - \en Revolution (true) or extrusion (false). \~ - \param[in] operationDirection - \ru Направление движения: вперед (true) или назад (false). - \en The motion direction: forward (true) or backward (false). \~ - \param[out] relativeSense - \ru Ориентация поверхности по отношению к операции. - \en The surface orientation relative to the operation. \~ - \param[out] resType - \ru Код результата операции. - \en Operation result code. \~ - \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. - \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (void) AnalyzeSurfaceRelationToSweptOperation( const MbSurface & cuttingSurface, - const MbCartPoint & imagePosition, - const MbCurve3D & curve, - const MbVector3D & direction, - const MbAxis3D & axis, - const bool rotation, - bool operationDirection, - bool & relativeSense, - MbResultType& resType ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти сегменты контура на поверхности, соответствующие швам и полюсам. - \en Find contour segments corresponding to the seams and poles. \~ - \details \ru Найти сегменты контура на поверхности, соответствующие швам и полюсам. \n - \en Find contour segments corresponding to the seams and poles. \n \~ - \param[in] surface - \ru Поверхность. - \en Surface. \~ - \param[in] contour - \ru Контур. - \en Contour. \~ - \param[out] seamsAndPoles - \ru Номера сегментов, соответствующих швам и полюсам. - \en Segment numbers corresponding to the seams and poles. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (void) FindPolesAndSeamsInContour( const MbSurface & surface, - const MbContour & contour, - c3d::IndicesVector & seamsAndPoles ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело выдавливания. - \en Create an extrusion solid. \~ - \details \ru Создать тело выдавливания. \n - solid1 и solid2 используются с опцией "До ближайших граней" этих тел. \n - \en Create an extrusion solid. \n - solid1 and solid2 are used with option "Up to the closest faces" of these solids. \n \~ - \param[in] sweptData - \ru Данные об образующей кривой. - \en The generating curve data. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in] solid1 - \ru До ближайших граней этого тела в прямом направлении. - \en Up to the closest faces of this solid in the forward direction. \~ - \param[in] solid2 - \ru До ближайших граней этого тела в обратном направлении. - \en Up to the closest faces of this solid in the backward direction. \~ - \param[in] checkIntersection - \ru Объединять тела solid1 и solid2 с проверкой пересечения. - \en Whether to union the solids solid1 and solid2 with the check for intersections. \~ - \param[in, out] params - \ru Параметры выдавливания. - Возвращают информацию для построения элементов массива операций до поверхности. - \en The extrusion parameters. - Returns the information for construction of the up-to-surface operation array elements. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователи сегментов образующего контура. - \en An objects defining a names of the generating contour segments. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtrusionSolid( const MbSweptData & sweptData, - const MbVector3D & direction, - const MbSolid * solid1, - const MbSolid * solid2, - bool checkIntersection, - const ExtrusionValues & params, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело вращения. - \en Create a solid of revolution. \~ - \details \ru Создать тело вращения по данным об образующей. \n - \en Create a solid of revolution by the generating curve data. \n \~ - \param[in] sweptData - \ru Данные об образующей кривой. - \en The generating curve data. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in, out] params - \ru Параметры вращения. - Возвращают информацию для построения элементов массива операций до поверхности. - \en The revolution parameters. - Returns the information for construction of the up-to-surface operation array elements. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователи сегментов образующего контура. - \en An objects defining a names of the generating contour segments. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RevolutionSolid( const MbSweptData & sweptData, - const MbAxis3D & axis, - const RevolutionValues & params, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кинематическое тело. - \en Create a sweeping solid. \~ - \details \ru Создать кинематическое тело путем движения образующей кривой вдоль направляющей кривой. \n - \en Create a sweeping solid by moving the generating curve along the guide curve. \n \~ - \param[in] sweptData - \ru Данные об образующей. - \en The generating curve data. \~ - \param[in] spine - \ru Направляющая кривая. - \en The spine curve. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователь контуров образующей. - \en An object defining the names of generating curve contours. \~ - \param[in] spineNames - \ru Именователь направляющей. - \en An object defining the name of a guide curve. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) EvolutionSolid( const MbSweptData & sweptData, - const MbCurve3D & spine, - const EvolutionValues & params, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - const MbSNameMaker & spineNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кинематическое тело. - \en Create a sweeping solid. \~ - \details \ru Создать кинематическое тело путем движения образующей кривой вдоль направляющей кривой c дополнительной информацией. \n - \en Create a sweeping solid by moving the generating curve along the guide curve with additional data. \n \~ - \param[in] sweptData - \ru Данные об образующей. - \en The generating curve data. \~ - \param[in] spine - \ru Направляющая кривая c дополнительной информацией. - \en The spine curve with additional data. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователь контуров образующей. - \en An object defining the names of generating curve contours. \~ - \param[in] spineNames - \ru Именователь направляющей. - \en An object defining the name of a guide curve. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) EvolutionSolid( const MbSweptData & sweptData, - const MbSpine & spine, - const EvolutionValues & params, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - const MbSNameMaker & spineNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по плоским сечениям. - \en Create a solid from a planar sections. \~ - \details \ru Создать тело по плоским сечениям c направляющей линией. \n - \en Create a solid from a planar sections with a guide curve. \n \~ - \param[in] pl - \ru Множество систем координат образующих контуров. - \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] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. - \en A point array on the generating contours which determines the start points of the contours. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] ns - \ru Именователи образующих контуров. - \en The objects defining the names of generating contours. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, - RPArray & c, - const MbCurve3D * spine, - const LoftedValues & params, - SArray * ps, - const MbSNameMaker & names, - RPArray & ns, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по пространственным сечениям. - \en Create a solid from a space sections. \~ - \details \ru Создать тело по пространственным сечениям c направляющей линией. \n - \en Create a solid from a space sections with a guide curve. \n \~ - \param[in] pl - \ru Множество систем координат образующих контуров. - \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] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. - \en An array of the guide curves that determines the trajectories of the corresponding points of the contours. \~ - \param[in] ps - \ru Множество точек на образующих контурах, задающее соответствующие точки (цепочки точек). - \en A point array on the generating contours which determines the corresponding points of the contours (chains of points). \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] ns - \ru Именователи образующих контуров. - \en The objects defining the names of generating contours. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, - RPArray & c, - const MbCurve3D * spine, // осевая линия может быть NULL - const LoftedValues & params, - RPArray * guideCurves, - SArray * ps, - const MbSNameMaker & names, - RPArray & ns, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по пространственным сечениям. - \en Create a solid from a space sections. \~ - \details \ru Создать тело по пространственным сечениям c направляющей линией. \n - \en Create a solid from a space sections with a guide curve. \n \~ - \param[in] surfs - \ru Множество поверхностей образующих контуров. - \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] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. - \en An array of the guide curves that determines the trajectories of the corresponding points of the contours. \~ - \param[in] ps - \ru Множество точек на образующих контурах, задающее соответствующие точки (цепочки точек). - \en A point array on the generating contours which determines the corresponding points of the contours (chains of points). \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] ns - \ru Именователи образующих контуров. - \en The objects defining the names of generating contours. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedSolid( RPArray & surfs, - RPArray & c, - const MbCurve3D * spine, // осевая линия может быть NULL - const LoftedValues & params, - RPArray * guideCurves, - SArray * ps, - const MbSNameMaker & names, - RPArray & ns, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело выдавливания и выполнить булеву операцию. - \en Create an extrusion solid and perform a boolean operation. \~ - \details \ru Создать тело выдавливания и выполнить булеву операцию типа oType с телом solid. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. - \en Create an extrusion solid and perform a boolean operation of type 'oType' with solid 'solid'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \~ - \param[in] solid - \ru Первое тело для булевой операции. - \en The first solid for a boolean operation. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] sweptData - \ru Данные об образующих кривых. - \en The generating curve data. \~ - \param[in] direction - \ru Направление выдавливания. - \en An extrusion direction. \~ - \param[in, out] params - \ru Параметры выдавливания. - Возвращают информацию для построения элементов массива операций до поверхности. - \en The extrusion parameters. - Returns the information for construction of the up-to-surface operation array elements. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователи образующих кривых. - \en The objects defining the names of generating lines. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtrusionResult( MbSolid & solid, - MbeCopyMode sameShell, - const MbSweptData & sweptData, - const MbVector3D & direction, - const ExtrusionValues & params, - OperationType oType, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело вращения и выполнить булеву операцию. - \en Create a revolution solid and perform a boolean operation. \~ - \details \ru Создать тело вращения и выполнить булеву операцию типа oType с телом solid. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. - \en Create a revolution solid and perform a boolean operation of type oType with solid 'solid'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \~ - \param[in] solid - \ru Первое тело для булевой операции. - \en The first solid for a boolean operation. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] sweptData - \ru Данные об образующих кривых. - \en The generating curve data. \~ - \param[in] axis - \ru Ось вращения. - \en Rotation axis. \~ - \param[in, out] params - \ru Параметры вращения. - Возвращают информацию для построения элементов массива операций до поверхности. - \en The revolution parameters. - Returns the information for construction of the up-to-surface operation array elements. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] contoursNames - \ru Именователи образующих кривых. - \en The objects defining the names of generating lines. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RevolutionResult( MbSolid & solid, - MbeCopyMode sameShell, - const MbSweptData & sweptData, - const MbAxis3D & axis, - const RevolutionValues & params, - OperationType oType, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Сориентировать образующий контур и направляющую кинематики. - \en Determine the orientation for a generating contour and for a guide curve of kinematics (evolution). \~ - \details \ru Выполнить ориентацию образующего контура и направляющей кривой для построения кинематического тела. \n - \en Orientate the generating contour and the guide curve for a sweeping solid construction. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] contours - \ru Образующие контуры. - \en Generating contours. \~ - \param[in] guide - \ru Направляющая кривая. - \en The spine curve. \~ - \param[in] parameters - \ru Параметры операции. - \en The operation parameters. \~ - \param[out] axis - \ru Ось доворота образующей. - \en The axis for the generating curve additional turn. \~ - \param[out] angle - \ru Угол доворота образующей. - \en The additional turn for generating line. \~ - \param[in] version - \ru Версия операции. - \en The version of the operation. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \warning \ru Вспомогательная функция операций EvolutionSolid и EvolutionResult. - \en An auxiliary function of operations EvolutionSolid and EvolutionResult. \~ - \ingroup Shell_Modeling -*/ -// --- -MATH_FUNC (MbResultType) EvolutionNormalize( const MbSurface & surface, - const RPArray & contours, - const MbCurve3D & guide, - const EvolutionValues & parameters, - MbAxis3D & axis, - double & angle, - VERSION version ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать усеченную замкнутую кривую на копии кривой. - \en Create a trimmed closed curve on a curve copy. \~ - \details \ru Выполнить построение копии замкнутой кривой с началом в точке, определяемой параметром t. \n - \en Create a copy of a closed curve starting at a point with parameter t. \n \~ - \param[in] curve - \ru Направляющая кривая. - \en The spine curve. \~ - \param[in] t - \ru Параметр кривой. - \en A curve parameter. \~ - \return \ru При удачной работе функция возвращает построенную копию кривой - с началом в заданной точке, в противном случае функция возвращает ноль. - \en Returns a constructed curve copy starting at the specified point if it has been successfully created, - otherwise it returns null. \~ - \warning \ru Вспомогательная функция операций EvolutionSolid и EvolutionResult. - \en An auxiliary function of operations EvolutionSolid and EvolutionResult. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCurve3D *) TrimClosedSpine( const MbCurve3D & curve, - double t ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кинематическое тело и выполнить булеву операцию. - \en Create an evolution solid and perform a boolean operation. \~ - \details \ru Создать кинематическое тело и выполнить булеву операцию типа oType с телом solid. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. - \en Create an evolution solid and perform a boolean operation of type oType with solid 'solid'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \~ - \param[in] solid - \ru Первое тело для булевой операции. - \en The first solid for a boolean operation. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] sweptData - \ru Данные об образующей. - \en The generating curve data. \~ - \param[in] spine - \ru Направляющая кривая. - \en The spine curve. \~ - \param[in] params - \ru Параметры кинематической операции. - \en Parameters of the sweeping operation. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] contoursNames - \ru Именователь контуров образующей. - \en An object defining the names of generating curve contours. \~ - \param[in] spineNames - \ru Именователь направляющей. - \en An object defining the name of a guide curve. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC(MbResultType) EvolutionResult( MbSolid & solid, - MbeCopyMode sameShell, - const MbSweptData & sweptData, - const MbCurve3D & spine, - const EvolutionValues & params, - OperationType oType, - const MbSNameMaker & operNames, - const RPArray & contoursNames, - const MbSNameMaker & spineNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по плоским сечениям и выполнить булеву операцию. - \en Create a solid from the planar sections and perform a boolean operation. \~ - \details \ru Создать тело по плоским сечениям и выполнить булеву операцию типа oType с телом solid. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. - \en Create a solid from a planar sections and perform a boolean operation of type oType with solid 'solid'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \~ - \param[in] solid - \ru Первое тело для булевой операции. - \en The first solid for a boolean operation. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] pl - \ru Множество систем координат образующих контуров. - \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] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. - \en A point array on the generating contours which determines the start points of the contours. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] ns - \ru Именователи образующих контуров. - \en The objects defining the names of generating contours. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC(MbResultType) LoftedResult( MbSolid & solid, - MbeCopyMode sameShell, - SArray & pl, - RPArray & c, - const MbCurve3D * spine, - const LoftedValues & params, - OperationType oType, - SArray * ps, - const MbSNameMaker & names, - RPArray & ns, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело по пространственным сечениям и выполнить булеву операцию. - \en Create a solid from the space sections and perform a boolean operation. \~ - \details \ru Создать тело по пространственным сечениям и выполнить булеву операцию типа oType с телом solid. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. - \en Create a solid from a space sections and perform a boolean operation of type oType with solid 'solid'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \~ - \param[in] solid - \ru Первое тело для булевой операции. - \en The first solid for a boolean operation. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] surfs - \ru Множество поверхностей контуров. - \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] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] guideCurves - \ru Массив направляющих кривых. - \en An array of the guide curves. \~ - \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. - \en A point array on the generating contours which determines the start points of the contours. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[in] ns - \ru Именователи образующих контуров. - \en The objects defining the names of generating contours. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC(MbResultType) LoftedResult( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & surfs, - RPArray & c, - const MbCurve3D * spine, - const LoftedValues & params, - OperationType oType, - RPArray * guideCurves, - SArray * ps, - const MbSNameMaker & names, - RPArray & ns, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Выполнить булеву операцию. - \en Perform a Boolean operation. \~ - \details \ru Функция выполняет указанную булеву операцию над двумя телами с возможностью управления слиянием граней и рёбер.\n - \en The function performs the specified Boolean operation on two solids with faces and edges merging control.\n \~ - \param[in] solid1 - \ru Набор граней первого тела. - \en The set of faces of the first solid. \~ - \param[in] sameShell1 - \ru Способ копирования граней первого тела. - \en Method of copying the faces of the first solid. \~ - \param[in] solid2 - \ru Набор граней второго тела. - \en The second solid face set. \~ - \param[in] sameShell2 - \ru Способ копирования граней второго тела. - \en Method of copying the faces of the second solid. \~ - \param[in] oType - \ru Тип булевой операции. - \en A Boolean operation type. \~ - \param[in] flags - \ru Управляющие флаги булевой операции. - \en Control flags of the Boolean operation. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] result - \ru Построенный набор граней. - \en Constructed set of faces. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BooleanResult( MbSolid & solid1, - MbeCopyMode sameShell1, - MbSolid & solid2, - MbeCopyMode sameShell2, - OperationType oType, - const MbBooleanFlags & flags, - const MbSNameMaker & operNames, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело путем булевой операции. - \en Create a solid using a boolean operation. \~ - \details \ru Создать тело путем булевой операции типа oType для тел solid1 и solid2. - Принимаемые значения OperationType для тел: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. \n - Функция работает только с замкнутыми телами, сливает подобные грани и рёбра. - Функция выполняет одноимённую булеву операцию над множествами точек, - расположенными внутри и на поверхности тел. - \en Create a solid by applying a boolean operation of type oType to solids 'solid1' and 'solid2'. - The possible values of 'OperationType' for solids: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \n - The function accepts only closed solids, similar faces and similar edges will be merged. - The function performs a boolean operation of the same name with a point sets - located inside the solids and on their boundary. \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] sameShell1 - \ru Режим копирования первого тела. - \en Whether to copy the first solid. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] sameShell2 - \ru Режим копирования второго тела. - \en Whether to copy the second solid. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BooleanSolid( MbSolid & solid1, - MbeCopyMode sameShell1, - MbSolid & solid2, - MbeCopyMode sameShell2, - OperationType oType, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело путем булевой операции. - \en Create a solid using a boolean operation. \~ - \details \ru Создать тело путем булевой операции типа oType для оболочек solid1 и solid2. - Один из операндов solid1 или solid2 - незамкнутая оболочка. - Принимаемые значения OperationType для оболочек: \n - bo_Variety - объединение, \n - bo_Internal - пересечение, \n - bo_External - вычитание. - \en Create a solid applying a boolean operation of type oType to shells 'solid1' and solid2'. - One of the operands 'solid1' and 'solid2' should be an open shell. - Possible values of 'OperationType' for a shells are: \n - bo_Variety - a union, \n - bo_Internal - an intersection, \n - bo_External - a subtraction. \~ - \param[in] solid1 - \ru Первое тело. - \en The first solid. \~ - \param[in] sameShell1 - \ru Режим копирования первого тела. - \en Whether to copy the first solid. \~ - \param[in] solid2 - \ru Второе тело. - \en The second solid. \~ - \param[in] sameShell2 - \ru Режим копирования второго тела. - \en Whether to copy the second solid. \~ - \param[in] oType - \ru Тип булевой операции. - \en A boolean operation type. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BooleanShell( MbSolid & solid1, - MbeCopyMode sameShell1, - MbSolid & solid2, - MbeCopyMode sameShell2, - OperationType oType, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отрезать часть тела поверхностью. - \en Cut a part of a solid off by a surface. \~ - \details \ru Отрезать часть тела пересекающей его поверхностью. \n - part = 1 - оставляем часть тела, расположенную сверху поверхности. \n - part = -1 - оставляем часть тела, расположенную снизу поверхности. \n - \en Cut a part of a solid off by a surface that intersects the solid. \n - part = 1 - a part of solid above the surface is to be retained. \n - part = -1 - a part of solid below the surface is to be retained. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the source solid. \~ - \param[in] surface - \ru Секущая поверхность. - \en A cutting plane. \~ - \param[in] retainedPart - \ru Направление отсечения. - \en The direction of cutting off. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] closed - \ru Флаг режима отсечения: true - сечем как тело, false - сечем как оболочку. - \en The flag of the cutting off mode: true - cut as a solid, false - cut as a shell. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, - MbeCopyMode sameShell, - const MbSurface & surface, - int retainedPart, - const MbSNameMaker & names, - bool closed, - const MbMergingFlags & flags, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отрезать часть тела выдавленным плоским контуром. - \en Cut a part of a solid off with an extruded planar contour. \~ - \details \ru Отрезать часть тела оболочкой, полученной выдавливанием плоского контура. \n - part = 1 - оставляем часть тела, расположенную сверху поверхности выдавливания. \n - part = -1 - оставляем часть тела, расположенную снизу поверхности выдавливания. \n - \en Cut a part of a solid by a shell of planar contour extrusion. \n - part = 1 - a part of solid above the extrusion surface is to be retained. \n - part = -1 - a part of solid below the extrusion surface is to be retained. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] place - \ru Система координат образующего контура. - \en The generating contour coordinate system. \~ - \param[in] contour - \ru Образующий контур. - \en The generating contour. \~ - \param[in] direction - \ru Направление выдавливания образующего контура. - \en An extrusion direction of the generating contour. \~ - \param[in] retainedPart - \ru Направление отсечения. - \en The direction of cutting off. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] closed - \ru Флаг режим отсечения: true - сечем как тело, false - сечем как оболочку. - \en The cutting off mode flag: true - cut as a solid, false - cut as a shell. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbContour & contour, - const MbVector3D & direction, - int retainedPart, - const MbSNameMaker & names, - bool closed, - const MbMergingFlags & flags, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разрезать тело поверхностью. - \en Cut a solid off by a surface. \~ - \details \ru Разрезать тело поверхностью с построением всех отрезанных частей. \n - \en Cut a solid off by a surface, keep all parts of the solid. \n - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. - \en Whether to copy the source solid. Built bodies can not move relative to each other when sameShell != Vm_Copy. \~ - \param[in] surface - \ru Секущая поверхность. - \en A cutting plane. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] closed - \ru Флаг режима отсечения: true - сечем как тело, false - сечем как оболочку. - \en The flag of the cutting off mode: true - cut as a solid, false - cut as a shell. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] result - \ru Построенные тела. - \en The resultant solids. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -DEPRECATE_DECLARE -MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, - MbeCopyMode sameShell, - const MbSurface & surface, - const MbSNameMaker & names, - bool closed, - const MbMergingFlags & flags, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разрезать тело выдавленным плоским контуром. - \en Cut a solid off with an extruded planar contour. \~ - \details \ru Разрезать тело оболочкой, полученной выдавливанием плоского контура, с построением всех отрезанных частей. \n - \en Cut a solid by a shell of planar contour extrusion, keep all parts of the solid. \n - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. - \en Whether to copy the source solid. Built bodies can not move relative to each other when sameShell != Vm_Copy. \~ - \param[in] place - \ru Система координат образующего контура. - \en The generating contour coordinate system. \~ - \param[in] contour - \ru Образующий контур. - \en The generating contour. \~ - \param[in] direction - \ru Направление выдавливания образующего контура. - \en An extrusion direction of the generating contour. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] closed - \ru Флаг режим отсечения: true - сечем как тело, false - сечем как оболочку. - \en The cutting off mode flag: true - cut as a solid, false - cut as a shell. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] result - \ru Построенные тела. - \en The resultant solids. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -DEPRECATE_DECLARE -MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbContour & contour, - const MbVector3D & direction, - const MbSNameMaker & names, - bool closed, - const MbMergingFlags & flags, - RPArray & result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разрезать тело на части. - \en Cut a solid into parts. \~ - \details \ru Разрезать тело на части. \n - \en Cut a solid into parts. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования исходного тела. - \en The mode of copying of the source solid. \~ - \param[in] cuttingParams - \ru Параметры операции. - \en Operation parameters. \~ - \param[out] results - \ru Построенные тела. - \en The resultant solids. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, - MbeCopyMode sameShell, - const MbShellCuttingParams & cuttingParams, - RPArray & results ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать симметричное тело относительно плоскости. - \en Create a symmetric solid relative to a plane. \~ - \details \ru Создать симметричное тело относительно плоскости XY локальной системы координат. \n - Функция создаёт симметричное тело с заданной плоскостью симметрии следующим образом. - Исходное тело режется плоскостью XY локальной системы координат, берётся часть исходного тела, - расположенная сверху режущей плоскости, строится зеркальная копия выбранной части исходного тела - и объединяется с выбранной частью исходного тела. \n - \en Crate a symmetric solid relative to XY-plane of a local coordinate system. \n - The function creates a symmetric solid with the specified plane of symmetry in the following way. - The source solid is cut off by the plane XY of the local coordinate system; a part of the source solid above the cutting plane - is retained. A mirror copy of the chosen part is created - and then is united with the chosen part of the source solid. \n \~ - \param[in] solid - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования оболочки. - \en Whether to copy the shell. \~ - \param[in] place - \ru Система координат плоскости симметрии. - \en The symmetry plane coordinate system. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SymmetrySolid( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать зеркальную копию тела относительно плоскости. - \en Create a mirror copy of a solid relative to a plane. \~ - \details \ru Создать зеркальную копию тела относительно плоскости XY локальной системы координат. \n - \en Create a mirror copy of a solid relative to the XY-plane of a local coordinate system. \n \~ - \param[in] solid - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] place - \ru Система координат плоскости симметрии. - \en The symmetry plane coordinate system. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) MirrorSolid( const MbSolid & solid, - const MbPlacement3D & place, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тело с ребром жёсткости. - \en Create a solid with a rib. \~ - \details \ru Создать тело с ребром жёсткости. \n - По заданному контуру функция строит ребро жёсткости и объединяет его с исходным телом. - Сегмент контура с указанным номером устанавливает вектор уклона. \n - \en Create a solid with a rib. \n - The function creates a rib from a given contour and unites it with the source solid. - The segment of the contour with the given number determines the slope vector. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] place - \ru Система координат образующего контура. - \en The generating contour coordinate system. \~ - \param[in] contour - \ru Формообразующий контур на плоскости XY системы координат place. - \en The generating contour on XY-plane of coordinate system 'place'. \~ - \param[in] index - \ru Номер сегмента в контуре. - \en The segment number in the contour. \~ - \param[in] pars - \ru Параметры ребра жёсткости. - \en Parameters of a rib. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RibSolid( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbContour & contour, - size_t index, - RibValues & pars, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать отдельное ребро жёсткости. - \en Create a separate rib. \~ - \details \ru Создать отдельное ребро жёсткости для исходного тела без приклеивания. \n - \en Create a separate rib for source solid without gluing. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] place - \ru Система координат образующего контура. - \en The generating contour coordinate system. \~ - \param[in] contour - \ru Образующий контур. - \en The generating contour. \~ - \param[in] index - \ru Номер сегмента в контуре. - \en The segment number in the contour. \~ - \param[in] pars - \ru Параметры ребра жёсткости. - \en Parameters of a rib. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RibElement( const MbSolid & solid, - const MbPlacement3D & place, - MbContour & contour, - size_t index, - RibValues & pars, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скруглить ребра постоянным радиусом. - \en Fillet edges with a constant radius. \~ - \details \ru Скруглить указанные рёбра тела постоянным радиусом. \n - Функция выполняет замену указанных рёбер исходного тела гранями, - гладко сопрягающими смежные грани указанных рёбер. В поперечном сечении - сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. \n - \en Fillet the specified edges of the solid with a constant radius. \n - The function performs the replacement of the specified edges of the source solid by faces - smoothly connecting the adjacent faces of the specified edges. The cross-section - of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] initCurves - \ru Множество скругляемых ребер тела. - \en A set of edges of the solid to fillet. \~ - \param[in] initBounds - \ru Множество граней для обрезки торцов. - \en A set of faces for trimming of the butt-ends. \~ - \param[in] params - \ru Параметры скругления рёбер. - \en Parameters of edges fillet. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & initCurves, - RPArray & initBounds, - const SmoothValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скруглить ребра переменным радиусом. - \en Fillet edges with a variable radius. \~ - \details \ru Скруглить указанные ребра тела переменным радиусом, задаваемым MbEdgeFunction.function. \n - Функция выполняет замену указанных рёбер исходного тела гранями, - гладко сопрягающими смежные грани указанных рёбер. В поперечном сечении - сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. - Параметры поперечного сечения могут изменяться по заданному закону. \n - \en Fillet the given edges of the solid with a variable radius specified by MbEdgeFunction.function. \n - The function performs the replacement of the specified edges of the source solid by faces - smoothly connecting the adjacent faces of the specified edges. The cross-section - of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. - The parameters of the cross-section can vary by the specified law. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] initCurves - \ru Множество скругляемых ребер тела с функциями изменения радиуса. - \en An array of edges of the solid to fillet together with the radius laws. \~ - \param[in] initBounds - \ru Множество граней для обрезки торцов. - \en A set of faces for trimming of the butt-ends. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, - MbeCopyMode sameShell, - SArray & initCurves, - RPArray & initBounds, - const SmoothValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скруглить вершины и примыкающие к ней рёбра постоянным радиусом. - \en Create fillets on vertices and the edges adjacent to these vertices with a constant radius. \~ - \details \ru Скруглить вершины и примыкающие к ней рёбра тела постоянным радиусом. \n - В вершинах должно стыковаться три ребра. - Функция выполняет замену указанных вершин и рёбер исходного тела гранями, - гладко сопрягающими смежные грани указанных вершин и рёбер. В поперечном сечении - сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. \n - \en Create fillets on vertices and the edges of the solid adjacent to these vertices with a constant radius. \n - Three edges must be incident to each vertex. - The functions performs replacement of the specified vertices and edges of the source solid by faces of the solid - smoothly connecting the faces adjacent to the specified vertices and edges. The cross-section - of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] initCurves - \ru Множество скругляемых ребер тела. - \en A set of edges of the solid to fillet. \~ - \param[in] initBounds - \ru Множество граней для обрезки торцев. - \en A set of faces for trimming of the butt-ends. \~ - \param[in] initVertices - \ru Множество скругляемых вершин. - \en A set of vertices to fillet. \~ - \param[in] params - \ru Параметры скругления рёбер. - \en Parameters of edges fillet. \~ - \param[in] cornerData - \ru Параметры скругления вершин. - \en Parameters of vertices fillet. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & initCurves, - RPArray & initBounds, - RPArray & initVertices, - const SmoothValues & params, - const CornerValues & cornerData, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Скруглить цепочку граней тела. - \en Create a fillet of faces of the solid. \~ - \details \ru Скруглить указанные грани тела. \n - Функция выполняет замену указанных граней исходного тела гранями, - гладко сопрягающими грани, связанные с указанными гранью. - В поперечном сечении сопрягающие грани имеют форму - дуги окружности, касающейся трёх граней исходного тела. \n - \en Create a fillet on the specified faces of the solid. \n - The function performs replacement of the specified faces of the source solid with faces - smoothly connecting the faces adjacent to the specified faces. - The cross-section of the connecting faces has a form of - a circle arc tangent to three faces of the source solid. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] initFaces - \ru Набор граней для скругления. - \en A set of faces to fillet. \~ - \param[in] initFacesLeft - \ru Набор ограничивающих слева граней. - \en A set of left bounding faces. \~ - \param[in] initFacesRight - \ru Набор ограничивающих справа граней. - \en A set of right bounding faces. \~ - \param[in] params - \ru Параметры скругления. - \en Parameters of fillet. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FullFilletSolid( MbSolid & solid, - MbeCopyMode sameShell, - const RPArray & initFaces, - const RPArray & initFacesLeft, - const RPArray & initFacesRight, - const FullFilletValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить фаски ребер тела. - \en Create chamfers for edges of the solid. \~ - \details \ru Построить фаски указанных ребер тела. \n - Функция выполняет замену указанных рёбер исходного тела гранями фасок. \n - \en Create chamfers for the specified edges of the solid. \n - The function performs replacement of the specified edges of the source solid with faces of chamfers. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] initCurves - \ru Множество скругляемых ребер тела. - \en An array of edges to create chamfer on. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ChamferSolid( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & initCurves, - const SmoothValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантное тело. - \en Create а equidistant solid. \~ - \details \ru Создать эквидистантное тело или оболочку. \n - \en Create an offset solid by equidistant faces or create an equidistant shell. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] offset - \ru Расстояние смещения граней. - \en The equidistant parameter. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetSolid( MbSolid & solid, - MbeCopyMode sameShell, - double offset, - const MbSNameMaker & names, - MbSolid *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тонкостенное тело исключением граней. - \en Create a thin-walled solid by exclusion of faces. \~ - \details \ru Создать тонкостенное тело исключением граней outFaces \n - и приданием одинаковой толщины оставшимся граням \n - или создание незамкнутой оболочки. \n - \en Create a thin-walled solid by exclusion of faces outFaces \n - and supplying the rest of faces with the same thickness \n - or create an open shell. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] outFaces - \ru Вскрываемые грани тела. - \en Faces of the solid to open. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. - \en Copy attributes of initial faces to offset faces. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ThinSolid( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & outFaces, - SweptValues & params, - const MbSNameMaker & names, - bool copyFaceAttrs, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать тонкостенное тело исключением граней. - \en Create a thin-walled solid by exclusion of faces. \~ - \details \ru Создать тонкостенное тело исключением граней outFaces \n - и приданием различной толщины оставшимся граням \n - или создание незамкнутой оболочки. \n - \en Create a thin-walled solid by exclusion of faces outFaces \n - and supplying the rest of faces with different thickness \n - or create an open shell. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] outFaces - \ru Вскрываемые грани тела. - \en Faces of the solid to open. \~ - \param[in] offFaces - \ru Множество граней, для которых заданы индивидуальные значения толщин. - \en An array of faces for which the individual values of thickness are specified. \~ - \param[in] offDists - \ru Множество индивидуальных значений толщин (должен быть синхронизирован с массивом offFaces). - \en An array of individual values of thickness (must be synchronized with the array 'offFaces'). \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. - \en Copy attributes of initial faces to offset faces. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling - \warning \ru Операция ПОЛНОЦЕННО НЕ РЕАЛИЗОВАНА! - \en The operation is NOT COMPLETELY IMPLEMENTED! \~ -*/ -// --- -MATH_FUNC (MbResultType) ThinSolid( MbSolid & solid, - MbeCopyMode sameShell, - RPArray & outFaces, - RPArray & offFaces, - SArray & offDists, - SweptValues & params, - const MbSNameMaker & names, - bool copyFaceAttrs, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Выполнить разбиение граней оболочки. - \en Perform splitting of a shell faces. \~ - \details \ru Выполнить разбиение граней оболочки поверхностями выдавливания контуров. \n - Функция создаёт копию тела и разбивает указанные грани поверхностями выдавливания контуров. \n - \en Perform splitting of a shell faces with surfaces of the contours extrusion. \n - The function creates a copy of a solid and splits the specified faces with surfaces of the contours extrusion. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] spPlace - \ru Система координат контуров. - \en The coordinate system of the contours. \~ - \param[in] spType - \ru Направление вытягивания. - \en The extrusion direction. \~ - \param[in] spContours - \ru Контура разбиения. - \en The contours of splitting. \~ - \param[in] spSame - \ru Использовать оригиналы или копии кривых. - \en Whether to use the originals or copies of curves. \~ - \param[in] selFaces - \ru Выбранные грани входного тела. - \en The chosen faces of the input solid. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplitSolid( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & spPlace, - MbeSenseValue spType, - const RPArray & spContours, - bool spSame, - RPArray & selFaces, - const MbMergingFlags & flags, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Выполнить разбиение граней оболочки. - \en Perform splitting of a shell faces. \~ - \details \ru Выполнить разбиение граней оболочки пространственными кривыми, поверхностями и оболочками. \n - Функция создаёт копию тела и разбивает указанные грани пространственными кривыми, поверхностями и оболочками. \n - Пространственные элементы разбиения не должны иметь полных или частичных наложений, а также - самопересечений. \n - \en Perform splitting of the shell faces with space curves, surfaces and shells. \n - The function creates a copy of the solid and splits the specified faces with space curves, surfaces and shells. \n - The spatial elements of a splitting must not have complete or partial overlaps, and also self-intersections. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] spItems - \ru Пространственные элементы разбиения. - \en A spatial elements of splitting. \~ - \param[in] spSame - \ru Использовать оригиналы или копии кривых. - \en Whether to use the originals or copies of curves. \~ - \param[in] selFaces - \ru Выбранные грани входного тела. - \en The chosen faces of the input solid. \~ - \param[in] flags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplitSolid( MbSolid & solid, - MbeCopyMode sameShell, - const RPArray & spItems, - bool spSame, - RPArray & selFaces, - const MbMergingFlags & flags, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Уклонить указанные грани тела. - \en Slope the specified faces of the solid. \~ - \details \ru Уклонить указанные грани тела от нейтральной изоплоскости на заданный угол. \n - \en Slope the specified faces of the solid at the specified angle relative to the neutral isoplane. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования входного тела. - \en Whether to copy the input solid. \~ - \param[in] neutralPlace - \ru Нейтральная плоскость. - \en The neutral plane. \~ - \param[in] angle - \ru Угол уклона. - \en The slope angle. \~ - \param[in] faces - \ru Уклоняемые грани во входном теле. - \en The faces of input solid to be sloped. \~ - \param[in] fp - \ru Признак захвата граней, гладко стыкующихся с уклоняемыми гранями. - \en Whether to capture the faces smoothly connected with the faces being sloped. \~ - \param[in] reverse - \ru Флаг обратного направления уклона. - \en Whether to slope in the reverse direction. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) DraftSolid( MbSolid & solid, - MbeCopyMode sameShell, - const MbPlacement3D & neutralPlace, - double angle, - const RPArray & faces, - MbeFacePropagation fp, - bool reverse, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Выполнить объединение пересекающихся тел. - \en Perform the union of intersecting solids. \~ - \details \ru Выполнить объединение пересекающихся тел и булеву операцию oType с телом solid, если оно не нулевое: \n - bo_Union - объединение, \n - bo_Intersect - пересечение, \n - bo_Difference - вычитание. \n - Если флаг проверки пересечения checkIntersect == true, то выполняется проверка на пересечение тел - и булева операция объединения пересекающихся тел заданного множества в одно тело. В противном случае - объединение тел заданного множества выполняется простым перекладыванием граней всех тел в одно новое тело. \n - Если флаг регулярности множества тел isArray == true, то тела множества расположены в узлах - прямоугольной или круговой сетки и позиции тел заданы в именах граней. \n - \en Perform the union of intersecting solids and a boolean operation oType with solid 'solid' if it is not null: \n - bo_Union - union, \n - bo_Intersect - intersection, \n - bo_Difference - subtraction. \n - If the flag of intersection check checkIntersect == true, check for solids intersection is performed - and the boolean operation of union the intersection solids of the specified set into one solid is performed. Otherwise - the union of solids from the given set is performed by simple moving the faces of all the solids into a new solid. \n - If the flag of solid set regularity isArray == true, the solids are located at the nodes - of rectangular or circular grid and positions of solids are specified in the names of faces. \n \~ - \param[in] solid - \ru Тело. - \en A solid. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] solids - \ru Множество тел. - \en An array of solids. \~ - \param[in] sameShells - \ru Режим копирования тел. - \en Whether to copy the solids. \~ - \param[in] oType - \ru Тип булевой операции между телом и массивом тел. - \en The type of the boolean operation for the solid and the set of solids. \~ - \param[in] checkIntersect - \ru Проверять пересечение тел. - \en Whether to check the solids intersection. \~ - \param[in] mergeFaces - \ru Сливать подобные грани. - \en \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] isArray - \ru Флаг регулярности множества тел. - \en A flag of solid set regularity. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \param[out] notGluedSolids - \ru Множество тел, которые не получилось приклеить. - \en An array of solids which was not glued. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) UnionResult( MbSolid * solid, - MbeCopyMode sameShell, - RPArray & solids, - MbeCopyMode sameShells, - OperationType oType, - bool checkIntersect, - bool mergeFaces, - const MbSNameMaker & names, - bool isArray, - MbSolid *& result, - RPArray * notGluedSolids = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать одно тело из присланных тел. - \en Create a solid from the specified solids. \~ - \details \ru Создать тело с объединением или без объединения пересекающихся тел. \n - Если флаг проверки пересечения checkIntersect == true, то выполняется проверка на пересечение тел - и булева операция объединения пересекающихся тел заданного множества в одно тело. В противном случае - объединение тел заданного множества выполняется простым перекладыванием граней всех тел в одно новое тело. \n - Если флаг регулярности множества тел isArray == true, то тела множества расположены в узлах - прямоугольной или круговой сетки и позиции тел заданы в именах граней. \n - \en Create a solid with or without union of the intersecting solids. \n - If the flag of intersection check checkIntersect == true, check for solids intersection is performed - and the boolean operation of union the intersection solids of the specified set into one solid is performed. Otherwise - the union of solids from the given set is performed by simple moving the faces of all the solids into a new solid. \n - If the flag of solid set regularity isArray == true, the solids are located at the nodes - of rectangular or circular grid and positions of solids are specified in the names of faces. \n \~ - \param[in] solids - \ru Множество тел. - \en An array of solids. \~ - \param[in] sameShells - \ru Режим копирования тел. - \en Whether to copy the solids. \~ - \param[in] checkIntersect - \ru Проверять пересечение тел. - \en Whether to check the solids intersection. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] isArray - \ru Флаг регулярности множества тел. - \en A flag of solid set regularity. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \param[out] notGluedSolids - \ru Множество тел, которые не получилось приклеить. - \en An array of solids which was not glued. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) UnionSolid( RPArray & solids, - MbeCopyMode sameShells, - bool checkIntersect, - const MbSNameMaker & names, - bool isArray, - MbSolid *& result, - RPArray * notGluedSolids = NULL ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать одно тело из присланных тел. - \en Create a solid from the specified solids. \~ - \details \ru Создать одно тело из присланных тел, не меняя их. \n - Объединение тел заданного множества выполняется простым перекладыванием - граней всех тел в одно новое тело. \n - \en Create a solid from the specified solids without the modification of the given solids. \n - The union of solids from the specified set is performed by simple moving - the faces of all the solids into a new solid. \n \~ - \param[in] solids - \ru Множество тел. - \en An array of solids. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) UnionSolid( const RPArray & solids, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разделить тело на отдельные части. - \en Split the solid into separate parts. \~ - \details \ru Если исходное тело распадается на части, то наибольшая часть остаётся в исходном теле, - а остальные части части будут сложены в присланный контейнер тел. \n - Если флаг сортировки sort == true, то в исходном теле останется часть с наибольшим габаритом, - а отделённые части будут сортированы по убыванию габарита. В противном случае в исходном теле - останется часть, топологически связанная с первой гранью, а отделённые части будут сортированы - по номеру начальной грани в исходном теле. \n - \en If the source solid is decomposed, the greatest part remains in the source solid, - and the other parts are put into the given array of solids. \n - If 'sort' == 'true', the part with the greatest bounding box will remain in the source solid, - and separated parts will be sorted by bounding box size in descending order. Otherwise a part topologically connected with the first face will remain in the source solid - and the separated parts will be sorted - by the number of the initial face in the source solid. \n \~ - \param[in,out] solid - \ru Исходное модифицируемое тело. - \en The source solid to be modified. \~ - \param[out] parts - \ru Отделённые части тела. - \en The separated parts of the solid. \~ - \param[in] sort - \ru Сортировать по убыванию габарита. - \en Whether to sort by the bounding box size in descending order. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \return \ru Возвращает количество отделенных частей. - \en Returns the number of the separated parts. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (size_t) DetachParts( MbSolid & solid, - RPArray & parts, - bool sort, - const MbSNameMaker & names ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Разделить тело на отдельные части. - \en Split the solid into separate parts. \~ - \details \ru Если исходное тело распадается на части, то все его части будут сложены в присланный контейнер тел. \n - Исходное тело остаётся неизменённым. \n - \en If the source solid is decomposed, all the parts of the solid will be put into the given array of solids. \n - The source solid remains unchanged. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[out] parts - \ru Части тела. - \en The parts of the solid. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \return \ru Возвращает количество созданных частей. - \en Returns the number of created parts. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (size_t) CreateParts( const MbSolid & solid, - RPArray & parts, - const MbSNameMaker & names ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку тела по поверхности и толщине. - \en Create a shell of the solid from a surface and a thickness. \~ - \details \ru Выполнить построение тела путём придания толщины заданной поверхности. \n - \en Create a solid by supplying the surface with a thickness. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] faceSense - \ru Ориентация нормали поверхности. - \en The surface normal orientation. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] name - \ru Основное простое имя. - \en The main simple name. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ThinSolid( const MbSurface & surface, - bool faceSense, - SweptValues & params, - const MbSNameMaker & names, - SimpleName name, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Cоздать отверстие, карман, фигурный паз в теле. - \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 \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Режим копирования тела. - \en Whether to copy the solid. \~ - \param[in] place - \ru Местная система координат для операции. - \en A local coordinate system for the operation. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) HoleSolid( MbSolid * solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const HoleValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Выделить в отдельное тело указанную часть распадающегося на части тела. - \en Extract the specified part of decomposing solid to a separate solid. \~ - \details \ru Создать тело, из указанной части тела, распадающегося на части. - Исходное тело должно состоять из отдельных частей. \n - \en Create a solid from the specified part of decomposing solid. - The source solid should consist of separate parts. \n \~ - \param[in] solid - \ru Разделяемое на части тело. - \en A decomposing solid. \~ - \param[in] id - \ru Номер выбранной части тела - \en The number of selected part of the solid. \~ - \param[in] path - \ru Идентификатор для выбранной части. - \en An identifier for the selected part. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in,out] partIndices - \ru Индексы частей тела. - \en Indices of the parts of the solid. \~ - \param[out] result - \ru Построенная оболочка (тело). - \en The resultant shell (solid). \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ShellPart( const MbSolid & solid, - size_t id, - const MbPath & path, - const MbSNameMaker & names, - MbPartSolidIndices & partIndices, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Размножить тело. - \en Duplicate the solid. \~ - \details \ru Размножить тело согласно параметрам и объединить копии в одно тело.\n - \en Duplicate the solid by the parameters and unite copies in one solid. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] params - \ru Параметры размножения. - \en The parameters of duplication. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] result - \ru Результирующее тело. - \en The result solid. \~ - \return \ru Возвращает код результата операции. - \en . \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) DuplicationSolid( const MbSolid & solid, - const DuplicationValues & params, - const MbSNameMaker & names, - MbSolid *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Cоздать одно тело слиток из присланных объектов. - \en Create an ingot solid from the specified objects. \~ - \details \ru Cоздать одно тело слиток из присланных объектов. \n - Среди присланных объектов используются тела, вставки тел и сборки тел, из которых строится одно тело, - которое по внешности совпадает с присланными телами и служит их упрощенным заменителем по внешним параметрам. \n - \en Create an ingot solid from the specified solids without the modification of the given solids. \n - Among the objects sent using the body, insert bodies and assembling bodies of which is built the same body, - which in appearance coincides with the bodies had been sent and serves as a substitute for their simplistic external parameters. \n \~ - \param[in] solids - \ru Множество тел. - \en An array of solids. \~ - \param[in] names - \ru Именователь. - \en An object for naming the new objects. \~ - \param[in] makeCopy - \ru Флаг копирования тел перед использованием: true - копировать, false - не копировать. - \en The flag of the copying solid before using: true - copy solid, false - not copy. \~ - \param[out] result - \ru Построенное тело. - \en The resultant solid. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Solid_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IngotSolid( RPArray & solids, - bool makeCopy, - const MbSNameMaker & names, - MbSolid *& result ); - - -#endif // __ACTION_SOLID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Функции создания тел, операции с телами. + \en Functions for creation of solids, operations on solids. \~ + \details \ru Процесс построения тел в геометрическом моделировании похож на процесс + изготовления моделируемого объекта. Сначала создаются тела простой формы, а далее + выполняется набор действий, позволяющих из тел простой формы получить более сложные тела. + При необходимости создаются вспомогательные объекты. Редактировать и создавать подобные + тела можно путём изменения параметров с последующим повторением процесса построения тел.\n + Все функции создания тел содержат в качестве входного параметр MbSNameMaker, + обеспечивающий именование граней, рёбер и вершин. + Первым параметром конструктора генератора имён MbSNameMaker служит главное имя операции. + По главному имени можно определить, в какой функции рождена та или иная грань, ребро, вершина. + Главное имя выдаёт метод GetMainName().\n + \en The process of solids creation in geometric modeling is similar to the process + of the modeled object manufacturing. Firstly solids of a simple form are created, and then + a set of operations are performed to obtain a more complex solids from solids of a simple form. + Auxiliary objects are created if necessary. The similar solids can be edited and created + by modifying of the parameters and further repeating the process of the solids creation.\n + All of the function contain input parameter MbSNameMaker, + providing the naming of faces, edges and vertices. + The first parameter to the constructor MbSNameMaker is the main name of the function. + You can determine which function is born one or the other face, edge, vertex by main name. + GetMainName() gives the main name of the function (face.GetMainName(), edge.GetMainName(), vertex.GetMainName()).\~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_SOLID_H +#define __ACTION_SOLID_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbItem; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbPartSolidIndices; +class MATH_CLASS MbSpine; +class MATH_CLASS MbMesh; +class MATH_CLASS MbGrid; +class MATH_CLASS MbCollection; +class MATH_CLASS IProgressIndicator; + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать элементарное тело. + \en Create an elementary solid. \~ + \details \ru Создать одно из элементарных тел по заданным точкам и типу: \n + solidType = et_Sphere - шар (3 точки), \n + solidType = et_Torus - тор (3 точки), \n + solidType = et_Cylinder - цилиндр (3 точки), \n + solidType = et_Cone - конус (3 точки), \n + solidType = et_Block - блок (4 точки), \n + solidType = et_Wedge - клин (4 точки), \n + solidType = et_Prism - призма (количество вершин основания+1 точка), \n + solidType = et_Pyramid - пирамида (количество вершин основания+1 точка), \n + solidType = et_Plate - плита (4 точки), + solidType = et_Icosahedron - икосаэдр (3 точки), \n + solidType = et_Polyhedron - многогранник (3 точки), \n + solidType = et_Tetrapipe - тетра-труба (3 точки), \n + solidType = et_Octapipe - окта-труба (3 точки). \n + \en Create one of elementary solids from the specified points and type: \n + solidType = et_Sphere - a sphere (3 points), \n + solidType = et_Torus - a torus (3 points), \n + solidType = et_Cylinder - a cylinder (3 points), \n + solidType = et_Cone - a cone (3 points), \n + solidType = et_Block - a block (4 points), \n + solidType = et_Wedge - a wedge (4 points), \n + solidType = et_Prism - a prism (points count is equal to the base vertices count + 1), \n + solidType = et_Pyramid - a pyramid (points count is equal to the base vertices count + 1), \n + solidType = et_Plate - a plate (4 points), \n + solidType = et_Icosahedron - an icosahedron (3 points), \n + solidType = et_Polyhedron - a polyhedron (3 points), \n + solidType = et_Tetrapipe - a tetra-pipe (3 points), \n + solidType = et_Octapipe - an octa-pipe (3 points). \n \~ + \param[in] points - \ru Набор точек. \n + points[0] определяет начало локальной системы координат. \n + Для сферы, тора, цилиндра и конуса: \n + points[1] определяет направление оси Z локальной системы. \n + points[2] определяет направление оси X локальной системы. \n + Для блока, клина и плиты: \n + points[1] определяет направление оси X локальной системы. \n + points[2] определяет направление оси Y локальной системы. \n + Кроме того, \n + points[1] определяет высоту цилиндра, высоту конуса, + большой радиус тора, длину блока, длину клина. \n + points[2] определяет радиус цилиндра, угол конуса как угол между векторами v1(points[0],points[1]) и v2(points[0],points[2]), + радиус сферы, малый радиус тора, ширину блока, ширину клина. \n + В случае конуса вектора v1(points[0],points[1]) и v2(points[0],points[2]) не должны быть параллельны или перпендикулярны друг другу. \n + Последняя точка определяет высоту блока, клина, плиты, вершину пирамиды. + \en A point set. \n + points[0] determines a local coordinate system origin. \n + For a sphere, a torus, a cylinder or a cone: \n + points[1] determines the direction of Z-axis of a local coordinate system. \n + points[2] determines the direction of X-axis of a local coordinate system. \n + For a block, a plate or a wedge: \n + points[1] determines the direction of X-axis of a local coordinate system. \n + points[2] determines the direction of Y-axis of a local coordinate system. \n + Also, \n + points[1] determines the height of a cylinder or a cone, + the major radius of a torus, the length of a block or a wedge. \n + points[2] determines the radius of a cylinder, cone angle as angle between vectors v1(points[0],points[1]) and v2(points[0],points[2]), + radius of a sphere, the minor radius of a torus, the width of a block or a wedge. \n + In the case of the cone of the vector v1(points [0], points [1]) and v2(points [0], points [2]) must not be parallel or perpendicular to each other. \n + The last point determines the height of a block, a wedge or a plate, the vertex of a pyramid. \~ + \param[in] solidType - \ru Тип создаваемого тела. + \en The solid type. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ElementarySolid( const SArray & points, + ElementaryShellType solidType, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по поверхности. + \en Create a solid from a surface. \~ + \details \ru Создать тело по элементарной поверхности. \n + Допускается только тип поверхности - цилиндр, конус, сфера, тор. + \en Create a solid from an elementary surface. \n + The only acceptable surface types are cylinder, cone, sphere, torus. \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ElementarySolid( const MbSurface & surface, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело на основе полигональной модели. + \en Create a solid on the basis of a polygonal geometric object. \~ + \details \ru Создать тело #MbSolid на основе полигональной модели #MbMesh. \n + \en Create a solid #MbSolid on the basis of a polygonal geometric object #MbMesh. \n \~ + \param[in] mesh - \ru Полигональная модель. + \en The polygonal geometric object. \~ + \param[in] params - \ru Параметры операции. + \en Operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) MeshSolid( const MbMesh & mesh, + const GridsToShellValues & params, + const MbSNameMaker & names, + MbSolid *& result, + IProgressIndicator * prog = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело на основе триангуляции. + \en Create a solid on the basis of a triangulation. \~ + \details \ru Создать тело #MbSolid на основе триангуляции #MbGrid. \n + \en Create a solid #MbSolid on the basis of a triangulation #MbGrid. \n \~ + \param[in] grid - \ru Полигональная модель. + \en The polygonal geometric object. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) GridSolid( const MbGrid & grid, + const MbSNameMaker & names, + MbSolid *& result, + IProgressIndicator * prog = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело на основе коллекции элементов. + \en Create a solid on the basis of elements. \~ + \details \ru Создать тело #MbSolid на основе коллекции элементов #MbCollection. \n + \en Create a solid #MbSolid on the basis of elements #MbCollection. \n \~ + \param[in] grid - \ru Коллекция элементов. + \en The elements collection. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CollectionSolid( const MbCollection & grid, + const MbSNameMaker & names, + MbSolid *& result, + IProgressIndicator * progBar = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело c заданной оболочкой. + \en Create a solid with a given shell. \~ + \details \ru Создать тело без истории построения с заданной оболочкой. \n + \en Create a solid with a given shell without a history. \n \~ + \param[in] shell - \ru Оболочка. + \en A shell. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \return \ru Возвращает тело без истории. + \en Returns a solid without the history. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbSolid *) CreateSolid( MbFaceShell & shell, + const MbSNameMaker & names ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Рассчитать глубину выдавливания или угол вращения. + \en Compute the extrusion depth or the rotation angle. \~ + \details \ru Рассчитать value - глубину выдавливания или угол вращения (0.0 : M_PI2) + для последующего построения тела путем выдавливания или вращения образующей кривой. \n + \en Compute 'value' - the extrusion depth or the rotation angle (0.0 : M_PI2) + for the further construction of a solid by extrusion or revolution of the generating curve. \n \~ + \param[in] sweptData - \ru Данные об образующей. + \en The generating curve data. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] rotation - \ru Вращение или выдавливание. + \en Rotation or extrusion. \~ + \param[in] operationDirection - \ru Вперед\назад. + \en Forward or backward direction. \~ + \param[in] point - \ru Точка, до которой требуется вращать или выдавливать поверхность. + \en The point to rotate or extrude the surface up to. \~ + \param[out] value - \ru Глубина выдавливания или угол вращения. + \en The extrusion depth or the rotation angle. \~ + \return \ru Возвращает true, если расчет выполнен успешно. + \en Returns true if the value has been successfully calculated. \~ + \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. + \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (bool) GetSweptValue( const MbSweptData & sweptData, + const MbAxis3D & axis, + const MbVector3D & direction, + const bool rotation, + const bool operationDirection, + const MbCartPoint3D & point, + double & value ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить начальное приближение для нахождения образа при вращении/выдавливании. + \en Get the initial approximation for image calculation while rotating/extruding. \~ + \details \ru Вычислить положение образа точки образующей кривой на поверхности для последующего + построения тела путем выдавливания или вращения образующей кривой до заданной поверхности. \n + \en Compute the position of a generating curve point image on a surface for further + solid construction by extrusion or revolution of the generating curve up to the specified surface. \n \~ + \param[in] generatrix - \ru Кривая. + \en The curve. \~ + \param[in] surface - \ru Поверхность, до которой строим операцию. + \en The surface to construct up to. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] rotation - \ru Вращение (true) или выдавливание (false) + \en Rotation (true) or extrusion (false) \~ + \param[out] imagePosition - \ru Точка образа на поверхности. + \en The image point on the surface. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. + \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (void) GetSweptImagePosition( const MbCurve3D & generatrix, + const MbSurface & surface, + const MbVector3D & direction, + const MbAxis3D & axis, + const bool rotation, + MbCartPoint & imagePosition, + MbResultType & resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти расстояния/углы от образующей до поверхности при вращении/выдавливании. + \en Calculate the distances/angles from generating curve to the surface while rotating/extruding. \~ + \details \ru Вычислить глубины выдавливания в прямом и обратном направлениях или углы вращения + в прямом и обратном направлениях для последующего построения тела путем выдавливания или вращения + образующей кривой до заданной поверхности, а также и габарит образа кривой. \n + \en Calculate the extrusion depths in forward and backward directions or the rotating angles + in forward and backward directions for further solid construction by extrusion or revolution + of the generating curve up to the specified surface; and also calculate the bounding box of the curve image. \n \~ + \param[in] surface - \ru Поверхность, до которой строим операцию. + \en The surface to construct up to. \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] rotation - \ru Вращение (true) или выдавливание (false). + \en Revolution (true) or extrusion (false). \~ + \param[in] operationDirection - \ru Направление движения: вперед (true) или назад (false). + \en The motion direction: forward (true) or backward (false). \~ + \param[out] imagePosition - \ru Точка на части поверхности, в которой лежит образ. + \en A point on a surface part that contains the image. \~ + \param[out] range - \ru Расстояния до поверхности в обратном и прямом направлениях. + \en The distance to surface in the backward and the forward directions. \~ + \param[out] rectOnSurface - \ru Габарит образа на поверхности. + \en The bounding box of image on the surface. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. + \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (void) GetRangeToSurface( const MbSurface & surface, + const MbCurve3D & curve, + const MbVector3D & direction, + const MbAxis3D & axis, + const bool rotation, + const bool operationDirection, + const MbCartPoint & imagePosition, + double range[2], + MbRect & rectOnSurface, + MbResultType & resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить площадь проекции кривой на виртуальную координатную плоскость. + \en Compute the area of a curve projection onto a virtual coordinate plane. \~ + \details \ru Вычислить площадь проекции кривой на виртуальную координатную плоскость \n + для определения ориентации образующей кривой в оболочке выдавливания и вращения. \n + Параметры direction и axis определяют направление выдавливания и ось вращения, + а параметр rotation определяет тип операции: \n + - выдавливание, вычисляется площадь проекции на плоскость XOY, \n + - вращение, вычисляется площадь "проекции" на "плоскость" ROZ. + Для незамкнутой кривой в расчет добавляется "замыкание отрезком". + \en Compute the area of a curve projection onto a virtual coordinate plane \n + to determine the generating curve orientation in the shell of extrusion and revolution. \n + Parameters 'direction' and 'axis' determine the extrusion direction and the rotation axis, + and parameter 'rotation' determines the operation type: \n + - extrusion, the area of projection onto the plane XOY is computed, \n + - revolution, the area of "projection" to the "plane" ROZ is computed. + For an open curve "enclosure by a segment" is considered. \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] rotation - \ru Вращение (true) или выдавливание (false). + \en Revolution (true) or extrusion (false). \~ + \return \ru Возвращает площадь проекции. + \en Returns the projection area. \~ + \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. + \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (double) AreaSign( const MbCurve3D & curve, + const MbAxis3D & axis, + const MbVector3D & direction, + bool rotation ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить ориентацию секущей грани относительно тела выдавливания/вращения. + \en Determine the orientation of a cutting surface relative to the extrusion/revolution solid. \~ + \details \ru Определить ориентацию секущей поверхности относительно тела, которое будет строиться + путём выдавливания или вращения образующей кривой до заданной поверхности. \n + \en Determine the orientation of a cutting surface relative to the solid which is to be constructed + by extrusion or revolution the generation curve up to the specified surface. \n \~ + \param[in] cuttingSurface - \ru Поверхность для анализа. + \en A surface to analyze. \~ + \param[in] imagePosition - \ru Место образа на поверхности. + \en An image location on the surface. \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in] rotation - \ru Вращение (true) или выдавливание (false). + \en Revolution (true) or extrusion (false). \~ + \param[in] operationDirection - \ru Направление движения: вперед (true) или назад (false). + \en The motion direction: forward (true) or backward (false). \~ + \param[out] relativeSense - \ru Ориентация поверхности по отношению к операции. + \en The surface orientation relative to the operation. \~ + \param[out] resType - \ru Код результата операции. + \en Operation result code. \~ + \warning \ru Вспомогательная функция операций ExtrusionSolid, RevolutionSolid, ExtrusionResult и RevolutionResult. + \en An auxiliary function of operations ExtrusionSolid, RevolutionSolid, ExtrusionResult and RevolutionResult. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (void) AnalyzeSurfaceRelationToSweptOperation( const MbSurface & cuttingSurface, + const MbCartPoint & imagePosition, + const MbCurve3D & curve, + const MbVector3D & direction, + const MbAxis3D & axis, + const bool rotation, + bool operationDirection, + bool & relativeSense, + MbResultType& resType ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти сегменты контура на поверхности, соответствующие швам и полюсам. + \en Find contour segments corresponding to the seams and poles. \~ + \details \ru Найти сегменты контура на поверхности, соответствующие швам и полюсам. \n + \en Find contour segments corresponding to the seams and poles. \n \~ + \param[in] surface - \ru Поверхность. + \en Surface. \~ + \param[in] contour - \ru Контур. + \en Contour. \~ + \param[out] seamsAndPoles - \ru Номера сегментов, соответствующих швам и полюсам. + \en Segment numbers corresponding to the seams and poles. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (void) FindPolesAndSeamsInContour( const MbSurface & surface, + const MbContour & contour, + c3d::IndicesVector & seamsAndPoles ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело выдавливания. + \en Create an extrusion solid. \~ + \details \ru Создать тело выдавливания. \n + solid1 и solid2 используются с опцией "До ближайших граней" этих тел. \n + \en Create an extrusion solid. \n + solid1 and solid2 are used with option "Up to the closest faces" of these solids. \n \~ + \param[in] sweptData - \ru Данные об образующей кривой. + \en The generating curve data. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in] solid1 - \ru До ближайших граней этого тела в прямом направлении. + \en Up to the closest faces of this solid in the forward direction. \~ + \param[in] solid2 - \ru До ближайших граней этого тела в обратном направлении. + \en Up to the closest faces of this solid in the backward direction. \~ + \param[in] checkIntersection - \ru Объединять тела solid1 и solid2 с проверкой пересечения. + \en Whether to union the solids solid1 and solid2 with the check for intersections. \~ + \param[in, out] params - \ru Параметры выдавливания. + Возвращают информацию для построения элементов массива операций до поверхности. + \en The extrusion parameters. + Returns the information for construction of the up-to-surface operation array elements. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователи сегментов образующего контура. + \en An objects defining a names of the generating contour segments. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtrusionSolid( const MbSweptData & sweptData, + const MbVector3D & direction, + const MbSolid * solid1, + const MbSolid * solid2, + bool checkIntersection, + const ExtrusionValues & params, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело вращения. + \en Create a solid of revolution. \~ + \details \ru Создать тело вращения по данным об образующей. \n + \en Create a solid of revolution by the generating curve data. \n \~ + \param[in] sweptData - \ru Данные об образующей кривой. + \en The generating curve data. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in, out] params - \ru Параметры вращения. + Возвращают информацию для построения элементов массива операций до поверхности. + \en The revolution parameters. + Returns the information for construction of the up-to-surface operation array elements. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователи сегментов образующего контура. + \en An objects defining a names of the generating contour segments. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RevolutionSolid( const MbSweptData & sweptData, + const MbAxis3D & axis, + const RevolutionValues & params, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кинематическое тело. + \en Create a sweeping solid. \~ + \details \ru Создать кинематическое тело путем движения образующей кривой вдоль направляющей кривой. \n + \en Create a sweeping solid by moving the generating curve along the guide curve. \n \~ + \param[in] sweptData - \ru Данные об образующей. + \en The generating curve data. \~ + \param[in] spine - \ru Направляющая кривая. + \en The spine curve. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователь контуров образующей. + \en An object defining the names of generating curve contours. \~ + \param[in] spineNames - \ru Именователь направляющей. + \en An object defining the name of a guide curve. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) EvolutionSolid( const MbSweptData & sweptData, + const MbCurve3D & spine, + const EvolutionValues & params, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + const MbSNameMaker & spineNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кинематическое тело. + \en Create a sweeping solid. \~ + \details \ru Создать кинематическое тело путем движения образующей кривой вдоль направляющей кривой c дополнительной информацией. \n + \en Create a sweeping solid by moving the generating curve along the guide curve with additional data. \n \~ + \param[in] sweptData - \ru Данные об образующей. + \en The generating curve data. \~ + \param[in] spine - \ru Направляющая кривая c дополнительной информацией. + \en The spine curve with additional data. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователь контуров образующей. + \en An object defining the names of generating curve contours. \~ + \param[in] spineNames - \ru Именователь направляющей. + \en An object defining the name of a guide curve. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) EvolutionSolid( const MbSweptData & sweptData, + const MbSpine & spine, + const EvolutionValues & params, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + const MbSNameMaker & spineNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по плоским сечениям. + \en Create a solid from a planar sections. \~ + \details \ru Создать тело по плоским сечениям c направляющей линией. \n + \en Create a solid from a planar sections with a guide curve. \n \~ + \param[in] pl - \ru Множество систем координат образующих контуров. + \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] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. + \en A point array on the generating contours which determines the start points of the contours. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] ns - \ru Именователи образующих контуров. + \en The objects defining the names of generating contours. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, + RPArray & c, + const MbCurve3D * spine, + const LoftedValues & params, + SArray * ps, + const MbSNameMaker & names, + RPArray & ns, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по пространственным сечениям. + \en Create a solid from a space sections. \~ + \details \ru Создать тело по пространственным сечениям c направляющей линией. \n + \en Create a solid from a space sections with a guide curve. \n \~ + \param[in] pl - \ru Множество систем координат образующих контуров. + \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] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. + \en An array of the guide curves that determines the trajectories of the corresponding points of the contours. \~ + \param[in] ps - \ru Множество точек на образующих контурах, задающее соответствующие точки (цепочки точек). + \en A point array on the generating contours which determines the corresponding points of the contours (chains of points). \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] ns - \ru Именователи образующих контуров. + \en The objects defining the names of generating contours. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedSolid( SArray & pl, + RPArray & c, + const MbCurve3D * spine, // осевая линия может быть NULL + const LoftedValues & params, + RPArray * guideCurves, + SArray * ps, + const MbSNameMaker & names, + RPArray & ns, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по пространственным сечениям. + \en Create a solid from a space sections. \~ + \details \ru Создать тело по пространственным сечениям c направляющей линией. \n + \en Create a solid from a space sections with a guide curve. \n \~ + \param[in] surfs - \ru Множество поверхностей образующих контуров. + \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] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] guideCurves - \ru Множество направляющих кривых, задающих траектории соответствующих точек контуров. + \en An array of the guide curves that determines the trajectories of the corresponding points of the contours. \~ + \param[in] ps - \ru Множество точек на образующих контурах, задающее соответствующие точки (цепочки точек). + \en A point array on the generating contours which determines the corresponding points of the contours (chains of points). \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] ns - \ru Именователи образующих контуров. + \en The objects defining the names of generating contours. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedSolid( RPArray & surfs, + RPArray & c, + const MbCurve3D * spine, // осевая линия может быть NULL + const LoftedValues & params, + RPArray * guideCurves, + SArray * ps, + const MbSNameMaker & names, + RPArray & ns, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело выдавливания и выполнить булеву операцию. + \en Create an extrusion solid and perform a boolean operation. \~ + \details \ru Создать тело выдавливания и выполнить булеву операцию типа oType с телом solid. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. + \en Create an extrusion solid and perform a boolean operation of type 'oType' with solid 'solid'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \~ + \param[in] solid - \ru Первое тело для булевой операции. + \en The first solid for a boolean operation. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] sweptData - \ru Данные об образующих кривых. + \en The generating curve data. \~ + \param[in] direction - \ru Направление выдавливания. + \en An extrusion direction. \~ + \param[in, out] params - \ru Параметры выдавливания. + Возвращают информацию для построения элементов массива операций до поверхности. + \en The extrusion parameters. + Returns the information for construction of the up-to-surface operation array elements. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователи образующих кривых. + \en The objects defining the names of generating lines. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtrusionResult( MbSolid & solid, + MbeCopyMode sameShell, + const MbSweptData & sweptData, + const MbVector3D & direction, + const ExtrusionValues & params, + OperationType oType, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело вращения и выполнить булеву операцию. + \en Create a revolution solid and perform a boolean operation. \~ + \details \ru Создать тело вращения и выполнить булеву операцию типа oType с телом solid. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. + \en Create a revolution solid and perform a boolean operation of type oType with solid 'solid'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \~ + \param[in] solid - \ru Первое тело для булевой операции. + \en The first solid for a boolean operation. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] sweptData - \ru Данные об образующих кривых. + \en The generating curve data. \~ + \param[in] axis - \ru Ось вращения. + \en Rotation axis. \~ + \param[in, out] params - \ru Параметры вращения. + Возвращают информацию для построения элементов массива операций до поверхности. + \en The revolution parameters. + Returns the information for construction of the up-to-surface operation array elements. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] contoursNames - \ru Именователи образующих кривых. + \en The objects defining the names of generating lines. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RevolutionResult( MbSolid & solid, + MbeCopyMode sameShell, + const MbSweptData & sweptData, + const MbAxis3D & axis, + const RevolutionValues & params, + OperationType oType, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Сориентировать образующий контур и направляющую кинематики. + \en Determine the orientation for a generating contour and for a guide curve of kinematics (evolution). \~ + \details \ru Выполнить ориентацию образующего контура и направляющей кривой для построения кинематического тела. \n + \en Orientate the generating contour and the guide curve for a sweeping solid construction. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] contours - \ru Образующие контуры. + \en Generating contours. \~ + \param[in] guide - \ru Направляющая кривая. + \en The spine curve. \~ + \param[in] parameters - \ru Параметры операции. + \en The operation parameters. \~ + \param[out] axis - \ru Ось доворота образующей. + \en The axis for the generating curve additional turn. \~ + \param[out] angle - \ru Угол доворота образующей. + \en The additional turn for generating line. \~ + \param[in] version - \ru Версия операции. + \en The version of the operation. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru Вспомогательная функция операций EvolutionSolid и EvolutionResult. + \en An auxiliary function of operations EvolutionSolid and EvolutionResult. \~ + \ingroup Shell_Modeling +*/ +// --- +MATH_FUNC (MbResultType) EvolutionNormalize( const MbSurface & surface, + const RPArray & contours, + const MbCurve3D & guide, + const EvolutionValues & parameters, + MbAxis3D & axis, + double & angle, + VERSION version ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать усеченную замкнутую кривую на копии кривой. + \en Create a trimmed closed curve on a curve copy. \~ + \details \ru Выполнить построение копии замкнутой кривой с началом в точке, определяемой параметром t. \n + \en Create a copy of a closed curve starting at a point with parameter t. \n \~ + \param[in] curve - \ru Направляющая кривая. + \en The spine curve. \~ + \param[in] t - \ru Параметр кривой. + \en A curve parameter. \~ + \return \ru При удачной работе функция возвращает построенную копию кривой + с началом в заданной точке, в противном случае функция возвращает ноль. + \en Returns a constructed curve copy starting at the specified point if it has been successfully created, + otherwise it returns null. \~ + \warning \ru Вспомогательная функция операций EvolutionSolid и EvolutionResult. + \en An auxiliary function of operations EvolutionSolid and EvolutionResult. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCurve3D *) TrimClosedSpine( const MbCurve3D & curve, + double t ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кинематическое тело и выполнить булеву операцию. + \en Create an evolution solid and perform a boolean operation. \~ + \details \ru Создать кинематическое тело и выполнить булеву операцию типа oType с телом solid. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. + \en Create an evolution solid and perform a boolean operation of type oType with solid 'solid'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \~ + \param[in] solid - \ru Первое тело для булевой операции. + \en The first solid for a boolean operation. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] sweptData - \ru Данные об образующей. + \en The generating curve data. \~ + \param[in] spine - \ru Направляющая кривая. + \en The spine curve. \~ + \param[in] params - \ru Параметры кинематической операции. + \en Parameters of the sweeping operation. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] contoursNames - \ru Именователь контуров образующей. + \en An object defining the names of generating curve contours. \~ + \param[in] spineNames - \ru Именователь направляющей. + \en An object defining the name of a guide curve. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC(MbResultType) EvolutionResult( MbSolid & solid, + MbeCopyMode sameShell, + const MbSweptData & sweptData, + const MbCurve3D & spine, + const EvolutionValues & params, + OperationType oType, + const MbSNameMaker & operNames, + const RPArray & contoursNames, + const MbSNameMaker & spineNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по плоским сечениям и выполнить булеву операцию. + \en Create a solid from the planar sections and perform a boolean operation. \~ + \details \ru Создать тело по плоским сечениям и выполнить булеву операцию типа oType с телом solid. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. + \en Create a solid from a planar sections and perform a boolean operation of type oType with solid 'solid'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \~ + \param[in] solid - \ru Первое тело для булевой операции. + \en The first solid for a boolean operation. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] pl - \ru Множество систем координат образующих контуров. + \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] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. + \en A point array on the generating contours which determines the start points of the contours. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] ns - \ru Именователи образующих контуров. + \en The objects defining the names of generating contours. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC(MbResultType) LoftedResult( MbSolid & solid, + MbeCopyMode sameShell, + SArray & pl, + RPArray & c, + const MbCurve3D * spine, + const LoftedValues & params, + OperationType oType, + SArray * ps, + const MbSNameMaker & names, + RPArray & ns, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело по пространственным сечениям и выполнить булеву операцию. + \en Create a solid from the space sections and perform a boolean operation. \~ + \details \ru Создать тело по пространственным сечениям и выполнить булеву операцию типа oType с телом solid. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. + \en Create a solid from a space sections and perform a boolean operation of type oType with solid 'solid'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \~ + \param[in] solid - \ru Первое тело для булевой операции. + \en The first solid for a boolean operation. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] surfs - \ru Множество поверхностей контуров. + \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] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] guideCurves - \ru Массив направляющих кривых. + \en An array of the guide curves. \~ + \param[in] ps - \ru Множество точек на образующих контурах, задающий их начальные точки. + \en A point array on the generating contours which determines the start points of the contours. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] ns - \ru Именователи образующих контуров. + \en The objects defining the names of generating contours. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC(MbResultType) LoftedResult( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & surfs, + RPArray & c, + const MbCurve3D * spine, + const LoftedValues & params, + OperationType oType, + RPArray * guideCurves, + SArray * ps, + const MbSNameMaker & names, + RPArray & ns, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Выполнить булеву операцию. + \en Perform a Boolean operation. \~ + \details \ru Функция выполняет указанную булеву операцию над двумя телами с возможностью управления слиянием граней и рёбер.\n + \en The function performs the specified Boolean operation on two solids with faces and edges merging control.\n \~ + \param[in] solid1 - \ru Набор граней первого тела. + \en The set of faces of the first solid. \~ + \param[in] sameShell1 - \ru Способ копирования граней первого тела. + \en Method of copying the faces of the first solid. \~ + \param[in] solid2 - \ru Набор граней второго тела. + \en The second solid face set. \~ + \param[in] sameShell2 - \ru Способ копирования граней второго тела. + \en Method of copying the faces of the second solid. \~ + \param[in] oType - \ru Тип булевой операции. + \en A Boolean operation type. \~ + \param[in] flags - \ru Управляющие флаги булевой операции. + \en Control flags of the Boolean operation. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] result - \ru Построенный набор граней. + \en Constructed set of faces. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BooleanResult( MbSolid & solid1, + MbeCopyMode sameShell1, + MbSolid & solid2, + MbeCopyMode sameShell2, + OperationType oType, + const MbBooleanFlags & flags, + const MbSNameMaker & operNames, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело путем булевой операции. + \en Create a solid using a boolean operation. \~ + \details \ru Создать тело путем булевой операции типа oType для тел solid1 и solid2. + Принимаемые значения OperationType для тел: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. \n + Функция работает только с замкнутыми телами, сливает подобные грани и рёбра. + Функция выполняет одноимённую булеву операцию над множествами точек, + расположенными внутри и на поверхности тел. + \en Create a solid by applying a boolean operation of type oType to solids 'solid1' and 'solid2'. + The possible values of 'OperationType' for solids: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \n + The function accepts only closed solids, similar faces and similar edges will be merged. + The function performs a boolean operation of the same name with a point sets + located inside the solids and on their boundary. \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] sameShell1 - \ru Режим копирования первого тела. + \en Whether to copy the first solid. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] sameShell2 - \ru Режим копирования второго тела. + \en Whether to copy the second solid. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BooleanSolid( MbSolid & solid1, + MbeCopyMode sameShell1, + MbSolid & solid2, + MbeCopyMode sameShell2, + OperationType oType, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело путем булевой операции. + \en Create a solid using a boolean operation. \~ + \details \ru Создать тело путем булевой операции типа oType для оболочек solid1 и solid2. + Один из операндов solid1 или solid2 - незамкнутая оболочка. + Принимаемые значения OperationType для оболочек: \n + bo_Variety - объединение, \n + bo_Internal - пересечение, \n + bo_External - вычитание. + \en Create a solid applying a boolean operation of type oType to shells 'solid1' and solid2'. + One of the operands 'solid1' and 'solid2' should be an open shell. + Possible values of 'OperationType' for a shells are: \n + bo_Variety - a union, \n + bo_Internal - an intersection, \n + bo_External - a subtraction. \~ + \param[in] solid1 - \ru Первое тело. + \en The first solid. \~ + \param[in] sameShell1 - \ru Режим копирования первого тела. + \en Whether to copy the first solid. \~ + \param[in] solid2 - \ru Второе тело. + \en The second solid. \~ + \param[in] sameShell2 - \ru Режим копирования второго тела. + \en Whether to copy the second solid. \~ + \param[in] oType - \ru Тип булевой операции. + \en A boolean operation type. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BooleanShell( MbSolid & solid1, + MbeCopyMode sameShell1, + MbSolid & solid2, + MbeCopyMode sameShell2, + OperationType oType, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отрезать часть тела поверхностью. + \en Cut a part of a solid off by a surface. \~ + \details \ru Отрезать часть тела пересекающей его поверхностью. \n + retainedPart = 1 - оставляем часть тела, расположенную сверху поверхности. \n + retainedPart = -1 - оставляем часть тела, расположенную снизу поверхности. \n + \en Cut a part of a solid off by a surface that intersects the solid. \n + retainedPart = 1 - a part of solid above the surface is to be retained. \n + retainedPart = -1 - a part of solid below the surface is to be retained. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the source solid. \~ + \param[in] surface - \ru Секущая поверхность. + \en A cutting plane. \~ + \param[in] retainedPart - \ru Направление отсечения. + \en The direction of cutting off. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] closed - \ru Флаг режима отсечения: true - сечем как тело, false - сечем как оболочку. + \en The flag of the cutting off mode: true - cut as a solid, false - cut as a shell. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, + MbeCopyMode sameShell, + const MbSurface & surface, + int retainedPart, + const MbSNameMaker & names, + bool closed, + const MbMergingFlags & flags, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отрезать часть тела выдавленным плоским контуром. + \en Cut a part of a solid off with an extruded planar contour. \~ + \details \ru Отрезать часть тела оболочкой, полученной выдавливанием плоского контура. \n + retainedPart = 1 - оставляем часть тела, расположенную сверху поверхности выдавливания. \n + retainedPart = -1 - оставляем часть тела, расположенную снизу поверхности выдавливания. \n + \en Cut a part of a solid by a shell of planar contour extrusion. \n + retainedPart = 1 - a part of solid above the extrusion surface is to be retained. \n + retainedPart = -1 - a part of solid below the extrusion surface is to be retained. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] place - \ru Система координат образующего контура. + \en The generating contour coordinate system. \~ + \param[in] contour - \ru Образующий контур. + \en The generating contour. \~ + \param[in] direction - \ru Направление выдавливания образующего контура. + \en An extrusion direction of the generating contour. \~ + \param[in] retainedPart - \ru Направление отсечения. + \en The direction of cutting off. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] closed - \ru Флаг режим отсечения: true - сечем как тело, false - сечем как оболочку. + \en The cutting off mode flag: true - cut as a solid, false - cut as a shell. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbContour & contour, + const MbVector3D & direction, + int retainedPart, + const MbSNameMaker & names, + bool closed, + const MbMergingFlags & flags, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разрезать тело поверхностью. + \en Cut a solid off by a surface. \~ + \details \ru Разрезать тело поверхностью с построением всех отрезанных частей. \n + \en Cut a solid off by a surface, keep all parts of the solid. \n + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. + \en Whether to copy the source solid. Built bodies can not move relative to each other when sameShell != Vm_Copy. \~ + \param[in] surface - \ru Секущая поверхность. + \en A cutting plane. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] closed - \ru Флаг режима отсечения: true - сечем как тело, false - сечем как оболочку. + \en The flag of the cutting off mode: true - cut as a solid, false - cut as a shell. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] result - \ru Построенные тела. + \en The resultant solids. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, + MbeCopyMode sameShell, + const MbSurface & surface, + const MbSNameMaker & names, + bool closed, + const MbMergingFlags & flags, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разрезать тело выдавленным плоским контуром. + \en Cut a solid off with an extruded planar contour. \~ + \details \ru Разрезать тело оболочкой, полученной выдавливанием плоского контура, с построением всех отрезанных частей. \n + \en Cut a solid by a shell of planar contour extrusion, keep all parts of the solid. \n + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. При sameShell != cm_Copy построенные тела нельзя перемещать относительно друг друга. + \en Whether to copy the source solid. Built bodies can not move relative to each other when sameShell != Vm_Copy. \~ + \param[in] place - \ru Система координат образующего контура. + \en The generating contour coordinate system. \~ + \param[in] contour - \ru Образующий контур. + \en The generating contour. \~ + \param[in] direction - \ru Направление выдавливания образующего контура. + \en An extrusion direction of the generating contour. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] closed - \ru Флаг режим отсечения: true - сечем как тело, false - сечем как оболочку. + \en The cutting off mode flag: true - cut as a solid, false - cut as a shell. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] result - \ru Построенные тела. + \en The resultant solids. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +DEPRECATE_DECLARE +MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbContour & contour, + const MbVector3D & direction, + const MbSNameMaker & names, + bool closed, + const MbMergingFlags & flags, + RPArray & result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разрезать тело на части. + \en Cut a solid into parts. \~ + \details \ru Разрезать тело на части. \n + \en Cut a solid into parts. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования исходного тела. + \en The mode of copying of the source solid. \~ + \param[in] cuttingParams - \ru Параметры операции. + \en Operation parameters. \~ + \param[out] results - \ru Построенные тела. + \en The resultant solids. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SolidCutting( MbSolid & solid, + MbeCopyMode sameShell, + const MbShellCuttingParams & cuttingParams, + RPArray & results ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать симметричное тело относительно плоскости. + \en Create a symmetric solid relative to a plane. \~ + \details \ru Создать симметричное тело относительно плоскости XY локальной системы координат. \n + Функция создаёт симметричное тело с заданной плоскостью симметрии следующим образом. + Исходное тело режется плоскостью XY локальной системы координат, берётся часть исходного тела, + расположенная сверху режущей плоскости, строится зеркальная копия выбранной части исходного тела + и объединяется с выбранной частью исходного тела. \n + \en Crate a symmetric solid relative to XY-plane of a local coordinate system. \n + The function creates a symmetric solid with the specified plane of symmetry in the following way. + The source solid is cut off by the plane XY of the local coordinate system; a part of the source solid above the cutting plane + is retained. A mirror copy of the chosen part is created + and then is united with the chosen part of the source solid. \n \~ + \param[in] solid - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования оболочки. + \en Whether to copy the shell. \~ + \param[in] place - \ru Система координат плоскости симметрии. + \en The symmetry plane coordinate system. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SymmetrySolid( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать зеркальную копию тела относительно плоскости. + \en Create a mirror copy of a solid relative to a plane. \~ + \details \ru Создать зеркальную копию тела относительно плоскости XY локальной системы координат. \n + \en Create a mirror copy of a solid relative to the XY-plane of a local coordinate system. \n \~ + \param[in] solid - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] place - \ru Система координат плоскости симметрии. + \en The symmetry plane coordinate system. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) MirrorSolid( const MbSolid & solid, + const MbPlacement3D & place, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тело с ребром жёсткости. + \en Create a solid with a rib. \~ + \details \ru Создать тело с ребром жёсткости. \n + По заданному контуру функция строит ребро жёсткости и объединяет его с исходным телом. + Сегмент контура с указанным номером устанавливает вектор уклона. \n + \en Create a solid with a rib. \n + The function creates a rib from a given contour and unites it with the source solid. + The segment of the contour with the given number determines the slope vector. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] place - \ru Система координат образующего контура. + \en The generating contour coordinate system. \~ + \param[in] contour - \ru Формообразующий контур на плоскости XY системы координат place. + \en The generating contour on XY-plane of coordinate system 'place'. \~ + \param[in] index - \ru Номер сегмента в контуре. + \en The segment number in the contour. \~ + \param[in] pars - \ru Параметры ребра жёсткости. + \en Parameters of a rib. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RibSolid( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbContour & contour, + size_t index, + RibValues & pars, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать отдельное ребро жёсткости. + \en Create a separate rib. \~ + \details \ru Создать отдельное ребро жёсткости для исходного тела без приклеивания. \n + \en Create a separate rib for source solid without gluing. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] place - \ru Система координат образующего контура. + \en The generating contour coordinate system. \~ + \param[in] contour - \ru Образующий контур. + \en The generating contour. \~ + \param[in] index - \ru Номер сегмента в контуре. + \en The segment number in the contour. \~ + \param[in] pars - \ru Параметры ребра жёсткости. + \en Parameters of a rib. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RibElement( const MbSolid & solid, + const MbPlacement3D & place, + MbContour & contour, + size_t index, + RibValues & pars, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скруглить ребра постоянным радиусом. + \en Fillet edges with a constant radius. \~ + \details \ru Скруглить указанные рёбра тела постоянным радиусом. \n + Функция выполняет замену указанных рёбер исходного тела гранями, + гладко сопрягающими смежные грани указанных рёбер. В поперечном сечении + сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. \n + \en Fillet the specified edges of the solid with a constant radius. \n + The function performs the replacement of the specified edges of the source solid by faces + smoothly connecting the adjacent faces of the specified edges. The cross-section + of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] initCurves - \ru Множество скругляемых ребер тела. + \en A set of edges of the solid to fillet. \~ + \param[in] initBounds - \ru Множество граней для обрезки торцов. + \en A set of faces for trimming of the butt-ends. \~ + \param[in] params - \ru Параметры скругления рёбер. + \en Parameters of edges fillet. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & initCurves, + RPArray & initBounds, + const SmoothValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скруглить ребра переменным радиусом. + \en Fillet edges with a variable radius. \~ + \details \ru Скруглить указанные ребра тела переменным радиусом, задаваемым MbEdgeFunction.function. \n + Функция выполняет замену указанных рёбер исходного тела гранями, + гладко сопрягающими смежные грани указанных рёбер. В поперечном сечении + сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. + Параметры поперечного сечения могут изменяться по заданному закону. \n + \en Fillet the given edges of the solid with a variable radius specified by MbEdgeFunction.function. \n + The function performs the replacement of the specified edges of the source solid by faces + smoothly connecting the adjacent faces of the specified edges. The cross-section + of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. + The parameters of the cross-section can vary by the specified law. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] initCurves - \ru Множество скругляемых ребер тела с функциями изменения радиуса. + \en An array of edges of the solid to fillet together with the radius laws. \~ + \param[in] initBounds - \ru Множество граней для обрезки торцов. + \en A set of faces for trimming of the butt-ends. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, + MbeCopyMode sameShell, + SArray & initCurves, + RPArray & initBounds, + const SmoothValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скруглить вершины и примыкающие к ней рёбра постоянным радиусом. + \en Create fillets on vertices and the edges adjacent to these vertices with a constant radius. \~ + \details \ru Скруглить вершины и примыкающие к ней рёбра тела постоянным радиусом. \n + В вершинах должно стыковаться три ребра. + Функция выполняет замену указанных вершин и рёбер исходного тела гранями, + гладко сопрягающими смежные грани указанных вершин и рёбер. В поперечном сечении + сопрягающие грани могут иметь форму дуги окружности, эллипса, гиперболы, параболы. \n + \en Create fillets on vertices and the edges of the solid adjacent to these vertices with a constant radius. \n + Three edges must be incident to each vertex. + The functions performs replacement of the specified vertices and edges of the source solid by faces of the solid + smoothly connecting the faces adjacent to the specified vertices and edges. The cross-section + of the connecting faces can be of the form of a circle, an ellipse, a hyperbola or a parabola. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] initCurves - \ru Множество скругляемых ребер тела. + \en A set of edges of the solid to fillet. \~ + \param[in] initBounds - \ru Множество граней для обрезки торцев. + \en A set of faces for trimming of the butt-ends. \~ + \param[in] initVertices - \ru Множество скругляемых вершин. + \en A set of vertices to fillet. \~ + \param[in] params - \ru Параметры скругления рёбер. + \en Parameters of edges fillet. \~ + \param[in] cornerData - \ru Параметры скругления вершин. + \en Parameters of vertices fillet. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FilletSolid( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & initCurves, + RPArray & initBounds, + RPArray & initVertices, + const SmoothValues & params, + const CornerValues & cornerData, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Скруглить цепочку граней тела. + \en Create a fillet of faces of the solid. \~ + \details \ru Скруглить указанные грани тела. \n + Функция выполняет замену указанных граней исходного тела гранями, + гладко сопрягающими грани, связанные с указанными гранью. + В поперечном сечении сопрягающие грани имеют форму + дуги окружности, касающейся трёх граней исходного тела. \n + \en Create a fillet on the specified faces of the solid. \n + The function performs replacement of the specified faces of the source solid with faces + smoothly connecting the faces adjacent to the specified faces. + The cross-section of the connecting faces has a form of + a circle arc tangent to three faces of the source solid. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] initFaces - \ru Набор граней для скругления. + \en A set of faces to fillet. \~ + \param[in] initFacesLeft - \ru Набор ограничивающих слева граней. + \en A set of left bounding faces. \~ + \param[in] initFacesRight - \ru Набор ограничивающих справа граней. + \en A set of right bounding faces. \~ + \param[in] params - \ru Параметры скругления. + \en Parameters of fillet. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FullFilletSolid( MbSolid & solid, + MbeCopyMode sameShell, + const RPArray & initFaces, + const RPArray & initFacesLeft, + const RPArray & initFacesRight, + const FullFilletValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить фаски ребер тела. + \en Create chamfers for edges of the solid. \~ + \details \ru Построить фаски указанных ребер тела. \n + Функция выполняет замену указанных рёбер исходного тела гранями фасок. \n + \en Create chamfers for the specified edges of the solid. \n + The function performs replacement of the specified edges of the source solid with faces of chamfers. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] initCurves - \ru Множество скругляемых ребер тела. + \en An array of edges to create chamfer on. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ChamferSolid( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & initCurves, + const SmoothValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантное тело. + \en Create а equidistant solid. \~ + \details \ru Создать эквидистантное тело или оболочку. \n + \en Create an offset solid by equidistant faces or create an equidistant shell. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] offset - \ru Расстояние смещения граней. + \en The equidistant parameter. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetSolid( MbSolid & solid, + MbeCopyMode sameShell, + double offset, + const MbSNameMaker & names, + MbSolid *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тонкостенное тело исключением граней. + \en Create a thin-walled solid by exclusion of faces. \~ + \details \ru Создать тонкостенное тело исключением граней outFaces \n + и приданием одинаковой толщины оставшимся граням \n + или создание незамкнутой оболочки. \n + \en Create a thin-walled solid by exclusion of faces outFaces \n + and supplying the rest of faces with the same thickness \n + or create an open shell. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] outFaces - \ru Вскрываемые грани тела. + \en Faces of the solid to open. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. + \en Copy attributes of initial faces to offset faces. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ThinSolid( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & outFaces, + SweptValues & params, + const MbSNameMaker & names, + bool copyFaceAttrs, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать тонкостенное тело исключением граней. + \en Create a thin-walled solid by exclusion of faces. \~ + \details \ru Создать тонкостенное тело исключением граней outFaces \n + и приданием различной толщины оставшимся граням \n + или создание незамкнутой оболочки. \n + \en Create a thin-walled solid by exclusion of faces outFaces \n + and supplying the rest of faces with different thickness \n + or create an open shell. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] outFaces - \ru Вскрываемые грани тела. + \en Faces of the solid to open. \~ + \param[in] offFaces - \ru Множество граней, для которых заданы индивидуальные значения толщин. + \en An array of faces for which the individual values of thickness are specified. \~ + \param[in] offDists - \ru Множество индивидуальных значений толщин (должен быть синхронизирован с массивом offFaces). + \en An array of individual values of thickness (must be synchronized with the array 'offFaces'). \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] copyFaceAttrs - \ru Копировать атрибуты из исходных граней в эквидистантные. + \en Copy attributes of initial faces to offset faces. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ThinSolid( MbSolid & solid, + MbeCopyMode sameShell, + RPArray & outFaces, + RPArray & offFaces, + SArray & offDists, + SweptValues & params, + const MbSNameMaker & names, + bool copyFaceAttrs, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Выполнить разбиение граней оболочки. + \en Perform splitting of a shell faces. \~ + \details \ru Выполнить разбиение граней оболочки поверхностями выдавливания контуров. \n + Функция создаёт копию тела и разбивает указанные грани поверхностями выдавливания контуров. \n + \en Perform splitting of a shell faces with surfaces of the contours extrusion. \n + The function creates a copy of a solid and splits the specified faces with surfaces of the contours extrusion. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] spPlace - \ru Система координат контуров. + \en The coordinate system of the contours. \~ + \param[in] spType - \ru Направление вытягивания. + \en The extrusion direction. \~ + \param[in] spContours - \ru Контура разбиения. + \en The contours of splitting. \~ + \param[in] spSame - \ru Использовать оригиналы или копии кривых. + \en Whether to use the originals or copies of curves. \~ + \param[in] selFaces - \ru Выбранные грани входного тела. + \en The chosen faces of the input solid. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplitSolid( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & spPlace, + MbeSenseValue spType, + const RPArray & spContours, + bool spSame, + RPArray & selFaces, + const MbMergingFlags & flags, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Выполнить разбиение граней оболочки. + \en Perform splitting of a shell faces. \~ + \details \ru Выполнить разбиение граней оболочки пространственными кривыми, поверхностями и оболочками. \n + Функция создаёт копию тела и разбивает указанные грани пространственными кривыми, поверхностями и оболочками. \n + Пространственные элементы разбиения не должны иметь полных или частичных наложений, а также - самопересечений. \n + \en Perform splitting of the shell faces with space curves, surfaces and shells. \n + The function creates a copy of the solid and splits the specified faces with space curves, surfaces and shells. \n + The spatial elements of a splitting must not have complete or partial overlaps, and also self-intersections. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] spItems - \ru Пространственные элементы разбиения. + \en A spatial elements of splitting. \~ + \param[in] spSame - \ru Использовать оригиналы или копии кривых. + \en Whether to use the originals or copies of curves. \~ + \param[in] selFaces - \ru Выбранные грани входного тела. + \en The chosen faces of the input solid. \~ + \param[in] flags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplitSolid( MbSolid & solid, + MbeCopyMode sameShell, + const RPArray & spItems, + bool spSame, + RPArray & selFaces, + const MbMergingFlags & flags, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Уклонить указанные грани тела. + \en Slope the specified faces of the solid. \~ + \details \ru Уклонить указанные грани тела от нейтральной изоплоскости на заданный угол. \n + \en Slope the specified faces of the solid at the specified angle relative to the neutral isoplane. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования входного тела. + \en Whether to copy the input solid. \~ + \param[in] neutralPlace - \ru Нейтральная плоскость. + \en The neutral plane. \~ + \param[in] angle - \ru Угол уклона. + \en The slope angle. \~ + \param[in] faces - \ru Уклоняемые грани во входном теле. + \en The faces of input solid to be sloped. \~ + \param[in] fp - \ru Признак захвата граней, гладко стыкующихся с уклоняемыми гранями. + \en Whether to capture the faces smoothly connected with the faces being sloped. \~ + \param[in] reverse - \ru Флаг обратного направления уклона. + \en Whether to slope in the reverse direction. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) DraftSolid( MbSolid & solid, + MbeCopyMode sameShell, + const MbPlacement3D & neutralPlace, + double angle, + const RPArray & faces, + MbeFacePropagation fp, + bool reverse, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Выполнить объединение пересекающихся тел. + \en Perform the union of intersecting solids. \~ + \details \ru Выполнить объединение пересекающихся тел и булеву операцию oType с телом solid, если оно не нулевое: \n + bo_Union - объединение, \n + bo_Intersect - пересечение, \n + bo_Difference - вычитание. \n + Если флаг проверки пересечения checkIntersect == true, то выполняется проверка на пересечение тел + и булева операция объединения пересекающихся тел заданного множества в одно тело. В противном случае + объединение тел заданного множества выполняется простым перекладыванием граней всех тел в одно новое тело. \n + Если флаг регулярности множества тел isArray == true, то тела множества расположены в узлах + прямоугольной или круговой сетки и позиции тел заданы в именах граней. \n + \en Perform the union of intersecting solids and a boolean operation oType with solid 'solid' if it is not null: \n + bo_Union - union, \n + bo_Intersect - intersection, \n + bo_Difference - subtraction. \n + If the flag of intersection check checkIntersect == true, check for solids intersection is performed + and the boolean operation of union the intersection solids of the specified set into one solid is performed. Otherwise + the union of solids from the given set is performed by simple moving the faces of all the solids into a new solid. \n + If the flag of solid set regularity isArray == true, the solids are located at the nodes + of rectangular or circular grid and positions of solids are specified in the names of faces. \n \~ + \param[in] solid - \ru Тело. + \en A solid. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] solids - \ru Множество тел. + \en An array of solids. \~ + \param[in] sameShells - \ru Режим копирования тел. + \en Whether to copy the solids. \~ + \param[in] oType - \ru Тип булевой операции между телом и массивом тел. + \en The type of the boolean operation for the solid and the set of solids. \~ + \param[in] checkIntersect - \ru Проверять пересечение тел. + \en Whether to check the solids intersection. \~ + \param[in] mergeFaces - \ru Управляющие флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] isArray - \ru Флаг регулярности множества тел. + \en A flag of solid set regularity. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \param[out] notGluedSolids - \ru Множество тел, которые не получилось приклеить. + \en An array of solids which was not glued. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) UnionResult( MbSolid * solid, + MbeCopyMode sameShell, + RPArray & solids, + MbeCopyMode sameShells, + OperationType oType, + bool checkIntersect, + const MbMergingFlags & mergeFlags, + const MbSNameMaker & names, + bool isArray, + MbSolid *& result, + RPArray * notGluedSolids = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать одно тело из присланных тел. + \en Create a solid from the specified solids. \~ + \details \ru Создать тело с объединением или без объединения пересекающихся тел. \n + Если флаг проверки пересечения checkIntersect == true, то выполняется проверка на пересечение тел + и булева операция объединения пересекающихся тел заданного множества в одно тело. В противном случае + объединение тел заданного множества выполняется простым перекладыванием граней всех тел в одно новое тело. \n + Если флаг регулярности множества тел isArray == true, то тела множества расположены в узлах + прямоугольной или круговой сетки и позиции тел заданы в именах граней. \n + \en Create a solid with or without union of the intersecting solids. \n + If the flag of intersection check checkIntersect == true, check for solids intersection is performed + and the boolean operation of union the intersection solids of the specified set into one solid is performed. Otherwise + the union of solids from the given set is performed by simple moving the faces of all the solids into a new solid. \n + If the flag of solid set regularity isArray == true, the solids are located at the nodes + of rectangular or circular grid and positions of solids are specified in the names of faces. \n \~ + \param[in] solids - \ru Множество тел. + \en An array of solids. \~ + \param[in] sameShells - \ru Режим копирования тел. + \en Whether to copy the solids. \~ + \param[in] checkIntersect - \ru Проверять пересечение тел. + \en Whether to check the solids intersection. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] isArray - \ru Флаг регулярности множества тел. + \en A flag of solid set regularity. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \param[out] notGluedSolids - \ru Множество тел, которые не получилось приклеить. + \en An array of solids which was not glued. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) UnionSolid( RPArray & solids, + MbeCopyMode sameShells, + bool checkIntersect, + const MbSNameMaker & names, + bool isArray, + MbSolid *& result, + RPArray * notGluedSolids = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать одно тело из присланных тел. + \en Create a solid from the specified solids. \~ + \details \ru Создать одно тело из присланных тел, не меняя их. \n + Объединение тел заданного множества выполняется простым перекладыванием + граней всех тел в одно новое тело. \n + \en Create a solid from the specified solids without the modification of the given solids. \n + The union of solids from the specified set is performed by simple moving + the faces of all the solids into a new solid. \n \~ + \param[in] solids - \ru Множество тел. + \en An array of solids. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) UnionSolid( const RPArray & solids, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разделить тело на отдельные части. + \en Split the solid into separate parts. \~ + \details \ru Если исходное тело распадается на части, то наибольшая часть остаётся в исходном теле, + а остальные части части будут сложены в присланный контейнер тел. \n + Если флаг сортировки sort == true, то в исходном теле останется часть с наибольшим габаритом, + а отделённые части будут сортированы по убыванию габарита. В противном случае в исходном теле + останется часть, топологически связанная с первой гранью, а отделённые части будут сортированы + по номеру начальной грани в исходном теле. \n + \en If the source solid is decomposed, the greatest part remains in the source solid, + and the other parts are put into the given array of solids. \n + If 'sort' == 'true', the part with the greatest bounding box will remain in the source solid, + and separated parts will be sorted by bounding box size in descending order. Otherwise a part topologically connected with the first face will remain in the source solid + and the separated parts will be sorted + by the number of the initial face in the source solid. \n \~ + \param[in,out] solid - \ru Исходное модифицируемое тело. + \en The source solid to be modified. \~ + \param[out] parts - \ru Отделённые части тела. + \en The separated parts of the solid. \~ + \param[in] sort - \ru Сортировать по убыванию габарита. + \en Whether to sort by the bounding box size in descending order. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \return \ru Возвращает количество отделенных частей. + \en Returns the number of the separated parts. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (size_t) DetachParts( MbSolid & solid, + RPArray & parts, + bool sort, + const MbSNameMaker & names ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Разделить тело на отдельные части. + \en Split the solid into separate parts. \~ + \details \ru Если исходное тело распадается на части, то все его части будут сложены в присланный контейнер тел. \n + Исходное тело остаётся неизменённым. \n + \en If the source solid is decomposed, all the parts of the solid will be put into the given array of solids. \n + The source solid remains unchanged. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[out] parts - \ru Части тела. + \en The parts of the solid. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \return \ru Возвращает количество созданных частей. + \en Returns the number of created parts. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (size_t) CreateParts( const MbSolid & solid, + RPArray & parts, + const MbSNameMaker & names ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку тела по поверхности и толщине. + \en Create a shell of the solid from a surface and a thickness. \~ + \details \ru Выполнить построение тела путём придания толщины заданной поверхности. \n + \en Create a solid by supplying the surface with a thickness. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] faceSense - \ru Ориентация нормали поверхности. + \en The surface normal orientation. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] name - \ru Основное простое имя. + \en The main simple name. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ThinSolid( const MbSurface & surface, + bool faceSense, + SweptValues & params, + const MbSNameMaker & names, + SimpleName name, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \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 \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Режим копирования тела. + \en Whether to copy the solid. \~ + \param[in] place - \ru Местная система координат для операции. + \en A local coordinate system for the operation. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) HoleSolid( MbSolid * solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const HoleValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Выделить в отдельное тело указанную часть распадающегося на части тела. + \en Extract the specified part of decomposing solid to a separate solid. \~ + \details \ru Создать тело, из указанной части тела, распадающегося на части. + Исходное тело должно состоять из отдельных частей. \n + \en Create a solid from the specified part of decomposing solid. + The source solid should consist of separate parts. \n \~ + \param[in] solid - \ru Разделяемое на части тело. + \en A decomposing solid. \~ + \param[in] id - \ru Номер выбранной части тела + \en The number of selected part of the solid. \~ + \param[in] path - \ru Идентификатор для выбранной части. + \en An identifier for the selected part. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in,out] partIndices - \ru Индексы частей тела. + \en Indices of the parts of the solid. \~ + \param[out] result - \ru Построенная оболочка (тело). + \en The resultant shell (solid). \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ShellPart( const MbSolid & solid, + size_t id, + const MbPath & path, + const MbSNameMaker & names, + MbPartSolidIndices & partIndices, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Размножить тело. + \en Duplicate the solid. \~ + \details \ru Размножить тело согласно параметрам и объединить копии в одно тело.\n + \en Duplicate the solid by the parameters and unite copies in one solid. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] params - \ru Параметры размножения. + \en The parameters of duplication. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] result - \ru Результирующее тело. + \en The result solid. \~ + \return \ru Возвращает код результата операции. + \en . \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) DuplicationSolid( const MbSolid & solid, + const DuplicationValues & params, + const MbSNameMaker & names, + MbSolid *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать одно тело слиток из присланных объектов. + \en Create an ingot solid from the specified objects. \~ + \details \ru Создать одно тело слиток из присланных объектов. \n + Среди присланных объектов используются тела, вставки тел и сборки тел, из которых строится одно тело, + которое по внешности совпадает с присланными телами и служит их упрощенным заменителем по внешним параметрам. \n + \en Create an ingot solid from the specified solids without the modification of the given solids. \n + Among the objects sent using the body, insert bodies and assembling bodies of which is built the same body, + which in appearance coincides with the bodies had been sent and serves as a substitute for their simplistic external parameters. \n \~ + \param[in] solids - \ru Множество тел. + \en An array of solids. \~ + \param[in] names - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] makeCopy - \ru Флаг копирования тел перед использованием: true - копировать, false - не копировать. + \en The flag of the copying solid before using: true - copy solid, false - not copy. \~ + \param[out] result - \ru Построенное тело. + \en The resultant solid. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Solid_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IngotSolid( RPArray & solids, + bool makeCopy, + const MbSNameMaker & names, + MbSolid *& result ); + + +#endif // __ACTION_SOLID_H diff --git a/C3d/Include/action_surface.h b/C3d/Include/action_surface.h index f8b285c..5cf68da 100644 --- a/C3d/Include/action_surface.h +++ b/C3d/Include/action_surface.h @@ -1,798 +1,865 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения поверхностей. - \en Functions for surfaces creation. \~ - \details \ru Поверхности являются основным элементом описания формы моделируемых объектов. - На базе поверхностей строятся грани, которые используются в твёрдых телах. - \en Surfaces is a basic element of the modeled objects shape description. - Faces are constructed on the basis of surfaces and then are used in solid solids. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_SURFACE_H -#define __ACTION_SURFACE_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbSurfaceCurve; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbGrid; -class MATH_CLASS MbRegion; - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать элементарную поверхность. - \en Create an elementary surface. \~ - \details \ru Создать одну из элементарных поверхностей по трем управляющим точкам и типу: \n - surfaceType == st_Plane - плоскость \n - surfaceType == st_ConeSurface - коническая поверхность \n - surfaceType == st_CylinderSurface - цилиндрическая поверхность \n - surfaceType == st_SphereSurface - сферическая поверхность \n - surfaceType == st_TorusSurface - поверхность тора \n - \en Create one of elementary surfaces from three points and a type: \n - surfaceType == st_Plane - a plane \n - surfaceType == st_ConeSurface - a conical surface \n - surfaceType == st_CylinderSurface - a cylindrical surface \n - surfaceType == st_SphereSurface - a spherical surface \n - surfaceType == st_TorusSurface - a torus surface \n \~ - \param[in] point0 - \ru Точка, определяющая начало локальной системы координат поверхности. - \en The origin of the surface local coordinate system. \~ - \param[in] point1 - \ru Точка, определяющая направление оси X локальной системы и радиус поверхности. - \en A point specifying the direction of X-axis of the local system and the surface radius. \~ - \param[in] point2 - \ru Точка, определяющая направление оси Y локальной системы. - \en A point specifying the direction of Y-axis of the local system. \~ - \param[in] surfaceType - \ru Тип поверхности. - \en The surface type. \~ - \param[out] result - \ru Построенная поверхность. - \en The constructed surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ElementarySurface( const MbCartPoint3D & point0, - const MbCartPoint3D & point1, - const MbCartPoint3D & point2, - MbeSpaceType surfaceType, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать плоскую NURBS - поверхность. - \en Create a planar NURBS - surface. \~ - \details \ru Создать плоскую NURBS - поверхность по угловым точкам. \n - \en Create a planar NURBS - surface given the corner points. \n \~ - \param[in] pUMinVMin - \ru Угловая точка поверхности. - \en A corner point of a surface. \~ - \param[in] pUMaxVMin - \ru Угловая точка поверхности. - \en A corner point of a surface. \~ - \param[in] pUMaxVMax - \ru Угловая точка поверхности. - \en A corner point of a surface. \~ - \param[in] pUMinVMax - \ru Угловая точка поверхности. - \en A corner point of a surface. \~ - \param[in] uCount - \ru Количество точек по U. - \en A number of points by U direction. \~ - \param[in] vCount - \ru Количество точек по V. - \en A number of points by V direction. \~ - \param[in] uDegree - \ru Порядок сплайнов по U. - \en Splines degree by U. \~ - \param[in] vDegree - \ru Порядок сплайнов по V. - \en Splines degree by V. \~ - \param[out] result - \ru Cплайновая поверхность. - \en The spline surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplineSurface( const MbCartPoint3D & pUMinVMin, const MbCartPoint3D & pUMaxVMin, - const MbCartPoint3D & pUMaxVMax, const MbCartPoint3D & pUMinVMax, - size_t uCount, size_t vCount, - size_t uDegree, size_t vDegree, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать NURBS - поверхность. - \en Create a NURBS - surface. \~ - \details \ru Создать NURBS - поверхность по массивам точек и весов. \n - контейнер weightList может быть пустым. \n - контейнер uKnotList может быть пустым. \n - контейнер vKnotList может быть пустым. \n - \en Create a NURBS - surface given arrays of points and weights. \n - container 'weightList' can be empty. \n - container 'uKnotList' can be empty. \n - container 'vKnotList' can be empty. \n \~ - \param[in] pointList - \ru Множество точек. - \en An array of points. \~ - \param[in] weightList - \ru Множество весов - \en An array of weights. \~ - \param[in] uCount - \ru Размерность массива точек по U. - \en The size of point array by U. \~ - \param[in] vCount - \ru Размерность массива точек по V. - \en The size of point array by V. \~ - \param[in] uDegree - \ru Порядок сплайнов по U. - \en Splines degree by U. \~ - \param[in] uKnotList - \ru Узловой вектор по U. - \en A knot vector by U. \~ - \param[in] uClosed - \ru Замкнутость по U. - \en Closedness by U. \~ - \param[in] vDegree - \ru Порядок сплайнов по V. - \en Splines degree by V. \~ - \param[in] vKnotList - \ru Узловой вектор по V. - \en A knot vector by V. \~ - \param[in] vClosed - \ru Замкнутость по V. - \en Closedness by V. \~ - \param[out] result - \ru Cплайновая поверхность. - \en The spline surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SplineSurface( const SArray & pointList, - const SArray & weightList, - size_t uCount, size_t vCount, - size_t uDegree, const SArray & uKnotList, bool uClosed, - size_t vDegree, const SArray & vKnotList, bool vClosed, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность выдавливания. - \en Create an extrusion surface. \~ - \details \ru Создать поверхность выдавливания кривой. \n - \en Create a surface of a curve extrusion. \n \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] direction - \ru Вектор выдавливания. - \en An extrusion vector. \~ - \param[in] simplify - \ru Упрощать поверхность, если возможно. - \en Simplify a surface if it's possible. \~ - \param[out] result - \ru Поверхность выдавливания. - \en An extrusion surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtrusionSurface( MbCurve3D & curve, const MbVector3D & direction, - bool simplify, MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность вращения. - \en Create a revolution surface. \~ - \details \ru Создать поверхность вращения кривой. \n - \en Create a curve revolution surface. \n \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] origin - \ru Точка положения оси вращения. - \en The rotation axis origin. \~ - \param[in] axis - \ru Направление оси вращения. - \en The rotation axis direction. \~ - \param[in] angle - \ru Угол вращения. - \en A rotation angle. \~ - \param[in] simplify - \ru Упрощать поверхность, если возможно. - \en Simplify a surface if it's possible. \~ - \param[out] result - \ru Поверхность вращения. - \en The revolution surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RevolutionSurface( MbCurve3D & curve, const MbCartPoint3D & origin, const MbVector3D & axis, double angle, - bool simplify, MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность движения. - \en Create an expansion surface. \~ - \details \ru Создать поверхность движения кривой. \n - \en Create a surface of a curve sweeping. \n \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] spine - \ru Направляющая кривая. - \en The spine curve. \~ - \param[out] result - \ru Поверхность движения с доворотами. - \en The expansion surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExpansionSurface( MbCurve3D & curve, MbCurve3D & spine, - MbCurve3D * curve1, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кинематическую поверхность. - \en Create an evolution surface. \~ - \details \ru Создать кинематическую поверхность по образующей и направляющей. \n - В случае, если spine имеет тип st_ConeSpiral, результатом построения - является спиральная поверхность. \n - \en Create an evolution surface from the generating curve and the guide curve. \n - If 'spine' has type st_ConeSpiral, the result of the construction - is a spiral surface. \n \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] spine - \ru Направляющая кривая. - \en The spine curve. \~ - \param[out] result - \ru Кинематическая поверхность или спиральная поверхность. - \en The evolution surface or a spiral surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) EvolutionSurface( MbCurve3D & curve, MbCurve3D & spine, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать спиральную поверхность. - \en Create a spiral surface. \~ - \details \ru Создать спиральную поверхность по образующей и 3 точкам. \n - \en Create a spiral surface from a generating line and three points. \n \~ - \param[in] curve - \ru Образующая кривая спирали. - \en The generating curve of a spiral. \~ - \param[in] p0 - \ru Начало локальной системы координат (ЛСК). - \en The origin of local coordinate system (LCS). \~ - \param[in] p1 - \ru Точка для формирования оси Z ЛСК. - \en A point specifying Z-axis of LCS. \~ - \param[in] p2 - \ru Точка для формирования оси X ЛСК. - \en A point specifying X-axis of LCS. \~ - \param[in] step - \ru Шаг спирали. - \en A pitch. \~ - \param[out] result - \ru Спиральная поверхность. - \en A spiral surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SpiralSurface( MbCurve3D & curve, - const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, - double step, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать секториальную поверхность. - \en Create a sectorial surface. \~ - \details \ru Создать секториальную поверхность по кривой и точке. \n - \en Create a sectorial surface from a curve and a point. \n \~ - \param[in] curve - \ru Образующая кривая. - \en The generating curve. \~ - \param[in] point - \ru Точка. - \en A point. \~ - \param[out] result - \ru Линейчатая поверхность в виде сектора. - \en The ruled surface in a form of a sector. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SectorSurface( MbCurve3D & curve, const MbCartPoint3D & point, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать линейчатую поверхность. - \en Create a ruled surface. \~ - \details \ru Создать линейчатую поверхность по двум кривым. \n - \en Create a ruled surface from two curves. \n \~ - \param[in] curve1 - \ru Первая образующая кривая. - \en The first generating curve. \~ - \param[in] curve2 - \ru Вторая образующая кривая. - \en The second generating curve. \~ - \param[in] simplify - \ru Упрощать поверхность, если возможно. - \en Simplify a surface if it's possible. \~ - \param[out] result - \ru Линейчатая поверхность. - \en The ruled surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) RuledSurface( MbCurve3D & curve1, MbCurve3D & curve2, - bool simplify, MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать треугольную поверхность. - \en Create a triangular surface. \~ - \details \ru Создать треугольную поверхность по трем кривым. \n - \en Create a triangular surface from three curves. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[in] curve3 - \ru Третья кривая. - \en The third curve. \~ - \param[out] result - \ru Треугольная поверхность по трём кривым. - \en The triangular surface by three curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CornerSurface( MbCurve3D & curve1, - MbCurve3D & curve2, - MbCurve3D & curve3, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать билинейную поверхность. - \en Create a bilinear surface. \~ - \details \ru Создать билинейную поверхность по четырем кривым. \n - \en Create a bilinear surface from four curves. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[in] curve3 - \ru Третья кривая. - \en The third curve. \~ - \param[in] curve4 - \ru Четвертая кривая. - \en The fourth curve. \~ - \param[out] result - \ru Билинейная поверхность по четырём кривым. - \en The bilinear surface from four curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CoverSurface( MbCurve3D & curve1, - MbCurve3D & curve2, - MbCurve3D & curve3, - MbCurve3D & curve4, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность по семейству кривых. - \en Create a surface by a set of curves. \~ - \details \ru Создать поверхность по семейству кривых. \n - begDirection направление в начале поверхности может быть нулевой длины. \n - endDirection направление в конце поверхности может быть нулевой длины. \n - \en Create a surface by a set of curves. \n - begDirection direction at the begining of the surface can be of zero length. \n - endDirection direction at the end of the surface can be of zero length. \n \~ - \param[in] curveList - \ru Семейство образующих кривых вдоль U-направления. - \en A set of generating curves along U direction. \~ - \param[in] closed - \ru Замкнутость вдоль V-направления. - \en Closedness by V direction. \~ - \param[in] begDirection - \ru Вектор направления в начале поверхности. - \en The vector of direction at the beginning of the surface. \~ - \param[in] endDirection - \ru Вектор направления в конце поверхности. - \en The vector of direction at the end of the surface. \~ - \param[out] result - \ru Поверхность по семейству кривых. - \en The surface from the set of curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, bool closed, - const MbVector3D & begDirection, const MbVector3D & endDirection, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность по семейству кривых и направляющей. - \en Create a surface from a set of curves and a spine curve. \~ - \details \ru Создать поверхность по семейству кривых и направляющей. \n - \en Create a surface from a set of curves and a spine curve. \n \~ - \param[in] curveList - \ru Семейство образующих кривых вдоль U-направления. - \en A set of generating curves along U direction. \~ - \param[in] spine - \ru Направляющая кривая. - \en The spine curve. \~ - \param[out] result - \ru Поверхность по семейству кривых и направляющей. - \en The surface from a set of curves and a spine curve. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, - MbCurve3D & spine, - MbSurface *& result, - bool isSimToEvol = true ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность на сетке кривых. - \en Create a surface constructed by the grid curves. \~ - \details \ru Создать поверхность на сетке кривых по двум семействам кривых. \n - \en Create a surface constructed by the grid curves given two sets of curves. \n \~ - \param[in] uCurveList - \ru Семейство кривых вдоль U-направления. - \en A curve set along U direction. \~ - \param[in] vCurveList - \ru Семейство кривых вдоль V-направления. - \en A curve set along V direction. \~ - \param[out] result - \ru Поверхность на сетке кривых. - \en The surface constructed by the grid curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) MeshSurface( const RPArray & uCurveList, - const RPArray & vCurveList, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантную поверхность. - \en Create an offset surface. \~ - \details \ru Создать эквидистантную поверхность к исходной поверхности. \n - \en Create an offset surface to a given surface. \n \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] distance - \ru Величина эквидистанты (знаковая). - \en The offset distance (signed). \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \param[out] result - \ru Эквидистантная поверхность. - \en The offset surface. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, - double distance, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантную поверхность. - \en Create an offset surface. \~ - \details \ru Создать эквидистантную поверхность по исходной поверхности. \n - \en Create an offset surface from the initial surface. \n \~ - \param[in] surface - \ru Базовая поверхность. - \en The base surface. \~ - \param[in] offsetUminVmin - \ru Смещение в точке Umin Vmin базовой поверхности. - \en Offset distance on point Umin Vmin of base surface. \~ - \param[in] offsetUmaxVmin - \ru Смещение в точке Umax Vmin базовой поверхности. - \en Offset distance on point Umax Vmin of base surface. \~ - \param[in] offsetUminVmax - \ru Смещение в точке Umin Vmax базовой поверхности. - \en Offset distance on point Umin Vmax of base surface. \~ - \param[in] offsetUmaxVmax - \ru Смещение в точке Umax Vmax базовой поверхности. - \en Offset distance on point Umax Vmax of base surface. \~ - \param[in] type - \ru Тип смещения точек: константный, линейный или кубический. - \en The offset type: constant, or linear, or cubic. \~ - \param[out] result - \ru Эквидистантная поверхность. - \en The offset surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, - double offsetUminVmin, - double offsetUmaxVmin, - double offsetUminVmax, - double offsetUmaxVmax, - MbeOffsetType type, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать продленную поверхность. - \en Create an extended surface. \~ - \details \ru Создать продленную поверхность по исходной поверхности. \n - \en Create an extended surface from the initial surface. \n \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] uMin - \ru Минимальное значение по U. - \en The minimal parameter value by U. \~ - \param[in] uMax - \ru Максимальное значение по U. - \en The maximal parameter value by U. \~ - \param[in] vMin - \ru Минимальное значение по V. - \en The minimal parameter value by V. \~ - \param[in] vMax - \ru Максимальное значение по V. - \en The maximal parameter value by V. \~ - \param[out] result - \ru Продлённая поверхность. - \en The extended surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ExtendedSurface( MbSurface & surface, - double uMin, - double uMax, - double vMin, - double vMax, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать деформированную поверхность. - \en Create a deformed surface. \~ - \details \ru Создать деформированную поверхность по исходной поверхности. \n - \en Create a deformed surface from the initial surface. \n \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] uCount - \ru Количество точек по U. - \en A number of points by U direction. \~ - \param[in] vCount - \ru Количество точек по V. - \en A number of points by V direction. \~ - \param[in] uDegree - \ru Порядок сплайнов по U. - \en Splines degree by U. \~ - \param[in] vDegree - \ru Порядок сплайнов по V. - \en Splines degree by V. \~ - \param[in] dist - \ru Величина сдвига вдоль нормали. - \en Shift along the normal. \~ - \param[out] result - \ru Деформированная поверхность. - \en The deformed surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) DeformedSurface( MbSurface & surface, - size_t uCount, size_t vCount, - size_t uDegree, size_t vDegree, - double dist, - MbSurface *& result); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность с заданной границей. - \en Create a surface with the given boundary. \~ - \details \ru Создать поверхность с заданной границей по массиву двумерных кривых. \n - Контейнер boundList может быть пустым. \n - \en Create a surface with the given boundary from an array of two-dimensional curves. \n - Container 'boundList' can be empty. \n \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] boundList - \ru Множество двумерных границ в виде кривых (первая кривая - внешний контур). - \en An array of two-dimensional boundaries in the form of curves (the first curve is an outer contour). \~ - \param[out] result - \ru Поверхность, ограниченная кривыми. - \en The surface bounded by the curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BoundedSurface( MbSurface & surface, - const RPArray & boundList, - MbSurface *& result ); - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность с заданной границей. - \en Create a surface with the given boundary. \~ - \details \ru Создать поверхность с заданной границей по массиву двумерных контуров. \n - \en Create a surface with the given boundary from an array of two-dimensional curves. \n \~ - \param[in] place - \ru Локальная система координат плоскости. - \en The local coordinate system of a plane. \~ - \param[in] region - \ru Множество двумерных границ в виде региона (первая контур - внешний). - \en An array of two-dimensional boundaries in the form of region (the first contour is outer). \~ - \param[out] result - \ru Поверхность, ограниченная кривыми. - \en The surface bounded by the curves. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BoundedSurface( const MbPlacement3D & place, const MbRegion & region, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать NURBS копию поверхности, ограниченную двумерными границами. - \en Create a NURBS surface copy with two-dimensional boundaries. \~ - \details \ru Создать NURBS копию поверхности, ограниченную двумерными границами проецированием пространственных границ \n - (предполагается, что пространственные граничные кривые лежат на поверхности). \n - \en Create a NURBS surface copy with two-dimensional boundaries by projecting of the spatial boundaries \n - (the boundary space curves are considered to belong to the surface) \n \~ - \param[in] surf - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] version - \ru Версия исполнения. - \en The version. \~ - \param[out] resSurface - \ru Сплайновая поверхность (ограниченная кривыми). - \en The spline surface (bounded by the curves). \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) NurbsSurface( const MbSurface & surf, VERSION version, MbSurface *& resSurface ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность симплексного сплайна. - \en Create a simplex spline surface. \~ - \details \ru Создать поверхность симплексного сплайна по массиву вершин. \n - \en Create a simplex spline surface from a point array. \n \~ - \param[in] pList - \ru Множество вершин. - \en An array of points. \~ - \param[out] resSurface - \ru Поверхность симплексного сплайна. - \en The simplex spline surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) SimplexSplineSurface( SArray & pList, MbSurface *& resSurface ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать треугольную поверхность Безье. - \en Create a triangular Bezier surface. \~ - \details \ru Создать треугольную поверхность Безье по 3 точкам. \n - \en Create a triangular Bezier surface from three points. \n \~ - \param[in] k - \ru Порядок поверхности. - \en The surface order. \~ - \param[in] p1 - \ru Первая точка. - \en The first point. \~ - \param[in] p2 - \ru Вторая точка. - \en The second point. \~ - \param[in] p3 - \ru Третья точка. - \en The third point. \~ - \param[out] resSurface - \ru Треугольная поверхность Безье. - \en The triangular Bezier surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) TriBezierSurface( ptrdiff_t k, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3, - MbSurface *& resSurface ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать треугольную В-сплайн поверхность. - \en Create a triangular B-spline surface. \~ - \details \ru Создать треугольную В-сплайн поверхность по 3 точкам. \n - \en Create a triangular B-spline surface from three points. \n \~ - \param[in] p0 - \ru Первая точка. - \en The first point. \~ - \param[in] p1 - \ru Вторая точка. - \en The second point. \~ - \param[in] p2 - \ru Третья точка. - \en The third point. \~ - \param[in] d - \ru Порядок поверхности. - \en The surface order. \~ - \param[out] resSurface - \ru Треугольная В-сплайн поверхность. - \en The triangular B-spline surface. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) TriSplineSurface( const MbCartPoint3D & p0, - const MbCartPoint3D & p1, - const MbCartPoint3D & p2, - const MbCartPoint3D & p3, - ptrdiff_t d, ptrdiff_t count, - MbSurface *& resSurface ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить характеристическую ломаную сплайновой поверхности. - \en Create a characteristic polyline of a spline surface. \~ - \details \ru Построить характеристическую ломаную сплайновой поверхности. \n - Функция работает с поверхностями типа st_SplineSurface, st_HermitSurface, - st_TriBezierSurface, st_TriSplineSurface. \n - \en Create a characteristic polyline of a spline surface. \n - The function accepts the surfaces of types st_SplineSurface, st_HermitSurface, - st_TriBezierSurface, st_TriSplineSurface. \n \~ - \param[in] surf - \ru Поверхность. - \en The surface. \~ - \param[out] segments - \ru Сегменты характеристической ломаной. - \en The characteristic polyline. \~ - \result \ru Возвращает true - если характеристическая ломаная получена. - \en Returns true - if the characteristic polyline is obtained. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) GetLineSegmentNURBSSurface( MbSurface & surf, RPArray & segments ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создание поверхности на сетке точек. - \en Create a surface from a points grid. \~ - \details \ru Создание поверхности на сетке точек и триангуляции. \n - Множество треугольников должен представлять собой правильную триангуляцию. - \en Create a surface from a points grid and triangulation. \n - The triangles array should form a regular triangulation. \~ - \param[in] grid - \ru Триангуляция. - \en A triangulation. \~ - \param[out] result - \ru Поверхность на сетке точек. - \en The surface on a point set. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) GridSurface( MbGrid & grid, MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать средние плоскости. - \en Create median planes. \~ - \details \ru Создать средние плоскости по двум кривым.\n - \en Create median planes from two curves.\n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] places - \ru Набор систем координат, задающих плоскости. - \en The set of coordinate systems which determine the planes. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \warning \ru В разработке. - \en Under development. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) MiddlePlaces( const MbCurve3D & curve1, - const MbCurve3D & curve2, - std::vector & places ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построение поверхности Кунса. - \en Construction of a Coons surface. \~ - \details \ru Построение бикубической поверхности Кунса на четырех кривых и их поперечных производных, касательной к четырём кривым на прверхностях. \n - \en The construction of Coons surface, which will be tangent to four surfaces and coincide with four curves on this surfaces on it sides.\n \~ - \param[in] surfaceCurve0 - \ru Кривая на поверхности 0. - \en The curve on surface0. \~ - \param[in] surfaceCurve1 - \ru Кривая на поверхности 1. - \en The curve on surface1. \~ - \param[in] surfaceCurve2 - \ru Кривая на поверхности 2. - \en The curve on surface2. \~ - \param[in] surfaceCurve3 - \ru Кривая на поверхности 3. - \en The curve on surface3. \~ - \param[out] result - \ru Построенная поверхность. - \en The constructed surface. \~ - \result \ru Возвращает код результата построения. - \en Returns operation result code. \~ - \warning \ru В разработке. - \en Under development. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateCoonsSurface( const MbSurfaceCurve & surfaceCurve0, - const MbSurfaceCurve & surfaceCurve1, - const MbSurfaceCurve & surfaceCurve2, - const MbSurfaceCurve & surfaceCurve3, - MbSurface *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построение поверхности-заплатки для заданных рёбер. - \en Construction of a surface-patch by the edges. \~ - \details \ru Построение поверхности-заплатки, гладко стыкующейся с поверхностями ребер. \n - \en Construction of a surface-patch, smoothly joining with the surfaces of the edges. \n \~ - \param[in] edges - \ru Ребра, с которыми требуется стыковать новую поверхность. - \en Edges to join the new surface. \~ - \param[out] result - \ru Построенные поверхности. - \en The constructed surfaces. \~ - \result \ru Возвращает код результата построения. - \en Returns operation result code. \~ - \warning \ru В разработке. - \en Under development. \~ - \ingroup Surface_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateSplinePatch( const std::vector & edges, - std::vector & result ); - - -#endif // __ACTION_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы построения поверхностей. + \en Functions for surfaces creation. \~ + \details \ru Поверхности являются основным элементом описания формы моделируемых объектов. + На базе поверхностей строятся грани, которые используются в твёрдых телах. + \en Surfaces is a basic element of the modeled objects shape description. + Faces are constructed on the basis of surfaces and then are used in solid solids. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_SURFACE_H +#define __ACTION_SURFACE_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbSurfaceCurve; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFunction; +class MATH_CLASS MbGrid; +class MATH_CLASS MbRegion; + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать элементарную поверхность. + \en Create an elementary surface. \~ + \details \ru Создать одну из элементарных поверхностей по трем управляющим точкам и типу: \n + surfaceType == st_Plane - плоскость \n + surfaceType == st_ConeSurface - коническая поверхность \n + surfaceType == st_CylinderSurface - цилиндрическая поверхность \n + surfaceType == st_SphereSurface - сферическая поверхность \n + surfaceType == st_TorusSurface - поверхность тора \n + \en Create one of elementary surfaces from three points and a type: \n + surfaceType == st_Plane - a plane \n + surfaceType == st_ConeSurface - a conical surface \n + surfaceType == st_CylinderSurface - a cylindrical surface \n + surfaceType == st_SphereSurface - a spherical surface \n + surfaceType == st_TorusSurface - a torus surface \n \~ + \param[in] point0 - \ru Точка, определяющая начало локальной системы координат поверхности. + \en The origin of the surface local coordinate system. \~ + \param[in] point1 - \ru Точка, определяющая направление оси X локальной системы и радиус поверхности. + \en A point specifying the direction of X-axis of the local system and the surface radius. \~ + \param[in] point2 - \ru Точка, определяющая направление оси Y локальной системы. + \en A point specifying the direction of Y-axis of the local system. \~ + \param[in] surfaceType - \ru Тип поверхности. + \en The surface type. \~ + \param[out] result - \ru Построенная поверхность. + \en The constructed surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ElementarySurface( const MbCartPoint3D & point0, + const MbCartPoint3D & point1, + const MbCartPoint3D & point2, + MbeSpaceType surfaceType, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать плоскую NURBS - поверхность. + \en Create a planar NURBS - surface. \~ + \details \ru Создать плоскую NURBS - поверхность по угловым точкам. \n + \en Create a planar NURBS - surface given the corner points. \n \~ + \param[in] pUMinVMin - \ru Угловая точка поверхности. + \en A corner point of a surface. \~ + \param[in] pUMaxVMin - \ru Угловая точка поверхности. + \en A corner point of a surface. \~ + \param[in] pUMaxVMax - \ru Угловая точка поверхности. + \en A corner point of a surface. \~ + \param[in] pUMinVMax - \ru Угловая точка поверхности. + \en A corner point of a surface. \~ + \param[in] uCount - \ru Количество точек по U. + \en A number of points by U direction. \~ + \param[in] vCount - \ru Количество точек по V. + \en A number of points by V direction. \~ + \param[in] uDegree - \ru Порядок сплайнов по U. + \en Splines degree by U. \~ + \param[in] vDegree - \ru Порядок сплайнов по V. + \en Splines degree by V. \~ + \param[out] result - \ru Cплайновая поверхность. + \en The spline surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplineSurface( const MbCartPoint3D & pUMinVMin, const MbCartPoint3D & pUMaxVMin, + const MbCartPoint3D & pUMaxVMax, const MbCartPoint3D & pUMinVMax, + size_t uCount, size_t vCount, + size_t uDegree, size_t vDegree, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать NURBS - поверхность. + \en Create a NURBS - surface. \~ + \details \ru Создать NURBS - поверхность по массивам точек и весов. \n + контейнер weightList может быть пустым. \n + контейнер uKnotList может быть пустым. \n + контейнер vKnotList может быть пустым. \n + \en Create a NURBS - surface given arrays of points and weights. \n + container 'weightList' can be empty. \n + container 'uKnotList' can be empty. \n + container 'vKnotList' can be empty. \n \~ + \param[in] pointList - \ru Множество точек. + \en An array of points. \~ + \param[in] weightList - \ru Множество весов + \en An array of weights. \~ + \param[in] uCount - \ru Размерность массива точек по U. + \en The size of point array by U. \~ + \param[in] vCount - \ru Размерность массива точек по V. + \en The size of point array by V. \~ + \param[in] uDegree - \ru Порядок сплайнов по U. + \en Splines degree by U. \~ + \param[in] uKnotList - \ru Узловой вектор по U. + \en A knot vector by U. \~ + \param[in] uClosed - \ru Замкнутость по U. + \en Closedness by U. \~ + \param[in] vDegree - \ru Порядок сплайнов по V. + \en Splines degree by V. \~ + \param[in] vKnotList - \ru Узловой вектор по V. + \en A knot vector by V. \~ + \param[in] vClosed - \ru Замкнутость по V. + \en Closedness by V. \~ + \param[out] result - \ru Cплайновая поверхность. + \en The spline surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SplineSurface( const SArray & pointList, + const SArray & weightList, + size_t uCount, size_t vCount, + size_t uDegree, const SArray & uKnotList, bool uClosed, + size_t vDegree, const SArray & vKnotList, bool vClosed, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность выдавливания. + \en Create an extrusion surface. \~ + \details \ru Создать поверхность выдавливания кривой. \n + \en Create a surface of a curve extrusion. \n \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] direction - \ru Вектор выдавливания. + \en An extrusion vector. \~ + \param[in] simplify - \ru Упрощать поверхность, если возможно. + \en Simplify a surface if it's possible. \~ + \param[out] result - \ru Поверхность выдавливания. + \en An extrusion surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtrusionSurface( MbCurve3D & curve, const MbVector3D & direction, + bool simplify, MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность вращения. + \en Create a revolution surface. \~ + \details \ru Создать поверхность вращения кривой. \n + \en Create a curve revolution surface. \n \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] origin - \ru Точка положения оси вращения. + \en The rotation axis origin. \~ + \param[in] axis - \ru Направление оси вращения. + \en The rotation axis direction. \~ + \param[in] angle - \ru Угол вращения. + \en A rotation angle. \~ + \param[in] simplify - \ru Упрощать поверхность, если возможно. + \en Simplify a surface if it's possible. \~ + \param[out] result - \ru Поверхность вращения. + \en The revolution surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RevolutionSurface( MbCurve3D & curve, const MbCartPoint3D & origin, const MbVector3D & axis, double angle, + bool simplify, MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность движения. + \en Create an expansion surface. \~ + \details \ru Создать поверхность движения кривой. \n + \en Create a surface of a curve sweeping. \n \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] spine - \ru Направляющая кривая. + \en The spine curve. \~ + \param[out] result - \ru Поверхность движения с доворотами. + \en The expansion surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExpansionSurface( MbCurve3D & curve, MbCurve3D & spine, + MbCurve3D * curve1, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кинематическую поверхность. + \en Create an evolution surface. \~ + \details \ru Создать кинематическую поверхность по образующей и направляющей. \n + В случае, если spine имеет тип st_ConeSpiral, результатом построения + является спиральная поверхность. \n + \en Create an evolution surface from the generating curve and the guide curve. \n + If 'spine' has type st_ConeSpiral, the result of the construction + is a spiral surface. \n \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] spine - \ru Направляющая кривая. + \en The spine curve. \~ + \param[out] result - \ru Кинематическая поверхность или спиральная поверхность. + \en The evolution surface or a spiral surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) EvolutionSurface( const MbCurve3D & curve, + const MbCurve3D & spine, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать спиральную поверхность. + \en Create a spiral surface. \~ + \details \ru Создать спиральную поверхность по образующей и 3 точкам. \n + \en Create a spiral surface from a generating line and three points. \n \~ + \param[in] curve - \ru Образующая кривая спирали. + \en The generating curve of a spiral. \~ + \param[in] sameCurve - \ru Использовать копию образующей кривой, если sameCurve равен false. + \en Use a copy of the generating curve if the flag "sameCurve" is false. \~ + \param[in] p0 - \ru Начало локальной системы координат (ЛСК). + \en The origin of local coordinate system (LCS). \~ + \param[in] p1 - \ru Точка для формирования оси Z ЛСК. + \en A point specifying Z-axis of LCS. \~ + \param[in] p2 - \ru Точка для формирования оси X ЛСК. + \en A point specifying X-axis of LCS. \~ + \param[in] step - \ru Шаг спирали. + \en A pitch. \~ + \param[out] result - \ru Спиральная поверхность. + \en A spiral surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SpiralSurface( const MbCurve3D & curve, + bool sameCurve, + const MbCartPoint3D & p0, + const MbCartPoint3D & p1, + const MbCartPoint3D & p2, + double step, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать секториальную поверхность. + \en Create a sectorial surface. \~ + \details \ru Создать секториальную поверхность по кривой и точке. \n + \en Create a sectorial surface from a curve and a point. \n \~ + \param[in] curve - \ru Образующая кривая. + \en The generating curve. \~ + \param[in] point - \ru Точка. + \en A point. \~ + \param[out] result - \ru Линейчатая поверхность в виде сектора. + \en The ruled surface in a form of a sector. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SectorSurface( const MbCurve3D & curve, + const MbCartPoint3D & point, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать линейчатую поверхность. + \en Create a ruled surface. \~ + \details \ru Создать линейчатую поверхность по двум кривым. \n + \en Create a ruled surface from two curves. \n \~ + \param[in] curve1 - \ru Первая образующая кривая. + \en The first generating curve. \~ + \param[in] curve2 - \ru Вторая образующая кривая. + \en The second generating curve. \~ + \param[in] simplify - \ru Упрощать поверхность, если возможно. + \en Simplify a surface if it's possible. \~ + \param[out] result - \ru Линейчатая поверхность. + \en The ruled surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) RuledSurface( MbCurve3D & curve1, MbCurve3D & curve2, + bool simplify, MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать треугольную поверхность. + \en Create a triangular surface. \~ + \details \ru Создать треугольную поверхность по трем кривым. \n + \en Create a triangular surface from three curves. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[in] curve3 - \ru Третья кривая. + \en The third curve. \~ + \param[out] result - \ru Треугольная поверхность по трём кривым. + \en The triangular surface by three curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CornerSurface( MbCurve3D & curve1, + MbCurve3D & curve2, + MbCurve3D & curve3, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать билинейную поверхность. + \en Create a bilinear surface. \~ + \details \ru Создать билинейную поверхность по четырем кривым. \n + \en Create a bilinear surface from four curves. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[in] curve3 - \ru Третья кривая. + \en The third curve. \~ + \param[in] curve4 - \ru Четвертая кривая. + \en The fourth curve. \~ + \param[out] result - \ru Билинейная поверхность по четырём кривым. + \en The bilinear surface from four curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CoverSurface( MbCurve3D & curve1, + MbCurve3D & curve2, + MbCurve3D & curve3, + MbCurve3D & curve4, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность по семейству кривых. + \en Create a surface by a set of curves. \~ + \details \ru Создать поверхность по семейству кривых. \n + begDirection направление в начале поверхности может быть нулевой длины. \n + endDirection направление в конце поверхности может быть нулевой длины. \n + \en Create a surface by a set of curves. \n + begDirection direction at the begining of the surface can be of zero length. \n + endDirection direction at the end of the surface can be of zero length. \n \~ + \param[in] curveList - \ru Семейство образующих кривых вдоль U-направления. + \en A set of generating curves along U direction. \~ + \param[in] closed - \ru Замкнутость вдоль V-направления. + \en Closedness by V direction. \~ + \param[in] begDirection - \ru Вектор направления в начале поверхности. + \en The vector of direction at the beginning of the surface. \~ + \param[in] endDirection - \ru Вектор направления в конце поверхности. + \en The vector of direction at the end of the surface. \~ + \param[out] result - \ru Поверхность по семейству кривых. + \en The surface from the set of curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, bool closed, + const MbVector3D & begDirection, const MbVector3D & endDirection, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность по семейству кривых и направляющей. + \en Create a surface from a set of curves and a spine curve. \~ + \details \ru Создать поверхность по семейству кривых и направляющей. \n + \en Create a surface from a set of curves and a spine curve. \n \~ + \param[in] curveList - \ru Семейство образующих кривых вдоль U-направления. + \en A set of generating curves along U direction. \~ + \param[in] spine - \ru Направляющая кривая. + \en The spine curve. \~ + \param[out] result - \ru Поверхность по семейству кривых и направляющей. + \en The surface from a set of curves and a spine curve. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) LoftedSurface( const RPArray & curveList, + MbCurve3D & spine, + MbSurface *& result, + bool isSimToEvol = true ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность на сетке кривых. + \en Create a surface constructed by the grid curves. \~ + \details \ru Создать поверхность на сетке кривых по двум семействам кривых. \n + \en Create a surface constructed by the grid curves given two sets of curves. \n \~ + \param[in] uCurveList - \ru Семейство кривых вдоль U-направления. + \en A curve set along U direction. \~ + \param[in] vCurveList - \ru Семейство кривых вдоль V-направления. + \en A curve set along V direction. \~ + \param[out] result - \ru Поверхность на сетке кривых. + \en The surface constructed by the grid curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) MeshSurface( const RPArray & uCurveList, + const RPArray & vCurveList, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную поверхность. + \en Create an offset surface. \~ + \details \ru Создать эквидистантную поверхность к исходной поверхности. \n + \en Create an offset surface to a given surface. \n \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] distance - \ru Величина эквидистанты (знаковая). + \en The offset distance (signed). \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \param[out] result - \ru Эквидистантная поверхность. + \en The offset surface. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, + double distance, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную поверхность. + \en Create an offset surface. \~ + \details \ru Создать эквидистантную поверхность по исходной поверхности. \n + \en Create an offset surface from the initial surface. \n \~ + \param[in] surface - \ru Базовая поверхность. + \en The base surface. \~ + \param[in] offsetUminVmin - \ru Смещение в точке Umin Vmin базовой поверхности. + \en Offset distance on point Umin Vmin of base surface. \~ + \param[in] offsetUmaxVmin - \ru Смещение в точке Umax Vmin базовой поверхности. + \en Offset distance on point Umax Vmin of base surface. \~ + \param[in] offsetUminVmax - \ru Смещение в точке Umin Vmax базовой поверхности. + \en Offset distance on point Umin Vmax of base surface. \~ + \param[in] offsetUmaxVmax - \ru Смещение в точке Umax Vmax базовой поверхности. + \en Offset distance on point Umax Vmax of base surface. \~ + \param[in] type - \ru Тип смещения точек: константный, линейный или кубический. + \en The offset type: constant, or linear, or cubic. \~ + \param[out] result - \ru Эквидистантная поверхность. + \en The offset surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetSurface( MbSurface & surface, + double offsetUminVmin, + double offsetUmaxVmin, + double offsetUminVmax, + double offsetUmaxVmax, + MbeOffsetType type, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать продленную поверхность. + \en Create an extended surface. \~ + \details \ru Создать продленную поверхность по исходной поверхности. \n + \en Create an extended surface from the initial surface. \n \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] uMin - \ru Минимальное значение по U. + \en The minimal parameter value by U. \~ + \param[in] uMax - \ru Максимальное значение по U. + \en The maximal parameter value by U. \~ + \param[in] vMin - \ru Минимальное значение по V. + \en The minimal parameter value by V. \~ + \param[in] vMax - \ru Максимальное значение по V. + \en The maximal parameter value by V. \~ + \param[out] result - \ru Продлённая поверхность. + \en The extended surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ExtendedSurface( MbSurface & surface, + double uMin, + double uMax, + double vMin, + double vMax, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать деформированную поверхность. + \en Create a deformed surface. \~ + \details \ru Создать деформированную поверхность по исходной поверхности. \n + \en Create a deformed surface from the initial surface. \n \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] uCount - \ru Количество точек по U. + \en A number of points by U direction. \~ + \param[in] vCount - \ru Количество точек по V. + \en A number of points by V direction. \~ + \param[in] uDegree - \ru Порядок сплайнов по U. + \en Splines degree by U. \~ + \param[in] vDegree - \ru Порядок сплайнов по V. + \en Splines degree by V. \~ + \param[in] dist - \ru Величина сдвига вдоль нормали. + \en Shift along the normal. \~ + \param[out] result - \ru Деформированная поверхность. + \en The deformed surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) DeformedSurface( MbSurface & surface, + size_t uCount, size_t vCount, + size_t uDegree, size_t vDegree, + double dist, + MbSurface *& result); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность с заданной границей. + \en Create a surface with the given boundary. \~ + \details \ru Создать поверхность с заданной границей по массиву двумерных кривых. \n + Контейнер boundList может быть пустым. \n + \en Create a surface with the given boundary from an array of two-dimensional curves. \n + Container 'boundList' can be empty. \n \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] boundList - \ru Множество двумерных границ в виде кривых (первая кривая - внешний контур). + \en An array of two-dimensional boundaries in the form of curves (the first curve is an outer contour). \~ + \param[out] result - \ru Поверхность, ограниченная кривыми. + \en The surface bounded by the curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BoundedSurface( MbSurface & surface, + const RPArray & boundList, + MbSurface *& result ); + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность с заданной границей. + \en Create a surface with the given boundary. \~ + \details \ru Создать поверхность с заданной границей по массиву двумерных контуров. \n + \en Create a surface with the given boundary from an array of two-dimensional curves. \n \~ + \param[in] place - \ru Локальная система координат плоскости. + \en The local coordinate system of a plane. \~ + \param[in] region - \ru Множество двумерных границ в виде региона (первая контур - внешний). + \en An array of two-dimensional boundaries in the form of region (the first contour is outer). \~ + \param[out] result - \ru Поверхность, ограниченная кривыми. + \en The surface bounded by the curves. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BoundedSurface( const MbPlacement3D & place, const MbRegion & region, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать NURBS копию поверхности, ограниченную двумерными границами. + \en Create a NURBS surface copy with two-dimensional boundaries. \~ + \details \ru Создать NURBS копию поверхности, ограниченную двумерными границами проецированием пространственных границ \n + (предполагается, что пространственные граничные кривые лежат на поверхности). \n + \en Create a NURBS surface copy with two-dimensional boundaries by projecting of the spatial boundaries \n + (the boundary space curves are considered to belong to the surface) \n \~ + \param[in] surf - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[out] resSurface - \ru Сплайновая поверхность (ограниченная кривыми). + \en The spline surface (bounded by the curves). \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) NurbsSurface( const MbSurface & surf, VERSION version, MbSurface *& resSurface ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность симплексного сплайна. + \en Create a simplex spline surface. \~ + \details \ru Создать поверхность симплексного сплайна по массиву вершин. \n + \en Create a simplex spline surface from a point array. \n \~ + \param[in] pList - \ru Множество вершин. + \en An array of points. \~ + \param[out] resSurface - \ru Поверхность симплексного сплайна. + \en The simplex spline surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SimplexSplineSurface( SArray & pList, MbSurface *& resSurface ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать треугольную поверхность Безье. + \en Create a triangular Bezier surface. \~ + \details \ru Создать треугольную поверхность Безье по 3 точкам. \n + \en Create a triangular Bezier surface from three points. \n \~ + \param[in] k - \ru Порядок поверхности. + \en The surface order. \~ + \param[in] p1 - \ru Первая точка. + \en The first point. \~ + \param[in] p2 - \ru Вторая точка. + \en The second point. \~ + \param[in] p3 - \ru Третья точка. + \en The third point. \~ + \param[out] resSurface - \ru Треугольная поверхность Безье. + \en The triangular Bezier surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) TriBezierSurface( ptrdiff_t k, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3, + MbSurface *& resSurface ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать треугольную В-сплайн поверхность. + \en Create a triangular B-spline surface. \~ + \details \ru Создать треугольную В-сплайн поверхность по 3 точкам. \n + \en Create a triangular B-spline surface from three points. \n \~ + \param[in] p0 - \ru Первая точка. + \en The first point. \~ + \param[in] p1 - \ru Вторая точка. + \en The second point. \~ + \param[in] p2 - \ru Третья точка. + \en The third point. \~ + \param[in] d - \ru Порядок поверхности. + \en The surface order. \~ + \param[out] resSurface - \ru Треугольная В-сплайн поверхность. + \en The triangular B-spline surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) TriSplineSurface( const MbCartPoint3D & p0, + const MbCartPoint3D & p1, + const MbCartPoint3D & p2, + const MbCartPoint3D & p3, + ptrdiff_t d, ptrdiff_t count, + MbSurface *& resSurface ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить характеристическую ломаную сплайновой поверхности. + \en Create a characteristic polyline of a spline surface. \~ + \details \ru Построить характеристическую ломаную сплайновой поверхности. \n + Функция работает с поверхностями типа st_SplineSurface, st_HermitSurface, + st_TriBezierSurface, st_TriSplineSurface. \n + \en Create a characteristic polyline of a spline surface. \n + The function accepts the surfaces of types st_SplineSurface, st_HermitSurface, + st_TriBezierSurface, st_TriSplineSurface. \n \~ + \param[in] surf - \ru Поверхность. + \en The surface. \~ + \param[out] segments - \ru Сегменты характеристической ломаной. + \en The characteristic polyline. \~ + \result \ru Возвращает true - если характеристическая ломаная получена. + \en Returns true - if the characteristic polyline is obtained. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) GetLineSegmentNURBSSurface( MbSurface & surf, RPArray & segments ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создание поверхности на сетке точек. + \en Create a surface from a points grid. \~ + \details \ru Создание поверхности на сетке точек и триангуляции. \n + Множество треугольников должен представлять собой правильную триангуляцию. + \en Create a surface from a points grid and triangulation. \n + The triangles array should form a regular triangulation. \~ + \param[in] grid - \ru Триангуляция. + \en A triangulation. \~ + \param[out] result - \ru Поверхность на сетке точек. + \en The surface on a point set. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) GridSurface( MbGrid & grid, MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать средние плоскости. + \en Create median planes. \~ + \details \ru Создать средние плоскости по двум кривым.\n + \en Create median planes from two curves.\n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] places - \ru Набор систем координат, задающих плоскости. + \en The set of coordinate systems which determine the planes. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) MiddlePlaces( const MbCurve3D & curve1, + const MbCurve3D & curve2, + std::vector & places ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение поверхности переменного сечения. + \en Construction of a swept section surface. \~ + \details \ru Поверхность переменного (конического) сечения образуется путем движения плоской кривой, являющейся коническим сечением, вдоль опорной кривой. + В процессе движения форма плоской кривой меняется в соответствии с дискриминантом конического сечения. + Начало плоской кривой располагается на начальной направляющей кривой, а конец - на конечной направляющей кривой. + Плоскость переменного сечения сохраняет ортогональность опорной кривой в процессе движения. + \en The swept (conic) 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 swept section preserves the orthogonality to the reference curve during movement. \~ + \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] form - \ru Форма сечения поверхности (0, 1, 2, 3). + \en The form of the surface section (0, 1, 2, 3). \~ + \param[in] sense - \ru Направление нормали поверхности направляющей кривой (для guide1==guide2). + \en The normal direction of guide curve surface (for guide1==guide2). \~ + \param[in] uBeg - \ru Минимальное значение первого параметра поверхности. + \en The minimum value of the first surface parameter. \~ + \param[in] uEnd - \ru Максимальное значение первого параметра поверхности. + \en The maximum value of the first surface parameter. \~ + \param[in] func - \ru Функция управления сечением поверхности. + \en Section control function. \~ + \param[in] patt - \ru Образующая кривая при form==cs_Shape. + \en Forming curve for form==cs_Shape. \~ + \param[in] accuracy - \ru Точность построения. + \en The accuracy of building. \~ + \param[in] vers - \ru Версия поверхности. + \en The surface version. \~ + \param[out] result - \ru Построенная поверхность. + \en The constructed surface. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) SectionSurface( const MbCurve3D & rc, + const MbCurve3D & g1, + const MbCurve3D & g2, + const MbCurve3D * c0, + size_t form, + bool sense, + double uBeg, + double uEnd, + MbFunction * func, + MbCurve * patt, + double accuracy, + VERSION vers, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение поверхности Кунса. + \en Construction of a Coons surface. \~ + \details \ru Построение бикубической поверхности Кунса на четырех кривых и их поперечных производных, касательной к четырём кривым на прверхностях. \n + \en The construction of Coons surface, which will be tangent to four surfaces and coincide with four curves on this surfaces on it sides.\n \~ + \param[in] surfaceCurve0 - \ru Кривая на поверхности 0. + \en The curve on surface0. \~ + \param[in] surfaceCurve1 - \ru Кривая на поверхности 1. + \en The curve on surface1. \~ + \param[in] surfaceCurve2 - \ru Кривая на поверхности 2. + \en The curve on surface2. \~ + \param[in] surfaceCurve3 - \ru Кривая на поверхности 3. + \en The curve on surface3. \~ + \param[out] result - \ru Построенная поверхность. + \en The constructed surface. \~ + \result \ru Возвращает код результата построения. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateCoonsSurface( const MbSurfaceCurve & surfaceCurve0, + const MbSurfaceCurve & surfaceCurve1, + const MbSurfaceCurve & surfaceCurve2, + const MbSurfaceCurve & surfaceCurve3, + MbSurface *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение поверхности-заплатки для заданных рёбер. + \en Construction of a surface-patch by the edges. \~ + \details \ru Построение поверхности-заплатки, гладко стыкующейся с поверхностями ребер. \n + \en Construction of a surface-patch, smoothly joining with the surfaces of the edges. \n \~ + \param[in] edges - \ru Ребра, с которыми требуется стыковать новую поверхность. + \en Edges to join the new surface. \~ + \param[out] result - \ru Построенные поверхности. + \en The constructed surfaces. \~ + \result \ru Возвращает код результата построения. + \en Returns operation result code. \~ + \warning \ru В разработке. + \en Under development. \~ + \ingroup Surface_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateSplinePatch( const std::vector & edges, + std::vector & result ); + + +#endif // __ACTION_SURFACE_H diff --git a/C3d/Include/action_surface_curve.h b/C3d/Include/action_surface_curve.h index d49cfc1..2d3dc64 100644 --- a/C3d/Include/action_surface_curve.h +++ b/C3d/Include/action_surface_curve.h @@ -1,1083 +1,1082 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Методы построения трехмерных кривых. - \en Functions for three-dimensional curves construction. \~ - \details \ru На базе кривых строятся рёбра. Рёбра используются в твёрдотельной и каркасной модели. - Кроме того, кривые используются для построения поверхностей, а также могут служить - вспомогательными элементами модели. - \en Edges are created on the basis of curves. Edges are used in solid and wireframe model. - In addition curves are used for construction of surfaces as well as can be used - as auxiliary elements of a model. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ACTION_SURFACE_CURVE_H -#define __ACTION_SURFACE_CURVE_H - - -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbCurve; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbContour3D; -class MATH_CLASS MbSurfaceCurve; -class MATH_CLASS MbSurface; -class MATH_CLASS MbElementarySurface; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbWireFrame; -class MATH_CLASS MbSNameMaker; - - -//------------------------------------------------------------------------------ -/** \brief \ru Рассчитать вершины ломаной. - \en Compute the vertices of a polyline. \~ - \details \ru Рассчитать вершины ломаной point1 и point2, соединяющей точки origin1 и origin2, - сдвинутые в направлениях direction1 и direction2 на расстояния length1 и length2, - которую можно скруглить радиусами radius1 и radius2. \n - \en Compute the vertices 'point1' and 'point2' of a polyline connecting points 'origin1' and 'origin2' - translated in the directions 'direction1' and 'direction2' by distances 'length1' and 'length2' - which can be rounded with radius 'radius1' and 'radius2'. \n \~ - \param[in] origin1 - \ru Первая точка. - \en The first point. \~ - \param[in] direction1 - \ru Направление сдвига первой точки. - \en The direction of the first point translation. \~ - \param[in] length1 - \ru Величина сдвига первой точки. - \en The distance of the first point translation. \~ - \param[in] radius1 - \ru Радиус скругления для первой точки. - \en The rounding radius for the first point. \~ - \param[in] origin2 - \ru Вторая точка. - \en The second point. \~ - \param[in] direction2 - \ru Направления сдвига для второй точки. - \en The direction of the second point translation. \~ - \param[in] length2 - \ru Величина сдвига для второй точки. - \en The distance of the second point translation. \~ - \param[in] radius2 - \ru Радиус скругления для второй точки. - \en The rounding radius for the second point. \~ - \param[out] result1 - \ru Первая точка ломаной. - \en The first point of the polyline. \~ - \param[out] result2 - \ru Вторая точка ломаной. - \en The second point of the polyline. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CalculatePipePoints( const MbCartPoint3D & origin1, - const MbVector3D & direction1, - double length1, double radius1, - const MbCartPoint3D & origin2, - const MbVector3D & direction2, - double length2, double radius2, - MbCartPoint3D & result1, MbCartPoint3D & result2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать эквидистантную кривую. - \en Create an offset curve. \~ - \details \ru Создать эквидистантную кривую по плоской кривой. \n - \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[out] result - \ru Эквидистантная кривая. - \en The offset curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, - double d, - 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 Постранственная кривая, к которой строится эквидистантная. - \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] bluntAngle - \ru Если true, то в притуплять острые углы. - \en If 'true', sharp corners are to be blunt. \~ - \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] 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 MbVector3D & offsetVect, - const bool useFillet, - const bool keepRadius, - const bool bluntAngle, - const bool fromBeg, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \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 \~ - \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] 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 MbFace & face, - const MbAxis3D & dirAxis, - double dist, - const MbSNameMaker & snMaker, - MbWireFrame *& 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 \~ - \param[in] surface - \ru Поверхность для проецирования. - \en The surface to project onto. \~ - \param[in] curve - \ru Проецируемая кривая. - \en The curve to project. \~ - \param[in] direction - \ru Направление проецирования (если не указано то проецирование по нормали). - \en The projection direction (if not specified, the projection along the normal). \~ - \param[in] createExact - \ru Создавать проекционную кривую при необходимости. - \en Create a projection curve if necessary. \~ - \param[in] truncateByBounds - \ru Усекать границами поверхности. - \en Truncate by the surface bounds. \~ - \param[in] version - \ru Версия исполнения. - \en The version. \~ - \param[out] result - \ru Множество кривых на поверхности. - \en An array of curves on the surface. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \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() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать пространственную кривую по двум плоским проекциям. - \en Create a space curve from two planar projections. \~ - \details \ru Создать пространственную кривую по двум плоским проекциям. \n - \en Create a space curve from two planar projections. \n \~ - \param[in] place1 - \ru Локальная система координат 1. - \en A local coordinate system 1. \~ - \param[in] curve1 - \ru Двумерная кривая 1. - \en A two-dimensional curve 1. \~ - \param[in] place2 - \ru Локальная система координат 2. - \en A local coordinate system 2. \~ - \param[in] curve2 - \ru Двумерная кривая 2. - \en A two-dimensional curve 2. \~ - \param[out] result - \ru Множество трехмерных кривых. - \en The array of three-dimensional curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \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() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать проекционную кривую по нормали или по направлению. - \en Create a projection curve from a normal or from a direction. \~ - \details \ru Создать проекционную кривую по нормали или по направлению. \n - Если проекция на конструктивную плоскость (плоскость без границ), - то создать на ее основе грань и прислать, а за ее удалением следит приславший. \n - \en Create a projection curve from a normal or from a direction. \n - If the projection is onto the constructive plane (a plane without bounds), - create a face on the basis of this projection. \n \~ - \param[in] curve - \ru Проецируемая кривая. - \en The curve to project. \~ - \param[in] faces - \ru Связный набор граней. - \en A connected set of faces. \~ - \param[in] dir - \ru Вектор направления (если его нет, проекция по нормали). - \en The direction vector (if it is absent, the normal projection). \~ - \param[in] createExact - \ru Создавать проекционную кривую при необходимости. - \en Create a projection curve if necessary. \~ - \param[in] truncateByBounds - \ru Усечь границами. - \en Truncate by bounds. \~ - \param[in] snMaker - \ru Именователь с версией. - \en An object defining the names with the version. \~ - \param[out] result - \ru Проекционные кривые. - \en The projection curves. \~ - \param[out] resultIndices - \ru Индексы соответствия (номера граней в исходном массиве). - \en The indices of faces in the initial array. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать проекционный проволочный каркас по нормали или по направлению. - \en Create a projection wireframe from a normal or from a direction. \~ - \details \ru Создать проекционный проволочный каркас по нормали или по направлению. \n - Если проекция на конструктивную плоскость (плоскость без границ), - то создать на ее основе грань и прислать, а за ее удалением следит приславший. \n - \en Create a projection curve from a normal or from a direction. \n - If the projection is onto the constructive plane (a plane without bounds), - create a face on the basis of this projection. \n \~ - \param[in] wireFrame - \ru Проецируемый проволочный каркас. - \en The wireframe to project. \~ - \param[in] sameWireFrame - \ru Использовать тот же экземпляр проволочного каркаса, или создать копию. - \en Flag whether to use the same wireframe or make a copy of it. \~ - \param[in] solid - \ru Тело. - \en Solid. \~ - \param[in] same - \ru Использовать ли тот же экземпляр журнала тела или создать копию. - \en Flag whether to use the same creators of the body or make a copy. \~ - \param[in] faceIndices - \ru Номера граней в первой оболочке. - \en The numbers of faces in the first shell. \~ - \param[in] dir - \ru Вектор направления (если его нет, проекция по нормали). - \en The direction vector (if it is absent, the normal projection). \~ - \param[in] createExact - \ru Создавать проекционную кривую при необходимости. - \en Create a projection curve if necessary. \~ - \param[in] truncateByBounds - \ru Усечь границами. - \en Truncate by bounds. \~ - \param[in] snMaker - \ru Именователь с версией. - \en An object defining the names with the version. \~ - \param[out] resFrame - \ru Результирующий проволочный каркас, в котором в атрибутах ребер лежат имена соответствующих граней. - \en The resulting wireframe, the attributes of the edges contain the names of corresponding faces. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Устранить наложение сегментов проекционной кривой. - \en Eliminate the projection curve segments overlay. \~ - \details \ru Устранить наложение сегментов проекционной кривой (вспомогательная функция для функции ProjectionCurve). \n - \en Eliminate the projection curve segments overlay (an auxiliary function for function ProjectionCurve). \n \~ - \param[in,out] curves - \ru Множество кривых. - \en An array of curves. \~ - \param[in,out] indices - \ru Множество индексов, синхронный с массивом кривых. - \en An array of indices synchronized with the array of curves. \~ - \return \ru Возвращает true, если что-то изменилось в наборе кривых. - \en Returns true if something has modified in the curve set. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (bool) EliminateProjectionCurveOverlay( RPArray & curves, - SArray * indices ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив линий очерка поверхности. - \en Create an array of isocline curves of the surface. \~ - \details \ru Создать массив линий очерка поверхности с обрезкой по области определения. \n - \en Create an array of isocline curves of the surface with truncation by the definition domain. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] eye - \ru Вектор взгляда. - \en The direction of view. \~ - \param[in] perspective - \ru Является ли проекция перспективной. - \en Whether the projection is perspective. \~ - \param[in] removeOnSurfaceBounds - \ru Удалить линии очерка, совпадающие с границами поверхности. - \en Remove the isocline curves coincident with the surface bounds. \~ - \param[out] result - \ru Выходной массив линий очерка. - \en The output array of isocline curves. \~ - \param[in] version - \ru Версия построения. - \en The version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Mapping -*/ -// --- -MATH_FUNC (MbResultType) SilhouetteCurve( const MbSurface & surface, - const MbVector3D & eye, - bool perspective, - bool removeOnSurfaceBounds, - RPArray & result, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив линий очерка грани. - \en Create an array of isocline curves of the face. \~ - \details \ru Создать массив линий очерка грани с обрезкой по области определения. \n - \en Create an array of isocline curves of the face with truncation by the definition domain. \n \~ - \param[in] face - \ru Грани. - \en The face. \~ - \param[in] eye - \ru Вектор взгляда. - \en The direction of view. \~ - \param[in] perspective - \ru Является ли проекция перспективной. - \en Whether the projection is perspective. \~ - \param[out] result - \ru Выходной массив линий очерка. - \en The output array of isocline curves. \~ - \param[in] version - \ru Версия построения. - \en The version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Mapping -*/ -// --- -MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, - const MbVector3D & eye, - bool perspective, - RPArray & result, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив линий очерка поверхности при вращательном движении вокруг оси. - \en Create an array of isocline curves of the rotated surface. \~ - \details \ru Создать массив линий очерка поверхности с обрезкой по области определения. \n - \en Create an array of isocline curves of the surface with truncation by the definition domain. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] axis - \ru Ось кругового взгляда (ось токарного сечения). - \en The axis of lathe section. \~ - \param[in] removeOnSurfaceBounds - \ru Удалить линии очерка, совпадающие с границами поверхности. - \en Remove the isocline curves coincident with the surface bounds. \~ - \param[out] result - \ru Выходной массив линий очерка. - \en The output array of isocline curves. \~ - \param[in] version - \ru Версия построения. - \en The version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Mapping -*/ -// --- -MATH_FUNC (MbResultType) SilhouetteCurve( const MbSurface & surface, - const MbAxis3D & axis, - bool removeOnSurfaceBounds, - RPArray & curves, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать массив линий очерка грани при вращательном движении вокруг оси. - \en Create an array of isocline curves of the rotated face. \~ - \details \ru Создать массив линий очерка грани с обрезкой по области определения. \n - \en Create an array of isocline curves of the face with truncation by the definition domain. \n \~ - \param[in] face - \ru Грани. - \en The face. \~ - \param[in] axis - \ru Ось кругового взгляда (ось токарного сечения). - \en The axis of lathe section. \~ - \param[out] result - \ru Выходной массив линий очерка. - \en The output array of isocline curves. \~ - \param[in] version - \ru Версия построения. - \en The version. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Mapping -*/ -// --- -MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, - const MbAxis3D & axis, - RPArray & curves, - VERSION version = Math::DefaultMathVersion() ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривые пересечения двух поверхностей. - \en Create the intersection curves of two surfaces. \~ - \details \ru Создать кривые пересечения двух поверхностей. Результат - массив кривых пересечения поверхностей. \n - \en Create the intersection curves of two surfaces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] surface1 - \ru Первая поверхность. - \en The first surface. \~ - \param[in] surface2 - \ru Вторая поверхность. - \en The second surface. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \warning \ru Лучше использовать IntersectionCurve на гранях, т.к. границы поверхностей могут бы неточные, \n - что приведет к неточному положению концов кривых пересечения в результате операции. \n - В гранях же границы поверхности точные, т.к. хранятся в виде кривых пересечения, - а не виде двумерных кривых. \n - \en It is better to use IntersectionCurve on faces since the surfaces bounds can be inexact, \n - and it will result in inexact position of intersection curves ends. \n - But the surface bounds in faces are exact since they are stored in the form of intersection curves, - not in the form of two-dimensional curves. \n \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, - const MbSurface & surface2, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривые пересечения двух граней. - \en Create intersection curves of two faces. \~ - \details \ru Создать кривые пересечения двух граней. Результат - массив кривых пересечения поверхностей. \n - \en Create intersection curves of two faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] face1 - \ru Первая грань оболочки. - \en The first face of the shell. \~ - \param[in] face2 - \ru Вторая грани оболочки. - \en The second face of the shell. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, MbFace & face2, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривые пересечения граней двух оболочек. - \en Create intersection curves of two shells faces. \~ - \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n - \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] solid1 - \ru Первая оболочка. - \en The first shell. \~ - \param[in] faceIndices1 - \ru Номера граней в первой оболочке. - \en The numbers of faces in the first shell. \~ - \param[in] solid2 - \ru Вторая оболочка. - \en The second shell. \~ - \param[in] faceIndices2 - \ru Номера граней во второй оболочке. - \en The numbers of faces in the second shell. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, - const MbSolid & solid2, const SArray & faceIndices2, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривые пересечения граней двух оболочек. - \en Create intersection curves of two shells faces. \~ - \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n - \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ - \param[in] solid1 - \ru Первая оболочка. - \en The first shell. \~ - \param[in] faceIndices1 - \ru Номера граней в первой оболочке. - \en The numbers of faces in the first shell. \~ - \param[in] same1 - \ru Использовать ли тот же журнал построителей первого тела или сделать копию. - \en Flag whether to use the same creators of the first body or make a copy. \~ - \param[in] solid2 - \ru Вторая оболочка. - \en The second shell. \~ - \param[in] faceIndices2 - \ru Номера граней во второй оболочке. - \en The numbers of faces in the second shell. \~ - \param[in] same2 - \ru Использовать ли тот же самый журнал построителей второго тела или сделать копию. - \en Flag whether to use the same creators of the second body or make a copy. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, const bool same1, - const MbSolid & solid2, const SArray & faceIndices2, const bool same2, - const MbSNameMaker & snMaker, MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать линию пересечения поверхностей. - \en Create an intersection curve of surfaces. \~ - \details \ru Создать линию пересечения поверхностей surf1 и surf2 по известным началу и концу линии пересечения. \n - \en Create an intersection curve of surfaces 'surf1' and 'surf2' from the specified start point and end point of the intersection curve. \n \~ - \param[in] surface1 - \ru Первая поверхность. - \en The first surface. \~ - \param[in] ext1 - \ru На расширенной первой поверхности. - \en Whether to create on the extended surface. \~ - \param[in] uv1beg - \ru Начальная точка на первой поверхности. - \en The start point on the first surface. \~ - \param[in] uv1end - \ru Конечная точка на первой поверхности. - \en The end point on the first surface. \~ - \param[in] surface2 - \ru Вторая поверхность. - \en The second surface. \~ - \param[in] ext2 - \ru На расширенной второй поверхности. - \en Whether to create on the extended second surface. \~ - \param[in] uv2beg - \ru Начальная точка на второй поверхности. - \en The start point on the second surface. \~ - \param[in] uv2end - \ru Конечная точка на второй поверхности. - \en The end point on the second surface. \~ - \param[in] dir - \ru Начальное направление создания линии пересечения. - \en The start direction for intersection curve creation. \~ - \param[out] result1 - \ru Двумерная кривая на первой поверхности. - \en The two-dimensional curve on the first surface. \~ - \param[out] result2 - \ru Двумерная кривая на второй поверхности. - \en The two-dimensional curve on the second surface. \~ - \param[out] label - \ru Тип полученной кривой пересечения. - \en The resultant intersection curve type. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, bool ext1, - const MbCartPoint & uv1beg, - const MbCartPoint & uv1end, - const MbSurface & surface2, bool ext2, - const MbCartPoint & uv2beg, - const MbCartPoint & uv2end, - const MbVector3D & dir, - MbCurve *& result1, - MbCurve *& result2, - MbeCurveBuildType & label ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать линию пересечения поверхностей. - \en Create an intersection curve of surfaces. \~ - \details \ru Создать линию пересечения поверхностей surf1 и surf2 по известным началу и концу линии пересечения и вспомогательной кривой. \n - \en Create an intersection curve of surfaces 'surf1' and 'surf2' from the specified start point and end point of the intersection curve - and guide curve that approximates the desired curve. \n \~ - \param[in] surface1 - \ru Первая поверхность. - \en The first surface. \~ - \param[in] ext1 - \ru На расширенной первой поверхности. - \en Whether to create on the extended surface. \~ - \param[in] uv1beg - \ru Начальная точка на первой поверхности. - \en The start point on the first surface. \~ - \param[in] uv1end - \ru Конечная точка на первой поверхности. - \en The end point on the first surface. \~ - \param[in] surface2 - \ru Вторая поверхность. - \en The second surface. \~ - \param[in] ext2 - \ru На расширенной второй поверхности. - \en Whether to create on the extended second surface. \~ - \param[in] uv2beg - \ru Начальная точка на второй поверхности. - \en The start point on the second surface. \~ - \param[in] uv2end - \ru Конечная точка на второй поверхности. - \en The end point on the second surface. \~ - \param[in] guideCurve - \ru Направляющая кривая, приближенно описывающая искомую кривую. - \en The guide curve that approximates the desired curve. \~ - \param[in] useRedetermination - \ru Флаг, определяющий нужно ли уточнять шаг построения следующей точки по сравнению с функцией DeviationStep. - \en The flag that determines whether it is necessary to specify the next point build step as compared to the DeviationStep function. \~ - \param[in] checkPoles - \ru Флаг необходимости проверки и корректировки полюсных точек. - \en The flag that determines whether it is necessary to check and correct pole points. \~ - \param[out] result1 - \ru Двумерная кривая на первой поверхности. - \en The two-dimensional curve on the first surface. \~ - \param[out] result2 - \ru Двумерная кривая на второй поверхности. - \en The two-dimensional curve on the second surface. \~ - \param[out] label - \ru Тип полученной кривой пересечения. - \en The resultant intersection curve type. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC( MbResultType ) IntersectionCurve( const MbSurface & surf1, bool ext1, - const MbCartPoint & uv1beg, - const MbCartPoint & uv1end, - const MbSurface & surf2, bool ext2, - const MbCartPoint & uv2beg, - const MbCartPoint & uv2end, - const MbCurve3D * guideCurve, - bool useRedetermination, - bool checkPoles, - MbCurve *& pCurve1, - MbCurve *& pCurve2, - MbeCurveBuildType & label ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать пространственный сплайн через точки и с сопряжениями. - \en Create a spatial spline through points and with the given derivatives. \~ - \details \ru Создать пространственный сплайн через точки и с сопряжениями. \n - Примечания: \n - Если есть сопряжения, то количество сопряжений должно быть равно количеству точек. \n - Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n - \en Create a spatial spline through points and with the given derivatives. \n - Notes: \n - If derivatives are specified, the number of derivatives should be equal to the number of points. \n - Missing derivatives should be represented by null pointers in the array \n \~ - \param[in] points - \ru Точки. - \en Points. \~ - \param[in] paramType - \ru Тип параметризации. - \en The parametrization type. \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline degree. \~ - \param[in] closed - \ru Замкнутость сплайна. - \en The spline closedness. \~ - \param[in] transitions - \ru Заданные сопряжения. - \en The specified derivatives. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать пространственный сплайн по точкам и с сопряжениями. - \en Create a spatial spline from points and derivatives. \~ - \details \ru Создать пространственный сплайн по точкам и с сопряжениями. \n - \en Create a spatial spline from points and derivatives. \n \~ - \param[in] points - \ru Множество точек. - \en An array of points. \~ - \param[in] degree - \ru Порядок сплайна. - \en A spline degree. \~ - \param[in] closed - \ru Строить замкнутый сплайн. - \en Create a closed spline. \~ - \param[in] weights - \ru Множество весов точек. - \en An array of points weights. \~ - \param[in] knots - \ru Узловой вектор сплайна. - \en A knot vector of the spline. \~ - \param[in] begData - \ru Сопряжение в начале. - \en The start derivative. \~ - \param[in] endData - \ru Сопряжение в конце. - \en The end derivative. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) SpaceSplineBy( const SArray & points, - size_t degree, - bool closed, - const SArray * weights, - const SArray * knots, - MbPntMatingData * begData, - MbPntMatingData * endData, - const MbSNameMaker & snMaker, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую на поверхности. - \en Create a curve on a surface. \~ - \details \ru Создать кривую на поверхности. \n - Примечания: \n - 1. Если есть сопряжения, то количество сопряжений должно быть равно количеству точек. \n - Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n - 2. Если сплайн строится через точки, то сопряжения могуть быть заданы произвольно. \n - 2. Если сплайн строится по полюсам и он незамкнут, то сопряжения могут быть только на концах. \n - 3. Если сплайн строится по полюсам и он замкнут, то сопряжения должны отсутствовать. \n - 4. Множество весов должен быть пуст или синхронизирован с массивом точек по количеству - (с опцией throughPoints веса игнорируются). \n - \en Create a curve on a surface. \n - Notes: \n - 1. If derivatives are specified, the number of derivatives should be equal to the number of points. \n - Missing derivatives should be represented by null pointers in the array \n - 2. If the spline is created from points, arbitrary derivatives can be defined. \n - 2. If the spline is created from poles and it is open, only the end derivatives can be specified. \n - 3. If the spline is constructed from poles and it is closed, the derivatives cannot be specified. \n - 4. An array of weights should be empty or synchronized with the point array by size - (with option throughPoints weights are ignored). \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] throughPoints - \ru Провести сплайн через точки. - \en Create a spline through points. \~ - \param[in] paramPnts - \ru Множество параметрических точек. - \en An array of parametric points. \~ - \param[in] paramWts - \ru Множество весов параметрических точек. - \en An array of parametric point weights. \~ - \param[in] paramClosed - \ru Строить замкнутый параметрический сплайн. - \en Create a closed parametric spline. \~ - \param[in] spaceTransitions - \ru Сопряжения в точках. - \en Derivatives in the points. \~ - \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 Возвращает код результата операции. - \en Returns operation result code. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать изопараметрическую кривую. - \en Create an isoparametric curve. \~ - \details \ru Создать изопараметрическую кривую на поверхности surface. \n - \en Create an isoparametric curve on surface 'surface'. \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] x - \ru Значение по первому параметру. - \en A value of the first parameter. \~ - \param[in] isU - \ru Первый параметр есть U. - \en Whether the first parameter is U. \~ - \param[in] yRange - \ru Диапазон по второму параметру (если не задан, используются параметрические границы поверхности). - \en A range of the second parameter (if not defined, the parametric bounds of the surface are used). \~ - \param[out] result - \ru Изопараметрическая кривая. - \en The isoparametric curve. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) IsoparametricCurve( const MbSurface & surface, - double x, bool isU, const MbRect1D * yRange, - MbCurve3D *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую - мостик, соединяющую кривые curve1 и curve2. - \en Create a transition curve connecting curves 'curve1' and 'curve2'. \~ - \details \ru Создать кривую - мостик, соединяющую кривые curve1 и curve2 кубическим сплайном Эрмита. \n - \en Create a transition curve connecting curves 'curve1' and 'curve2' by a cubic Hermite spline. \n \~ - \param[in] curve1 - \ru Сопрягаемая кривая 1. - \en A curve 1 to be connected. \~ - \param[in] t1 - \ru Параметр точки на сопрягаемой кривой 1. - \en A point parameter on the curve 1. \~ - \param[in] sense1 - \ru Начало мостика совпадает с направлением кривой curve1 (true). - \en The beginning of the transition curve is equal to the direction of 'curve1' (true). \~ - \param[in] curve2 - \ru Сопрягаемая кривая 2. - \en A curve 2 to be connected. \~ - \param[in] t2 - \ru Параметр точки на сопрягаемой кривой 2. - \en A point parameter on the curve 2. \~ - \param[in] sense2 - \ru Конец мостика совпадает с направлением кривой curve2 (true). - \en The end of the transition curve is equal to the direction of 'curve2' (true). \~ - \param[in] names - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) BridgeCurve( const MbCurve3D & curve1, double t1, bool sense1, - const MbCurve3D & curve2, double t2, bool sense2, - const MbSNameMaker & names, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать составную кривую плавного соединения концов двух кривых. - \en Create a composite curve smoothly connecting two curves ends. \~ - \details \ru Создать составную кривую плавного соединения концов двух кривых. \n - Полученная кривая состоит из трёхмерной дуги радиуса radius1, - отрезка (в определенных случаях отрезок отсутствует), - трёхмерной дуги радиуса radius2. - \en Create a composite curve smoothly connecting two curves ends. \n - The constructed curve consists of a three-dimensional arc of radius 'radius1', - a segment (in specific cases a segment is absent), - a three-dimensional arc of radius 'radius2'. \~ - \param[in] curve1 - \ru Соединяемая кривая 1. - \en A curve 1 to be connected. \~ - \param[in] isBegin1 - \ru Начало соединяемой кривой 1 (true). - \en The beginning of the curve 1 (true). \~ - \param[in] radius1 - \ru Радиус сопряжения у соединяемой кривой 1. - \en The conjugation raidus of curve 1. \~ - \param[in] curve2 - \ru Соединяемая кривая 2. - \en A curve 2 to be connected. \~ - \param[in] isBegin2 - \ru Начало соединяемой кривой 2 (true). - \en The beginning of the curve 2 (true). \~ - \param[in] radius2 - \ru Радиус сопряжения у соединяемой кривой 2. - \en The conjugation raidus of curve 2. \~ - \param[in] names - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) ConnectingCurve( const MbCurve3D & curve1, bool isBegin1, double radius1, - const MbCurve3D & curve2, bool isBegin2, double radius2, - const MbSNameMaker & names, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать соединительную NURBS кривую для кривых curve1 и curve2. - \en Create a connecting NURBS curve for curves 'curve1' and 'curve2'. \~ - \details \ru Создать соединительную NURBS кривую для кривых curve1 и curve2. \n - t1 и t2 - параметры кривых curve1 и curve2, в точках которых начинается и заканчивается соединение.\n - \en Create a connecting NURBS curve for curves 'curve1' and 'curve2'. \n - t1 and t2 are parameters of curves 'curve1' and 'curve2' which correspond to the start point and the end point of the connecting curve.\n \~ - \param[in] curve1 - \ru Соединяемая кривая 1. - \en A curve 1 to be connected. \~ - \param[in] t1 - \ru Параметр точки на кривой 1. - \en A point parameter on curve 1. \~ - \param[in] mating1 - \ru Тип соединения кривой 1. - \en The connection type for curve 1. \~ - \param[in] curve2 - \ru Соединяемая кривая 2. - \en A curve 2 to be connected. \~ - \param[in] t2 - \ru Параметр точки на кривой 2. - \en A point parameter on curve 2. \~ - \param[in] mating2 - \ru Тип соединения кривой 2. - \en The connection type for curve 2. \~ - \param[in] tension1 - \ru Параметр "натяжение" соединительной кривой на стыке с кривой 1 ( 0<= tension1 <=1). - \en The "tension" parameter of the connecting curve at the intersection with the curve 1 (0 <= tension1 <=1). \~ - \param[in] tension2 - \ru Параметр "натяжение" соединительной кривой на стыке с кривой 2( 0<= tension2 <=1). - \en The "tension" parameter of the connecting curve at the intersection with the curve 2 (0 <= tension2 <=1). \~ - \param[in] names - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbResultType) ConnectingSpline( const MbCurve3D & curve1, double t1, MbeMatingType mating1, - const MbCurve3D & curve2, double t2, MbeMatingType mating2, - double tension1, double tension2, - const MbSNameMaker & names, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую для плавного соединения (скругления) кривых. - \en Create a fillet curve for curves. \~ - \details \ru Создать кривую для плавного соединения (скругления) кривых. \n - Для плавного сопряжения кривых curve1 и curve2 строится кривая filletCurve. \n - При входе t1 и t2 - начальные приближения, определяющие сектор построения скругления, - w1 и w2 - не используются. \n - При входе type - тип скругления (обычное или на поверхности). \n - На выходе t1 и t2 - будут равны параметрам касания кривых curve1 и curve2 с кривой filletCurve. \n - На выходе t1 и w1 - определяют параметры сохраняемого участка при обрезке кривой curve1. \n - На выходе t2 и w2 - определяют параметры сохраняемого участка при обрезке кривой curve2. \n - Параметр radius - радиус дуги или цилиндра. \n - Если радиус radius не задан (равен нулю), то он вычисляется из условия, - что начало кривой сопряжения будет находится в точке с параметором t1, - t1 и t2 - параметры кривых curve1 и curve2, в соответствующих точках которых начинается и заканчивается скругление. \n - Параметр sense - прямое или обратное направление кривой скругления. \n - Кривая filletCurve - это кривая сопряжения, дуга (когда surface == NULL) или кривая на поверхности цилиндра surface. \n - Поверхность surface - это цилиндрическая поверхность, на которой строится кривая сопряжения в общем случае. - Поверхность surface нельзя удалять, на этой поверхности построена кривая сопряжения filletCurve, - при удалении filletCurve удалится surface, если не был дополнительно выполнен surface->AddRef(). \n - \en Create a fillet curve for curves. \n - Curve 'filletCurve' is created for smooth connection of curves 'curve1' and 'curve2'. \n - On input t1 and t2 are the initial estimations which determine a sector for fillet construction, - w1 and w2 are not used. \n - On input 'type' is a fillet type (ordinary or on a surface). \n - On output t1 and t2 are the parameters of touching of curves 'curve1' and 'curve2' with curve 'filletCurve'. \n - On output t1 and w1 determines parameters of a part to be kept while trimming curve1. \n - On output t2 and w2 determines parameters of a part to be kept while trimming curve2. \n - Parameter 'radius' is a radius of an arc or a cylinder. \n - If radius 'radius' is not defined (equal to zero), it is computed from the condition - 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 - Surface 'surface' is a cylindric surface on which the fillet curve is constructed in general case. - Surface 'surface' must not be deleted since the fillet curve 'filletCurve' is created on this surface; - 'surface' will be deleted while deleting 'filletCurve' if surface->AddRef() was not additionally used. \n \~ - \param[in] curve1 - \ru Соединяемая кривая 1. - \en A curve 1 to be connected. \~ - \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 соединения с кривой соединения. - \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 Радиус дуги или цилиндра. - \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. \~ - \param[out] unchanged - \ru Не изменился радиус соединения (true) или изменился (false). - \en The fillet radius has not changed (true) or has changed (false). \~ - \param[in] type - \ru Тип скругления. - \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 (can be NULL). \~ - \param[out] result - \ru Каркас с построенными кривыми. - \en The frame with the constructed curves. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) FilletCurve( const MbCurve3D & curve1, double & t1, double & w1, - const MbCurve3D & curve2, double & t2, double & w2, - double & radius, bool sense, bool & unchanged, - const MbeConnectingType type, - const MbSNameMaker & names, - MbElementarySurface *& surface, - MbWireFrame *& result ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить изменение радиуса при перемещении средней точки кривой скругления. - \en Determine the radius variation while translating the middle point of the fillet curve. \~ - \details \ru Определить изменение радиуса при перемещении средней точки кривой скругления \n - от центра на расстояние len (с учётом знака len). \n - \en Determine the radius variation while translating the middle point of the fillet curve \n - from the centre on distance 'len' (signed). \n \~ - \param[in] filletCurve - \ru Кривая скругления. - \en The fillet curve. \~ - \param[in] radius - \ru Радиус скругления. - \en The radius of fillet. \~ - \param[in] sense - \ru Направления смещения средней точки кривой скругления. - \en A direction of the middle point of the fillet curve translation. \~ - \param[in] len - \ru Величина смещения средней точки кривой скругления. - \en A value of translation of the fillet curve middle point. \~ - \param[in] curve1 - \ru Первая сопрягаемая кривая. - \en The first curve to fillet. \~ - \param[in] t1 - \ru Параметр начала кривой скругления на первой сопрягаемой кривой. - \en The parameter of fillet curve start point on the first curve. \~ - \param[in] curve2 - \ru Вторая сопрягаемая кривая. - \en The second curve to fillet. \~ - \param[in] t2 - \ru Параметр конца кривой скругления на второй сопрягаемой кривой. - \en The parameter of fillet curve end point on the second curve. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (double) GetFilletRadiusDelta( const MbCurve3D & filletCurve, - double radius, bool sense, double len, - const MbCurve3D & curve1, double t1, - const MbCurve3D & curve2, double t2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить изменение радиуса при перемещении средней точки кривой скругления. - \en Determine the radius variation while translating the middle point of the fillet curve. \~ - \details \ru Определить изменение радиуса при перемещении средней точки кривой скругления \n - от центра на расстояние len (с учётом знака len). \n - \en Determine the radius variation while translating the middle point of the fillet curve \n - from the centre on distance 'len' (signed). \n \~ - \param[in] filletCurve - \ru Кривая скругления. - \en The fillet curve. \~ - \param[in] radius - \ru Радиус скругления. - \en The radius of fillet. \~ - \param[in] sense - \ru Направления смещения средней точки кривой скругления. - \en A direction of the middle point of the fillet curve translation. \~ - \param[in] len - \ru Величина смещения средней точки кривой скругления. - \en A value of translation of the fillet curve middle point. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (double) GetFilletRadiusDelta( const MbCurve3D & filletCurve, - double radius, bool sense, double len ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую для плавного соединения (скругления) всех кривых контура. - \en Create a curve for fillet of all the curves of a contour. \~ - \details \ru Создать кривую для плавного соединения (скругления) всех кривых контура contour. \n - type - тип скругления (обычное или на поверхности). \n - radiuses - радиусы скругления, i-й радиус соответствует стыку i-го и i+1-го сегмента. \n - Если две кривых в контуре гладко стыкуются, в этом стыке скругление не делается, радиус игнорируется. \n - \en Create a curve for fillet of all the curves of a contour 'contour'. \n - 'type' is a fillet type (ordinary or on a surface). \n - 'radiuses' are the fillet radii, the i-th radius corresponds to the joint of the i-th and the i+1-th segments. \n - If two curves in contours are smoothly connected, the fillet is not created at this joint, the radius is ignored. \n \~ - \param[in] contour - \ru Исходный контур. - \en The initial contour. \~ - \param[in] radiuses - \ru Множество радиусов скругления. - \en An array of fillet radii. \~ - \param[out] result - \ru Контур со скруглениями. Имя сегмента скругления - Hash32SN() имен исходных сегменов. - \en The contour with the fillets. The name of the fillet segment - Hash32SN() of initial segments names. \~ - \param[in] type - \ru Тип выполняемых скруглений. - \en The type of fillets. \~ - \return \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbResultType) CreateContourFillets( const MbContour3D & contour, - SArray & radiuses, - MbCurve3D *& result, - const MbeConnectingType type ); - - -#endif // __ACTION_SURFACE_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Методы построения трехмерных кривых. + \en Functions for three-dimensional curves construction. \~ + \details \ru На базе кривых строятся рёбра. Рёбра используются в твёрдотельной и каркасной модели. + Кроме того, кривые используются для построения поверхностей, а также могут служить + вспомогательными элементами модели. + \en Edges are created on the basis of curves. Edges are used in solid and wireframe model. + In addition curves are used for construction of surfaces as well as can be used + as auxiliary elements of a model. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ACTION_SURFACE_CURVE_H +#define __ACTION_SURFACE_CURVE_H + + +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbCurve; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbContour3D; +class MATH_CLASS MbSurfaceCurve; +class MATH_CLASS MbSurface; +class MATH_CLASS MbElementarySurface; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbWireFrame; +class MATH_CLASS MbSNameMaker; + + +//------------------------------------------------------------------------------ +/** \brief \ru Рассчитать вершины ломаной. + \en Compute the vertices of a polyline. \~ + \details \ru Рассчитать вершины ломаной point1 и point2, соединяющей точки origin1 и origin2, + сдвинутые в направлениях direction1 и direction2 на расстояния length1 и length2, + которую можно скруглить радиусами radius1 и radius2. \n + \en Compute the vertices 'point1' and 'point2' of a polyline connecting points 'origin1' and 'origin2' + translated in the directions 'direction1' and 'direction2' by distances 'length1' and 'length2' + which can be rounded with radius 'radius1' and 'radius2'. \n \~ + \param[in] origin1 - \ru Первая точка. + \en The first point. \~ + \param[in] direction1 - \ru Направление сдвига первой точки. + \en The direction of the first point translation. \~ + \param[in] length1 - \ru Величина сдвига первой точки. + \en The distance of the first point translation. \~ + \param[in] radius1 - \ru Радиус скругления для первой точки. + \en The rounding radius for the first point. \~ + \param[in] origin2 - \ru Вторая точка. + \en The second point. \~ + \param[in] direction2 - \ru Направления сдвига для второй точки. + \en The direction of the second point translation. \~ + \param[in] length2 - \ru Величина сдвига для второй точки. + \en The distance of the second point translation. \~ + \param[in] radius2 - \ru Радиус скругления для второй точки. + \en The rounding radius for the second point. \~ + \param[out] result1 - \ru Первая точка ломаной. + \en The first point of the polyline. \~ + \param[out] result2 - \ru Вторая точка ломаной. + \en The second point of the polyline. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CalculatePipePoints( const MbCartPoint3D & origin1, + const MbVector3D & direction1, + double length1, double radius1, + const MbCartPoint3D & origin2, + const MbVector3D & direction2, + double length2, double radius2, + MbCartPoint3D & result1, MbCartPoint3D & result2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать эквидистантную кривую. + \en Create an offset curve. \~ + \details \ru Создать эквидистантную кривую по плоской кривой. \n + \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[out] result - \ru Эквидистантная кривая. + \en The offset curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) OffsetPlaneCurve( const MbCurve3D & curve, + double d, + 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 Постранственная кривая, к которой строится эквидистантная. + \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] bluntAngle - \ru Если true, то в притуплять острые углы. + \en If 'true', sharp corners are to be blunt. \~ + \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] 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 MbVector3D & offsetVect, + const bool useFillet, + const bool keepRadius, + const bool bluntAngle, + const bool fromBeg, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \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 \~ + \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] 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 MbFace & face, + const MbAxis3D & dirAxis, + double dist, + const MbSNameMaker & snMaker, + MbWireFrame *& 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 \~ + \param[in] surface - \ru Поверхность для проецирования. + \en The surface to project onto. \~ + \param[in] curve - \ru Проецируемая кривая. + \en The curve to project. \~ + \param[in] direction - \ru Направление проецирования (если не указано то проецирование по нормали). + \en The projection direction (if not specified, the projection along the normal). \~ + \param[in] createExact - \ru Создавать проекционную кривую при необходимости. + \en Create a projection curve if necessary. \~ + \param[in] truncateByBounds - \ru Усекать границами поверхности. + \en Truncate by the surface bounds. \~ + \param[in] version - \ru Версия исполнения. + \en The version. \~ + \param[out] result - \ru Множество кривых на поверхности. + \en An array of curves on the surface. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \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() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать пространственную кривую по двум плоским проекциям. + \en Create a space curve from two planar projections. \~ + \details \ru Создать пространственную кривую по двум плоским проекциям. \n + \en Create a space curve from two planar projections. \n \~ + \param[in] place1 - \ru Локальная система координат 1. + \en A local coordinate system 1. \~ + \param[in] curve1 - \ru Двумерная кривая 1. + \en A two-dimensional curve 1. \~ + \param[in] place2 - \ru Локальная система координат 2. + \en A local coordinate system 2. \~ + \param[in] curve2 - \ru Двумерная кривая 2. + \en A two-dimensional curve 2. \~ + \param[out] result - \ru Множество трехмерных кривых. + \en The array of three-dimensional curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \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() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать проекционную кривую по нормали или по направлению. + \en Create a projection curve from a normal or from a direction. \~ + \details \ru Создать проекционную кривую по нормали или по направлению. \n + Если проекция на конструктивную плоскость (плоскость без границ), + то создать на ее основе грань и прислать, а за ее удалением следит приславший. \n + \en Create a projection curve from a normal or from a direction. \n + If the projection is onto the constructive plane (a plane without bounds), + create a face on the basis of this projection. \n \~ + \param[in] curve - \ru Проецируемая кривая. + \en The curve to project. \~ + \param[in] faces - \ru Связный набор граней. + \en A connected set of faces. \~ + \param[in] dir - \ru Вектор направления (если его нет, проекция по нормали). + \en The direction vector (if it is absent, the normal projection). \~ + \param[in] createExact - \ru Создавать проекционную кривую при необходимости. + \en Create a projection curve if necessary. \~ + \param[in] truncateByBounds - \ru Усечь границами. + \en Truncate by bounds. \~ + \param[in] snMaker - \ru Именователь с версией. + \en An object defining the names with the version. \~ + \param[out] result - \ru Проекционные кривые. + \en The projection curves. \~ + \param[out] resultIndices - \ru Индексы соответствия (номера граней в исходном массиве). + \en The indices of faces in the initial array. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать проекционный проволочный каркас по нормали или по направлению. + \en Create a projection wireframe from a normal or from a direction. \~ + \details \ru Создать проекционный проволочный каркас по нормали или по направлению. \n + Если проекция на конструктивную плоскость (плоскость без границ), + то создать на ее основе грань и прислать, а за ее удалением следит приславший. \n + \en Create a projection curve from a normal or from a direction. \n + If the projection is onto the constructive plane (a plane without bounds), + create a face on the basis of this projection. \n \~ + \param[in] wireFrame - \ru Проецируемый проволочный каркас. + \en The wireframe to project. \~ + \param[in] sameWireFrame - \ru Использовать тот же экземпляр проволочного каркаса, или создать копию. + \en Flag whether to use the same wireframe or make a copy of it. \~ + \param[in] solid - \ru Тело. + \en Solid. \~ + \param[in] same - \ru Использовать ли тот же экземпляр журнала тела или создать копию. + \en Flag whether to use the same creators of the body or make a copy. \~ + \param[in] faceIndices - \ru Номера граней в первой оболочке. + \en The numbers of faces in the first shell. \~ + \param[in] dir - \ru Вектор направления (если его нет, проекция по нормали). + \en The direction vector (if it is absent, the normal projection). \~ + \param[in] createExact - \ru Создавать проекционную кривую при необходимости. + \en Create a projection curve if necessary. \~ + \param[in] truncateByBounds - \ru Усечь границами. + \en Truncate by bounds. \~ + \param[in] snMaker - \ru Именователь с версией. + \en An object defining the names with the version. \~ + \param[out] resFrame - \ru Результирующий проволочный каркас, в котором в атрибутах ребер лежат имена соответствующих граней. + \en The resulting wireframe, the attributes of the edges contain the names of corresponding faces. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Устранить наложение сегментов проекционной кривой. + \en Eliminate the projection curve segments overlay. \~ + \details \ru Устранить наложение сегментов проекционной кривой (вспомогательная функция для функции ProjectionCurve). \n + \en Eliminate the projection curve segments overlay (an auxiliary function for function ProjectionCurve). \n \~ + \param[in,out] curves - \ru Множество кривых. + \en An array of curves. \~ + \param[in,out] indices - \ru Множество индексов, синхронный с массивом кривых. + \en An array of indices synchronized with the array of curves. \~ + \return \ru Возвращает true, если что-то изменилось в наборе кривых. + \en Returns true if something has modified in the curve set. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (bool) EliminateProjectionCurveOverlay( RPArray & curves, + SArray * indices ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив линий очерка поверхности. + \en Create an array of isocline curves of the surface. \~ + \details \ru Создать массив линий очерка поверхности с обрезкой по области определения. \n + \en Create an array of isocline curves of the surface with truncation by the definition domain. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] eye - \ru Вектор взгляда. + \en The direction of view. \~ + \param[in] perspective - \ru Является ли проекция перспективной. + \en Whether the projection is perspective. \~ + \param[in] removeOnSurfaceBounds - \ru Удалить линии очерка, совпадающие с границами поверхности. + \en Remove the isocline curves coincident with the surface bounds. \~ + \param[out] result - \ru Выходной массив линий очерка. + \en The output array of isocline curves. \~ + \param[in] version - \ru Версия построения. + \en The version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Mapping +*/ +// --- +MATH_FUNC (MbResultType) SilhouetteCurve( const MbSurface & surface, + const MbVector3D & eye, + bool perspective, + bool removeOnSurfaceBounds, + RPArray & result, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив линий очерка грани. + \en Create an array of isocline curves of the face. \~ + \details \ru Создать массив линий очерка грани с обрезкой по области определения. \n + \en Create an array of isocline curves of the face with truncation by the definition domain. \n \~ + \param[in] face - \ru Грани. + \en The face. \~ + \param[in] eye - \ru Вектор взгляда. + \en The direction of view. \~ + \param[in] perspective - \ru Является ли проекция перспективной. + \en Whether the projection is perspective. \~ + \param[out] result - \ru Выходной массив линий очерка. + \en The output array of isocline curves. \~ + \param[in] version - \ru Версия построения. + \en The version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Mapping +*/ +// --- +MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, + const MbVector3D & eye, + bool perspective, + RPArray & result, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив линий очерка поверхности при вращательном движении вокруг оси. + \en Create an array of isocline curves of the rotated surface. \~ + \details \ru Создать массив линий очерка поверхности с обрезкой по области определения. \n + \en Create an array of isocline curves of the surface with truncation by the definition domain. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] axis - \ru Ось кругового взгляда (ось токарного сечения). + \en The axis of lathe section. \~ + \param[in] removeOnSurfaceBounds - \ru Удалить линии очерка, совпадающие с границами поверхности. + \en Remove the isocline curves coincident with the surface bounds. \~ + \param[out] result - \ru Выходной массив линий очерка. + \en The output array of isocline curves. \~ + \param[in] version - \ru Версия построения. + \en The version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Mapping +*/ +// --- +MATH_FUNC (MbResultType) SilhouetteCurve( const MbSurface & surface, + const MbAxis3D & axis, + bool removeOnSurfaceBounds, + RPArray & curves, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать массив линий очерка грани при вращательном движении вокруг оси. + \en Create an array of isocline curves of the rotated face. \~ + \details \ru Создать массив линий очерка грани с обрезкой по области определения. \n + \en Create an array of isocline curves of the face with truncation by the definition domain. \n \~ + \param[in] face - \ru Грани. + \en The face. \~ + \param[in] axis - \ru Ось кругового взгляда (ось токарного сечения). + \en The axis of lathe section. \~ + \param[out] result - \ru Выходной массив линий очерка. + \en The output array of isocline curves. \~ + \param[in] version - \ru Версия построения. + \en The version. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Mapping +*/ +// --- +MATH_FUNC (MbResultType) SilhouetteCurve( const MbFace & face, + const MbAxis3D & axis, + RPArray & curves, + VERSION version = Math::DefaultMathVersion() ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения двух поверхностей. + \en Create the intersection curves of two surfaces. \~ + \details \ru Создать кривые пересечения двух поверхностей. Результат - массив кривых пересечения поверхностей. \n + \en Create the intersection curves of two surfaces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] surface1 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] surface2 - \ru Вторая поверхность. + \en The second surface. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \warning \ru Лучше использовать IntersectionCurve на гранях, т.к. границы поверхностей могут бы неточные, \n + что приведет к неточному положению концов кривых пересечения в результате операции. \n + В гранях же границы поверхности точные, т.к. хранятся в виде кривых пересечения, + а не виде двумерных кривых. \n + \en It is better to use IntersectionCurve on faces since the surfaces bounds can be inexact, \n + and it will result in inexact position of intersection curves ends. \n + But the surface bounds in faces are exact since they are stored in the form of intersection curves, + not in the form of two-dimensional curves. \n \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, + const MbSurface & surface2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения двух граней. + \en Create intersection curves of two faces. \~ + \details \ru Создать кривые пересечения двух граней. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two faces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] face1 - \ru Первая грань оболочки. + \en The first face of the shell. \~ + \param[in] face2 - \ru Вторая грани оболочки. + \en The second face of the shell. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IntersectionCurve( MbFace & face1, + MbFace & face2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения граней двух оболочек. + \en Create intersection curves of two shells faces. \~ + \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ + \param[in] faceIndices1 - \ru Номера граней в первой оболочке. + \en The numbers of faces in the first shell. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ + \param[in] faceIndices2 - \ru Номера граней во второй оболочке. + \en The numbers of faces in the second shell. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, + const MbSolid & solid2, const SArray & faceIndices2, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривые пересечения граней двух оболочек. + \en Create intersection curves of two shells faces. \~ + \details \ru Создать кривые пересечения граней двух оболочек. Результат - массив кривых пересечения поверхностей. \n + \en Create intersection curves of two shells faces. The result is an array of intersection curves of surfaces. \n \~ + \param[in] solid1 - \ru Первая оболочка. + \en The first shell. \~ + \param[in] faceIndices1 - \ru Номера граней в первой оболочке. + \en The numbers of faces in the first shell. \~ + \param[in] same1 - \ru Использовать ли тот же журнал построителей первого тела или сделать копию. + \en Flag whether to use the same creators of the first body or make a copy. \~ + \param[in] solid2 - \ru Вторая оболочка. + \en The second shell. \~ + \param[in] faceIndices2 - \ru Номера граней во второй оболочке. + \en The numbers of faces in the second shell. \~ + \param[in] same2 - \ru Использовать ли тот же самый журнал построителей второго тела или сделать копию. + \en Flag whether to use the same creators of the second body or make a copy. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSolid & solid1, const SArray & faceIndices1, const bool same1, + const MbSolid & solid2, const SArray & faceIndices2, const bool same2, + const MbSNameMaker & snMaker, MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать линию пересечения поверхностей. + \en Create an intersection curve of surfaces. \~ + \details \ru Создать линию пересечения поверхностей surf1 и surf2 по известным началу и концу линии пересечения. \n + \en Create an intersection curve of surfaces 'surf1' and 'surf2' from the specified start point and end point of the intersection curve. \n \~ + \param[in] surface1 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] ext1 - \ru На расширенной первой поверхности. + \en Whether to create on the extended surface. \~ + \param[in] uv1beg - \ru Начальная точка на первой поверхности. + \en The start point on the first surface. \~ + \param[in] uv1end - \ru Конечная точка на первой поверхности. + \en The end point on the first surface. \~ + \param[in] surface2 - \ru Вторая поверхность. + \en The second surface. \~ + \param[in] ext2 - \ru На расширенной второй поверхности. + \en Whether to create on the extended second surface. \~ + \param[in] uv2beg - \ru Начальная точка на второй поверхности. + \en The start point on the second surface. \~ + \param[in] uv2end - \ru Конечная точка на второй поверхности. + \en The end point on the second surface. \~ + \param[in] dir - \ru Начальное направление создания линии пересечения. + \en The start direction for intersection curve creation. \~ + \param[out] result1 - \ru Двумерная кривая на первой поверхности. + \en The two-dimensional curve on the first surface. \~ + \param[out] result2 - \ru Двумерная кривая на второй поверхности. + \en The two-dimensional curve on the second surface. \~ + \param[out] label - \ru Тип полученной кривой пересечения. + \en The resultant intersection curve type. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) IntersectionCurve( const MbSurface & surface1, bool ext1, + const MbCartPoint & uv1beg, + const MbCartPoint & uv1end, + const MbSurface & surface2, bool ext2, + const MbCartPoint & uv2beg, + const MbCartPoint & uv2end, + const MbVector3D & dir, + MbCurve *& result1, + MbCurve *& result2, + MbeCurveBuildType & label ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать линию пересечения поверхностей. + \en Create an intersection curve of surfaces. \~ + \details \ru Создать линию пересечения поверхностей surf1 и surf2 по известным началу и концу линии пересечения и вспомогательной кривой. \n + \en Create an intersection curve of surfaces 'surf1' and 'surf2' from the specified start point and end point of the intersection curve + and guide curve that approximates the desired curve. \n \~ + \param[in] surface1 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] ext1 - \ru На расширенной первой поверхности. + \en Whether to create on the extended surface. \~ + \param[in] uv1beg - \ru Начальная точка на первой поверхности. + \en The start point on the first surface. \~ + \param[in] uv1end - \ru Конечная точка на первой поверхности. + \en The end point on the first surface. \~ + \param[in] surface2 - \ru Вторая поверхность. + \en The second surface. \~ + \param[in] ext2 - \ru На расширенной второй поверхности. + \en Whether to create on the extended second surface. \~ + \param[in] uv2beg - \ru Начальная точка на второй поверхности. + \en The start point on the second surface. \~ + \param[in] uv2end - \ru Конечная точка на второй поверхности. + \en The end point on the second surface. \~ + \param[in] guideCurve - \ru Направляющая кривая, приближенно описывающая искомую кривую. + \en The guide curve that approximates the desired curve. \~ + \param[in] useRedetermination - \ru Флаг, определяющий нужно ли уточнять шаг построения следующей точки по сравнению с функцией DeviationStep. + \en The flag that determines whether it is necessary to specify the next point build step as compared to the DeviationStep function. \~ + \param[in] checkPoles - \ru Флаг необходимости проверки и корректировки полюсных точек. + \en The flag that determines whether it is necessary to check and correct pole points. \~ + \param[out] result1 - \ru Двумерная кривая на первой поверхности. + \en The two-dimensional curve on the first surface. \~ + \param[out] result2 - \ru Двумерная кривая на второй поверхности. + \en The two-dimensional curve on the second surface. \~ + \param[out] label - \ru Тип полученной кривой пересечения. + \en The resultant intersection curve type. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC( MbResultType ) IntersectionCurve( const MbSurface & surf1, bool ext1, + const MbCartPoint & uv1beg, + const MbCartPoint & uv1end, + const MbSurface & surf2, bool ext2, + const MbCartPoint & uv2beg, + const MbCartPoint & uv2end, + const MbCurve3D * guideCurve, + bool useRedetermination, + bool checkPoles, + MbCurve *& pCurve1, + MbCurve *& pCurve2, + MbeCurveBuildType & label ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать пространственный сплайн через точки и с сопряжениями. + \en Create a spatial spline through points and with the given derivatives. \~ + \details \ru Создать пространственный сплайн через точки и с сопряжениями. \n + Примечания: \n + Если есть сопряжения, то количество сопряжений должно быть равно количеству точек. \n + Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n + \en Create a spatial spline through points and with the given derivatives. \n + Notes: \n + If derivatives are specified, the number of derivatives should be equal to the number of points. \n + Missing derivatives should be represented by null pointers in the array \n \~ + \param[in] points - \ru Точки. + \en Points. \~ + \param[in] paramType - \ru Тип параметризации. + \en The parametrization type. \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline degree. \~ + \param[in] closed - \ru Замкнутость сплайна. + \en The spline closedness. \~ + \param[in] transitions - \ru Заданные сопряжения. + \en The specified derivatives. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать пространственный сплайн по точкам и с сопряжениями. + \en Create a spatial spline from points and derivatives. \~ + \details \ru Создать пространственный сплайн по точкам и с сопряжениями. \n + \en Create a spatial spline from points and derivatives. \n \~ + \param[in] points - \ru Множество точек. + \en An array of points. \~ + \param[in] degree - \ru Порядок сплайна. + \en A spline degree. \~ + \param[in] closed - \ru Строить замкнутый сплайн. + \en Create a closed spline. \~ + \param[in] weights - \ru Множество весов точек. + \en An array of points weights. \~ + \param[in] knots - \ru Узловой вектор сплайна. + \en A knot vector of the spline. \~ + \param[in] begData - \ru Сопряжение в начале. + \en The start derivative. \~ + \param[in] endData - \ru Сопряжение в конце. + \en The end derivative. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) SpaceSplineBy( const SArray & points, + size_t degree, + bool closed, + const SArray * weights, + const SArray * knots, + MbPntMatingData * begData, + MbPntMatingData * endData, + const MbSNameMaker & snMaker, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую на поверхности. + \en Create a curve on a surface. \~ + \details \ru Создать кривую на поверхности. \n + Примечания: \n + 1. Если есть сопряжения, то количество сопряжений должно быть равно количеству точек. \n + Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n + 2. Если сплайн строится через точки, то сопряжения могуть быть заданы произвольно. \n + 2. Если сплайн строится по полюсам и он незамкнут, то сопряжения могут быть только на концах. \n + 3. Если сплайн строится по полюсам и он замкнут, то сопряжения должны отсутствовать. \n + 4. Множество весов должен быть пуст или синхронизирован с массивом точек по количеству + (с опцией throughPoints веса игнорируются). \n + \en Create a curve on a surface. \n + Notes: \n + 1. If derivatives are specified, the number of derivatives should be equal to the number of points. \n + Missing derivatives should be represented by null pointers in the array \n + 2. If the spline is created from points, arbitrary derivatives can be defined. \n + 2. If the spline is created from poles and it is open, only the end derivatives can be specified. \n + 3. If the spline is constructed from poles and it is closed, the derivatives cannot be specified. \n + 4. An array of weights should be empty or synchronized with the point array by size + (with option throughPoints weights are ignored). \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] throughPoints - \ru Провести сплайн через точки. + \en Create a spline through points. \~ + \param[in] paramPnts - \ru Множество параметрических точек. + \en An array of parametric points. \~ + \param[in] paramWts - \ru Множество весов параметрических точек. + \en An array of parametric point weights. \~ + \param[in] paramClosed - \ru Строить замкнутый параметрический сплайн. + \en Create a closed parametric spline. \~ + \param[in] spaceTransitions - \ru Сопряжения в точках. + \en Derivatives in the points. \~ + \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 Возвращает код результата операции. + \en Returns operation result code. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать изопараметрическую кривую. + \en Create an isoparametric curve. \~ + \details \ru Создать изопараметрическую кривую на поверхности surface. \n + \en Create an isoparametric curve on surface 'surface'. \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] x - \ru Значение по первому параметру. + \en A value of the first parameter. \~ + \param[in] isU - \ru Первый параметр есть U. + \en Whether the first parameter is U. \~ + \param[in] yRange - \ru Диапазон по второму параметру (если не задан, используются параметрические границы поверхности). + \en A range of the second parameter (if not defined, the parametric bounds of the surface are used). \~ + \param[out] result - \ru Изопараметрическая кривая. + \en The isoparametric curve. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) IsoparametricCurve( const MbSurface & surface, + double x, bool isU, const MbRect1D * yRange, + MbCurve3D *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую - мостик, соединяющую кривые curve1 и curve2. + \en Create a transition curve connecting curves 'curve1' and 'curve2'. \~ + \details \ru Создать кривую - мостик, соединяющую кривые curve1 и curve2 кубическим сплайном Эрмита. \n + \en Create a transition curve connecting curves 'curve1' and 'curve2' by a cubic Hermite spline. \n \~ + \param[in] curve1 - \ru Сопрягаемая кривая 1. + \en A curve 1 to be connected. \~ + \param[in] t1 - \ru Параметр точки на сопрягаемой кривой 1. + \en A point parameter on the curve 1. \~ + \param[in] sense1 - \ru Начало мостика совпадает с направлением кривой curve1 (true). + \en The beginning of the transition curve is equal to the direction of 'curve1' (true). \~ + \param[in] curve2 - \ru Сопрягаемая кривая 2. + \en A curve 2 to be connected. \~ + \param[in] t2 - \ru Параметр точки на сопрягаемой кривой 2. + \en A point parameter on the curve 2. \~ + \param[in] sense2 - \ru Конец мостика совпадает с направлением кривой curve2 (true). + \en The end of the transition curve is equal to the direction of 'curve2' (true). \~ + \param[in] names - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) BridgeCurve( const MbCurve3D & curve1, double t1, bool sense1, + const MbCurve3D & curve2, double t2, bool sense2, + const MbSNameMaker & names, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать составную кривую плавного соединения концов двух кривых. + \en Create a composite curve smoothly connecting two curves ends. \~ + \details \ru Создать составную кривую плавного соединения концов двух кривых. \n + Полученная кривая состоит из трёхмерной дуги радиуса radius1, + отрезка (в определенных случаях отрезок отсутствует), + трёхмерной дуги радиуса radius2. + \en Create a composite curve smoothly connecting two curves ends. \n + The constructed curve consists of a three-dimensional arc of radius 'radius1', + a segment (in specific cases a segment is absent), + a three-dimensional arc of radius 'radius2'. \~ + \param[in] curve1 - \ru Соединяемая кривая 1. + \en A curve 1 to be connected. \~ + \param[in] isBegin1 - \ru Начало соединяемой кривой 1 (true). + \en The beginning of the curve 1 (true). \~ + \param[in] radius1 - \ru Радиус сопряжения у соединяемой кривой 1. + \en The conjugation raidus of curve 1. \~ + \param[in] curve2 - \ru Соединяемая кривая 2. + \en A curve 2 to be connected. \~ + \param[in] isBegin2 - \ru Начало соединяемой кривой 2 (true). + \en The beginning of the curve 2 (true). \~ + \param[in] radius2 - \ru Радиус сопряжения у соединяемой кривой 2. + \en The conjugation raidus of curve 2. \~ + \param[in] names - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) ConnectingCurve( const MbCurve3D & curve1, bool isBegin1, double radius1, + const MbCurve3D & curve2, bool isBegin2, double radius2, + const MbSNameMaker & names, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать соединительную NURBS кривую для кривых curve1 и curve2. + \en Create a connecting NURBS curve for curves 'curve1' and 'curve2'. \~ + \details \ru Создать соединительную NURBS кривую для кривых curve1 и curve2. \n + t1 и t2 - параметры кривых curve1 и curve2, в точках которых начинается и заканчивается соединение.\n + \en Create a connecting NURBS curve for curves 'curve1' and 'curve2'. \n + t1 and t2 are parameters of curves 'curve1' and 'curve2' which correspond to the start point and the end point of the connecting curve.\n \~ + \param[in] curve1 - \ru Соединяемая кривая 1. + \en A curve 1 to be connected. \~ + \param[in] t1 - \ru Параметр точки на кривой 1. + \en A point parameter on curve 1. \~ + \param[in] mating1 - \ru Тип соединения кривой 1. + \en The connection type for curve 1. \~ + \param[in] curve2 - \ru Соединяемая кривая 2. + \en A curve 2 to be connected. \~ + \param[in] t2 - \ru Параметр точки на кривой 2. + \en A point parameter on curve 2. \~ + \param[in] mating2 - \ru Тип соединения кривой 2. + \en The connection type for curve 2. \~ + \param[in] tension1 - \ru Параметр "натяжение" соединительной кривой на стыке с кривой 1 ( 0<= tension1 <=1). + \en The "tension" parameter of the connecting curve at the intersection with the curve 1 (0 <= tension1 <=1). \~ + \param[in] tension2 - \ru Параметр "натяжение" соединительной кривой на стыке с кривой 2( 0<= tension2 <=1). + \en The "tension" parameter of the connecting curve at the intersection with the curve 2 (0 <= tension2 <=1). \~ + \param[in] names - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbResultType) ConnectingSpline( const MbCurve3D & curve1, double t1, MbeMatingType mating1, + const MbCurve3D & curve2, double t2, MbeMatingType mating2, + double tension1, double tension2, + const MbSNameMaker & names, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую для плавного соединения (скругления) кривых. + \en Create a fillet curve for curves. \~ + \details \ru Создать кривую для плавного соединения (скругления) кривых. \n + Для плавного сопряжения кривых curve1 и curve2 строится кривая filletCurve. \n + При входе t1 и t2 - начальные приближения, определяющие сектор построения скругления, + w1 и w2 - не используются. \n + При входе type - тип скругления (обычное или на поверхности). \n + На выходе t1 и t2 - будут равны параметрам касания кривых curve1 и curve2 с кривой filletCurve. \n + На выходе t1 и w1 - определяют параметры сохраняемого участка при обрезке кривой curve1. \n + На выходе t2 и w2 - определяют параметры сохраняемого участка при обрезке кривой curve2. \n + Параметр radius - радиус дуги или цилиндра. \n + Если радиус radius не задан (равен нулю), то он вычисляется из условия, + что начало кривой сопряжения будет находится в точке с параметором t1, + t1 и t2 - параметры кривых curve1 и curve2, в соответствующих точках которых начинается и заканчивается скругление. \n + Параметр sense - прямое или обратное направление кривой скругления. \n + Кривая filletCurve - это кривая сопряжения, дуга (когда surface == NULL) или кривая на поверхности цилиндра surface. \n + Поверхность surface - это цилиндрическая поверхность, на которой строится кривая сопряжения в общем случае. + Для управления жизненным циклом поверхномти следует миспользовать методы ::AddRefItem(surface) и ::ReleaseItem(surface). \n + \en Create a fillet curve for curves. \n + Curve 'filletCurve' is created for smooth connection of curves 'curve1' and 'curve2'. \n + On input t1 and t2 are the initial estimations which determine a sector for fillet construction, + w1 and w2 are not used. \n + On input 'type' is a fillet type (ordinary or on a surface). \n + On output t1 and t2 are the parameters of touching of curves 'curve1' and 'curve2' with curve 'filletCurve'. \n + On output t1 and w1 determines parameters of a part to be kept while trimming curve1. \n + On output t2 and w2 determines parameters of a part to be kept while trimming curve2. \n + Parameter 'radius' is a radius of an arc or a cylinder. \n + If radius 'radius' is not defined (equal to zero), it is computed from the condition + 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 + 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 соединения с кривой соединения. + \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 соединения с кривой соединения. + \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 Радиус дуги или цилиндра. + \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. \~ + \param[out] unchanged - \ru Не изменился радиус соединения (true) или изменился (false). + \en The fillet radius has not changed (true) or has changed (false). \~ + \param[in] type - \ru Тип скругления. + \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] result - \ru Каркас с построенными кривыми. + \en The frame with the constructed curves. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) FilletCurve( const MbCurve3D & curve1, double & t1, double & w1, + const MbCurve3D & curve2, double & t2, double & w2, + double & radius, bool sense, bool & unchanged, + const MbeConnectingType type, + const MbSNameMaker & names, + MbElementarySurface *& surface, + MbWireFrame *& result ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить изменение радиуса при перемещении средней точки кривой скругления. + \en Determine the radius variation while translating the middle point of the fillet curve. \~ + \details \ru Определить изменение радиуса при перемещении средней точки кривой скругления \n + от центра на расстояние len (с учётом знака len). \n + \en Determine the radius variation while translating the middle point of the fillet curve \n + from the centre on distance 'len' (signed). \n \~ + \param[in] filletCurve - \ru Кривая скругления. + \en The fillet curve. \~ + \param[in] radius - \ru Радиус скругления. + \en The radius of fillet. \~ + \param[in] sense - \ru Направления смещения средней точки кривой скругления. + \en A direction of the middle point of the fillet curve translation. \~ + \param[in] len - \ru Величина смещения средней точки кривой скругления. + \en A value of translation of the fillet curve middle point. \~ + \param[in] curve1 - \ru Первая сопрягаемая кривая. + \en The first curve to fillet. \~ + \param[in] t1 - \ru Параметр начала кривой скругления на первой сопрягаемой кривой. + \en The parameter of fillet curve start point on the first curve. \~ + \param[in] curve2 - \ru Вторая сопрягаемая кривая. + \en The second curve to fillet. \~ + \param[in] t2 - \ru Параметр конца кривой скругления на второй сопрягаемой кривой. + \en The parameter of fillet curve end point on the second curve. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (double) GetFilletRadiusDelta( const MbCurve3D & filletCurve, + double radius, bool sense, double len, + const MbCurve3D & curve1, double t1, + const MbCurve3D & curve2, double t2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить изменение радиуса при перемещении средней точки кривой скругления. + \en Determine the radius variation while translating the middle point of the fillet curve. \~ + \details \ru Определить изменение радиуса при перемещении средней точки кривой скругления \n + от центра на расстояние len (с учётом знака len). \n + \en Determine the radius variation while translating the middle point of the fillet curve \n + from the centre on distance 'len' (signed). \n \~ + \param[in] filletCurve - \ru Кривая скругления. + \en The fillet curve. \~ + \param[in] radius - \ru Радиус скругления. + \en The radius of fillet. \~ + \param[in] sense - \ru Направления смещения средней точки кривой скругления. + \en A direction of the middle point of the fillet curve translation. \~ + \param[in] len - \ru Величина смещения средней точки кривой скругления. + \en A value of translation of the fillet curve middle point. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (double) GetFilletRadiusDelta( const MbCurve3D & filletCurve, + double radius, bool sense, double len ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую для плавного соединения (скругления) всех кривых контура. + \en Create a curve for fillet of all the curves of a contour. \~ + \details \ru Создать кривую для плавного соединения (скругления) всех кривых контура contour. \n + type - тип скругления (обычное или на поверхности). \n + radiuses - радиусы скругления, i-й радиус соответствует стыку i-го и i+1-го сегмента. \n + Если две кривых в контуре гладко стыкуются, в этом стыке скругление не делается, радиус игнорируется. \n + \en Create a curve for fillet of all the curves of a contour 'contour'. \n + 'type' is a fillet type (ordinary or on a surface). \n + 'radiuses' are the fillet radii, the i-th radius corresponds to the joint of the i-th and the i+1-th segments. \n + If two curves in contours are smoothly connected, the fillet is not created at this joint, the radius is ignored. \n \~ + \param[in] contour - \ru Исходный контур. + \en The initial contour. \~ + \param[in] radiuses - \ru Множество радиусов скругления. + \en An array of fillet radii. \~ + \param[out] result - \ru Контур со скруглениями. Имя сегмента скругления - Hash32SN() имен исходных сегменов. + \en The contour with the fillets. The name of the fillet segment - Hash32SN() of initial segments names. \~ + \param[in] type - \ru Тип выполняемых скруглений. + \en The type of fillets. \~ + \return \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbResultType) CreateContourFillets( const MbContour3D & contour, + SArray & radiuses, + MbCurve3D *& result, + const MbeConnectingType type ); + + +#endif // __ACTION_SURFACE_CURVE_H diff --git a/C3d/Include/alg_base.h b/C3d/Include/alg_base.h index 6f8e9d7..3f9ef51 100644 --- a/C3d/Include/alg_base.h +++ b/C3d/Include/alg_base.h @@ -287,7 +287,7 @@ inline bool ArFind( const Vector & arParam, double t, ptrdiff_t & id ) } while ( rangeId > 8 ) { // \ru До тех пор пока диапазон больше восьми \en Until the range contains more than eight elements - ptrdiff_t mIndex = ( rangeId / 2 ) + idLeft; // \ru Найти индекс в середине диапазона \en Find the index in the middle of the range + size_t mIndex = ( rangeId / 2 ) + idLeft; // \ru Найти индекс в середине диапазона \en Find the index in the middle of the range if ( arParam[mIndex] < t ) // \ru Если t больше серединного параметра \en If t is greater than the middle parameter idLeft = mIndex; // \ru Установить левую границу \en Set the left bound @@ -507,71 +507,8 @@ bool IsMonotonic( const TypeVector & items, bool isAscending, bool allowEqual = \ingroup Base_Algorithms */ // --- -template -bool ArePointsOnLine( const SArray & pnts, double metricEps = METRIC_EPSILON ) -{ - bool onLine = false; - - size_t cnt = pnts.size(); - double lenEps = std_min( LENGTH_EPSILON, metricEps ); - lenEps = std_max( EXTENT_EQUAL, lenEps ); - - if ( cnt > 2 ) { - const Point & pnt0 = pnts[0]; - - Vector tau( pnt0, pnts[1] ); - double tauLen = tau.Length(); - if ( tauLen <= lenEps ) { - for ( size_t k = 2; k < cnt; k++ ) { - const Point & pntk = pnts[k]; - tau.Init( pnt0, pntk ); - tauLen = tau.Length(); - if ( tauLen > lenEps ) - break; - } - } - if ( tauLen > lenEps ) { - onLine = true; - tau /= tauLen; - Vector vect; - Point pnt; - for ( size_t k = 1; k < cnt; k++ ) { - const Point & pntk = pnts[k]; - vect.Init( pnt0, pntk ); - vect = tau * (vect * tau); - pnt = pnt0 + vect; - if ( pntk.DistanceToPoint( pnt ) > metricEps ) { - onLine = false; - break; - } - } - } - } - else if ( cnt == 2 ) { - if ( pnts[0].DistanceToPoint( pnts[1] ) > lenEps ) - onLine = true; - } - - return onLine; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Лежат ли точки на линии. - \en Whether points lie on the line. \~ - \details \ru Лежат ли точки на линии (улучшенный вариант IsPointOnLine). \n - \en Whether points lie on the line (improved variant of IsPointOnLine). \n \~ - \param[in] pnts - \ru Набор точек. - \en Point set. \~ - \param[in] metricEps - \ru Точность проверки. - \en Check accuracy. \~ - \return \ru true, если точки лежат на линии, \n иначе false - \en True if points lie on line, \n otherwise false. \~ - \ingroup Base_Algorithms -*/ -// --- -template -bool ArePointsOnLine( const std::vector & pnts, double metricEps = METRIC_EPSILON ) +template +bool ArePointsOnLine( const PointsVector & pnts, double metricEps = METRIC_EPSILON ) { bool onLine = false; @@ -635,8 +572,8 @@ bool ArePointsOnLine( const std::vector & pnts, double metricEps = METRIC \ingroup Base_Algorithms */ // --- -template -bool IsPlanar( const PointsVector & pnts, MbPlacement3D * place, double mEps = METRIC_EPSILON ) +template +bool IsPlanar( const SpacePointsVector & pnts, MbPlacement3D * place, double mEps = METRIC_EPSILON ) { bool isPlanar = false; mEps = ::fabs( mEps ); @@ -743,8 +680,8 @@ bool IsPlanar2( const Array2 & pnts, MbPlacement3D * place, double mEps = \en Set the range of parameter. \~ \details \ru Установить (репараметризовать) область изменения параметра в массиве. \n \en Set (reparametrize) range of parameter in the array. \n \~ - \param[in,out] params - \ru Множество параметров, упорядоченный по возрастанию параметра. - \en The array of parameters sorted in ascending order. \~ + \param[in,out] tarr - \ru Множество параметров, упорядоченных по возрастанию параметра. + \en The array of parameters sorted in ascending order. \~ \param[in] pmin - \ru Минимальное значение параметра. \en Minimal value of parameter. \~ \param[in] pmax - \ru Максимальное значение параметра. diff --git a/C3d/Include/alg_circle_curve.h b/C3d/Include/alg_circle_curve.h index 8769b69..5a442d5 100644 --- a/C3d/Include/alg_circle_curve.h +++ b/C3d/Include/alg_circle_curve.h @@ -233,7 +233,7 @@ private: \ingroup Curve_Modeling */ // --- -MATH_FUNC (ptrdiff_t) CircleTanLineLineRad( MbLine & pl1, MbLine & pl2, double rad, MbTempCircle * pc ); +MATH_FUNC (ptrdiff_t) CircleTanLineLineRad( const MbLine & pl1, const MbLine & pl2, double rad, MbTempCircle * pc ); //------------------------------------------------------------------------------ @@ -280,7 +280,7 @@ MATH_FUNC (ptrdiff_t) CircleTanLineCircleRadius( const MbLine & pl1, const MbArc \ingroup Curve_Modeling */ // --- -MATH_FUNC (ptrdiff_t) CircleTanCircleCircleRad( MbArc & pc1, MbArc & pc2, double rad, +MATH_FUNC (ptrdiff_t) CircleTanCircleCircleRad( const MbArc & pc1, const MbArc & pc2, double rad, MbTempCircle * pc ); @@ -300,7 +300,7 @@ MATH_FUNC (ptrdiff_t) CircleTanCircleCircleRad( MbArc & pc1, MbArc & pc2, double \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTanCurveCentre( const MbCurve & pCurve, MbCartPoint & pnt, +MATH_FUNC (void) CircleTanCurveCentre( const MbCurve & pCurve, const MbCartPoint & pnt, PArray & pCircle ); @@ -322,9 +322,10 @@ MATH_FUNC (void) CircleTanCurveCentre( const MbCurve & pCurve, MbCartPoint & pnt \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTangentCurveTwoPoints( const MbCurve & pCurve, - MbCartPoint & on1, MbCartPoint & on2, - PArray & pCircle ); +MATH_FUNC (void) CircleTangentCurveTwoPoints( const MbCurve & pCurve, + const MbCartPoint & on1, + const MbCartPoint & on2, + PArray & pCircle ); //------------------------------------------------------------------------------ @@ -345,8 +346,10 @@ MATH_FUNC (void) CircleTangentCurveTwoPoints( const MbCurve & pCurve, \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTangentCurveRPointOn( const MbCurve & pCurve, double radius, MbCartPoint & on, - PArray & pCircle ); +MATH_FUNC (void) CircleTangentCurveRPointOn( const MbCurve & pCurve, + double radius, + const MbCartPoint & on, + PArray & pCircle ); //------------------------------------------------------------------------------ @@ -367,8 +370,10 @@ MATH_FUNC (void) CircleTangentCurveRPointOn( const MbCurve & pCurve, double radi \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTanTwoCurvesRadius( const MbCurve & pCurve1, const MbCurve & pCurve2, double rad, - PArray & pCircle ); +MATH_FUNC (void) CircleTanTwoCurvesRadius( const MbCurve & pCurve1, + const MbCurve & pCurve2, + double rad, + PArray & pCircle ); //------------------------------------------------------------------------------ @@ -389,8 +394,10 @@ MATH_FUNC (void) CircleTanTwoCurvesRadius( const MbCurve & pCurve1, const MbCurv \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTanTwoCurvesPointOn( const MbCurve & pCurve1, const MbCurve & pCurve2, const MbCartPoint & pOn, - PArray & pCircle ); +MATH_FUNC (void) CircleTanTwoCurvesPointOn( const MbCurve & pCurve1, + const MbCurve & pCurve2, + const MbCartPoint & pOn, + PArray & pCircle ); //------------------------------------------------------------------------------ @@ -411,8 +418,10 @@ MATH_FUNC (void) CircleTanTwoCurvesPointOn( const MbCurve & pCurve1, const MbCur \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleOriginOneTangentTwo( const MbCurve & pCurve1, const MbCurve & pCurve2, const MbCartPoint & pp, - RPArray & pCircle ); +MATH_FUNC (void) CircleOriginOneTangentTwo( const MbCurve & pCurve1, + const MbCurve & pCurve2, + const MbCartPoint & pp, + RPArray & pCircle ); //------------------------------------------------------------------------------ @@ -441,7 +450,7 @@ MATH_FUNC (void) CircleOriginOneTangentTwo( const MbCurve & pCurve1, const MbCur \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTanCurvePointOnAngle( MbCurve & curve, MbCartPoint & p1, double angle, +MATH_FUNC (void) CircleTanCurvePointOnAngle( const MbCurve & curve, const MbCartPoint & p1, double angle, PArray & circles ); @@ -463,9 +472,10 @@ MATH_FUNC (void) CircleTanCurvePointOnAngle( MbCurve & curve, MbCartPoint & p1, \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) ArcTangentCurveTwoPoints( const MbCurve & pCurve, - MbCartPoint & on1, MbCartPoint & on2, - PArray & arc ); +MATH_FUNC (void) ArcTangentCurveTwoPoints( const MbCurve & pCurve, + const MbCartPoint & on1, + const MbCartPoint & on2, + PArray & arc ); //------------------------------------------------------------------------------ @@ -486,8 +496,10 @@ MATH_FUNC (void) ArcTangentCurveTwoPoints( const MbCurve & pCurve, \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) ArcTangentCurveRPointOn( const MbCurve & pCurve, double radius, MbCartPoint & on, - PArray & arc ); +MATH_FUNC (void) ArcTangentCurveRPointOn( const MbCurve & pCurve, + double radius, + const MbCartPoint & on, + PArray & arc ); //------------------------------------------------------------------------------ @@ -506,8 +518,9 @@ MATH_FUNC (void) ArcTangentCurveRPointOn( const MbCurve & pCurve, double radius, \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) ArcTangentCurveContinue( MbLine & line, MbCartPoint & p2, - PArray & arc ); +MATH_FUNC (void) ArcTangentCurveContinue( const MbLine & line, + const MbCartPoint & p2, + PArray & arc ); //------------------------------------------------------------------------------ @@ -530,8 +543,10 @@ MATH_FUNC (void) ArcTangentCurveContinue( MbLine & line, MbCartPoint & p2, \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) ArcTangentCurveRadContinue( MbLine & line, double rad, MbCartPoint & p2, - PArray & arc ); +MATH_FUNC (void) ArcTangentCurveRadContinue( const MbLine & line, + double rad, + const MbCartPoint & p2, + PArray & arc ); //------------------------------------------------------------------------------ @@ -556,9 +571,11 @@ MATH_FUNC (void) ArcTangentCurveRadContinue( MbLine & line, double rad, MbCartPo \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) CircleTanThreeCurves( const MbCurve * curve1, const MbCurve * curve2, const MbCurve * curve3, - MbCartPoint & pnt, - PArray & circle ); +MATH_FUNC (void) CircleTanThreeCurves( const MbCurve * curve1, + const MbCurve * curve2, + const MbCurve * curve3, + const MbCartPoint & pnt, + PArray & circle ); //----------------------------------------------------------------------------- @@ -576,7 +593,7 @@ MATH_FUNC (void) CircleTanThreeCurves( const MbCurve * curve1, const MbCurve * c */ // --- MATH_FUNC (void) CreateNewCircles( PArray & cTmp, - PArray & pCircle ); + PArray & pCircle ); #endif // __ALG_CIRCLE_CURVE_H diff --git a/C3d/Include/alg_curve_delete_part.h b/C3d/Include/alg_curve_delete_part.h index 7721781..d141186 100644 --- a/C3d/Include/alg_curve_delete_part.h +++ b/C3d/Include/alg_curve_delete_part.h @@ -38,9 +38,10 @@ \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbeState) DeleteCurvePart( List & curveList, - const MbCartPoint & pnt, - MbCurve * curve, MbCurve *& part2 ); +MATH_FUNC (MbeState) DeleteCurvePart( List & curveList, + const MbCartPoint & pnt, + MbCurve * curve, + MbCurve *& part2 ); //------------------------------------------------------------------------------ @@ -70,7 +71,8 @@ MATH_FUNC (MbeState) DeleteCurvePart( List & curveList, MATH_FUNC (MbeState) DeleteCurvePart( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, - MbCurve * curve, MbCurve *& part2 ); + MbCurve * curve, + MbCurve *& part2 ); //------------------------------------------------------------------------------ @@ -99,9 +101,10 @@ MATH_FUNC (MbeState) DeleteCurvePart( const MbCartPoint & p1, \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbeState) TrimmCurvePart( List & curveList, - const MbCartPoint & pnt, - MbCurve * curve, MbCurve *& part2 ); +MATH_FUNC (MbeState) TrimmCurvePart( List & curveList, + const MbCartPoint & pnt, + MbCurve * curve, + MbCurve *& part2 ); //------------------------------------------------------------------------------ @@ -133,13 +136,14 @@ MATH_FUNC (MbeState) TrimmCurvePart( List & curveList, MATH_FUNC (MbeState) TrimmCurvePart( const MbCartPoint & p1, const MbCartPoint & p2, const MbCartPoint & p3, - MbCurve * curve, MbCurve *& part2 ); + MbCurve * curve, + MbCurve *& part2 ); //------------------------------------------------------------------------------ -/** \brief \ru Выровнить кривую. +/** \brief \ru Выровнять кривую. \en Justify the curve. \~ - \details \ru Выровнить кривую по отношению к заданной кривой и точке на кривой.\n + \details \ru Выровнять кривую по отношению к заданной кривой и точке на кривой.\n Кривая усекается точкой пересечения ее с граничной кривой, ближайшей к заданной точке. Остается часть кривой со стороны указанной точки. \en Justify the curve relative to the given curve and a point on the curve.\n @@ -160,8 +164,10 @@ MATH_FUNC (MbeState) TrimmCurvePart( const MbCartPoint & p1, \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbeState) JustifyCurve( MbCurve * curve, MbCurve * limitCurve, - const MbCartPoint & pnt, MbCurve *& part2 ); +MATH_FUNC (MbeState) JustifyCurve( MbCurve * curve, + const MbCurve * limitCurve, + const MbCartPoint & pnt, + MbCurve *& part2 ); //------------------------------------------------------------------------------ @@ -266,15 +272,16 @@ MATH_FUNC (MbeState) BreakByCurvesArr( MbCurve & curve, \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbeState) BreakCurve( MbCurve & curve, - const MbCartPoint & p1, const MbCartPoint & p2, +MATH_FUNC (MbeState) BreakCurve( MbCurve & curve, + const MbCartPoint & p1, + const MbCartPoint & p2, PArray & part2 ); //------------------------------------------------------------------------------ /** \brief \ru Разбить кривую.. \en Split the curve. \~ - \details \ru Разбить кривую на ресколько равных частей. + \details \ru Разбить кривую на несколько равных частей. \en Split the curve by several equal pieces. \~ \param[in, out] curve - \ru Разбиваемая кривая. \en The curve for splitting. \~ @@ -294,22 +301,23 @@ MATH_FUNC (MbeState) BreakCurveNParts( MbCurve & curve, ptrdiff_t partsCount, co //------------------------------------------------------------------------------ -/** \brief \ru Удлиннить кривую. +/** \brief \ru Удлинить кривую. \en Extend the curve. \~ - \details \ru Удлиннить кривую curve до кривой-границы limitCurve с конца ближайшего к точке pnt + \details \ru Удлинить кривую curve до кривой-границы limitCurve с конца ближайшего к точке pnt \en Extend the curve to the given curve-boundary limitCurve from the end nearest to the given point pnt. \~ \param[in, out] curve - \ru Изменяемая кривая. \en The modified curve. \~ \param[in] limitCurve - \ru Кривая-граница. \en The curve-boundary \~ - \param[in] pnt - \ru Точка, показывающая удлинняемый конец кривой. + \param[in] pnt - \ru Точка, показывающая удлиняемый конец кривой. \en The point indicating the extended end of a curve. \~ \return \ru Состояние кривой после ее модификации. \en The state of a curve after modification. \~ \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbeState) ExtendCurveToCurve( MbCurve * curve, const MbCurve * limitCurve, +MATH_FUNC (MbeState) ExtendCurveToCurve( MbCurve * curve, + const MbCurve * limitCurve, const MbCartPoint & pnt ); diff --git a/C3d/Include/alg_curve_distance.h b/C3d/Include/alg_curve_distance.h index 853aae7..f7b4ec4 100644 --- a/C3d/Include/alg_curve_distance.h +++ b/C3d/Include/alg_curve_distance.h @@ -260,15 +260,14 @@ MATH_FUNC (void) CircleCentreOnCurveTwoPoints( const MbCurve & pCurve, const MbC //------------------------------------------------------------------------------ -/** \brief \ru Расстояние между объектами. - \en Distance between objects. \~ - \details \ru Расстояние между двумя объектами.\n - \en The distance between two objects.\n \~ +/** \brief \ru Расстояние между кривыми. + \en Distance between curves. \~ + \details \ru Расстояние между двумя кривыми.\n + \en The distance between two curves.\n \~ \ingroup Algorithms_2D */ // --- -class MATH_CLASS MbDistance { -public : +struct MATH_CLASS MbDistance { double u; ///< \ru Параметр на первой кривой. \en Parameter on the first curve. double v; ///< \ru Параметр на второй кривой. \en Parameter on the second curve. double d; ///< \ru Минимальное расстояние. \en Minimal distance. diff --git a/C3d/Include/alg_curve_envelope.h b/C3d/Include/alg_curve_envelope.h index f545999..2eebdb3 100644 --- a/C3d/Include/alg_curve_envelope.h +++ b/C3d/Include/alg_curve_envelope.h @@ -31,17 +31,18 @@ \en The array of points of intersection with the nearest curve. \~ \param[out] contour - \ru Контур для добавления сегмента. \en The contour for adding the segment to. \~ - \param[out] crossRight - \ru Узел - массив точек пересечения кривой в сторону продолжения конутра. + \param[out] crossRight - \ru Узел - массив точек пересечения кривой в сторону продолжения контура. \en The node - the array of intersection points in the side of contour extension. \~ \return \ru true, если сегмент добавлен. \en true if a segment has been added. \~ \ingroup Algorithms_2D */ // --- -MATH_FUNC (bool) BeginEnvelopeContour( MbCartPoint & insidePnt, const MbCurve * selectCurve, - SArray & cross, - MbContour & contour, - SArray & crossRight ); +MATH_FUNC (bool) BeginEnvelopeContour( const MbCartPoint & insidePnt, + const MbCurve * selectCurve, + SArray & cross, + MbContour & contour, + SArray & crossRight ); //------------------------------------------------------------------------------ @@ -58,7 +59,7 @@ MATH_FUNC (bool) BeginEnvelopeContour( MbCartPoint & insidePnt, const MbCurve * \ingroup Algorithms_2D */ // --- -MATH_FUNC (MbCurve *) FindNearestCurve( List & curveList, MbCartPoint & pnt ); +MATH_FUNC (MbCurve *) FindNearestCurve( List & curveList, const MbCartPoint & pnt ); //------------------------------------------------------------------------------ @@ -79,9 +80,10 @@ MATH_FUNC (MbCurve *) FindNearestCurve( List & curveList, MbCartPoint & \ingroup Algorithms_2D */ // --- -MATH_FUNC (void) IntersectWithAll( const MbCurve * selectCurve, - LIterator & fromCurve, - SArray & cross, bool self ); +MATH_FUNC (void) IntersectWithAll( const MbCurve * selectCurve, + LIterator & fromCurve, + SArray & cross, + bool self ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/alg_curve_equid.h b/C3d/Include/alg_curve_equid.h index 35c5abe..1f4e536 100644 --- a/C3d/Include/alg_curve_equid.h +++ b/C3d/Include/alg_curve_equid.h @@ -31,10 +31,10 @@ 1 - справа по направлению,\n 2 - с двух сторон. \en Attribute defining the side to construct:\n - 0 - on the left by derection,\n - 1 - on the right by derection,\n + 0 - on the left by direction,\n + 1 - on the right by direction,\n 2 - on the both sides. \~ - \param[in] arcMode - \ru Cпособ обхода углов:\n + \param[in] arcMode - \ru Способ обхода углов:\n true - дугой, false - срезом. \en The way of traverse of angles:\n @@ -53,9 +53,14 @@ \ingroup Algorithms_2D */ // --- -MATH_FUNC (void) Equid( const MbCurve *curve, double radLeft, double radRight, - int side, bool arcMode, bool degState, - PArray &equLeft, PArray &equRight ); +MATH_FUNC (void) Equid( const MbCurve * curve, + double radLeft, + double radRight, + int side, + bool arcMode, + bool degState, + PArray & equLeft, + PArray & equRight ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/alg_curve_fillet.h b/C3d/Include/alg_curve_fillet.h index 21d3c9f..67d2852 100644 --- a/C3d/Include/alg_curve_fillet.h +++ b/C3d/Include/alg_curve_fillet.h @@ -48,12 +48,12 @@ class MATH_CLASS MbContour; \ingroup Algorithms_2D */ // --- -MATH_FUNC (bool) Fillet( MbCurve * curve1, const MbCartPoint & pnt1, bool trim1, - MbCurve * curve2, const MbCartPoint & pnt2, bool trim2, - double rad, +MATH_FUNC (bool) Fillet( MbCurve * curve1, const MbCartPoint & pnt1, bool trim1, + MbCurve * curve2, const MbCartPoint & pnt2, bool trim2, + double rad, MbeState & state1, MbeState & state2, - MbArc *& arc ); + MbArc *& arc ); //------------------------------------------------------------------------------ @@ -94,11 +94,13 @@ MATH_FUNC (bool) Fillet( MbCurve * curve1, const MbCartPoint & pnt1, bool trim1, \ingroup Algorithms_2D */ // --- -MATH_FUNC (bool) Chamfer( MbCurve * curve1, const MbCartPoint & pnt1, bool trim1, - MbCurve * curve2, const MbCartPoint & pnt2, bool trim2, - double len, double angle, bool type, - MbeState & state1, - MbeState & state2, +MATH_FUNC (bool) Chamfer( MbCurve * curve1, const MbCartPoint & pnt1, bool trim1, + MbCurve * curve2, const MbCartPoint & pnt2, bool trim2, + double len, + double angle, + bool type, + MbeState & state1, + MbeState & state2, MbLineSegment *& lineseg ); diff --git a/C3d/Include/alg_curve_hatch.h b/C3d/Include/alg_curve_hatch.h index f315c35..4cb5e74 100644 --- a/C3d/Include/alg_curve_hatch.h +++ b/C3d/Include/alg_curve_hatch.h @@ -20,16 +20,18 @@ Для штриховки. \en Find intersection of a curve with horizontal line. For hatching. \~ - \param[in] y - \ru Координата у горизонтальной прямой. - \en The coordinate of a horizontal line. \~ - \param[in] curve - \ru Кривая. - \en The curve. \~ - \param[out] crossPnt - \ru Точки пересечения. - \en Intersection points. \~ + \param[in] y - \ru Координата у горизонтальной прямой. + \en The coordinate of a horizontal line. \~ + \param[in] curve - \ru Кривая. + \en The curve. \~ + \param[out] crossPnt - \ru Точки пересечения. + \en Intersection points. \~ + \param[in] skipTouchPoints - \ru Пропускать точки касания. true - пропускаем точки касания, false - старое поведение функции. + \en Skip touch points. true - skip touch points, false - old function behavior. \~ \ingroup Algorithms_2D */ // --- -MATH_FUNC (void) HatchIntersectLine( double y, MbCurve * curve, SArray & crossPnt ); +MATH_FUNC (void) HatchIntersectLine( double y, const MbCurve * curve, SArray & crossPnt, bool skipTouchPoints = false ); //------------------------------------------------------------------------------ @@ -48,7 +50,7 @@ MATH_FUNC (void) HatchIntersectLine( double y, MbCurve * curve, SArray & crossPnt ); +MATH_FUNC (void) HatchIntersectCircle( const MbCurve * circle, const MbCurve * curve, SArray & crossPnt ); #endif // __ALG_CURVE_HATCH_H diff --git a/C3d/Include/alg_curve_tangent.h b/C3d/Include/alg_curve_tangent.h index d16da71..6dfa427 100644 --- a/C3d/Include/alg_curve_tangent.h +++ b/C3d/Include/alg_curve_tangent.h @@ -17,8 +17,8 @@ /** \brief \ru Построить касательные прямые. \en Construct a line. \~ \details \ru Построить все возможные прямые через точку касательно данной кривой.\n - Базовая точка прямой сопадает с точкой касания. - \en Construct a line passing throgh a point and tangent to a given curve.\n + Базовая точка прямой совпадает с точкой касания. + \en Construct a line passing through a point and tangent to a given curve.\n A line origin is coincident with a tangency point. \~ \param[in] pnt - \ru Точка, через которую проходит прямая. \en The point which the line passing through. \~ @@ -26,12 +26,12 @@ \en The curve which the constructed line should be tangent to. \~ \param[out] pLine - \ru Набор прямых. \en The set of lines. \~ - \param[in] lineAsCurve - \ru Обрабатывать прямую, ломаную и отрезок как кривую в общеи мслучае. + \param[in] lineAsCurve - \ru Обрабатывать прямую, ломаную и отрезок как кривую в общем случае. \en Work with MbLline, MbPolyline, MbLineSegment as with MbCurve. \~ \ingroup Curve_Modeling */ // --- -MATH_FUNC (void) LinePointTangentCurve( MbCartPoint & pnt, const MbCurve & pCurve, +MATH_FUNC (void) LinePointTangentCurve( const MbCartPoint & pnt, const MbCurve & pCurve, PArray & pLine, bool lineAsCurve = false ); @@ -39,7 +39,7 @@ MATH_FUNC (void) LinePointTangentCurve( MbCartPoint & pnt, const MbCurve & pCurv /** \brief \ru Построить прямые под углом. \en Construct lines passing at angle. \~ \details \ru Построить прямые, проходящие под углом angle к оси 0X и касательные к кривой.\n - Базовая точка прямой сопадает с точкой касания. + Базовая точка прямой совпадает с точкой касания. \en Construct lines at angle "angle" to the axis OX and tangent to the curve.\n A line origin is coincident with a tangency point. \~ \param[in] angle - \ru Угол к оси абсцисс. @@ -60,7 +60,7 @@ MATH_FUNC (void) LineAngleTangentCurve( double angle, const MbCurve & pCurve, \en Construct lines tangent to circles. \~ \details \ru Построить прямые, касательные к двум окружностям, заданным центрами и радиусами.\n - Базовая точка прямой сопадает с точкой касания первой окружности. + Базовая точка прямой совпадает с точкой касания первой окружности. Функция строит от 0 до 4 прямых. \en Construct lines tangent to two circles. with given centers and radii.\n @@ -94,7 +94,7 @@ MATH_FUNC (ptrdiff_t) LineTan2Circles( const MbCartPoint & centre1, double radiu /** \brief \ru Построить касательную прямую. \en Construct a tangent line. \~ \details \ru Построить прямую, касательную двум кривым.\n - Базовая точка прямой сопадает с точкой касания первой кривой. + Базовая точка прямой совпадает с точкой касания первой кривой. \en Construct a line tangent to two curves.\n A line origin is coincident with a point of tangency on the first curve. \~ \param[in] pCurve1 - \ru Первая кривая, которой должна касаться построенная прямая. @@ -141,9 +141,9 @@ MATH_FUNC (ptrdiff_t) LineAngleTanCircle( double angle, const MbCartPoint & cent //------------------------------------------------------------------------------ -/** \brief \ru Перестывить прямые. +/** \brief \ru Переставить прямые. \en Swap lines. \~ - \details \ru Перестывить прямые местами. + \details \ru Переставить прямые местами. \en Swap lines. \~ \param[in] l1 - \ru Первая прямая. \en The first line. \~ diff --git a/C3d/Include/alg_dimension.h b/C3d/Include/alg_dimension.h index d80d839..3b69601 100644 --- a/C3d/Include/alg_dimension.h +++ b/C3d/Include/alg_dimension.h @@ -1,446 +1,446 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Радиальный размер к поверхности. Расстояние между поверхностями. - \en Radial dimension of surface. Distance between surfaces. \~ - \details \ru Функции построения окружности или дуги для радиального размера к поверхности. - Функция вычисления экстремальных расстояний между поверхностями. - \en Functions of construction of a circle or an arc for radial dimension of surface. - A function of calculation of extreme distances between surfaces. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef __ALG_DIMENSION_H -#define __ALG_DIMENSION_H - - -#include -#include -#include - - -class MATH_CLASS MbCartPoint3D; -class MATH_CLASS MbVector3D; -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbPlaneCurve; -class MATH_CLASS MbSurface; -class IProgressIndicator; - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Построение окружности или дуги для радиального размера к поверхности, \en Construction of a circle or an arc for radial dimension of surface -// \ru имеющей круговую параметрическую линию u=const или v=const \en which has a circular parametric line u=const or v=const. -// \ru Перечень поверхностей, имеющих параметрическую линию u=const или u=const: \en The enumeration of surfaces which have a parametric line u=const or u=const: -// MbCylinderSurface, v=const -// MbConeSurface, v=const -// MbSphereSurface, u=const -// MbTorusSurface, u=const -// MbLoftedSurface, v=const -// MbElevationSurface, v=const -// MbExtrusionSurface, v=const -// MbRevolutionSurface, u=const -// MbEvolutionSurface, u=const -// MbExactionSurface, u=const -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. - \en Construct a circle or an arc for radial dimension of surface. \~ - \details \ru Построение выполняется по заданной параметрической точке поверхности. Поверхность - должна иметь круговую параметрическую линию u=const или v=const. Перечень поверхностей, - имеющих параметрическую линию u=const или v=const: - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. - \en Construction is performed by the given parametric point on surface. A surface - should have a circular parametric line u=const or v=const. The enumeration of surfaces - which have a parametric line u=const or v=const. - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] surface_uv - \ru Координаты исходной точки на поверхности. - \en Coordinates of the initial point on surface. \~ - \param[out] plane_curve - \ru Требуемая окружность или дуга. - \en The required circle or an arc. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, - const MbCartPoint & surface_uv, - MbPlaneCurve *& plane_curve ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. - \en Construct a circle or an arc for radial dimension of surface. \~ - \details \ru Построение выполняется по заданной по заданной пространственной точке. Поверхность - должна иметь круговую параметрическую линию u=const или v=const. Перечень поверхностей, - имеющих параметрическую линию u=const или u=const: - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. - \en Construction is performed by the given spatial point. A surface - should have a circular parametric line u=const or v=const. The enumeration of surfaces - which have a parametric line u=const or v=const. - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] point - \ru Пространственные координаты исходной точки. - \en Space coordinates of the initial point. \~ - \param[out] plane_curve - \ru Требуемая окружность или дуга. - \en The required circle or an arc. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, - const MbCartPoint3D & point, - MbPlaneCurve *& plane_curve ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. - \en Construct a circle or an arc for radial dimension of surface. \~ - \details \ru Построение выполняется по заданному плейсменту. Поверхность должна иметь - круговую параметрическую линию u=const или v=const. Перечень поверхностей, имеющих - параметрическую линию u=const или u=const: - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. - \en Construction is performed by the given placement. A surface should have - a circular parametric line u=const or v=const. The enumeration of surfaces with - a parametric line u=const or v=const. - MbCylinderSurface v=const, \n MbConeSurface v=const, \n - MbSphereSurface u=const, \n MbTorusSurface u=const, \n - MbLoftedSurface v=const, \n MbElevationSurface v=const, \n - MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n - MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \param[in] place - \ru Исходный плейсмент. - \en The initial placement. \~ - \param[out] plane_curve - \ru Требуемая окружность или дуга. - \en The required circle or an arc. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, - const MbPlacement3D & place, - MbPlaneCurve *& plane_curve ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Можно ли построить окружность или дугу для радиального размера к поверхности. - \en Whether a circle or an arc can be constructed for radial dimension of surface. \~ - \details \ru Можно построить, если тип базовой поверхности: st_CylinderSurface или st_ConeSurface, - или st_SphereSurface, или st_TorusSurface. - \en It can be constructed if the type of a base surface is st_CylinderSurface or st_ConeSurface, - or st_SphereSurface, or st_TorusSurface. \~ - \param[in] surface - \ru Исходная поверхность. - \en The initial surface. \~ - \return \ru true, если можно построить. - \en true if it can be constructed. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) IsPossibleRadiusDimension3D( const MbSurface & surface ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Результат замера расстояния и угла между поверхностями. - \en The result of measurement of dimension and angle between surfaces. \~ - \details \ru Результат замера расстояния и угла между поверхностями. - \en The result of measurement of dimension and angle between surfaces. \~ - \ingroup Algorithms_3D -*/ -// --- -enum MbeSurfAxesMeasureRes -{ - // \ru ошибочные результат \en mistaken result - samr_SurfSurf_Failed = -3, ///< \ru Ошибка при работе с поверхностями. \en An error is occurred while working with surfaces. - samr_AxisSurf_Failed = -2, ///< \ru Ошибка при работе с осью и поверхностю. \en An error is occurred while working with axis and surface. - samr_AxisAxis_Failed = -1, ///< \ru Ошибка при работе с осями. \en An error is occurred while working with axes. - // \ru пустой результат \en an empty result. - samr_Undefined = 0, ///< \ru Не получилось или не измерялось. \en Failed or didn't measured. - // \ru две оси \en two axes - samr_AxisAxis_Coaxial, ///< \ru Оси совпадают. \en Axes are coincident. - samr_AxisAxis_Parallel, ///< \ru Оси параллельны. \en Axes are parallel. - samr_AxisAxis_Intersecting, ///< \ru Оси пересекаются. \en Axes are crossed. - samr_AxisAxis_Distant, ///< \ru Оси на расстоянии. \en Axes are located at a distance. - // \ru одна ось (какая из осей есть, см. по возвращаемому флагу функции замера) \en one axis (see the returned flag of measurement function to detect which one exactly) - samr_AxisSurf_Colinear, ///< \ru Ось лежит на поверхности. \en The axis lies on the surface. - samr_AxisSurf_Parallel, ///< \ru Ось параллельна поверхности. \en The axis is parallel to the surface. - samr_AxisSurf_Intersecting, ///< \ru Ось пересекает поверхность. \en The axis crosses the surface. - samr_AxisSurf_Distant, ///< \ru Ось на расстоянии от поверхности. \en The axis is located at a distance from the surface. - // \ru две плоские поверхности \en two planar surfaces - samr_SurfSurf_Colinear, ///< \ru Одна поверхность лежит на другой. \en One surface lies on another one. - samr_SurfSurf_Parallel, ///< \ru Поверхности параллельны. \en Surfaces are parallel. - samr_SurfSurf_Intersecting, ///< \ru Поверхности пересекаются. \en Surfaces are intersecting inside domain. - // \ru samr_SurfSurf_Distant, // находятся на расстоянии \en samr_SurfSurf_Distant, // located at a distance - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Расстояние между осями поверхностей. - \en Distance between axes of surfaces. \~ - \details \ru Рассчитывается расстояние между осями поверхностей, имеющих оси вращения, - или расстояние между поверхностью, имеющей ось, и плоской поверхностью. - \en Calculate distance between axes of revolution surfaces - or distance between revolution surface and planar surface. \~ - \param[in] surface1, sameSense1 - \ru Первая поверхность и ее направление. - \en The first surface and its direction. \~ - \param[in] surface2, sameSense2 - \ru Вторая поверхность и ее направление. - \en The second surface and its direction. \~ - \param[out] axis1, exist1 - \ru Ось первой поверхности и флаг ее наличия. - \en The axis of the first surface and the flag of its existence. \~ - \param[out] axis2, exist2 - \ru Ось второй поверхности и флаг ее наличия. - \en The axis of the second surface and the flag of its existence. \~ - \param[out] p1 - \ru Точка на первой оси или поверхности. - \en The point on the first axis or surface. \~ - \param[out] p2 - \ru Точка на второй оси или поверхности. - \en The point on the second axis or surface. \~ - \param[out] angle - \ru Угол между осями или осью поверхностью. - \en The angle between axes or between an axis and a surface. \~ - \param[out] distance - \ru Минимальное расстояние между осями. - \en Minimal distance between axes. \~ - \param[in] angle - \ru Угловая погрешность. - \en The angle accuracy. \~ - \return \ru Вариант полученного замера или вариант ошибки. - \en The variant of the obtained measurement or the variant of error. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbeSurfAxesMeasureRes) SurfAxesDistAngle( const MbSurface & surface1, bool sameSense1, - const MbSurface & surface2, bool sameSense2, - MbAxis3D & axis1, bool & exist1, - MbAxis3D & axis2, bool & exist2, - MbCartPoint3D & p1, - MbCartPoint3D & p2, - double & angle, - double & distance, - double angleEps = ANGLE_EPSILON ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Расстояние между точками на поверхности. - \en Distance between points on surface. \~ - \details \ru Класс содержит данные о расстоянии между точками и координатами этих точек - на поверхностях. - \en The class contains data about the distance between points and their coordinates - on surfaces. \~ - \ingroup Algorithms_3D -*/ -// --- -class MATH_CLASS MbSurfDist { - friend class MbMinMaxSurfDists; -private: - double d; ///< \ru Расстояние. \en Distance. - MbCartPoint uv1; ///< \ru Параметр на первой поверхности. \en Parameter on the first surface. - MbCartPoint uv2; ///< \ru Параметр на второй поверхности. \en Parameter on the second surface. - uint8 sign; ///< \ru Знак расстояния. \en Sign of direction. - -public: - /// \ru Конструктор. \en Constructor. - MbSurfDist() : d( UNDEFINED_DBL ), uv1(), uv2(), sign( 1 ) {} - /// \ru Конструктор по данным. \en The constructor by data. - MbSurfDist( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ) { Init( _d, _uv1, _uv2, plus ); } - /// \ru Конструктор копирования. \en Copy constructor. - MbSurfDist( const MbSurfDist & other ) { Init( other ); } - /// \ru Деструктор. \en The destructor. - virtual ~MbSurfDist() {} -public: - /// \ru Функция копирования. \en Copy function. - void Init( const MbSurfDist & obj ) { d = obj.d; uv1 = obj.uv1; uv2 = obj.uv2; sign = obj.sign; } - /// \ru Получить расстояние. \en Get distance. - double GetDistance() const { return d; } - /// \ru Получить точку на первой поверхности. \en Get the point on the first surface. - const MbCartPoint & GetPointOne() const { return uv1; } - /// \ru Получить точку на второй поверхности. \en Get the point on the second surface. - const MbCartPoint & GetPointTwo() const { return uv2; } - /// \ru Расстояние положительное? \en Is the distance positive? - bool IsPositive() const { return (sign > 0); } - /// \ru Расстояние отрицательное? \en Is the distance negative? - bool IsNegative() const { return (sign < 1); } - /// \ru Оператор присваивания. \en Assignment operator. - const MbSurfDist & operator = ( const MbSurfDist & other ) { Init( other ); return (*this); } - -private: - void Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ); -}; - - -//------------------------------------------------------------------------------ -// \ru инициализатор \en Initializer -// --- -inline void MbSurfDist::Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ) -{ - d = _d; - uv1 = _uv1; - uv2 = _uv2; - sign = plus ? 1 : 0; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Расстояния с точками между поверхностями. - \en Distances between surfaces with points. \~ - \details \ru Расстояния с точками между поверхностями. - \en Distances between surfaces with points. \~ - \ingroup Algorithms_3D -*/ -// --- -class MATH_CLASS MbMinMaxSurfDists { -private : - SArray surfDistances; ///< \ru Расстояние и параметры на поверхностях. \en Distance and parameters on surfaces. - mutable double midDistance; ///< \ru Среднее расстояние. \en Average distance. - mutable double minDistance; ///< \ru Минимальное расстояние. \en Minimal distance. - mutable double maxDistance; ///< \ru Максимальное расстояние. \en Maximal distance. - mutable bool sorted; ///< \ru Признак сортированности. \en Attribute of being sorted. - -public: - MbMinMaxSurfDists( size_t nReserve = 0 ); ///< \ru Конструктор. \en Constructor. - virtual ~MbMinMaxSurfDists(); ///< \ru Деструктор. \en Destructor. - -public: - bool IsEmpty() const { return (surfDistances.Count() < 1); } ///< \ru Есть ли замеры? \en Are there any measurements? - size_t GetCount() const { return surfDistances.Count(); } ///< \ru Количество замеров. \en The number of measurements. - ptrdiff_t GetMaxIndex() const { return surfDistances.MaxIndex(); } ///< \ru Индекс последнего замера. \en Index of the last measurement - void Reserve( size_t nReserve ); ///< \ru Зарезервировать память под nReserve элементов. \en Reserve memory for 'nReserve' elements. - void RemoveAll( bool bAdjustMemory ); ///< \ru Удалить все элементы \en Delete all elements. - void AdjustMemory(); ///< \ru Освободить лишнюю память \en Free the unnecessary memory. - - /// \ru Получить расстояние по индексу. \en Get the distance by the index. - bool GetDistance( size_t k, double & d ) const; - /// \ru Получить расстояние со знаком, по индексу. \en Get the signed distance by the index. - bool GetSignedDistance( size_t k, double & d ) const; - /// \ru Считаем ли вы расстояние отрицательным. \en Whether the distance is negative. - bool IsNegativeDistance( size_t k ) const { return ((k < surfDistances.Count()) ? surfDistances[k].IsNegative() : false); } - /// \ru Получить минимальное расстояние. \en Get minimal distance. - bool GetMinDistance( double & d ) const; - /// \ru Получить максимальное расстояние. \en Get maximal distance. - bool GetMaxDistance( double & d ) const; - /// \ru Получить среднее расстояние. \en Get average distance. - bool GetMidDistance( double & d ) const; - /// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface. - bool GetSurfDistance( size_t k, double & d, MbCartPoint & uv1, MbCartPoint & uv2 ) const; - /// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface. - bool GetSurfDistance( size_t k, double & d, bool & plus, MbCartPoint & uv1, MbCartPoint & uv2 ) const; - /// \ru Добавить расстояние и точки на поверхностях. \en Add distance and points on surface. - bool AddSurfDistance( double distance, bool plus, const MbCartPoint & uv1, const MbCartPoint & uv2, - bool bAddEqual, double eps = LENGTH_EPSILON ); - /// \ru Сортировать по возрастанию расстояния. \en Sort by distance in the ascending order. - void Sort(); - /// \ru Убрать объекты с одинаковыми расстояниями. \en Remove objects with similar distances. - void RemoveEqualDistances( double eps = LENGTH_EPSILON ); - - void operator = ( const MbMinMaxSurfDists & ); ///< \ru Оператор присваивания. \en Assignment operator. - -private: - MbMinMaxSurfDists( const MbMinMaxSurfDists & ); -}; - - -//------------------------------------------------------------------------------ -// \ru выдать расстояние \en get the distance -// --- -inline bool MbMinMaxSurfDists::GetDistance( size_t k, double & d ) const -{ - if ( k < surfDistances.Count() ) { - d = surfDistances[k].GetDistance(); - return true; - } - return false; -} - - -//------------------------------------------------------------------------------ -// \ru выдать расстояние со знаком \en get signed distance -// --- -inline bool MbMinMaxSurfDists::GetSignedDistance( size_t k, double & d ) const -{ - if ( k < surfDistances.Count() ) { - d = surfDistances[k].GetDistance(); - if ( surfDistances[k].IsNegative() ) - d = -d; - return true; - } - return false; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Экстремальные расстояния между поверхностями. - \en Extreme distances between surfaces. \~ - \details \ru Экстремальные расстояния между поверхностями по сетке на первой поверхности, - причем замеры осуществляются в заданном направлении (если есть вектор) - или по нормалям к первой поверхности. - \en Extreme distances between surfaces by mesh on the first surface, - measurements are performed in a given direction (if the vector is set) - or by normals of the first surface. \~ - \param[in] surface1 - \ru Первая поверхность. - \en The first surface. \~ - \param[in] u1cnt - \ru Количество точек по u (первая поверхность). - \en The number of points by u (the first surface) \~ - \param[in] v1cnt - \ru Количество точек по v (первая поверхность). - \en The number of points by v (the first surface) \~ - \param[in] dir - \ru Вектор заданного направления (если нет, то по нормали). - \en The vector of direction (if not set then by the normal). \~ - \param[in] orient - \ru Направление поиска. - \en Direction of search. \~ - \param[in] useEqualDistances - \ru Оставлять равные равные расстояния. - \en Whether to use the equal distances. \~ - \param[in] surface2 - \ru Вторая поверхность. - \en The second surface. \~ - \param[in,out] nMin - \ru Кол-во регистрируемых минимумов. - \en The number of registrated minimums. \~ - \param[in,out] nMax - \ru Кол-во регистрируемых максимумов. - \en The number of registrated maximums. \~ - \param[out] allResults - \ru Все результаты. - \en All results. \~ - \param[out] minResults - \ru Результаты-минимумы. - \en Results-minimums. \~ - \param[out] maxResults - \ru Результаты-максимумы. - \en Results-maximums. \~ - \param[in,out] indicator - \ru Интерфейс-индикатор процесса выполнения. - \en Interface-indicator of the execution process. \~ - \return \ru Возвращает результат замера (получен, не получен или же процесс был прерван). - \en Returns the result of measurement (obtained, not obtained, or the process has been aborted). \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (MbeProcessState) MinMaxDistances( const MbSurface & surface1, - ptrdiff_t u1cnt, - ptrdiff_t v1cnt, - const MbVector3D * dir, - const MbeSenseValue & orient, - bool useEqualDistances, - const MbSurface & surface2, - ptrdiff_t & nMin, - ptrdiff_t & nMax, - MbMinMaxSurfDists & allResults, - MbMinMaxSurfDists & minResults, - MbMinMaxSurfDists & maxResults, - IProgressIndicator * indicator = NULL ); - - -#endif // __ALG_DIMENSION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Радиальный размер к поверхности. Расстояние между поверхностями. + \en Radial dimension of surface. Distance between surfaces. \~ + \details \ru Функции построения окружности или дуги для радиального размера к поверхности. + Функция вычисления экстремальных расстояний между поверхностями. + \en Functions of construction of a circle or an arc for radial dimension of surface. + A function of calculation of extreme distances between surfaces. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + + +#ifndef __ALG_DIMENSION_H +#define __ALG_DIMENSION_H + + +#include +#include +#include + + +class MATH_CLASS MbCartPoint3D; +class MATH_CLASS MbVector3D; +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbPlaneCurve; +class MATH_CLASS MbSurface; +class IProgressIndicator; + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru Построение окружности или дуги для радиального размера к поверхности, \en Construction of a circle or an arc for radial dimension of surface +// \ru имеющей круговую параметрическую линию u=const или v=const \en which has a circular parametric line u=const or v=const. +// \ru Перечень поверхностей, имеющих параметрическую линию u=const или u=const: \en The enumeration of surfaces which have a parametric line u=const or u=const: +// MbCylinderSurface, v=const +// MbConeSurface, v=const +// MbSphereSurface, u=const +// MbTorusSurface, u=const +// MbLoftedSurface, v=const +// MbElevationSurface, v=const +// MbExtrusionSurface, v=const +// MbRevolutionSurface, u=const +// MbEvolutionSurface, u=const +// MbExactionSurface, u=const +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. + \en Construct a circle or an arc for radial dimension of surface. \~ + \details \ru Построение выполняется по заданной параметрической точке поверхности. Поверхность + должна иметь круговую параметрическую линию u=const или v=const. Перечень поверхностей, + имеющих параметрическую линию u=const или v=const: + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. + \en Construction is performed by the given parametric point on surface. A surface + should have a circular parametric line u=const or v=const. The enumeration of surfaces + which have a parametric line u=const or v=const. + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] surface_uv - \ru Координаты исходной точки на поверхности. + \en Coordinates of the initial point on surface. \~ + \param[out] plane_curve - \ru Требуемая окружность или дуга. + \en The required circle or an arc. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, + const MbCartPoint & surface_uv, + MbPlaneCurve *& plane_curve ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. + \en Construct a circle or an arc for radial dimension of surface. \~ + \details \ru Построение выполняется по заданной по заданной пространственной точке. Поверхность + должна иметь круговую параметрическую линию u=const или v=const. Перечень поверхностей, + имеющих параметрическую линию u=const или u=const: + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. + \en Construction is performed by the given spatial point. A surface + should have a circular parametric line u=const or v=const. The enumeration of surfaces + which have a parametric line u=const or v=const. + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] point - \ru Пространственные координаты исходной точки. + \en Space coordinates of the initial point. \~ + \param[out] plane_curve - \ru Требуемая окружность или дуга. + \en The required circle or an arc. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, + const MbCartPoint3D & point, + MbPlaneCurve *& plane_curve ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить окружность или дугу для радиального размера к поверхности. + \en Construct a circle or an arc for radial dimension of surface. \~ + \details \ru Построение выполняется по заданному плейсменту. Поверхность должна иметь + круговую параметрическую линию u=const или v=const. Перечень поверхностей, имеющих + параметрическую линию u=const или u=const: + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. + \en Construction is performed by the given placement. A surface should have + a circular parametric line u=const or v=const. The enumeration of surfaces with + a parametric line u=const or v=const. + MbCylinderSurface v=const, \n MbConeSurface v=const, \n + MbSphereSurface u=const, \n MbTorusSurface u=const, \n + MbLoftedSurface v=const, \n MbElevationSurface v=const, \n + MbExtrusionSurface v=const, \n MbRevolutionSurface u=const, \n + MbEvolutionSurface u=const, \n MbExactionSurface u=const. \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \param[in] place - \ru Исходный плейсмент. + \en The initial placement. \~ + \param[out] plane_curve - \ru Требуемая окружность или дуга. + \en The required circle or an arc. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (void) RadiusDimension3D( const MbSurface & surface, + const MbPlacement3D & place, + MbPlaneCurve *& plane_curve ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Можно ли построить окружность или дугу для радиального размера к поверхности. + \en Whether a circle or an arc can be constructed for radial dimension of surface. \~ + \details \ru Можно построить, если тип базовой поверхности: st_CylinderSurface или st_ConeSurface, + или st_SphereSurface, или st_TorusSurface. + \en It can be constructed if the type of a base surface is st_CylinderSurface or st_ConeSurface, + or st_SphereSurface, or st_TorusSurface. \~ + \param[in] surface - \ru Исходная поверхность. + \en The initial surface. \~ + \return \ru true, если можно построить. + \en true if it can be constructed. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) IsPossibleRadiusDimension3D( const MbSurface & surface ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Результат замера расстояния и угла между поверхностями. + \en The result of measurement of dimension and angle between surfaces. \~ + \details \ru Результат замера расстояния и угла между поверхностями. + \en The result of measurement of dimension and angle between surfaces. \~ + \ingroup Algorithms_3D +*/ +// --- +enum MbeSurfAxesMeasureRes +{ + // \ru ошибочные результат \en mistaken result + samr_SurfSurf_Failed = -3, ///< \ru Ошибка при работе с поверхностями. \en An error is occurred while working with surfaces. + samr_AxisSurf_Failed = -2, ///< \ru Ошибка при работе с осью и поверхностю. \en An error is occurred while working with axis and surface. + samr_AxisAxis_Failed = -1, ///< \ru Ошибка при работе с осями. \en An error is occurred while working with axes. + // \ru пустой результат \en an empty result. + samr_Undefined = 0, ///< \ru Не получилось или не измерялось. \en Failed or didn't measured. + // \ru две оси \en two axes + samr_AxisAxis_Coaxial, ///< \ru Оси совпадают. \en Axes are coincident. + samr_AxisAxis_Parallel, ///< \ru Оси параллельны. \en Axes are parallel. + samr_AxisAxis_Intersecting, ///< \ru Оси пересекаются. \en Axes are crossed. + samr_AxisAxis_Distant, ///< \ru Оси на расстоянии. \en Axes are located at a distance. + // \ru одна ось (какая из осей есть, см. по возвращаемому флагу функции замера) \en one axis (see the returned flag of measurement function to detect which one exactly) + samr_AxisSurf_Colinear, ///< \ru Ось лежит на поверхности. \en The axis lies on the surface. + samr_AxisSurf_Parallel, ///< \ru Ось параллельна поверхности. \en The axis is parallel to the surface. + samr_AxisSurf_Intersecting, ///< \ru Ось пересекает поверхность. \en The axis crosses the surface. + samr_AxisSurf_Distant, ///< \ru Ось на расстоянии от поверхности. \en The axis is located at a distance from the surface. + // \ru две плоские поверхности \en two planar surfaces + samr_SurfSurf_Colinear, ///< \ru Одна поверхность лежит на другой. \en One surface lies on another one. + samr_SurfSurf_Parallel, ///< \ru Поверхности параллельны. \en Surfaces are parallel. + samr_SurfSurf_Intersecting, ///< \ru Поверхности пересекаются. \en Surfaces are intersecting inside domain. + // \ru samr_SurfSurf_Distant, // находятся на расстоянии \en samr_SurfSurf_Distant, // located at a distance + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Расстояние между осями поверхностей. + \en Distance between axes of surfaces. \~ + \details \ru Рассчитывается расстояние между осями поверхностей, имеющих оси вращения, + или расстояние между поверхностью, имеющей ось, и плоской поверхностью. + \en Calculate distance between axes of revolution surfaces + or distance between revolution surface and planar surface. \~ + \param[in] surface1, sameSense1 - \ru Первая поверхность и ее направление. + \en The first surface and its direction. \~ + \param[in] surface2, sameSense2 - \ru Вторая поверхность и ее направление. + \en The second surface and its direction. \~ + \param[out] axis1, exist1 - \ru Ось первой поверхности и флаг ее наличия. + \en The axis of the first surface and the flag of its existence. \~ + \param[out] axis2, exist2 - \ru Ось второй поверхности и флаг ее наличия. + \en The axis of the second surface and the flag of its existence. \~ + \param[out] p1 - \ru Точка на первой оси или поверхности. + \en The point on the first axis or surface. \~ + \param[out] p2 - \ru Точка на второй оси или поверхности. + \en The point on the second axis or surface. \~ + \param[out] angle - \ru Угол между осями или осью поверхностью. + \en The angle between axes or between an axis and a surface. \~ + \param[out] distance - \ru Минимальное расстояние между осями. + \en Minimal distance between axes. \~ + \param[in] angle - \ru Угловая погрешность. + \en The angle accuracy. \~ + \return \ru Вариант полученного замера или вариант ошибки. + \en The variant of the obtained measurement or the variant of error. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbeSurfAxesMeasureRes) SurfAxesDistAngle( const MbSurface & surface1, bool sameSense1, + const MbSurface & surface2, bool sameSense2, + MbAxis3D & axis1, bool & exist1, + MbAxis3D & axis2, bool & exist2, + MbCartPoint3D & p1, + MbCartPoint3D & p2, + double & angle, + double & distance, + double angleEps = ANGLE_EPSILON ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Расстояние между точками на поверхности. + \en Distance between points on surface. \~ + \details \ru Класс содержит данные о расстоянии между точками и координатами этих точек + на поверхностях. + \en The class contains data about the distance between points and their coordinates + on surfaces. \~ + \ingroup Algorithms_3D +*/ +// --- +class MATH_CLASS MbSurfDist { + friend class MbMinMaxSurfDists; +private: + double d; ///< \ru Расстояние. \en Distance. + MbCartPoint uv1; ///< \ru Параметр на первой поверхности. \en Parameter on the first surface. + MbCartPoint uv2; ///< \ru Параметр на второй поверхности. \en Parameter on the second surface. + uint8 sign; ///< \ru Знак расстояния. \en Sign of direction. + +public: + /// \ru Конструктор. \en Constructor. + MbSurfDist() : d( UNDEFINED_DBL ), uv1(), uv2(), sign( 1 ) {} + /// \ru Конструктор по данным. \en The constructor by data. + MbSurfDist( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ) { Init( _d, _uv1, _uv2, plus ); } + /// \ru Конструктор копирования. \en Copy constructor. + MbSurfDist( const MbSurfDist & other ) { Init( other ); } + /// \ru Деструктор. \en The destructor. + virtual ~MbSurfDist() {} +public: + /// \ru Функция копирования. \en Copy function. + void Init( const MbSurfDist & obj ) { d = obj.d; uv1 = obj.uv1; uv2 = obj.uv2; sign = obj.sign; } + /// \ru Получить расстояние. \en Get distance. + double GetDistance() const { return d; } + /// \ru Получить точку на первой поверхности. \en Get the point on the first surface. + const MbCartPoint & GetPointOne() const { return uv1; } + /// \ru Получить точку на второй поверхности. \en Get the point on the second surface. + const MbCartPoint & GetPointTwo() const { return uv2; } + /// \ru Расстояние положительное? \en Is the distance positive? + bool IsPositive() const { return (sign > 0); } + /// \ru Расстояние отрицательное? \en Is the distance negative? + bool IsNegative() const { return (sign < 1); } + /// \ru Оператор присваивания. \en Assignment operator. + const MbSurfDist & operator = ( const MbSurfDist & other ) { Init( other ); return (*this); } + +private: + void Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ); +}; + + +//------------------------------------------------------------------------------ +// \ru инициализатор \en Initializer +// --- +inline void MbSurfDist::Init( double _d, const MbCartPoint & _uv1, const MbCartPoint & _uv2, bool plus ) +{ + d = _d; + uv1 = _uv1; + uv2 = _uv2; + sign = plus ? 1 : 0; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Расстояния с точками между поверхностями. + \en Distances between surfaces with points. \~ + \details \ru Расстояния с точками между поверхностями. + \en Distances between surfaces with points. \~ + \ingroup Algorithms_3D +*/ +// --- +class MATH_CLASS MbMinMaxSurfDists { +private : + SArray surfDistances; ///< \ru Расстояние и параметры на поверхностях. \en Distance and parameters on surfaces. + mutable double midDistance; ///< \ru Среднее расстояние. \en Average distance. + mutable double minDistance; ///< \ru Минимальное расстояние. \en Minimal distance. + mutable double maxDistance; ///< \ru Максимальное расстояние. \en Maximal distance. + mutable bool sorted; ///< \ru Признак сортированности. \en Attribute of being sorted. + +public: + MbMinMaxSurfDists( size_t nReserve = 0 ); ///< \ru Конструктор. \en Constructor. + virtual ~MbMinMaxSurfDists(); ///< \ru Деструктор. \en Destructor. + +public: + bool IsEmpty() const { return (surfDistances.Count() < 1); } ///< \ru Есть ли замеры? \en Are there any measurements? + size_t GetCount() const { return surfDistances.Count(); } ///< \ru Количество замеров. \en The number of measurements. + ptrdiff_t GetMaxIndex() const { return surfDistances.MaxIndex(); } ///< \ru Индекс последнего замера. \en Index of the last measurement + void Reserve( size_t nReserve ); ///< \ru Зарезервировать память под nReserve элементов. \en Reserve memory for 'nReserve' elements. + void RemoveAll( bool bAdjustMemory ); ///< \ru Удалить все элементы \en Delete all elements. + void AdjustMemory(); ///< \ru Освободить лишнюю память \en Free the unnecessary memory. + + /// \ru Получить расстояние по индексу. \en Get the distance by the index. + bool GetDistance( size_t k, double & d ) const; + /// \ru Получить расстояние со знаком, по индексу. \en Get the signed distance by the index. + bool GetSignedDistance( size_t k, double & d ) const; + /// \ru Считаем ли вы расстояние отрицательным. \en Whether the distance is negative. + bool IsNegativeDistance( size_t k ) const { return ((k < surfDistances.Count()) ? surfDistances[k].IsNegative() : false); } + /// \ru Получить минимальное расстояние. \en Get minimal distance. + bool GetMinDistance( double & d ) const; + /// \ru Получить максимальное расстояние. \en Get maximal distance. + bool GetMaxDistance( double & d ) const; + /// \ru Получить среднее расстояние. \en Get average distance. + bool GetMidDistance( double & d ) const; + /// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface. + bool GetSurfDistance( size_t k, double & d, MbCartPoint & uv1, MbCartPoint & uv2 ) const; + /// \ru Получить расстояние и точки на поверхностях. \en Get distance and points on surface. + bool GetSurfDistance( size_t k, double & d, bool & plus, MbCartPoint & uv1, MbCartPoint & uv2 ) const; + /// \ru Добавить расстояние и точки на поверхностях. \en Add distance and points on surface. + bool AddSurfDistance( double distance, bool plus, const MbCartPoint & uv1, const MbCartPoint & uv2, + bool bAddEqual, double eps = LENGTH_EPSILON ); + /// \ru Сортировать по возрастанию расстояния. \en Sort by distance in the ascending order. + void Sort(); + /// \ru Убрать объекты с одинаковыми расстояниями. \en Remove objects with similar distances. + void RemoveEqualDistances( double eps = LENGTH_EPSILON ); + + void operator = ( const MbMinMaxSurfDists & ); ///< \ru Оператор присваивания. \en Assignment operator. + +private: + MbMinMaxSurfDists( const MbMinMaxSurfDists & ); +}; + + +//------------------------------------------------------------------------------ +// \ru выдать расстояние \en get the distance +// --- +inline bool MbMinMaxSurfDists::GetDistance( size_t k, double & d ) const +{ + if ( k < surfDistances.Count() ) { + d = surfDistances[k].GetDistance(); + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +// \ru выдать расстояние со знаком \en get signed distance +// --- +inline bool MbMinMaxSurfDists::GetSignedDistance( size_t k, double & d ) const +{ + if ( k < surfDistances.Count() ) { + d = surfDistances[k].GetDistance(); + if ( surfDistances[k].IsNegative() ) + d = -d; + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Экстремальные расстояния между поверхностями. + \en Extreme distances between surfaces. \~ + \details \ru Экстремальные расстояния между поверхностями по сетке на первой поверхности, + причем замеры осуществляются в заданном направлении (если есть вектор) + или по нормалям к первой поверхности. + \en Extreme distances between surfaces by mesh on the first surface, + measurements are performed in a given direction (if the vector is set) + or by normals of the first surface. \~ + \param[in] surface1 - \ru Первая поверхность. + \en The first surface. \~ + \param[in] u1cnt - \ru Количество точек по u (первая поверхность). + \en The number of points by u (the first surface) \~ + \param[in] v1cnt - \ru Количество точек по v (первая поверхность). + \en The number of points by v (the first surface) \~ + \param[in] dir - \ru Вектор заданного направления (если нет, то по нормали). + \en The vector of direction (if not set then by the normal). \~ + \param[in] orient - \ru Направление поиска. + \en Direction of search. \~ + \param[in] useEqualDistances - \ru Оставлять равные равные расстояния. + \en Whether to use the equal distances. \~ + \param[in] surface2 - \ru Вторая поверхность. + \en The second surface. \~ + \param[in,out] nMin - \ru Кол-во регистрируемых минимумов. + \en The number of registrated minimums. \~ + \param[in,out] nMax - \ru Кол-во регистрируемых максимумов. + \en The number of registrated maximums. \~ + \param[out] allResults - \ru Все результаты. + \en All results. \~ + \param[out] minResults - \ru Результаты-минимумы. + \en Results-minimums. \~ + \param[out] maxResults - \ru Результаты-максимумы. + \en Results-maximums. \~ + \param[in,out] indicator - \ru Интерфейс-индикатор процесса выполнения. + \en Interface-indicator of the execution process. \~ + \return \ru Возвращает результат замера (получен, не получен или же процесс был прерван). + \en Returns the result of measurement (obtained, not obtained, or the process has been aborted). \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (MbeProcessState) MinMaxDistances( const MbSurface & surface1, + ptrdiff_t u1cnt, + ptrdiff_t v1cnt, + const MbVector3D * dir, + const MbeSenseValue & orient, + bool useEqualDistances, + const MbSurface & surface2, + ptrdiff_t & nMin, + ptrdiff_t & nMax, + MbMinMaxSurfDists & allResults, + MbMinMaxSurfDists & minResults, + MbMinMaxSurfDists & maxResults, + IProgressIndicator * indicator = NULL ); + + +#endif // __ALG_DIMENSION_H diff --git a/C3d/Include/alg_diskrete_length_data.h b/C3d/Include/alg_diskrete_length_data.h index 72434a7..0bbbeb4 100644 --- a/C3d/Include/alg_diskrete_length_data.h +++ b/C3d/Include/alg_diskrete_length_data.h @@ -59,7 +59,7 @@ public: class MATH_CLASS CosinusoidPar { public : static const double maxAmpl; ///< \ru Максимальное значение амплитуды. \en Maximal value of amplitude. - static const double minAmpl; ///< \ru Минимальное значение амплитуды. \en Minimal value of amplitude. + static const double minAmpl; ///< \ru Минимальное значение амплитуды. \en Minimal value of amplitude. Param m_WaveLineAmpl; ///< \ru Величина амплитуды. \en Amplitude value. Param m_WaveLineAmplByPercent; ///< \ru Амплитуда задается в процентах от длины волны. \en The amplitude is defined as a percentage of the wave length. diff --git a/C3d/Include/alg_draw.h b/C3d/Include/alg_draw.h index 48f85a9..8d077cb 100644 --- a/C3d/Include/alg_draw.h +++ b/C3d/Include/alg_draw.h @@ -10,7 +10,6 @@ #ifndef __ALG_DRAW_H #define __ALG_DRAW_H - #include #include #include @@ -41,6 +40,8 @@ #define TRGB_CERISE 255, 0, 125 ///< \ru Светло-вишневый цвет. \en Cerise color. \~ \ingroup Drawing #define TRGB_OLIVE 128, 128, 0 ///< \ru Оливковый цвет. \en Olive color. \~ \ingroup Drawing #define TRGB_SPRINGGREEN 0, 255, 127 ///< \ru Весенне-зеленый цвет. \en Spring green color. \~ \ingroup Drawing +#define TRGB_AVIATION 125, 225, 255 ///< \ru Авиационный цвет. \en Aviation color. \~ \ingroup Drawing +#define TRGB_GOLD 205, 255, 25 ///< \ru Золотой цвет. \en Gold color. \~ \ingroup Drawing #define TRGB_DELETE TRGB_GREEN // \ru цвет удаляемых объектов \en A color of deleted objects #define TRGB_NEW TRGB_RED // \ru цвет вновь создаваемых объектов \en A color of new objects @@ -145,6 +146,11 @@ public: virtual void DrawItem( const MbCurve * curve, const MbSurface * surface, int R, int G, int B, int width = 1 ) = 0; /// \ru Отрисовать карту кривой на поверхности. \en Draw a map of a curve on a surface. virtual void DrawCurveMap( const MbCurve * curve, const MbSurface * surface, int R, int G, int B ) = 0; + // \ru Отрисовать карту кривой на поверхности в масштабе, определяемом так, чтобы активная область окна покрывалась заданным прямоугольником rect. + // Флаг isotropic отвечает за отрисовку объектов равных масштабах по осям. Если isotropic==false, окружность может отобразиться как эллипс, квадрат как прямоугольник и т.п. + // \en Draw a map of a curve on a surface with a specified scale determined as a way of covering an active window by the given rectangle rect. + // The flag isotropic is responsible for drawing in equal scales along the axes. If isotropic==false then a circle can be shown as an ellipsis, a square as an rectangle etc. + virtual void DrawCurveMap( const MbCurve * curve, const MbSurface * surface, const MbRect & rect, int R, int G, int B, const int boundaryWidth, const int curveWidth, const bool isotropic, const bool showSurfaceBoundaries ) = 0; /// \ru Отрисовать кривую на поверхности. \en Draw a curve on a surface. virtual void DrawSurfaceCurveMap( const MbSurfaceCurve * scurve, int R, int G, int B ) = 0; /// \ru Отрисовать точку на поверхности. \en Draw a point on a surface. @@ -192,7 +198,6 @@ OBVIOUS_PRIVATE_COPY( IfDrawGI ) #if defined(_DRAWGI) - //------------------------------------------------------------------------------ /** \brief \ru Функции отладочной отрисовки объектов приложения. \en Functions of debug drawing of application objects. \~ @@ -1001,7 +1006,7 @@ void DrawItem( SPtr & item, int R, int G, int B ) { template void DrawItems( const PtrArray & items, int R, int G, int B ) { - for ( size_t k = 0, cnt = items.Count(); k < cnt; k++ ) + for ( size_t k = 0, cnt = items.size(); k < cnt; ++k ) DrawGI::DrawItem( items[k], R, G, B ); } @@ -1022,7 +1027,7 @@ void DrawVertexEdges( const Vertex * vertex, int vR, int vG, int vB, MbMesh edgeMesh; MbStepData stepData( ist_SpaceStep, Math::visualSag ); MbFormNote note(true, false); - for ( size_t k = 0, cnt = edges.Count(); k < cnt; k++ ) { + for ( size_t k = 0, cnt = edges.size(); k < cnt; ++k ) { if ( edges[k] != NULL ) { edges[k]->GetCurve().CalculateMesh( stepData, note, edgeMesh ); DrawGI::DrawMesh( &edgeMesh, TRGB_WHITE ); diff --git a/C3d/Include/alg_max_distance.h b/C3d/Include/alg_max_distance.h index 32b07f8..8c0dcfb 100644 --- a/C3d/Include/alg_max_distance.h +++ b/C3d/Include/alg_max_distance.h @@ -1,165 +1,165 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Определение расстояния между объектами. - \en Definition of distance between objects. \~ - \details \ru Функции определения максимальных расстояний между различными - трехмерными объектами. - \en Functions for definition of maximal distances between different - three-dimensional objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef __ALG_MAX_DISTANCE_H -#define __ALG_MAX_DISTANCE_H - - -#include - - -class MATH_CLASS MbCartPoint; -class MATH_CLASS MbCartPoint3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние между точкой и кривой. - \en Find the maximal distance between a point and a curve. \~ - \details \ru Максимальное расстояние между точкой и кривой. - \en The maximal distance between a point and a curve. \~ - \param[in] pnt - \ru Исходная точка. - \en The initial point. \~ - \param[in] curv - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] t - \ru Параметр на кривой, при котором достигается искомое расстояние. - \en The parameter on a curve where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbCurve3D & curv, - double & t, - double & distance ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние между двумя кривыми. - \en Find the maximal distance between two curves. \~ - \details \ru Найти максимальное расстояние между двумя кривыми. - \en Find the maximal distance between two curves. \~ - \param[in] curv1, curv2 - \ru Исходные кривая. - \en The initial curves. \~ - \param[out] t1, t2 - \ru Параметры на кривых, при которых достигается искомое расстояние. - \en The parameters on curves where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv1, const MbCurve3D & curv2, - double & t1, double & t2, - double & distance ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние между точкой и поверхностью. - \en Find the maximal distance between a point and a surface. \~ - \details \ru Найти максимальное расстояние между точкой и поверхностью. - \en Find the maximal distance between a point and a surface. \~ - \param[in] pnt - \ru Исходная точка. - \en The initial point. \~ - \param[in] surf - \ru Исходная поверхность. - \en The initial surface. \~ - \param[out] uv - \ru Параметры точки на поверхности, при которой достигается искомое расстояние. - \en The point parameters on a surface where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbSurface & surf, - MbCartPoint & uv, - double & distance ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние между кривой и поверхностью. - \en Find the maximal distance between a curve and a surface. \~ - \details \ru Найти максимальное расстояние между кривой и поверхностью. - \en Find the maximal distance between a curve and a surface. \~ - \param[in] curv - \ru Исходная кривая. - \en The initial curve. \~ - \param[in] surf - \ru Исходная поверхность. - \en The initial surface. \~ - \param[out] t - \ru Параметр на кривой, при котором достигается искомое расстояние. - \en The parameter on a curve where the required distance is reached. \~ - \param[out] uv - \ru Параметры точки на поверхности, при которой достигается искомое расстояние. - \en The point parameters on a surface where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv, const MbSurface & surf, - double & t, MbCartPoint & uv, - double & distance ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние между поверхностями. - \en Find the maximal distance between two surfaces. \~ - \details \ru Найти максимальное расстояние между поверхностями. - \en Find the maximal distance between two surfaces. \~ - \param[in] surf1, surf2 - \ru Исходные поверхности. - \en The initial surfaces. \~ - \param[out] uv1, uv2 - \ru Параметры точек на поверхностях, при которых достигается искомое расстояние. - \en The parameters on surfaces where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbSurface & surf1, const MbSurface & surf2, - MbCartPoint & uv1, MbCartPoint & uv2, - double & distance ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти максимальное расстояние от оси до кривой. - \en Find the maximal distance between an axis an a curve. \~ - \details \ru Ищется максимальное расстояние от оси до кривой перпендикулярно оси. - \en Find the maximal distance between an axis and a curve perpendicularly to an axis. \~ - \param[in] axis - \ru Исходная ось. - \en The initial axis. \~ - \param[in] curve - \ru Исходная кривая. - \en The initial curve. \~ - \param[out] param - \ru Параметр на кривой, при котором достигается искомое расстояние. - \en The parameter on a curve where the required distance is reached. \~ - \param[out] distance - \ru Искомое расстояние. - \en The required distance. \~ - \return \ru true, если максимальное расстояние было найдено. - \en true if the maximal distance has been found. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) MaxDistance( const MbAxis3D & axis, const MbCurve3D & curve, - double & param, - double & distance ); - - -#endif // __ALG_MAX_DISTANCE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Определение расстояния между объектами. + \en Definition of distance between objects. \~ + \details \ru Функции определения максимальных расстояний между различными + трехмерными объектами. + \en Functions for definition of maximal distances between different + three-dimensional objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + + +#ifndef __ALG_MAX_DISTANCE_H +#define __ALG_MAX_DISTANCE_H + + +#include + + +class MATH_CLASS MbCartPoint; +class MATH_CLASS MbCartPoint3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние между точкой и кривой. + \en Find the maximal distance between a point and a curve. \~ + \details \ru Максимальное расстояние между точкой и кривой. + \en The maximal distance between a point and a curve. \~ + \param[in] pnt - \ru Исходная точка. + \en The initial point. \~ + \param[in] curv - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] t - \ru Параметр на кривой, при котором достигается искомое расстояние. + \en The parameter on a curve where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbCurve3D & curv, + double & t, + double & distance ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние между двумя кривыми. + \en Find the maximal distance between two curves. \~ + \details \ru Найти максимальное расстояние между двумя кривыми. + \en Find the maximal distance between two curves. \~ + \param[in] curv1, curv2 - \ru Исходные кривая. + \en The initial curves. \~ + \param[out] t1, t2 - \ru Параметры на кривых, при которых достигается искомое расстояние. + \en The parameters on curves where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv1, const MbCurve3D & curv2, + double & t1, double & t2, + double & distance ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние между точкой и поверхностью. + \en Find the maximal distance between a point and a surface. \~ + \details \ru Найти максимальное расстояние между точкой и поверхностью. + \en Find the maximal distance between a point and a surface. \~ + \param[in] pnt - \ru Исходная точка. + \en The initial point. \~ + \param[in] surf - \ru Исходная поверхность. + \en The initial surface. \~ + \param[out] uv - \ru Параметры точки на поверхности, при которой достигается искомое расстояние. + \en The point parameters on a surface where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbCartPoint3D & pnt, const MbSurface & surf, + MbCartPoint & uv, + double & distance ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние между кривой и поверхностью. + \en Find the maximal distance between a curve and a surface. \~ + \details \ru Найти максимальное расстояние между кривой и поверхностью. + \en Find the maximal distance between a curve and a surface. \~ + \param[in] curv - \ru Исходная кривая. + \en The initial curve. \~ + \param[in] surf - \ru Исходная поверхность. + \en The initial surface. \~ + \param[out] t - \ru Параметр на кривой, при котором достигается искомое расстояние. + \en The parameter on a curve where the required distance is reached. \~ + \param[out] uv - \ru Параметры точки на поверхности, при которой достигается искомое расстояние. + \en The point parameters on a surface where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbCurve3D & curv, const MbSurface & surf, + double & t, MbCartPoint & uv, + double & distance ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние между поверхностями. + \en Find the maximal distance between two surfaces. \~ + \details \ru Найти максимальное расстояние между поверхностями. + \en Find the maximal distance between two surfaces. \~ + \param[in] surf1, surf2 - \ru Исходные поверхности. + \en The initial surfaces. \~ + \param[out] uv1, uv2 - \ru Параметры точек на поверхностях, при которых достигается искомое расстояние. + \en The parameters on surfaces where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbSurface & surf1, const MbSurface & surf2, + MbCartPoint & uv1, MbCartPoint & uv2, + double & distance ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти максимальное расстояние от оси до кривой. + \en Find the maximal distance between an axis an a curve. \~ + \details \ru Ищется максимальное расстояние от оси до кривой перпендикулярно оси. + \en Find the maximal distance between an axis and a curve perpendicularly to an axis. \~ + \param[in] axis - \ru Исходная ось. + \en The initial axis. \~ + \param[in] curve - \ru Исходная кривая. + \en The initial curve. \~ + \param[out] param - \ru Параметр на кривой, при котором достигается искомое расстояние. + \en The parameter on a curve where the required distance is reached. \~ + \param[out] distance - \ru Искомое расстояние. + \en The required distance. \~ + \return \ru true, если максимальное расстояние было найдено. + \en true if the maximal distance has been found. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) MaxDistance( const MbAxis3D & axis, const MbCurve3D & curve, + double & param, + double & distance ); + + +#endif // __ALG_MAX_DISTANCE_H diff --git a/C3d/Include/alg_mesh_to_brep.h b/C3d/Include/alg_mesh_to_brep.h index 46b28a9..d19605d 100644 --- a/C3d/Include/alg_mesh_to_brep.h +++ b/C3d/Include/alg_mesh_to_brep.h @@ -1,96 +1,102 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief Функции преобразования полигональной модели в граничное представление. - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ALG_MESH_TO_BREP_H -#define __ALG_MESH_TO_BREP_H - -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCartPoint3D; -class MATH_CLASS MbVector3D; -class MATH_CLASS MbFaceShell; -class MATH_CLASS MbMesh; -class MATH_CLASS MbGrid; -class MATH_CLASS MbCollection; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbTriangle; -class MATH_CLASS IProgressIndicator; -class MATH_CLASS ProgressBarWrapper; -struct MATH_CLASS GridsToShellValues; - - -//------------------------------------------------------------------------------ -// Удалить дублирующие с заданной точностью друг друга точки. -// --- -bool RemoveRedundantPoints( std::vector & points, - std::vector & triangles, - double epsilon, - ProgressBarWrapper * baseProgBar ); - -//------------------------------------------------------------------------------ -// Удалить дублирующие с заданной точностью друг друга точки. -// --- -bool RemoveRedundantPoints( std::vector< std::pair > & pointNormals, - std::vector & triangles, - double epsilon, - ProgressBarWrapper * baseProgBar ); - -//------------------------------------------------------------------------------ -// Удалить дублирующие с заданной точностью друг друга точки. -// --- -bool RemoveRedundantPoints( std::vector & points, - std::vector & indexes, - double epsilon ); - -//------------------------------------------------------------------------------ -// Объединить ребра двух смежных плоских граней с полигональной границей -// (возвращает общее после сшивки ребро) -// --- -MbCurveEdge * StitchAdjacentGridsEdges( MbFace & face1, MbOrientedEdge & edge1, - MbFace & face2, MbLoop & loop2, size_t e2Ind ); - -//------------------------------------------------------------------------------ -// Обеспечить связность треугольных граней -// --- -bool ConnectTriangleFaces( const c3d::FacesSPtrVector & faces, - const std::vector< std::pair > & edgesPairs, - std::vector< std::pair > * combinedPairs, - ProgressBarWrapper * baseProgBar ); - -//------------------------------------------------------------------------------ -// Преобразовать триангуляцию в оболочку. -// --- -MbFaceShell * ConvertGridToShell( const MbGrid & grid, const GridsToShellValues & params, const MbSNameMaker & snMaker, - MbResultType & res, IProgressIndicator * progBar = NULL ); - - -//------------------------------------------------------------------------------ -// Преобразовать полигональную модель в оболочку. -// --- -MbFaceShell * ConvertMeshToShell( const MbMesh & mesh, const GridsToShellValues & params, const MbSNameMaker & snMaker, - MbResultType & res, IProgressIndicator * progBar = NULL ); - - -//------------------------------------------------------------------------------ -// Преобразовать триангуляцию в оболочку. -// --- -MbFaceShell * ConvertCollectionToShell( const MbCollection & grid, - bool mergeFaces, - const MbSNameMaker & snMaker, - MbResultType & res, - IProgressIndicator * progIndicator ); - - -#endif // __ALG_UTILITES_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief Функции преобразования полигональной модели в граничное представление. + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ALG_MESH_TO_BREP_H +#define __ALG_MESH_TO_BREP_H + +#include +#include +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCartPoint3D; +class MATH_CLASS MbVector3D; +class MATH_CLASS MbFaceShell; +class MATH_CLASS MbMesh; +class MATH_CLASS MbGrid; +class MATH_CLASS MbCollection; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS IProgressIndicator; +class MATH_CLASS ProgressBarWrapper; +struct MATH_CLASS GridsToShellValues; + + +//------------------------------------------------------------------------------ +// Удалить дублирующие с заданной точностью друг друга точки. +// --- +bool RemoveRedundantPoints( c3d::SpacePointsVector & points, + c3d::MeshTrianglesVector & triangles, + double epsilon, + ProgressBarWrapper * baseProgBar ); + +//------------------------------------------------------------------------------ +// Удалить дублирующие с заданной точностью друг друга точки. +// --- +bool RemoveRedundantPoints( std::vector & pointNormals, + c3d::MeshTrianglesVector & triangles, + double epsilon, + ProgressBarWrapper * baseProgBar ); + +//------------------------------------------------------------------------------ +// Удалить дублирующие с заданной точностью друг друга точки. +// --- +bool RemoveRedundantPoints( c3d::SpacePointsVector & points, + c3d::UintVector & indexes, + double epsilon ); + +//------------------------------------------------------------------------------ +// Объединить ребра двух смежных плоских граней с полигональной границей +// (возвращает общее после сшивки ребро) +// --- +MbCurveEdge * StitchAdjacentGridsEdges( MbFace & face1, MbOrientedEdge & edge1, + MbFace & face2, MbLoop & loop2, size_t e2Ind ); + +//---------------------------------------------------------s--------------------- +// Обеспечить связность треугольных граней +// --- +bool ConnectTriangleFaces( const c3d::FacesSPtrVector & faces, + const std::vector & edgesPairs, + std::vector * combinedPairs, + ProgressBarWrapper * baseProgBar ); + +//------------------------------------------------------------------------------ +// Преобразовать триангуляцию в оболочку. +// --- +MbFaceShell * ConvertGridToShell( const MbGrid & grid, + const GridsToShellValues & params, + const MbSNameMaker & snMaker, + MbResultType & res, + IProgressIndicator * progBar = NULL ); + + +//------------------------------------------------------------------------------ +// Преобразовать полигональную модель в оболочку. +// --- +MbFaceShell * ConvertMeshToShell( const MbMesh & mesh, + const GridsToShellValues & params, + const MbSNameMaker & snMaker, + MbResultType & res, + IProgressIndicator * progBar = NULL ); + + +//------------------------------------------------------------------------------ +// Преобразовать триангуляцию в оболочку. +// --- +MbFaceShell * ConvertCollectionToShell( const MbCollection & grid, + bool mergeFaces, + const MbSNameMaker & snMaker, + MbResultType & res, + IProgressIndicator * progIndicator ); + + +#endif // __ALG_UTILITES_H diff --git a/C3d/Include/alg_nurbs_conic.h b/C3d/Include/alg_nurbs_conic.h index eb11ebc..637741f 100644 --- a/C3d/Include/alg_nurbs_conic.h +++ b/C3d/Include/alg_nurbs_conic.h @@ -1,377 +1,377 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение конических сечений в виде NURBS-кривой. - \en Construction of conic sections as NURBS curves. \~ - \details \ru Построение конических сечений производится следующими способами: - по двум точкам, вершине и дискриминанту, по трем точкам и вершине, - по трем точкам и двум наклонам, по двум точкам, двум наклонам и дискриминанту, - по четырем точкам и наклону и по пяти точкам. \n - NURBS кривая, описывающая конику, строится по трем точкам: началу и концу коники и - средней точке (вершине угола, в который надо вписать конику). - Принимая весы начальной и конечной точки равными 1 и рассчитывая вес средней точки, - по трем точкам и трем весам строится NURBS 3-го порядка, который будет искомой коникой. - \en Construction of conic sections is performed in the following way: - by two points, a vertex and a discriminant, by three points and a vertex, - by three points and two inclinations, by two points, two inclinations and discriminant, - by four points and inclination and by five points. \n - A NURBS curve describing a conic is constructed by three points: a start and an end of a conic and - an average point (a vertex of angle which should be inscribed into the conic). - Let weights of the start point and the end point be equal to 1. After calculating of the weight of the average point - NURBS of third degree is constructed by these three weights. This NURBS is the required conic. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef __ALG_NURBS_CONIC_H -#define __ALG_NURBS_CONIC_H - - -#include - - -class MbCurve3D; -class MbNurbs3D; -class MbCartPoint3D; -class MbVector3D; - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по двум точкам вершине и дискриминанту. - \en Construct a conic section by two points, an angle vertex and a discriminant. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - двум точкам, которые задают начало и конец кривой, вершине инженерного - треугольника и дискриминанту, который используется для определения третьей точки кривой. - \en Construction of a conic section as a NURBS curve of the third degree by - two points setting ends of a curve, a vertex of enginer - triangle and a discriminant which is used for the definition of the third point. \~ - \param[in] mbPoint0 - \ru Координаты начала коники. - \en Coordinates of the conic start point. \~ - \param[in] mbPoint1 - \ru Координаты вершины угла, в который надо вписать конику. - \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ - \param[in] mbPoint2 - \ru Координаты конца коники. - \en Coordinates of the conic end point. \~ - \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он - автоматически будет сброшен до значения 0.99999999. - \en The discriminant is less than 1. Otherwise it - will be set to 0.99999999 automatically. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for a given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_1( const MbCartPoint3D & mbPoint0, const MbCartPoint3D & mbPoint1, - const MbCartPoint3D & mbPoint2, double fDiscr ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по двум точкам вершине и дискриминанту. - \en Construct a conic section by two points, an angle vertex and a discriminant. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - двум точкам, которые задают начало и конец кривой, вершине инженерного - треугольника и дискриминанту, который используется для определения третьей точки кривой. - \en Construction of a conic section as a NURBS curve of the third degree by - two points setting ends of a curve, a vertex of enginer - triangle and a discriminant which is used for the definition of the third point. \~ - \param[in] mbPoint0 - \ru Координаты начала коники. - \en Coordinates of the conic start point. \~ - \param[in] mbPoint1 - \ru Координаты вершины угла, в который надо вписать конику. - \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ - \param[in] mbPoint2 - \ru Координаты конца коники. - \en Coordinates of the conic end point. \~ - \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он - автоматически будет сброшен до значения 0.99999999. - \en The discriminant is less than 1. Otherwise it - will be set to 0.99999999 automatically. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for a given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_1( const MbCartPoint & mbPoint0, const MbCartPoint & mbPoint1, - const MbCartPoint & mbPoint2, double fDiscr ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по трем точкам и вершине. - \en Construct a conic section by three points, and an angle vertex. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - трем точкам: началу, концу и средней точке кривой, а также вершине угла, в который - должна быть вписана коника. - \en Construction of a conic section as a NURBS curve of the third degree by - three points: ends of a curve, its average point and by a vertex of an angle, - a conic should be inscribed in. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; - точек должно быть 3. - \en The container for points of a conic: start point, average point and end point; - there should be exactly 3 points. \~ - \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. - \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_2( std::vector & vmbConicPoints, const MbCartPoint3D & mbVertex ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по трем точкам и вершине. - \en Construct a conic section by three points, and an angle vertex. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - трем точкам: началу, концу и средней точке кривой, а также вершине угла, в который - должна быть вписана коника. - \en Construction of a conic section as a NURBS curve of the third degree by - three points: ends of a curve, its average point and by a vertex of an angle, - a conic should be inscribed in. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; - точек должно быть 3. - \en The container for points of a conic: start point, average point and end point; - there should be exactly 3 points. \~ - \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. - \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_2( std::vector & vmbConicPoints, const MbCartPoint & mbVertex ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по трем точкам и двум наклонам. - \en Construct a conic section by three points and two inclinations. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 3-ем точкам, которые задают начало, конец и среднюю точку кривой и двум - наклонам, выходящим из начальной и конечной точек. - \en Construction of a conic section as a NURBS curve of the third degree by - 3 points setting begin, end and an average point of a curve and two - inclinations outgoing from the start point and from the end point \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; - точек должно быть 3. - \en The container for points of a conic: start point, average point and end point; - there should be exactly 3 points. \~ - \param[in] mbTangent1 - \ru Наклон в начале кривой. - \en Inclination at start of a curve. \~ - \param[in] mbTangent2 - \ru Наклон в конце кривой. - \en Inclination at end of a curve. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_3( const std::vector & vmbConicPoints, - MbVector3D & mbTangent1, MbVector3D & mbTangent2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по трем точкам и двум наклонам. - \en Construct a conic section by three points and two inclinations. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 3-ем точкам, которые задают начало, конец и среднюю точку кривой и двум - наклонам, выходящим из начальной и конечной точек. - \en Construction of a conic section as a NURBS curve of the third degree by - 3 points setting begin, end and an average point of a curve and two - inclinations outgoing from the start point and from the end point \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; - точек должно быть 3. - \en The container for points of a conic: start point, average point and end point; - there should be exactly 3 points. \~ - \param[in] mbTangent1 - \ru Наклон в начале кривой. - \en Inclination at start of a curve. \~ - \param[in] mbTangent2 - \ru Наклон в конце кривой. - \en Inclination at end of a curve. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_3( const std::vector & vmbConicPoints, MbVector & mbTangent1, MbVector & mbTangent2 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по двум точкам, двум наклонам и дискриминанту. - \en Construct a conic section by two points, two inclinations and a discriminant. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 2-ум точкам, которые задают начало и конец кривой, двум наклонам, выходящим из этих точек - и дискриминанту. - \en Construction of a conic section as a NURBS curve of the third degree by - 2 points setting start and end of a curve, two incllinations outgoing from these points - and a discriminant. \~ - \param[in] mbPoint1 - \ru Координаты начала коники. - \en Coordinates of the conic start point. \~ - \param[in] mbPoint2 - \ru Координаты конца коники. - \en Coordinates of the conic end point. \~ - \param[in] mbTangent1 - \ru Наклон в начале коники. - \en Inclination at start of conic. \~ - \param[in] mbTangent2 - \ru Наклон в конце коники. - \en Inclination at end of conic. \~ - \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он - автоматически будет сброшен до значения 0.99999999. - \en The discriminant is less than 1. Otherwise it - will be set to 0.99999999 automatically. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_4( const MbCartPoint3D & mbPoint1, const MbCartPoint3D & mbPoint2, - const MbVector3D & mbTangent1, const MbVector3D & mbTangent2, double fDiscr ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по двум точкам, двум наклонам и дискриминанту. - \en Construct a conic section by two points, two inclinations and a discriminant. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 2-ум точкам, которые задают начало и конец кривой, двум наклонам, выходящим из этих точек - и дискриминанту. - \en Construction of a conic section as a NURBS curve of the third degree by - 2 points setting start and end of a curve, two incllinations outgoing from these points - and a discriminant. \~ - \param[in] mbPoint1 - \ru Координаты начала коники. - \en Coordinates of the conic start point. \~ - \param[in] mbPoint2 - \ru Координаты конца коники. - \en Coordinates of the conic end point. \~ - \param[in] mbTangent1 - \ru Наклон в начале коники. - \en Inclination at start of conic. \~ - \param[in] mbTangent2 - \ru Наклон в конце коники. - \en Inclination at end of conic. \~ - \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он - автоматически будет сброшен до значения 0.99999999. - \en The discriminant is less than 1. Otherwise it - will be set to 0.99999999 automatically. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось построить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_4( const MbCartPoint & mbPoint1, const MbCartPoint & mbPoint2, - const MbVector & mbTangent1, const MbVector & mbTangent2, double fDiscr ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по четырем точкам и наклону. - \en Construct a conic section by four points, and an inclination. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 4-ем точкам и наклону в первой из них. \n - Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 - и касательной к ней в начальной точке (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 - получим СЛАУ. Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. - \en Construction of a conic section as a NURBS curve of the third degree by - 4 points and inclination in the first of them. \n - By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 - and its tangent at the start point (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 - we get the SLAE. Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; - точек должно быть 4. - \en The container for points of a conic: the first point is start point, the last point is end point. - there should be exactly 4 points. \~ - \param[in] mbTangent1 - \ru Наклон в точке коники. - \en Inclination at point of conic. \~ - \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. - \en Point number at which the inclination is specified. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_5( const std::vector & vmbConicPoints, MbVector3D & mbTangent1, size_t tanPntNb = 1 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по четырем точкам и наклону. - \en Construct a conic section by four points, and an inclination. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по - 4-ем точкам и наклону в первой из них. \n - Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 - и касательной к ней в начальной точке (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 - получим СЛАУ. Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. - \en Construction of a conic section as a NURBS curve of the third degree by - 4 points and inclination in the first of them. \n - By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 - and its tangent at the start point (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 - we get the SLAE. Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; - точек должно быть 4. - \en The container for points of a conic: the first point is start point, the last point is end point. - there should be exactly 4 points. \~ - \param[in] mbTangent1 - \ru Наклон в точке коники. - \en Inclination at point of conic. \~ - \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. - \en Point number at which the inclination is specified. \~ - \return \ru Указатель на построенную кривую \n - NULL, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_5( const std::vector & vmbConicPoints, MbVector & mbTangent1, size_t tanPntNb = 1 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по пяти точкам. - \en Construct a conic section by five points. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по 5-ти точкам.\n - Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 получим СЛАУ. - Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. - \en Construction of a conic section as a NURBS curve of the third degree by 5 points.\n - By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 we get the SLAE. - Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; - точек должно быть 5. - \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, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC ( MbCurve3D * ) NurbsConic_6( const std::vector & vmbConicPoints ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить коническое сечение по пяти точкам. - \en Construct a conic section by five points. \~ - \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по 5-ти точкам.\n - Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 получим СЛАУ. - Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. - \en Construction of a conic section as a NURBS curve of the third degree by 5 points.\n - By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 we get the SLAE. - Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ - \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; - точек должно быть 5. - \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, если не удалось постороить конику для заданных параметров. - \en The pointer to the constructed curve \n - is NULL if a try to construct a conic for given parameters has failed. \~ - \ingroup Curve_Modeling -*/ -// --- -MATH_FUNC ( MbCurve * ) NurbsConic_6( const std::vector & vmbConicPoints ); - - -#endif // __ALG_NURBS_CONIC_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение конических сечений в виде NURBS-кривой. + \en Construction of conic sections as NURBS curves. \~ + \details \ru Построение конических сечений производится следующими способами: + по двум точкам, вершине и дискриминанту, по трем точкам и вершине, + по трем точкам и двум наклонам, по двум точкам, двум наклонам и дискриминанту, + по четырем точкам и наклону и по пяти точкам. \n + NURBS кривая, описывающая конику, строится по трем точкам: началу и концу коники и + средней точке (вершине угола, в который надо вписать конику). + Принимая весы начальной и конечной точки равными 1 и рассчитывая вес средней точки, + по трем точкам и трем весам строится NURBS 3-го порядка, который будет искомой коникой. + \en Construction of conic sections is performed in the following way: + by two points, a vertex and a discriminant, by three points and a vertex, + by three points and two inclinations, by two points, two inclinations and discriminant, + by four points and inclination and by five points. \n + A NURBS curve describing a conic is constructed by three points: a start and an end of a conic and + an average point (a vertex of angle which should be inscribed into the conic). + Let weights of the start point and the end point be equal to 1. After calculating of the weight of the average point + NURBS of third degree is constructed by these three weights. This NURBS is the required conic. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + + +#ifndef __ALG_NURBS_CONIC_H +#define __ALG_NURBS_CONIC_H + + +#include + + +class MbCurve3D; +class MbNurbs3D; +class MbCartPoint3D; +class MbVector3D; + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по двум точкам вершине и дискриминанту. + \en Construct a conic section by two points, an angle vertex and a discriminant. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + двум точкам, которые задают начало и конец кривой, вершине инженерного + треугольника и дискриминанту, который используется для определения третьей точки кривой. + \en Construction of a conic section as a NURBS curve of the third degree by + two points setting ends of a curve, a vertex of enginer + triangle and a discriminant which is used for the definition of the third point. \~ + \param[in] mbPoint0 - \ru Координаты начала коники. + \en Coordinates of the conic start point. \~ + \param[in] mbPoint1 - \ru Координаты вершины угла, в который надо вписать конику. + \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ + \param[in] mbPoint2 - \ru Координаты конца коники. + \en Coordinates of the conic end point. \~ + \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он + автоматически будет сброшен до значения 0.99999999. + \en The discriminant is less than 1. Otherwise it + will be set to 0.99999999 automatically. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось построить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for a given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_1( const MbCartPoint3D & mbPoint0, const MbCartPoint3D & mbPoint1, + const MbCartPoint3D & mbPoint2, double fDiscr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по двум точкам вершине и дискриминанту. + \en Construct a conic section by two points, an angle vertex and a discriminant. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + двум точкам, которые задают начало и конец кривой, вершине инженерного + треугольника и дискриминанту, который используется для определения третьей точки кривой. + \en Construction of a conic section as a NURBS curve of the third degree by + two points setting ends of a curve, a vertex of enginer + triangle and a discriminant which is used for the definition of the third point. \~ + \param[in] mbPoint0 - \ru Координаты начала коники. + \en Coordinates of the conic start point. \~ + \param[in] mbPoint1 - \ru Координаты вершины угла, в который надо вписать конику. + \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ + \param[in] mbPoint2 - \ru Координаты конца коники. + \en Coordinates of the conic end point. \~ + \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он + автоматически будет сброшен до значения 0.99999999. + \en The discriminant is less than 1. Otherwise it + will be set to 0.99999999 automatically. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось построить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for a given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_1( const MbCartPoint & mbPoint0, const MbCartPoint & mbPoint1, + const MbCartPoint & mbPoint2, double fDiscr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по трем точкам и вершине. + \en Construct a conic section by three points, and an angle vertex. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + трем точкам: началу, концу и средней точке кривой, а также вершине угла, в который + должна быть вписана коника. + \en Construction of a conic section as a NURBS curve of the third degree by + three points: ends of a curve, its average point and by a vertex of an angle, + a conic should be inscribed in. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; + точек должно быть 3. + \en The container for points of a conic: start point, average point and end point; + there should be exactly 3 points. \~ + \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. + \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_2( std::vector & vmbConicPoints, const MbCartPoint3D & mbVertex ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по трем точкам и вершине. + \en Construct a conic section by three points, and an angle vertex. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + трем точкам: началу, концу и средней точке кривой, а также вершине угла, в который + должна быть вписана коника. + \en Construction of a conic section as a NURBS curve of the third degree by + three points: ends of a curve, its average point and by a vertex of an angle, + a conic should be inscribed in. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; + точек должно быть 3. + \en The container for points of a conic: start point, average point and end point; + there should be exactly 3 points. \~ + \param[in] mbVertex - \ru Координаты вершины угла, в который надо вписать конику. + \en Coordinates of the vertex of angle which should be inscribed into the conic. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_2( std::vector & vmbConicPoints, const MbCartPoint & mbVertex ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по трем точкам и двум наклонам. + \en Construct a conic section by three points and two inclinations. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 3-ем точкам, которые задают начало, конец и среднюю точку кривой и двум + наклонам, выходящим из начальной и конечной точек. + \en Construction of a conic section as a NURBS curve of the third degree by + 3 points setting begin, end and an average point of a curve and two + inclinations outgoing from the start point and from the end point \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; + точек должно быть 3. + \en The container for points of a conic: start point, average point and end point; + there should be exactly 3 points. \~ + \param[in] mbTangent1 - \ru Наклон в начале кривой. + \en Inclination at start of a curve. \~ + \param[in] mbTangent2 - \ru Наклон в конце кривой. + \en Inclination at end of a curve. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_3( const std::vector & vmbConicPoints, + MbVector3D & mbTangent1, MbVector3D & mbTangent2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по трем точкам и двум наклонам. + \en Construct a conic section by three points and two inclinations. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 3-ем точкам, которые задают начало, конец и среднюю точку кривой и двум + наклонам, выходящим из начальной и конечной точек. + \en Construction of a conic section as a NURBS curve of the third degree by + 3 points setting begin, end and an average point of a curve and two + inclinations outgoing from the start point and from the end point \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: начало, средняя точка, конец; + точек должно быть 3. + \en The container for points of a conic: start point, average point and end point; + there should be exactly 3 points. \~ + \param[in] mbTangent1 - \ru Наклон в начале кривой. + \en Inclination at start of a curve. \~ + \param[in] mbTangent2 - \ru Наклон в конце кривой. + \en Inclination at end of a curve. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_3( const std::vector & vmbConicPoints, MbVector & mbTangent1, MbVector & mbTangent2 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по двум точкам, двум наклонам и дискриминанту. + \en Construct a conic section by two points, two inclinations and a discriminant. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 2-ум точкам, которые задают начало и конец кривой, двум наклонам, выходящим из этих точек + и дискриминанту. + \en Construction of a conic section as a NURBS curve of the third degree by + 2 points setting start and end of a curve, two incllinations outgoing from these points + and a discriminant. \~ + \param[in] mbPoint1 - \ru Координаты начала коники. + \en Coordinates of the conic start point. \~ + \param[in] mbPoint2 - \ru Координаты конца коники. + \en Coordinates of the conic end point. \~ + \param[in] mbTangent1 - \ru Наклон в начале коники. + \en Inclination at start of conic. \~ + \param[in] mbTangent2 - \ru Наклон в конце коники. + \en Inclination at end of conic. \~ + \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он + автоматически будет сброшен до значения 0.99999999. + \en The discriminant is less than 1. Otherwise it + will be set to 0.99999999 automatically. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось построить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_4( const MbCartPoint3D & mbPoint1, const MbCartPoint3D & mbPoint2, + const MbVector3D & mbTangent1, const MbVector3D & mbTangent2, double fDiscr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по двум точкам, двум наклонам и дискриминанту. + \en Construct a conic section by two points, two inclinations and a discriminant. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 2-ум точкам, которые задают начало и конец кривой, двум наклонам, выходящим из этих точек + и дискриминанту. + \en Construction of a conic section as a NURBS curve of the third degree by + 2 points setting start and end of a curve, two incllinations outgoing from these points + and a discriminant. \~ + \param[in] mbPoint1 - \ru Координаты начала коники. + \en Coordinates of the conic start point. \~ + \param[in] mbPoint2 - \ru Координаты конца коники. + \en Coordinates of the conic end point. \~ + \param[in] mbTangent1 - \ru Наклон в начале коники. + \en Inclination at start of conic. \~ + \param[in] mbTangent2 - \ru Наклон в конце коники. + \en Inclination at end of conic. \~ + \param[in] fDiscr - \ru Дискриминант < 1, если задать дискриминант >= 1, то он + автоматически будет сброшен до значения 0.99999999. + \en The discriminant is less than 1. Otherwise it + will be set to 0.99999999 automatically. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось построить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_4( const MbCartPoint & mbPoint1, const MbCartPoint & mbPoint2, + const MbVector & mbTangent1, const MbVector & mbTangent2, double fDiscr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по четырем точкам и наклону. + \en Construct a conic section by four points, and an inclination. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 4-ем точкам и наклону в первой из них. \n + Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 + и касательной к ней в начальной точке (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 + получим СЛАУ. Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. + \en Construction of a conic section as a NURBS curve of the third degree by + 4 points and inclination in the first of them. \n + By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 + and its tangent at the start point (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 + we get the SLAE. Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; + точек должно быть 4. + \en The container for points of a conic: the first point is start point, the last point is end point. + there should be exactly 4 points. \~ + \param[in] mbTangent1 - \ru Наклон в точке коники. + \en Inclination at point of conic. \~ + \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. + \en Point number at which the inclination is specified. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_5( const std::vector & vmbConicPoints, MbVector3D & mbTangent1, size_t tanPntNb = 1 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по четырем точкам и наклону. + \en Construct a conic section by four points, and an inclination. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по + 4-ем точкам и наклону в первой из них. \n + Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 + и касательной к ней в начальной точке (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 + получим СЛАУ. Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. + \en Construction of a conic section as a NURBS curve of the third degree by + 4 points and inclination in the first of them. \n + By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 + and its tangent at the start point (x1, y1): (2Ax1 + By1 + D)(x - x1) + (2Cy1 + Bx1 + E)(y - y1) = 0 + we get the SLAE. Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; + точек должно быть 4. + \en The container for points of a conic: the first point is start point, the last point is end point. + there should be exactly 4 points. \~ + \param[in] mbTangent1 - \ru Наклон в точке коники. + \en Inclination at point of conic. \~ + \param[in] tanPntNb - \ru Номер точке, в которой задан наклон. + \en Point number at which the inclination is specified. \~ + \return \ru Указатель на построенную кривую \n + NULL, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_5( const std::vector & vmbConicPoints, MbVector & mbTangent1, size_t tanPntNb = 1 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по пяти точкам. + \en Construct a conic section by five points. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по 5-ти точкам.\n + Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 получим СЛАУ. + Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. + \en Construction of a conic section as a NURBS curve of the third degree by 5 points.\n + By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 we get the SLAE. + Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; + точек должно быть 5. + \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, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC ( MbCurve3D * ) NurbsConic_6( const std::vector & vmbConicPoints ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить коническое сечение по пяти точкам. + \en Construct a conic section by five points. \~ + \details \ru Построение конического сечения в виде NURBS-кривой 3-го порядка по 5-ти точкам.\n + Путем подставления начальных точек в общее уравнение коники Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 получим СЛАУ. + Решив СЛАУ относительно параметров A,B,C,D,E, найдем искомую конику. + \en Construction of a conic section as a NURBS curve of the third degree by 5 points.\n + By substituting of start points in the common equation of the conic Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 we get the SLAE. + Having SLAE solved relative to parameters A,B,C,D,E we find the required conic. \~ + \param[in] vmbConicPoints - \ru Контейнер точек коники: первая точка начальная, последняя - конечная; + точек должно быть 5. + \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, если не удалось постороить конику для заданных параметров. + \en The pointer to the constructed curve \n + is NULL if a try to construct a conic for given parameters has failed. \~ + \ingroup Curve_Modeling +*/ +// --- +MATH_FUNC ( MbCurve * ) NurbsConic_6( const std::vector & vmbConicPoints ); + + +#endif // __ALG_NURBS_CONIC_H diff --git a/C3d/Include/assembly.h b/C3d/Include/assembly.h index 85ee33a..971b4c9 100644 --- a/C3d/Include/assembly.h +++ b/C3d/Include/assembly.h @@ -1,392 +1,397 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Сборочная единица. - \en Assembly unit. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __ASSEMBLY_H -#define __ASSEMBLY_H - -#include -#include -#include -#include -#include - - -class MbConstraintSystem; -class MATH_CLASS MtGeomArgument; -class MATH_CLASS MtGeomConstraint; -class MATH_CLASS MtConstraintIter; -struct ItAssemblyReactor; -struct ItAssemblyImportData; -struct ItModelVisitor; -class MbModelTreeReader; -class MATH_CLASS MbAssembly; - -namespace c3d // namespace C3D -{ -typedef SPtr AssemblySPtr; -typedef SPtr ConstAssemblySPtr; - -typedef std::vector AssembliesVector; -typedef std::vector ConstAssembliesVector; - -typedef std::vector AssembliesSPtrVector; -typedef std::vector ConstAssembliesSPtrVector; -} - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Сборочная единица. - \en Assembly unit. \~ - \details \ru Сборка состоит из множества объектов геометрической модели MbItem. - Сборка может содержать объекты любого подкласса MbItem, в том числе и сборочные - единицы (тип MbAssembly). - \en The assembly consists of a set of objects of geometric model MbItem. - The assembly may contain objects of any sub-class of MbItem, including - assembly units (of type MbAssembly). - \par \ru Отношение "часть-целое". - \en Relationship "is a part of". - \ru Сборочная единица - это объект модели объединяющий в себе набор других объектов. - Такое объединение рассматривается как агрегация, устанавливающая отношение - владения между сборкой и её собственными суб-объектами. Это предполагает что любой - объект модели типа MbItem может принадлежать только одной сборке. - \en Assembly unit is object of model aggregating a collection of other objects. - Such an association is regarded as an aggregation establishing an ownership - between the assembly and its proper sub-objects. This implies that any - model object of type MbItem can belong to only assembly. - \~ - \ingroup Model_Items -*/ -//--- -class MATH_CLASS MbAssembly : public MbItem -{ -private: - typedef sorting_array ItemContainer; - typedef ItemContainer::iterator item_iterator; - -private: - ItemContainer assemblyItems; ///< \ru Множество объектов сборки. \en A set of assembly objects. - MbConstraintSystem * constraintSystem; ///< \ru Система ограничений сборки. \en Constraint system of assembly unit. - mutable ItAssemblyReactor * m_reactor; ///< \ru Обработчик события, связанные с решением сборки. \en The event handles related to solving the assembly. - -protected: - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbAssembly( const MbAssembly & init, MbRegDuplicate * iReg ); - -public: - /// \ru Конструктор пустой сборки. \en Construct an empty assembly. - MbAssembly(); - /// \ru Конструктор по объекту. \en The constructor by an object. - explicit MbAssembly( MbItem & ); - /// \ru Конструктор по объектам в локальной системе координат. \en The constructor by objects in a local coordinate system. - template - MbAssembly( const ItemsVector & items ); - // \ru Деструктор. \en Destructor. - virtual ~MbAssembly(); - -public: - VISITING_CLASS( MbAssembly ); - - // \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 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 - virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. - 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 MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create own property. - 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. - - // \ru Выдать локальную систему координат объектов сборки. \en Get the local coordinate system of assembly items. - virtual bool GetPlacement( MbPlacement3D & ) const; - // \ru Установить локальную систему координат объектов сборки. \en Set coordinate system of assembly items. - virtual bool SetPlacement( const MbPlacement3D & ); - // \ru Перестроить объект по журналу построения. \en Rebuild 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. - // \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. - virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; - // \ru Добавить полигональную сетку объекта. \en Add a polygonal mesh of the object. - virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; - // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. - virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; - // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. - 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; - // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ - virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, - RPArray & items, SArray & matrs ); - // \ru Дать все полигональные объекты, отображающие геометрические элементы, участвующие в геометрических огриничениях.\en Get all polygonal objects for drawing the elements participated in geometric constraints. \~ - bool GetConstraintMesh( std::vector & meshes ) const; - // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ - virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; - // \ru Дать объект по его пути положения в модели и матрицу преобразования объекта в глобальную систему координат. \en Get the object by its path in the model and get the matrix of transformation of the object to the global coordinate system. - virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; - // \ru Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Найти объект и матрицу его преобразования в глобальную систему координат. \en Find the object and the matrix of its transformation to the global coordinate system. - virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Дать объект с заданным именем и матрицу его преобразования в глобальную систему координат. \en Get the object with the specified name and the matrix of its transformation to the global coordinate system. - 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 ); - // \ru Сдвинуть вдоль вектора с использованием регистратора селектированные содержимые объекты. \en Move selected objects along the vector using the registrator. - virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = 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 ); - /// \ru Отдать селектированные содержимые объекты. \en Get selected objects. - bool DetachSelected( RPArray & items, SArray & matrs, bool selected = true ); - /// \ru Отцепить все видимые или невидимые объекты. \en Detach all visible or invisible objects. \~ - bool DetachInvisible( RPArray & items, SArray & matrs, bool invisible = true ); - /// \ru Отцепить все объекты с указанным свойством. \en Detach all objects with pointed attribute. \~ - bool DetachByAttribute( RPArray & items, SArray & matrs, int attribute ); - /** \brief \ru Алгоритм общего назначения для обхода дерева модели в глубину. - \en General-purpose algorithm traversing the model graph in depth. */ - void Traverse( ItModelVisitor & ) const; - -public: - /** \ru \name Функции сборочной единицы. - \en \name The assembly unit functions. - \{ */ - /// \ru Выдать непосредственный объект сборки по идентификатору. \en Get the immediate item of assembly by identifier. - const MbItem * SubItem( SimpleName n ) const { return _ItemByName(n); } - /// \ru Добавить объект в сборку. \en Add an item to the assembly. - MbItem * AddItem( MbItem & item ); - /** - \brief \ru Добавить вставку геометрического объекта. - \en Add an instance of the geometric object. \~ - \param item - \ru Источник, на котором основан экземпляр вставки. - \en A source item on which the instance is based. - \param lcs - \ru Локальная система координат экземпляра вставляемого объекта. - \en Local coordinate system of the instanced object. \~ - \return \ru Экземпляр класса MbInstance, размещающего объект в пространстве сборки. - \en An Instance of class MbInstance placing the item in the space of the assembly. - */ - MbItem * AddInstance( MbItem & item, const MbPlacement3D & lcs ); - /** \brief \ru Заменить объект. - \en Replace an item. \~ - \details \ru Заменить объект новым. - \en Replace an item by a new one. \~ - \param[in] item - \ru Заменяемый объект. - \en An item to be replaced. \~ - \param[in] newItem - \ru Новый объект. - \en A new item. \~ - \return \ru Возвращает true, если замена была выполнена. - \en Returns true if the replacement has been performed. \~ - */ - bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); - - /// \ru Выдать все объекты. \en Get all the items. - void GetItems( RPArray & items ) const; - /// \ru Выдать все объекты. \en Get all the items. - void GetItems( RPArray & items ); - - /// \ru Отцепить объект по индексу. \en Detach the item by index. - MbItem* DetachItem ( size_t ind ); - /// \ru Отцепить объект, если такой есть в сборке. \en Detach the item if it belongs to the assembly. - bool DetachItem ( MbItem * obj ); - /// \ru Удалить объект, если такой есть в сборке или в подсборках. \en Delete the item if it belongs to the assembly or its sub-assemblies. - bool DeleteItem ( MbItem * obj ); - /// \ru Удалить все объекты сборки. \en Delete all the assembly items. - void DeleteItems(); - /// \ru Выдать количество объектов сборки. \en Get the assembly item count. - size_t ItemsCount() const { return assemblyItems.size(); } - /// \ru Вернуть true, если сборка не содержит геометрических объекты. \en Return true, if the assembly has no geometric objects. - bool IsEmpty() const { return assemblyItems.empty(); } - /// \ru Выдать объект по индексу. \en Get the item by index. - const MbItem * GetItem( size_t i ) const; - /// \ru Выдать объект по индексу для модификации. \en Get the item by index for modification. - MbItem * SetItem( size_t i ); - /// \ru Содержит ли сборка присланный объект? \en Does the assembly contain the given item? - bool ContainsItem( const MbItem * obj ) const; - /// \ru Вычислить габарит сборки. \en Calculate the bounding box of the assembly. - void CalculateGabarit( MbCube & cube ) const; - /// \ru Выдать количество граней. \en Get the number of faces. - size_t GetFacesCount() const; - /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. - template - void GetFacesSet( FacesVector & faces ) const; -public: - /** \} - \ru \name Функции системы ограничений. - \en \name The constraint system functions. - \{ */ - /// \ru Добавить ограничение для пары геометрических объектов. \en Add geometric constraint. - MtGeomConstraint AddConstraint( MtMateType, const MtGeomArgument &, const MtGeomArgument &, MtParVariant = MtParVariant::undef ); - /// \ru Изменить значение управляющего размера. \en Change the value of driving dimension. - MtResultCode3D ChangeDimension( MtGeomConstraint & dimCon, double newVal ); - /// \ru Решить ограничения сборки. \en Evaluate constraints. - MtResultCode3D EvaluateConstraints(); - /// \ru Выдать диапазон итераторов для обхода всех ограничений сборки. \en Get a range of iterators to traverse all assembly constraints. - void GetConstraints( MtConstraintIter & begIter, MtConstraintIter & endIter ) const; - /// \ru Задать или сбросить обработчик событий решателя. \en Set or reset an handler of constraint solving events. - void SetReactor( ItAssemblyReactor * ) const; - /// \ru Импортировать систему ограничений из приложения САПР. \ru Import the constraint system from CAD application. - bool Import( ItAssemblyImportData & ); - -public: - /** \} */ - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAssembly ); - - static const MbPlacement3D & GetPlacement() { return MbPlacement3D::global; } // This function is deprecated. Use MbInstanse to give the assembly its own placement. - - friend class MbModelTreeReader; - -private: - // \ru Инициализатор по массиву составляющих объектов. // \en Initializer to aggregate items in the assembly. - template - void _Init( const ItemsVector & ); - // Найти объект по геометрическому объекту - template - const MbItem * _FindItem( const ItemType * s, MbPath & path, MbMatrix3D & from ) const; - // Поиск в глубину среди подчиненных - template - const MbItem * _FindRecursively( const ItemType * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Выдать объект по идентификатору. \en Get the item by identifier. - const MbItem * _ItemByName( SimpleName ) const; - // \ru Генерация имени для нового элемента сборки. \en Generate identifier for new assembly item. - SimpleName _NewItemName() const; - /// \ru Добавить в сборку объекты сборки без трансформации. \en Add assembly items to the assembly without transformation. - bool _AddAssemblyItems( MbAssembly & ); - - OBVIOUS_PRIVATE_COPY( MbAssembly ); -}; // MbAssembly - -IMPL_PERSISTENT_OPS( MbAssembly ) - - -//---------------------------------------------------------------------------------------- -// Экспериментальный посетитель дерева модели -/* - Возможные применения: - - Сбор любых данных об/из иерархии модели; - - Загрузка подсборок и вставок в утилиту поиска соударений (MbCollisionDetectionUtility); - - Геометрический поиск с выдачей маршрута(MbPath) и матрицу отображения МСК вставок и подсборок; - - Восстановление текущей матрицы и маршрута MbPath по hash-коду ссылок в системе - геометрических ограничений; -*/ -//--- -struct ItModelVisitor -{ -public: - virtual void VisitItem( const MbItem * ) = 0; - virtual void FinishItem( const MbItem * ) = 0; - virtual bool ExamineSubItem( const MbItem * owner, const MbItem * subItem ) = 0; - virtual void ExamineInstance( const MbInstance * inst, const MbItem * srcItem ) = 0; -}; - - -//---------------------------------------------------------------------------------------- -// \ru Конструктор по объектам. \en The constructor by objects. -//--- -template -MbAssembly::MbAssembly( const ItemsVector & items ) - : MbItem() - , assemblyItems() - , constraintSystem( NULL ) - , m_reactor( NULL ) -{ -#ifdef C3D_DEBUG - // Check a condition of the single owner. - for ( size_t i = 0, iCount = items.size(); i < iCount; ++i ) - { - if ( items[i]->GetItemName() != UNDEFINED_SNAME ) - { - C3D_ASSERT_UNCONDITIONAL( false ); // The item has already a name. It's probably means that the item is owned another assembly. - break; - } - } -#endif // C3D_DEBUG - - _Init( items ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Инициализатор по массиву составляющих объектов. -// \en Initializer to aggregate items in the assembly. -//--- -template -void MbAssembly::_Init( const ItemsVector & items ) -{ - C3D_ASSERT( assemblyItems.empty() && (constraintSystem == NULL) ); - SimpleName idCounter = 0; - - for ( size_t i = 0, iCount = items.size(); i < iCount; ++i ) - { - if ( MbItem * item = items[i] ) { - if ( item->GetItemName() == UNDEFINED_SNAME ) { - item->SetItemName( idCounter ); - } - else { - C3D_ASSERT( idCounter <= item->GetItemName() ); - idCounter = max_of( idCounter, item->GetItemName() ); - } - ++idCounter; - item->AddRef(); - assemblyItems.push_back( item ); - } - } -} - - -//---------------------------------------------------------------------------------------- -// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. -//--- -template -void MbAssembly::GetFacesSet( FacesVector & faces ) const -{ - for ( size_t i = assemblyItems.size(); i--; ) - { - if ( const MbItem * assemblyItem = assemblyItems[i] ) - { - if ( assemblyItem->IsA() == st_Solid ) - static_cast(*assemblyItem).GetFacesSet( faces ); - else if ( assemblyItem->IsA() == st_Instance ) - static_cast(*assemblyItem).GetFacesSet( faces ); - else if ( assemblyItem->IsA() == st_Assembly ) - static_cast(*assemblyItem).GetFacesSet( faces ); - } - } -} - -//---------------------------------------------------------------------------------------- -// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. -//--- -template -void MbInstance::GetFacesSet( FacesVector & faces ) const -{ - if ( item != NULL ) { - if ( item->IsA() == st_Solid ) - static_cast( *item ).GetFacesSet( faces ); - else if ( item->IsA() == st_Assembly ) - static_cast( *item ).GetFacesSet( faces ); - else if ( item->IsA() == st_Instance ) - static_cast( *item ).GetFacesSet( faces ); - } -} - - -#endif // __ASSEMBLY_H +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Сборочная единица. + \en Assembly unit. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __ASSEMBLY_H +#define __ASSEMBLY_H + +#include +#include +#include +#include +#include + + +class MbConstraintSystem; +class MATH_CLASS MtGeomArgument; +class MATH_CLASS MtGeomConstraint; +class MATH_CLASS MtConstraintIter; +struct ItAssemblyReactor; +struct ItAssemblyImportData; +struct ItModelVisitor; +class MbModelTreeReader; +class MATH_CLASS MbAssembly; + +namespace c3d // namespace C3D +{ +typedef SPtr AssemblySPtr; +typedef SPtr ConstAssemblySPtr; + +typedef std::vector AssembliesVector; +typedef std::vector ConstAssembliesVector; + +typedef std::vector AssembliesSPtrVector; +typedef std::vector ConstAssembliesSPtrVector; +} + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Сборочная единица. + \en Assembly unit. \~ + \details \ru Сборка состоит из множества объектов геометрической модели MbItem. + Сборка может содержать объекты любого подкласса MbItem, в том числе и сборочные + единицы (тип MbAssembly). + \en The assembly consists of a set of objects of geometric model MbItem. + The assembly may contain objects of any sub-class of MbItem, including + assembly units (of type MbAssembly). + \par \ru Отношение "часть-целое". + \en Relationship "is a part of". + \ru Сборочная единица - это объект модели объединяющий в себе набор других объектов. + Такое объединение рассматривается как агрегация, устанавливающая отношение + владения между сборкой и её собственными суб-объектами. Это предполагает что любой + объект модели типа MbItem может принадлежать только одной сборке. + \en Assembly unit is object of model aggregating a collection of other objects. + Such an association is regarded as an aggregation establishing an ownership + between the assembly and its proper sub-objects. This implies that any + model object of type MbItem can belong to only assembly. + \~ + \ingroup Model_Items +*/ +//--- +class MATH_CLASS MbAssembly : public MbItem +{ +private: + typedef sorting_array ItemContainer; + typedef ItemContainer::iterator item_iterator; + +private: + ItemContainer assemblyItems; ///< \ru Множество объектов сборки. \en A set of assembly objects. + MbConstraintSystem * constraintSystem; ///< \ru Система ограничений сборки. \en Constraint system of assembly unit. + mutable ItAssemblyReactor * m_reactor; ///< \ru Обработчик события, связанные с решением сборки. \en The event handles related to solving the assembly. + +protected: + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbAssembly( const MbAssembly & init, MbRegDuplicate * iReg ); + +public: + /// \ru Конструктор пустой сборки. \en Construct an empty assembly. + MbAssembly(); + /// \ru Конструктор по объекту. \en The constructor by an object. + explicit MbAssembly( MbItem & ); + /// \ru Конструктор по объектам в локальной системе координат. \en The constructor by objects in a local coordinate system. + template + MbAssembly( const ItemsVector & items ); + // \ru Деструктор. \en Destructor. + virtual ~MbAssembly(); + +public: + VISITING_CLASS( MbAssembly ); + + // \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 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 + virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. + 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 MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create own property. + 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. + + // \ru Выдать локальную систему координат объектов сборки. \en Get the local coordinate system of assembly items. + virtual bool GetPlacement( MbPlacement3D & ) const; + // \ru Установить локальную систему координат объектов сборки. \en Set coordinate system of assembly items. + virtual bool SetPlacement( const MbPlacement3D & ); + // \ru Перестроить объект по журналу построения. \en Rebuild 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. + // \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. + virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; + // \ru Добавить полигональную сетку объекта. \en Add a polygonal mesh of the object. + virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; + // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. + virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; + // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. + 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; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + RPArray & items, SArray & matrs ); + // \ru Дать все полигональные объекты, отображающие геометрические элементы, участвующие в геометрических огриничениях.\en Get all polygonal objects for drawing the elements participated in geometric constraints. \~ + bool GetConstraintMesh( std::vector & meshes ) const; + // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ + virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; + // \ru Дать объект по его пути положения в модели и матрицу преобразования объекта в глобальную систему координат. \en Get the object by its path in the model and get the matrix of transformation of the object to the global coordinate system. + virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; + // \ru Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Найти объект и матрицу его преобразования в глобальную систему координат. \en Find the object and the matrix of its transformation to the global coordinate system. + virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Дать объект с заданным именем и матрицу его преобразования в глобальную систему координат. \en Get the object with the specified name and the matrix of its transformation to the global coordinate system. + 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 ); + // \ru Сдвинуть вдоль вектора с использованием регистратора селектированные содержимые объекты. \en Move selected objects along the vector using the registrator. + virtual void MoveSelected( const MbVector3D & to, MbRegTransform * iReg = 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 ); + /// \ru Отдать селектированные содержимые объекты. \en Get selected objects. + bool DetachSelected( RPArray & items, SArray & matrs, bool selected = true ); + /// \ru Отцепить все видимые или невидимые объекты. \en Detach all visible or invisible objects. \~ + bool DetachInvisible( RPArray & items, SArray & matrs, bool invisible = true ); + /// \ru Отцепить все объекты с указанным свойством. \en Detach all objects with pointed attribute. \~ + bool DetachByAttribute( RPArray & items, SArray & matrs, int attribute ); + /** \brief \ru Алгоритм общего назначения для обхода дерева модели в глубину. + \en General-purpose algorithm traversing the model graph in depth. */ + void Traverse( ItModelVisitor & ) const; + +public: + /** \ru \name Функции сборочной единицы. + \en \name The assembly unit functions. + \{ */ + /// \ru Выдать непосредственный объект сборки по идентификатору. \en Get the immediate item of assembly by identifier. + const MbItem * SubItem( SimpleName n ) const { return _ItemByName(n); } + /// \ru Добавить объект в сборку. \en Add an item to the assembly. + MbItem * AddItem( MbItem & item ); + /** + \brief \ru Добавить вставку геометрического объекта. + \en Add an instance of the geometric object. \~ + \param item - \ru Источник, на котором основан экземпляр вставки. + \en A source item on which the instance is based. + \param lcs - \ru Локальная система координат экземпляра вставляемого объекта. + \en Local coordinate system of the instanced object. \~ + \return \ru Экземпляр класса MbInstance, размещающего объект в пространстве сборки. + \en An Instance of class MbInstance placing the item in the space of the assembly. + */ + MbItem * AddInstance( MbItem & item, const MbPlacement3D & lcs ); + /** \brief \ru Заменить объект. + \en Replace an item. \~ + \details \ru Заменить объект новым. + \en Replace an item by a new one. \~ + \param[in] item - \ru Заменяемый объект. + \en An item to be replaced. \~ + \param[in] newItem - \ru Новый объект. + \en A new item. \~ + \return \ru Возвращает true, если замена была выполнена. + \en Returns true if the replacement has been performed. \~ + */ + bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); + + /// \ru Выдать все объекты. \en Get all the items. + void GetItems( RPArray & items ) const; + /// \ru Выдать все объекты. \en Get all the items. + void GetItems( RPArray & items ); + + /// \ru Отцепить объект по индексу. \en Detach the item by index. + MbItem* DetachItem ( size_t ind ); + /// \ru Отцепить объект, если такой есть в сборке. \en Detach the item if it belongs to the assembly. + bool DetachItem ( MbItem * obj ); + /// \ru Удалить объект, если такой есть в сборке или в подсборках. \en Delete the item if it belongs to the assembly or its sub-assemblies. + bool DeleteItem ( MbItem * obj ); + /// \ru Удалить все объекты сборки. \en Delete all the assembly items. + void DeleteItems(); + /// \ru Выдать количество объектов сборки. \en Get the assembly item count. + size_t ItemsCount() const { return assemblyItems.size(); } + /// \ru Вернуть true, если сборка не содержит геометрических объекты. \en Return true, if the assembly has no geometric objects. + bool IsEmpty() const { return assemblyItems.empty(); } + /// \ru Выдать объект по индексу. \en Get the item by index. + const MbItem * GetItem( size_t i ) const; + /// \ru Выдать объект по индексу для модификации. \en Get the item by index for modification. + MbItem * SetItem( size_t i ); + /// \ru Содержит ли сборка присланный объект? \en Does the assembly contain the given item? + bool ContainsItem( const MbItem * obj ) const; + /// \ru Вычислить габарит сборки. \en Calculate the bounding box of the assembly. + void CalculateGabarit( MbCube & cube ) const; + /// \ru Выдать количество граней. \en Get the number of faces. + size_t GetFacesCount() const; + /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. + template + void GetFacesSet( FacesVector & faces ) const; +public: + /** \} + \ru \name Функции системы ограничений. + \en \name The constraint system functions. + \{ */ + /// \ru Добавить ограничение для пары геометрических объектов. \en Add geometric constraint. + MtGeomConstraint AddConstraint( MtMateType, const MtGeomArgument &, const MtGeomArgument &, MtParVariant = MtParVariant::undef ); + /// \ru Изменить значение управляющего размера. \en Change the value of driving dimension. + MtResultCode3D ChangeDimension( MtGeomConstraint & dimCon, double newVal ); + /// \ru Решить ограничения сборки. \en Evaluate constraints. + MtResultCode3D EvaluateConstraints(); + /// \ru Выдать диапазон итераторов для обхода всех ограничений сборки. \en Get a range of iterators to traverse all assembly constraints. + void GetConstraints( MtConstraintIter & begIter, MtConstraintIter & endIter ) const; + /// \ru Задать или сбросить обработчик событий решателя. \en Set or reset an handler of constraint solving events. + void SetReactor( ItAssemblyReactor * ) const; + /// \ru Импортировать систему ограничений из приложения САПР. \ru Import the constraint system from CAD application. + bool Import( ItAssemblyImportData & ); + +public: + /** \} */ + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAssembly ); + + static const MbPlacement3D & GetPlacement() { return MbPlacement3D::global; } // This function is deprecated. Use MbInstanse to give the assembly its own placement. + + friend class MbModelTreeReader; + +private: + // \ru Инициализатор по массиву составляющих объектов. // \en Initializer to aggregate items in the assembly. + template + void _Init( const ItemsVector & ); + // Найти объект по геометрическому объекту + template + const MbItem * _FindItem( const ItemType * s, MbPath & path, MbMatrix3D & from ) const; + // Поиск в глубину среди подчиненных + template + const MbItem * _FindRecursively( const ItemType * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Выдать объект по идентификатору. \en Get the item by identifier. + const MbItem * _ItemByName( SimpleName ) const; + // \ru Генерация имени для нового элемента сборки. \en Generate identifier for new assembly item. + SimpleName _NewItemName() const; + /// \ru Добавить в сборку объекты сборки без трансформации. \en Add assembly items to the assembly without transformation. + bool _AddAssemblyItems( MbAssembly & ); + + OBVIOUS_PRIVATE_COPY( MbAssembly ); +}; // MbAssembly + +IMPL_PERSISTENT_OPS( MbAssembly ) + + +//---------------------------------------------------------------------------------------- +// Экспериментальный посетитель дерева модели +/* + Возможные применения: + - Сбор любых данных об/из иерархии модели; + - Загрузка подсборок и вставок в утилиту поиска соударений (MbCollisionDetectionUtility); + - Геометрический поиск с выдачей маршрута(MbPath) и матрицу отображения МСК вставок и подсборок; + - Восстановление текущей матрицы и маршрута MbPath по hash-коду ссылок в системе + геометрических ограничений; +*/ +//--- +struct ItModelVisitor +{ +public: + virtual void VisitItem( const MbItem * ) = 0; + virtual void FinishItem( const MbItem * ) = 0; + virtual bool ExamineSubItem( const MbRefItem * owner, const MbItem * subItem ) = 0; + virtual void ExamineInstance( const MbInstance * inst, const MbItem * srcItem ) = 0; +}; + +//---------------------------------------------------------------------------------------- +// Алгоритм общего назначения для обхода дерева модели в глубину. +// General-purpose algorithm traversing the model graph in depth. +//--- +MATH_FUNC(void) Traverse( const MbItem *, ItModelVisitor & ); + +//---------------------------------------------------------------------------------------- +// \ru Конструктор по объектам. \en The constructor by objects. +//--- +template +MbAssembly::MbAssembly( const ItemsVector & items ) + : MbItem() + , assemblyItems() + , constraintSystem( NULL ) + , m_reactor( NULL ) +{ +#ifdef C3D_DEBUG + // Check a condition of the single owner. + for ( size_t i = 0, iCount = items.size(); i < iCount; ++i ) + { + if ( items[i]->GetItemName() != c3d::UNDEFINED_SNAME ) + { + C3D_ASSERT_UNCONDITIONAL( false ); // The item has already a name. It's probably means that the item is owned another assembly. + break; + } + } +#endif // C3D_DEBUG + + _Init( items ); +} + + +//---------------------------------------------------------------------------------------- +// \ru Инициализатор по массиву составляющих объектов. +// \en Initializer to aggregate items in the assembly. +//--- +template +void MbAssembly::_Init( const ItemsVector & items ) +{ + C3D_ASSERT( assemblyItems.empty() && (constraintSystem == NULL) ); + SimpleName idCounter = 0; + + for ( size_t i = 0, iCount = items.size(); i < iCount; ++i ) + { + if ( MbItem * item = items[i] ) { + if ( item->GetItemName() == c3d::UNDEFINED_SNAME ) { + item->SetItemName( idCounter ); + } + else { + C3D_ASSERT( idCounter <= item->GetItemName() ); + idCounter = max_of( idCounter, item->GetItemName() ); + } + ++idCounter; + item->AddRef(); + assemblyItems.push_back( item ); + } + } +} + + +//---------------------------------------------------------------------------------------- +// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. +//--- +template +void MbAssembly::GetFacesSet( FacesVector & faces ) const +{ + for ( size_t i = assemblyItems.size(); i--; ) + { + if ( const MbItem * assemblyItem = assemblyItems[i] ) + { + if ( assemblyItem->IsA() == st_Solid ) + static_cast(*assemblyItem).GetFacesSet( faces ); + else if ( assemblyItem->IsA() == st_Instance ) + static_cast(*assemblyItem).GetFacesSet( faces ); + else if ( assemblyItem->IsA() == st_Assembly ) + static_cast(*assemblyItem).GetFacesSet( faces ); + } + } +} + +//---------------------------------------------------------------------------------------- +// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. +//--- +template +void MbInstance::GetFacesSet( FacesVector & faces ) const +{ + if ( item != NULL ) { + if ( item->IsA() == st_Solid ) + static_cast( *item ).GetFacesSet( faces ); + else if ( item->IsA() == st_Assembly ) + static_cast( *item ).GetFacesSet( faces ); + else if ( item->IsA() == st_Instance ) + static_cast( *item ).GetFacesSet( faces ); + } +} + + +#endif // __ASSEMBLY_H diff --git a/C3d/Include/assisting_item.h b/C3d/Include/assisting_item.h index 34f3a39..73fa9df 100644 --- a/C3d/Include/assisting_item.h +++ b/C3d/Include/assisting_item.h @@ -1,100 +1,100 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Вспомогательный объект геометрической модели. - \en Assisting item of the geometric model. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ASSISTING_ITEM_H -#define __ASSISTING_ITEM_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbCube; -class MATH_CLASS MbProperties; -class MATH_CLASS MbMesh; - - -//------------------------------------------------------------------------------ -/** \brief \ru Вспомогательный объект геометрической модели. - \en Assisting item of the geometric model. \~ - \details \ru Вспомогательный объект позволяет использовать в геометрической модели такие объекты, - как локальная система координат, ось, матрица преобразования для позиционирования других объектов.\n - \en The assisting item allows to use such an objects in a geometric model - as a local coordinate system, axis, transformation matrix for the other objects location.\n \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbAssistingItem : public MbItem { -protected : - MbPlacement3D place; ///< \ru Локальная система координат. \en Local coordinate system. - -protected : - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbAssistingItem( const MbAssistingItem &, MbRegDuplicate * ); -public : - /// \ru Конструктор по локальной системе координат. \en Constructor by a local coordinate system. - MbAssistingItem( const MbPlacement3D & ); -public : - /// \ru Деструктор. \en Destructor. - virtual ~MbAssistingItem(); - -public : - VISITING_CLASS( MbAssistingItem ); - - // \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 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. - virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. - 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 MbProperty & CreateProperty( MbePrompt name ) const; // \ru Создать собственное свойство. \en Create own 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. - - /// \ru Получить систему координат объекта. \en Get the coordinate system of an item. - virtual bool GetPlacement( MbPlacement3D & ) const; - /// \ru Установить систему координат объекта. \en Set the coordinate system of an item. - virtual bool SetPlacement( const MbPlacement3D & p ); - - // \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 Дать матрицу преобразования из локальной системы объекта. \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 \name Функции вспомогательного объекта. - \en \name Functions of assisting item. - \{ */ - /// \ru Выдать систему координат объекта. \en Get the coordinate system of an item. - const MbPlacement3D & GetPlacement() const { return place; } - /// \ru Выдать систему координат объекта для редактирования. \en Get the coordinate system of an item for editing. - MbPlacement3D & SetPlacement() { return place; } - /** \} */ - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAssistingItem ) -OBVIOUS_PRIVATE_COPY( MbAssistingItem ) -}; - -IMPL_PERSISTENT_OPS( MbAssistingItem ) - -#endif // __ASSISTING_ITEM_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вспомогательный объект геометрической модели. + \en Assisting item of the geometric model. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ASSISTING_ITEM_H +#define __ASSISTING_ITEM_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbCube; +class MATH_CLASS MbProperties; +class MATH_CLASS MbMesh; + + +//------------------------------------------------------------------------------ +/** \brief \ru Вспомогательный объект геометрической модели. + \en Assisting item of the geometric model. \~ + \details \ru Вспомогательный объект позволяет использовать в геометрической модели такие объекты, + как локальная система координат, ось, матрица преобразования для позиционирования других объектов.\n + \en The assisting item allows to use such an objects in a geometric model + as a local coordinate system, axis, transformation matrix for the other objects location.\n \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbAssistingItem : public MbItem { +protected : + MbPlacement3D place; ///< \ru Локальная система координат. \en Local coordinate system. + +protected : + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbAssistingItem( const MbAssistingItem &, MbRegDuplicate * ); +public : + /// \ru Конструктор по локальной системе координат. \en Constructor by a local coordinate system. + MbAssistingItem( const MbPlacement3D & ); +public : + /// \ru Деструктор. \en Destructor. + virtual ~MbAssistingItem(); + +public : + VISITING_CLASS( MbAssistingItem ); + + // \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 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. + virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. + 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 MbProperty & CreateProperty( MbePrompt name ) const; // \ru Создать собственное свойство. \en Create own 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. + + /// \ru Получить систему координат объекта. \en Get the coordinate system of an item. + virtual bool GetPlacement( MbPlacement3D & ) const; + /// \ru Установить систему координат объекта. \en Set the coordinate system of an item. + virtual bool SetPlacement( const MbPlacement3D & p ); + + // \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 Дать матрицу преобразования из локальной системы объекта. \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 \name Функции вспомогательного объекта. + \en \name Functions of assisting item. + \{ */ + /// \ru Выдать систему координат объекта. \en Get the coordinate system of an item. + const MbPlacement3D & GetPlacement() const { return place; } + /// \ru Выдать систему координат объекта для редактирования. \en Get the coordinate system of an item for editing. + MbPlacement3D & SetPlacement() { return place; } + /** \} */ + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAssistingItem ) +OBVIOUS_PRIVATE_COPY( MbAssistingItem ) +}; + +IMPL_PERSISTENT_OPS( MbAssistingItem ) + +#endif // __ASSISTING_ITEM_H diff --git a/C3d/Include/attr_color.h b/C3d/Include/attr_color.h index 0b57bab..2205b3a 100644 --- a/C3d/Include/attr_color.h +++ b/C3d/Include/attr_color.h @@ -11,11 +11,11 @@ #define __ATTR_COLOR_H -#include +#include #include -#define __RGB__ 3 +const_expr uint __RGB__ = 3; //------------------------------------------------------------------------------ @@ -44,6 +44,33 @@ inline uint32 RGB2uint32( double r, double g, double b ) } +//------------------------------------------------------------------------------ +/** \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. \~ @@ -64,6 +91,72 @@ void uint322RGB( uint32 color, float_t& r, float_t& g, float_t& b ) { } +//------------------------------------------------------------------------------ +/** \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. \~ @@ -243,7 +336,7 @@ public : /// \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 ) { + 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. diff --git a/C3d/Include/attr_common_attribute.h b/C3d/Include/attr_common_attribute.h new file mode 100644 index 0000000..ae22d14 --- /dev/null +++ b/C3d/Include/attr_common_attribute.h @@ -0,0 +1,302 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Подтип обобщенные атрибуты. + \en Common attributes subtype. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_COMMON_ATTRIBUE_H +#define __ATTR_COMMON_ATTRIBUE_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Обобщенный атрибут - базовый класс. + \en Common attribute - the base class. \~ + \details \ru Обобщенный атрибут - базовый класс. \n + \en Common attribute - the base class. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbCommonAttribute : public MbAttribute { +protected : + c3d::string_t prompt_; ///< \ru Строка описания. \en String of description. + bool changeable; ///< \ru Признак редактируемости. \en Attribute of editability. + +protected : + /// \ru Конструктор. \en Constructor. + MbCommonAttribute( const c3d::string_t & prompt, const bool change ); + /// \ru Конструктор. \en Constructor. + explicit MbCommonAttribute( const bool change ); + /// \ru Деструктор. \en Destructor. + virtual ~MbCommonAttribute(); + +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 bool IsSame( const MbAttribute &, double accuracy ) const; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. + virtual bool Init( const MbAttribute & ) = 0; // \ru Инициализировать данные по присланным. \en Initialize data. + + // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = 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. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + + virtual void GetCharValue( TCHAR * v ) const = 0; // \ru Выдать строковое значение свойства. \en Get a string value of the property. + virtual void GetProperties( MbProperties & ) = 0; // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ) = 0; // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + /** \brief \ru Выдать подсказку атрибута. \en Get a prompt of attribute. + \details \ru Строковое значение, которое может быть использовано, как совего рода тэг, имя или пометка атрибута. + \en String value which can be used as some kind of tag, name or label of an attribute. + */ + const c3d::string_t & GetPrompt() const; + /// \ru Выдать признак изменяемости. \en Get an attribute of changeability. + bool IsChangeable() const; + +DECLARE_PERSISTENT_CLASS( MbCommonAttribute ) +OBVIOUS_PRIVATE_COPY( MbCommonAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbCommonAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru bool атрибут. + \en Bool attribute. \~ + \details \ru bool атрибут. \n + \en Bool attribute. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbBoolAttribute : public MbCommonAttribute { +private: + bool value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbBoolAttribute( const c3d::string_t & prompt, bool change, bool initValue ); + /// \ru Деструктор. \en Destructor. + virtual ~MbBoolAttribute(); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + bool GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( bool val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBoolAttribute ) +OBVIOUS_PRIVATE_COPY( MbBoolAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbBoolAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru int атрибут. + \en Int attribute. \~ + \details \ru int атрибут. \n + \en Int attribute. \n \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbIntAttribute : public MbCommonAttribute { +private: + int value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbIntAttribute( const c3d::string_t & prompt, bool change, int initValue ); + /// \ru Деструктор. \en Destructor. + virtual ~MbIntAttribute(); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + int GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( int val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntAttribute ) +OBVIOUS_PRIVATE_COPY( MbIntAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbIntAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru int64 атрибут. + \en Int64 attribute. \~ + \details \ru int64 атрибут. \n + \en Int64 attribute. \n \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbInt64Attribute : public MbCommonAttribute { +private: + int64 value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbInt64Attribute( const c3d::string_t & prompt, bool change, int64 initValue ); + /// \ru Деструктор. \en Destructor. + virtual ~MbInt64Attribute(); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + int64 GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( int64 val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbInt64Attribute ) +OBVIOUS_PRIVATE_COPY( MbInt64Attribute ) +}; + +IMPL_PERSISTENT_OPS( MbInt64Attribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru double атрибут. + \en Double attribute. \~ + \details \ru double атрибут. \n + \en Double attribute. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbDoubleAttribute : public MbCommonAttribute { +private: + double value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbDoubleAttribute( const c3d::string_t & prompt, bool change, double initValue ); + /// \ru Деструктор. \en Destructor. + virtual ~MbDoubleAttribute(); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + double GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( double val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDoubleAttribute ) +OBVIOUS_PRIVATE_COPY( MbDoubleAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbDoubleAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru String атрибут. + \en String attribute. \~ + \details \ru String атрибут. \n + \en String attribute. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbStringAttribute : public MbCommonAttribute { +private: + c3d::string_t value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbStringAttribute( const c3d::string_t & prompt, bool change, const c3d::string_t & string ); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + c3d::string_t GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( c3d::string_t & val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +protected: + virtual ~MbStringAttribute(); // Use AddRef/Release or smart pointer SPtr to destruct it correctly. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStringAttribute ) +OBVIOUS_PRIVATE_COPY( MbStringAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbStringAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru Бинарный атрибут. + \en Binary attribute. \~ + \details \ru Бинарный атрибут. \n + \en Binary attribute. \n \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbBinaryAttribute : public MbCommonAttribute { +private: + std::vector value_; ///< \ru Значение. \en The value. + +public: + /// \ru Конструктор. \en Constructor. + explicit MbBinaryAttribute( const c3d::string_t & prompt, bool change, const std::vector & value ); + +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 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + std::vector GetValue() const; // \ru Выдать значение свойства. \en Get a value of the property. + bool SetValue( std::vector & val ); // \ru Установить новое значение свойства. \en Set new value of the property. + +protected: + virtual ~MbBinaryAttribute(); // Use AddRef/Release or smart pointer SPtr to destruct it correctly. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBinaryAttribute ) +OBVIOUS_PRIVATE_COPY( MbBinaryAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbBinaryAttribute ) + +#endif // __ATTR_COMMON_ATTRIBUE_H diff --git a/C3d/Include/attr_dencity.h b/C3d/Include/attr_dencity.h index e4738af..025963d 100644 --- a/C3d/Include/attr_dencity.h +++ b/C3d/Include/attr_dencity.h @@ -1,163 +1,163 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибуты. Плотность. - \en Attributes. Density. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_DENCITY_H -#define __ATTR_DENCITY_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Плотность. - \en Density. \~ - \details \ru Плотность. \n - \en Density. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbDencity : public MbElementaryAttribute { -protected : - double dencity; ///< \ru Плотность. \en Density. - -protected : - /// \ru Конструктор. \en Constructor. - MbDencity( const MbDencity & init ); -public : - /// \ru Конструктор. \en Constructor. - MbDencity( double init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbDencity(); - - // \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 density. - void Init( double init ) { dencity = init; } - /// \ru Дать плотность. \en Get a density. - double Dencity() const { return dencity; } - - 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 MbDencity & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDencity ) - -}; // MbDencity - -IMPL_PERSISTENT_OPS( MbDencity ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Жесткость. - \en The stiffness. \~ - \details \ru Механические характеристики материала: модуль Юнга и коэффициент Пуассана. \n - \en Mechanical properties of the material: Young's modulus and Poisson's ratio. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbElasticity : public MbElementaryAttribute { -protected : - double young; ///< \ru Модуль Юнга. \en The Young's modulus of material. - double poisson; ///< \ru Коэффициент Пуассона. \en The Poisson's ratio of material. - -protected : - /// \ru Конструктор. \en Constructor. - MbElasticity( const MbElasticity & init ); -public : - /// \ru Конструктор. \en Constructor. - MbElasticity( double e, double v ); - /// \ru Деструктор. \en Destructor. - virtual ~MbElasticity(); - - // \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 density. - void Init( double e_, double v_ ) { young = e_; poisson = v_; } - /// \ru Дать Модуль Юнга. \en Get an Young's modulus. - double YoungModulus() const { return young; } - /// \ru Дать Коэффициент Пуассона. \en Get a Poisson's ratio. - double PoissonRatio() const { return poisson; } - - 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 MbElasticity & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbElasticity ) - -}; // MbElasticity - -IMPL_PERSISTENT_OPS( MbElasticity ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Деформации / Напряжения. - \en The strains / The tensions. \~ - \details \ru Напряжённо деформированное состояние объекта - три деформации или три напряжения. \n - \en Tension strain state of an object. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbStrains : public MbElementaryAttribute { -protected : - double strain1; ///< \ru Деформация 1 / Напряжение 1. \en The strain 1 / The tension 1. - double strain2; ///< \ru Деформация 2 / Напряжение 2. \en The strain 2 / The tension 2. - double strain3; ///< \ru Деформация 3 / Напряжение 3. \en The strain 3 / The tension 3. - -protected : - /// \ru Конструктор. \en Constructor. - MbStrains( const MbStrains & init ); -public : - /// \ru Конструктор. \en Constructor. - MbStrains( double e1, double e2, double e3 ); - /// \ru Деструктор. \en Destructor. - virtual ~MbStrains(); - - // \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 density. - void Init( double e1, double e2, double e3 ) { strain1 = e1; strain2 = e2; strain3 = e3; } - /// \ru Дать деформированное состояние объекта. \en Get a deformed state. - double Strain( size_t i ) const { if ( i <= 1 ) return strain1; else if ( i == 2 ) return strain1; else return strain3; } - - 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 MbStrains & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStrains ) - -}; // MbStrains - -IMPL_PERSISTENT_OPS( MbStrains ) - - -#endif // __ATTR_DENCITY_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибуты. Плотность. + \en Attributes. Density. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_DENCITY_H +#define __ATTR_DENCITY_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Плотность. + \en Density. \~ + \details \ru Плотность. \n + \en Density. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbDencity : public MbElementaryAttribute { +protected : + double dencity; ///< \ru Плотность. \en Density. + +protected : + /// \ru Конструктор. \en Constructor. + MbDencity( const MbDencity & init ); +public : + /// \ru Конструктор. \en Constructor. + MbDencity( double init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbDencity(); + + // \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 density. + void Init( double init ) { dencity = init; } + /// \ru Дать плотность. \en Get a density. + double Dencity() const { return dencity; } + + 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 MbDencity & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDencity ) + +}; // MbDencity + +IMPL_PERSISTENT_OPS( MbDencity ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Жесткость. + \en The stiffness. \~ + \details \ru Механические характеристики материала: модуль Юнга и коэффициент Пуассана. \n + \en Mechanical properties of the material: Young's modulus and Poisson's ratio. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbElasticity : public MbElementaryAttribute { +protected : + double young; ///< \ru Модуль Юнга. \en The Young's modulus of material. + double poisson; ///< \ru Коэффициент Пуассона. \en The Poisson's ratio of material. + +protected : + /// \ru Конструктор. \en Constructor. + MbElasticity( const MbElasticity & init ); +public : + /// \ru Конструктор. \en Constructor. + MbElasticity( double e, double v ); + /// \ru Деструктор. \en Destructor. + virtual ~MbElasticity(); + + // \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 density. + void Init( double e_, double v_ ) { young = e_; poisson = v_; } + /// \ru Дать Модуль Юнга. \en Get an Young's modulus. + double YoungModulus() const { return young; } + /// \ru Дать Коэффициент Пуассона. \en Get a Poisson's ratio. + double PoissonRatio() const { return poisson; } + + 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 MbElasticity & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbElasticity ) + +}; // MbElasticity + +IMPL_PERSISTENT_OPS( MbElasticity ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Деформации / Напряжения. + \en The strains / The tensions. \~ + \details \ru Напряжённо деформированное состояние объекта - три деформации или три напряжения. \n + \en Tension strain state of an object. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbStrains : public MbElementaryAttribute { +protected : + double strain1; ///< \ru Деформация 1 / Напряжение 1. \en The strain 1 / The tension 1. + double strain2; ///< \ru Деформация 2 / Напряжение 2. \en The strain 2 / The tension 2. + double strain3; ///< \ru Деформация 3 / Напряжение 3. \en The strain 3 / The tension 3. + +protected : + /// \ru Конструктор. \en Constructor. + MbStrains( const MbStrains & init ); +public : + /// \ru Конструктор. \en Constructor. + MbStrains( double e1, double e2, double e3 ); + /// \ru Деструктор. \en Destructor. + virtual ~MbStrains(); + + // \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 density. + void Init( double e1, double e2, double e3 ) { strain1 = e1; strain2 = e2; strain3 = e3; } + /// \ru Дать деформированное состояние объекта. \en Get a deformed state. + double Strain( size_t i ) const { if ( i <= 1 ) return strain1; else if ( i == 2 ) return strain1; else return strain3; } + + 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 MbStrains & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStrains ) + +}; // MbStrains + +IMPL_PERSISTENT_OPS( MbStrains ) + + +#endif // __ATTR_DENCITY_H diff --git a/C3d/Include/attr_elementary_attribute.h b/C3d/Include/attr_elementary_attribute.h new file mode 100644 index 0000000..c5fd3bf --- /dev/null +++ b/C3d/Include/attr_elementary_attribute.h @@ -0,0 +1,68 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Подтип элементарные атрибуты. + \en Elementary attributes subtype. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_ELEMENTARY_ATTRIBUTE_H +#define __ATTR_ELEMENTARY_ATTRIBUTE_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Элементарный атрибут - базовый класс. + \en Elementary attribute - the base class. \~ + \details \ru Элементарный атрибут - базовый класс. \n + \en Elementary attribute - the base class. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbElementaryAttribute : public MbAttribute { +protected: + MbElementaryAttribute(); +public: + virtual ~MbElementaryAttribute(); + +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 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. + + // \ru Действия при изменении владельца, не связанное с другими действиями. \en Actions which are not associated with other actions when changing the owner. + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // \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 ); + // \ru Действия при перемещении владельца. \en Actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Действия при вращении владельца. \en Actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Действия при копировании владельца. \en Actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + // \ru Действия при объединении владельца. \en Actions when merging the owner. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Действия при замене владельца. \en Actions when replacing the owner. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Действия при разделении владельца. \en Actions when splitting the owner. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // \ru Действия при удалении владельца. \en Actions when merging the owner. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + + virtual void GetProperties( MbProperties & ) = 0; // \ru Выдать свойства объекта \en Get properties of the object + virtual size_t SetProperties( const MbProperties & ) = 0; // \ru Установить свойства объекта \en Set properties of object + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта \en Get a name of object property + +DECLARE_PERSISTENT_CLASS( MbElementaryAttribute ) +OBVIOUS_PRIVATE_COPY( MbElementaryAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbElementaryAttribute ) + +#endif // __ATTR_ELEMENTARY_ATTRIBUTE_H diff --git a/C3d/Include/attr_flange_attribute.h b/C3d/Include/attr_flange_attribute.h new file mode 100644 index 0000000..a76278f --- /dev/null +++ b/C3d/Include/attr_flange_attribute.h @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибут отбортовки листового тела. + \en Swept flange attribute of a sheet solid. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_FLANGE_ATTRIBUTE_H +#define __ATTR_FLANGE_ATTRIBUTE_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Атрибут отбортовки листового тела. + \en Swept flange attribute of a sheet solid. \~ + \details \ru . + \en \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbSheetFlangingAttribute : public MbCommonAttribute { +protected : + MbBendByEdgeValues params; ///< \ru Параметры операции. \en The operation parameters. + MbSNameMaker names; ///< \ru Именователь операции. \en An object defining names generation in the operation. + +public : + /// \ru Конструктор. \en Constructor. + MbSheetFlangingAttribute( const MbBendByEdgeValues & pars, const MbSNameMaker & n, const bool changeable ); + /// \ru Конструктор. \en Constructor. + MbSheetFlangingAttribute( const MbBendByEdgeValues & pars, const MbSNameMaker & n, const bool changeable, const c3d::string_t & itemPrompt ); + /// \ru Деструктор. \en Destructor. + virtual ~MbSheetFlangingAttribute(); + +private: + // \ru Конструктор копирования. \en Copy constructor. + MbSheetFlangingAttribute( const MbSheetFlangingAttribute & init, MbRegDuplicate * iReg ); + +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; + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + + virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. + 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. + + /// \ru Дать параметры операции. \en Get operation parameters. + const MbBendByEdgeValues & GetFlangeValues() const { return params; } + /// \ru Дать именователь операции. \en Get an object defining a name of the operation. + const MbSNameMaker & GetNameMaker() const { return names; } + +DECLARE_PERSISTENT_CLASS( MbSheetFlangingAttribute ) +OBVIOUS_PRIVATE_COPY( MbSheetFlangingAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbSheetFlangingAttribute ) + +#endif // __ATTR_FLANGE_ATTRIBUTE_H diff --git a/C3d/Include/attr_geometric_attribute.h b/C3d/Include/attr_geometric_attribute.h new file mode 100644 index 0000000..05968b1 --- /dev/null +++ b/C3d/Include/attr_geometric_attribute.h @@ -0,0 +1,89 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Геометрический атрибут. + \en Geometric attribute. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_GEOMETRIC_ATTRIBUTE_H +#define __ATTR_GEOMETRIC_ATTRIBUTE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbSpaceItem; +class MATH_CLASS MbProperty; +class MATH_CLASS MbProperties; +class MbRegTransform; +class MbRegDuplicate; + + +//------------------------------------------------------------------------------ +/** \brief \ru Геометрический атрибут. + \en Geometric attribute. \~ + \details \ru Геометрический атрибут. \n + \en Geometric attribute. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbGeomAttribute : public MbCommonAttribute { +protected : + MbSpaceItem * spaceItem; ///< \ru Геометрический объект. \en A geometric object. + MbeCreatorType type; ///< \ru Тип операции. \en Operation type. + bool keepItem; ///< \ru Сохранять исходный объект при копировании. \en Save the initial object when copying. + +private: + // \ru Конструктор копирования. \en Copy constructor. + MbGeomAttribute( const MbGeomAttribute & init, MbRegDuplicate * iReg ); +public : + /// \ru Конструктор. \en Constructor. + MbGeomAttribute( const MbSpaceItem & item, MbeCreatorType t, bool keepItem ); + /// \ru Конструктор. \en Constructor. + MbGeomAttribute( const MbSpaceItem & item, MbeCreatorType t, bool keepItem, const c3d::string_t & itemPrompt ); + /// \ru Деструктор. \en Destructor. + virtual ~MbGeomAttribute(); + +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; + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + + virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. + 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. + /// \ru Дать геометрический объект. \en Get geometric object. + const MbSpaceItem * GetSpaceItem() const { return spaceItem; } + MbSpaceItem * SetSpaceItem() { return spaceItem; } + /// \ru Заменить геометрический объект. \en Replace geometric object. + void ChangeSpaceItem( MbSpaceItem & init ); + /// \ru Дать тип операции. \en Get operation type. + MbeCreatorType GetOperationType() const { return type; } + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbGeomAttribute ) +OBVIOUS_PRIVATE_COPY( MbGeomAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbGeomAttribute ) + +#endif // __ATTR_GEOMETRIC_ATTRIBUTE_H diff --git a/C3d/Include/attr_identifier.h b/C3d/Include/attr_identifier.h index 16bff54..adfe68e 100644 --- a/C3d/Include/attr_identifier.h +++ b/C3d/Include/attr_identifier.h @@ -1,322 +1,322 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Идентификатор объекта. - \en Object identifier. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_IDENTIFIER_H -#define __ATTR_IDENTIFIER_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Идентификатор объекта. - \en Object identifier. \~ - \details \ru Идентификатор объекта. \n - \en Object identifier. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbIdentifier : public MbElementaryAttribute { -protected : - int32 identifier; ///< \ru Идентификатор объекта. \en Object identifier. - -protected : - /// \ru Конструктор. \en Constructor. - MbIdentifier( const MbIdentifier & ); -public : - /// \ru Конструктор. \en Constructor. - MbIdentifier( int32 init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbIdentifier(); - - // \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. - 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. - - // \ru Специфические свойства объекта. \en Specific functions of object. - - /// \ru Установить идентификатор. \en Set identifier. - void Init( int32 init ) { identifier = init; } - /// \ru Дать идентификатор объекта. \en Get identifier of object. - int32 Identifier() const { return identifier; } - -private: - MbIdentifier & operator = ( const MbIdentifier & ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIdentifier ) -}; // MbIdentifier - -IMPL_PERSISTENT_OPS( MbIdentifier ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Топологическое имя. - \en Topological name. \~ - \details \ru Топологическое имя. \n - \en Topological name. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbNameAttribute : public MbElementaryAttribute { - typedef std::vector NameAttributesVector; -protected : - MbName tName; ///< \ru Топологическое имя объекта. \en A name of a topological object -private: - NameAttributesVector parentNames; ///< \ru Топологические имена родителей объекта. \en Topological names of object parents. - mutable bool isTemporal; ///< \ru Атрибут временный, на время операции (Этот признак не пишется и не читается). \en Attribute is temporary, for the duration of the operation only (This tag is not read or written). - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbNameAttribute( const MbNameAttribute & ); -public : - /// \ru Конструктор. \en Constructor. - MbNameAttribute( bool isTemporal = false ); - /// \ru Конструктор. \en Constructor. - MbNameAttribute( const MbName &, bool isTemporal = false ); - /// \ru Деструктор. \en Destructor. - virtual ~MbNameAttribute(); - - // \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 Perform actions when merging the owner. - virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - - /// \ru Выдать имя. \en Get name. - const MbName & GetName() const { return tName; } - /// \ru Выдать имя. \en Get name. - MbName & SetName() { return tName; } - /// \ru Установить имя. \en Set name. - void SetName( const MbName &, bool deleteParentNames = true ); - - /// \ru Определить, есть ли хоть одно имя родительского объекта. \en Determine whether at least one name of parent object exists. - bool IsAnyParentName() const { return (parentNames.size() > 0); } - /// \ru Выдать количество родительских имен первого уровня. \en Get the number of parent names of the first level. - size_t GetParentNamesCount() const { return parentNames.size(); } - /// \ru Удалить имена родительских объектов. \en Delete names of parent objects. - void DeleteParentNames(); - /// \ru Добавить имя родительского объекта. \en Add a name of parent object. - bool AddParentName( const MbName &, bool isTemporal = false ); - /// \ru Добавить имена родительских объектов. \en Add names of parent objects. - bool AddParentNames( const MbNameAttribute &, double accuracy ); - /// \ru Получить имена родительских объектов. \en Get names of parent objects. - void GetParentNames( std::vector & ) const; - ///< \ru Является ли атрибут временным. \en Whether this attribute is temporary. - bool IsTemporal() const { return isTemporal; } - - 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: - MbNameAttribute & operator = ( const MbNameAttribute & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNameAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbNameAttribute ) - -//------------------------------------------------------------------------------ -/** \brief \ru Метка времени обновления. - \en Stamp of update time. \~ - \details \ru Метка времени обновления. \n - \en Stamp of update time. \n \~ - \ingroup Model_Attributes -*/ -class MATH_CLASS MbUpdateStamp : public MbElementaryAttribute -{ -protected : - uint32 updStamp; ///< \ru Значение метки. \en The value of stamp. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbUpdateStamp( const MbUpdateStamp & ); -public : - /// \ru Конструктор. \en Constructor. - MbUpdateStamp(); - /// \ru Конструктор. \en Constructor. - MbUpdateStamp( uint32 stampVal ); - /// \ru Деструктор. \en Destructor. - virtual ~MbUpdateStamp(); - - // \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 Reset a value of a stamp of update time. - void ResetStamp() { updStamp = 0; } - /// \ru Проверить, равно ли значение метки нулю. \en Check whether the value of a stamp is null. - bool IsNull () const { return updStamp == 0; } - /// \ru Дать значение метки времени обновления. \en Get the value of a stamp of update time. - uint32 GetStamp () const { return updStamp; } - - /// \ru Увеличить значение метки на единицу. \en Increase the value of stamp by one. - void Increment () { updStamp++; } - /// \ru Установить значение метки максимальным из присланного и действующего. \en Set the value of stamp to the maximum from the given value and the current value. - void Maximize ( uint32 val ) { if (val > updStamp) updStamp = val; } - - - 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: - MbUpdateStamp & operator = ( const MbUpdateStamp & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUpdateStamp ) -}; - -IMPL_PERSISTENT_OPS( MbUpdateStamp ) - -//------------------------------------------------------------------------------ -/** \brief \ru Атрибут "якорь". - \en Attribute "anchor". \~ - \details \ru Атрибут "якорь". \n - \en Attribute "anchor". \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbAnchorAttribute : public MbAttribute { -public: - enum AnchorType { - ant_Undefined = 0, ///< \ru Неопределенный тип. \en An undefined type. - ant_TopoName, ///< \ru Для топологического имени. \en For a topological name. - }; - -protected : - uint8 aType; ///< \ru Тип якорного атрибута. \en Type of an anchor attribute. - -protected : - /// \ru Конструктор копирования. \en Copy constructor. - MbAnchorAttribute( const MbAnchorAttribute & ); -public : - /// \ru Конструктор. \en Constructor. - MbAnchorAttribute(); - /// \ru Конструктор. \en Constructor. - MbAnchorAttribute( AnchorType type ); - /// \ru Деструктор. \en Destructor. - virtual ~MbAnchorAttribute(); - - // \ru Общие функции объекта. \en Common functions of object. - - 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 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 Get type of an anchor attribute. - AnchorType GetAnchorType() { return static_cast(aType); } - - // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. - virtual void OnChangeOwner( const MbAttributeContainer & owner ); - // \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 & matr, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D & to, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * iReg = 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. - virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. - virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); - // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. - virtual void OnDeleteOwner( const MbAttributeContainer & owner ); - - 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: - MbAnchorAttribute & operator = ( const MbAnchorAttribute & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAnchorAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbAnchorAttribute ) - -//------------------------------------------------------------------------------ -/** \brief \ru Признак исполнения (варианта реализации модели). - \en Indication of embodiment (variant of model implementation). \~ - \details \ru Признак исполнения (варианта реализации модели). \n - \en Indication of embodiment (variant of model implementation). \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbEmbodimentAttribute : public MbElementaryAttribute { -protected: - SimpleName m_name; ///< \ru Имя исполнения. \en Name of embodiment. - SimpleName m_parent; ///< \ru Имя родительского исполнения. \en Name of parent embodiment. - bool m_current; ///< \ru Признак, является ли исполнение текущим. \en Flag, whether the embodiment is current. - -protected: - // \ru Конструктор. \en Constructor. - MbEmbodimentAttribute( const MbEmbodimentAttribute & ); -public: - // \ru Конструктор. \en Constructor. - MbEmbodimentAttribute(); - // \ru Конструктор. \en Constructor. - MbEmbodimentAttribute( const SimpleName & name1, const SimpleName & name2, bool curr = false ); - // \ru Деструктор. \en Destructor. - virtual ~MbEmbodimentAttribute(); - - // \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 ) 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. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - - // \ru Специфические функции объекта. \en Specific functions of object. - - // \ru Установить родительское исполнение. \en Set a parent embodiment. - void Init( const SimpleName & name1, const SimpleName & name2, bool curr = false ) { - m_name = name1; m_parent = name2; m_current = curr; - } - // \ru Выдать имя исполнения. \en Get a name of embodiment. - SimpleName Name() const { return m_name; } - // \ru Выдать имя родительского исполнения. \en Get a name of parent embodiment. - SimpleName ParentName() const { return m_parent; } - // \ru Является ли исполнение текущим. \en Whether the embodiment is current. - bool IsCurrent() const { return m_current; } - -private: - void operator = ( const MbEmbodimentAttribute & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbEmbodimentAttribute ) - -}; // MbEmbodimentAttribute - -IMPL_PERSISTENT_OPS( MbEmbodimentAttribute ) - - -#endif // __ATTR_IDENTIFIER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Идентификатор объекта. + \en Object identifier. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_IDENTIFIER_H +#define __ATTR_IDENTIFIER_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Идентификатор объекта. + \en Object identifier. \~ + \details \ru Идентификатор объекта. \n + \en Object identifier. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbIdentifier : public MbElementaryAttribute { +protected : + int32 identifier; ///< \ru Идентификатор объекта. \en Object identifier. + +protected : + /// \ru Конструктор. \en Constructor. + MbIdentifier( const MbIdentifier & ); +public : + /// \ru Конструктор. \en Constructor. + MbIdentifier( int32 init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbIdentifier(); + + // \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. + 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. + + // \ru Специфические свойства объекта. \en Specific functions of object. + + /// \ru Установить идентификатор. \en Set identifier. + void Init( int32 init ) { identifier = init; } + /// \ru Дать идентификатор объекта. \en Get identifier of object. + int32 Identifier() const { return identifier; } + +private: + MbIdentifier & operator = ( const MbIdentifier & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIdentifier ) +}; // MbIdentifier + +IMPL_PERSISTENT_OPS( MbIdentifier ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Топологическое имя. + \en Topological name. \~ + \details \ru Топологическое имя. \n + \en Topological name. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbNameAttribute : public MbElementaryAttribute { + typedef std::vector NameAttributesVector; +protected : + MbName tName; ///< \ru Топологическое имя объекта. \en A name of a topological object +private: + NameAttributesVector parentNames; ///< \ru Топологические имена родителей объекта. \en Topological names of object parents. + bool isTemporal; ///< \ru Атрибут временный, на время операции (Этот признак не пишется и не читается). \en Attribute is temporary, for the duration of the operation only (This tag is not read or written). + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbNameAttribute( const MbNameAttribute & ); +public : + /// \ru Конструктор. \en Constructor. + MbNameAttribute( bool isTemporal = false ); + /// \ru Конструктор. \en Constructor. + MbNameAttribute( const MbName &, bool isTemporal = false ); + /// \ru Деструктор. \en Destructor. + virtual ~MbNameAttribute(); + + // \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 Perform actions when merging the owner. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + + /// \ru Выдать имя. \en Get name. + const MbName & GetName() const { return tName; } + /// \ru Выдать имя. \en Get name. + MbName & SetName() { return tName; } + /// \ru Установить имя. \en Set name. + void SetName( const MbName &, bool deleteParentNames = true ); + + /// \ru Определить, есть ли хоть одно имя родительского объекта. \en Determine whether at least one name of parent object exists. + bool IsAnyParentName() const { return (parentNames.size() > 0); } + /// \ru Выдать количество родительских имен первого уровня. \en Get the number of parent names of the first level. + size_t GetParentNamesCount() const { return parentNames.size(); } + /// \ru Удалить имена родительских объектов. \en Delete names of parent objects. + void DeleteParentNames(); + /// \ru Добавить имя родительского объекта. \en Add a name of parent object. + bool AddParentName( const MbName &, bool isTemporal = false ); + /// \ru Добавить имена родительских объектов. \en Add names of parent objects. + bool AddParentNames( const MbNameAttribute &, double accuracy ); + /// \ru Получить имена родительских объектов. \en Get names of parent objects. + void GetParentNames( c3d::ConstNamesVector & ) const; + ///< \ru Является ли атрибут временным. \en Whether this attribute is temporary. + bool IsTemporal() const { return isTemporal; } + + 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: + MbNameAttribute & operator = ( const MbNameAttribute & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNameAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbNameAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru Метка времени обновления. + \en Stamp of update time. \~ + \details \ru Метка времени обновления. \n + \en Stamp of update time. \n \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbUpdateStamp : public MbElementaryAttribute +{ +protected : + uint32 updStamp; ///< \ru Значение метки. \en The value of stamp. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbUpdateStamp( const MbUpdateStamp & ); +public : + /// \ru Конструктор. \en Constructor. + MbUpdateStamp(); + /// \ru Конструктор. \en Constructor. + MbUpdateStamp( uint32 stampVal ); + /// \ru Деструктор. \en Destructor. + virtual ~MbUpdateStamp(); + + // \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 Reset a value of a stamp of update time. + void ResetStamp() { updStamp = 0; } + /// \ru Проверить, равно ли значение метки нулю. \en Check whether the value of a stamp is null. + bool IsNull () const { return updStamp == 0; } + /// \ru Дать значение метки времени обновления. \en Get the value of a stamp of update time. + uint32 GetStamp () const { return updStamp; } + + /// \ru Увеличить значение метки на единицу. \en Increase the value of stamp by one. + void Increment () { updStamp++; } + /// \ru Установить значение метки максимальным из присланного и действующего. \en Set the value of stamp to the maximum from the given value and the current value. + void Maximize ( uint32 val ) { if (val > updStamp) updStamp = val; } + + + 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: + MbUpdateStamp & operator = ( const MbUpdateStamp & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUpdateStamp ) +}; + +IMPL_PERSISTENT_OPS( MbUpdateStamp ) + +//------------------------------------------------------------------------------ +/** \brief \ru Атрибут "якорь". + \en Attribute "anchor". \~ + \details \ru Атрибут "якорь". \n + \en Attribute "anchor". \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbAnchorAttribute : public MbAttribute { +public: + enum AnchorType { + ant_Undefined = 0, ///< \ru Неопределенный тип. \en An undefined type. + ant_TopoName, ///< \ru Для топологического имени. \en For a topological name. + }; + +protected : + uint8 aType; ///< \ru Тип якорного атрибута. \en Type of an anchor attribute. + +protected : + /// \ru Конструктор копирования. \en Copy constructor. + MbAnchorAttribute( const MbAnchorAttribute & ); +public : + /// \ru Конструктор. \en Constructor. + MbAnchorAttribute(); + /// \ru Конструктор. \en Constructor. + MbAnchorAttribute( AnchorType type ); + /// \ru Деструктор. \en Destructor. + virtual ~MbAnchorAttribute(); + + // \ru Общие функции объекта. \en Common functions of object. + + 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 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 Get type of an anchor attribute. + AnchorType GetAnchorType() { return static_cast(aType); } + + // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = 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. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + + 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: + MbAnchorAttribute & operator = ( const MbAnchorAttribute & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAnchorAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbAnchorAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru Признак исполнения (варианта реализации модели). + \en Indication of embodiment (variant of model implementation). \~ + \details \ru Признак исполнения (варианта реализации модели). \n + \en Indication of embodiment (variant of model implementation). \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbEmbodimentAttribute : public MbElementaryAttribute { +protected: + SimpleName m_name; ///< \ru Имя исполнения. \en Name of embodiment. + SimpleName m_parent; ///< \ru Имя родительского исполнения. \en Name of parent embodiment. + bool m_current; ///< \ru Признак, является ли исполнение текущим. \en Flag, whether the embodiment is current. + +protected: + // \ru Конструктор. \en Constructor. + MbEmbodimentAttribute( const MbEmbodimentAttribute & ); +public: + // \ru Конструктор. \en Constructor. + MbEmbodimentAttribute(); + // \ru Конструктор. \en Constructor. + MbEmbodimentAttribute( const SimpleName & name1, const SimpleName & name2, bool curr = false ); + // \ru Деструктор. \en Destructor. + virtual ~MbEmbodimentAttribute(); + + // \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 ) 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. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + // \ru Специфические функции объекта. \en Specific functions of object. + + // \ru Установить родительское исполнение. \en Set a parent embodiment. + void Init( const SimpleName & name1, const SimpleName & name2, bool curr = false ) { + m_name = name1; m_parent = name2; m_current = curr; + } + // \ru Выдать имя исполнения. \en Get a name of embodiment. + SimpleName Name() const { return m_name; } + // \ru Выдать имя родительского исполнения. \en Get a name of parent embodiment. + SimpleName ParentName() const { return m_parent; } + // \ru Является ли исполнение текущим. \en Whether the embodiment is current. + bool IsCurrent() const { return m_current; } + +private: + void operator = ( const MbEmbodimentAttribute & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbEmbodimentAttribute ) + +}; // MbEmbodimentAttribute + +IMPL_PERSISTENT_OPS( MbEmbodimentAttribute ) + + +#endif // __ATTR_IDENTIFIER_H diff --git a/C3d/Include/attr_product.h b/C3d/Include/attr_product.h index d5a83b5..8fbf40e 100644 --- a/C3d/Include/attr_product.h +++ b/C3d/Include/attr_product.h @@ -1,432 +1,471 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибуты изделий. - \en Product attributes. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include -#include -#include - - -#ifndef __ATTR_PRODUCT_H -#define __ATTR_PRODUCT_H - - -//------------------------------------------------------------------------------ -/** \brief \ru Родительский класс атрибутов изделий. - \en Base calss of product attributes. -*/ -// --- -class MATH_CLASS MbProductAttribute : public MbAttribute { -protected : - MbProductAttribute(); // \ru Конструктор. \en Constructor. -public : - // \ru Деструктор. \en Destructor. - virtual ~MbProductAttribute(); - -public : - virtual MbeAttributeType AttributeFamily() const; - // Выдать подтип атрибута (временно). - virtual MbeAttributeType AttributeType() const = 0; - // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = 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; - - virtual MbePrompt GetPropertyName() = 0; - - // Действия при изменении владельца, не связанное с другими действиями. - virtual void OnChangeOwner( const MbAttributeContainer & owner ); - // Действия при конвертации владельца. - virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - // Действия при трансформировании владельца. - virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D & matr, MbRegTransform * iReg = NULL ); - // Действия при перемещении владельца. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D & to, MbRegTransform * iReg = NULL ); - // Действия при вращении владельца. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - // Действия при копировании владельца. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * iReg = NULL ); - // Действия при объединении владельца. - virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - // Действия при замене владельца. - virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - // Действия при разделении владельца. - virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); - // Действия при удалении владельца. - virtual void OnDeleteOwner( const MbAttributeContainer & owner ); - -DECLARE_PERSISTENT_CLASS( MbProductAttribute ) -OBVIOUS_PRIVATE_COPY( MbProductAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbProductAttribute ) - -//------------------------------------------------------------------------------ -/** \brief \ru Сведения о лице в организации. - \en Information related to a person and the organization he/she in. -*/ -// --- -class MATH_CLASS MbPersonOrganizationInfo : public MbProductAttribute { - c3d::string_t personId; ///< \ru Идентификатор лица. \en Identifier of the person. - c3d::string_t lastName; ///< \ru Фамилия. \en Last name. - c3d::string_t firstName; ///< \ru Имя. \en First name. - std::list middleNames; ///< \ru Отчество/средние имена. \en Middle names. - std::list prefixTitles; ///< \ru Титулы предшествующие. \en Prefix titles. - std::list suffixTitles; ///< \ru Титулы завершающие. \en Suffix titles. - c3d::string_t orgId; ///< \ru Идентификатор организации. \en Identifier of the organization. - c3d::string_t orgLabel; ///< \ru Название организации. \en Label of the organization. - c3d::string_t orgDescription; ///< \ru Описание организации. \en Description of the organization. - std::set roles; ///< \ru Роли лица по отношению к изделию. \en The person's roles concerning a product. -protected : - // Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. - MbPersonOrganizationInfo( const MbPersonOrganizationInfo & ); -public : - // Конструктор без параметров для наследников. - MbPersonOrganizationInfo(); - // Деструктор. - virtual ~MbPersonOrganizationInfo(); - -public : - // Выдать подтип атрибута (временно). - virtual MbeAttributeType AttributeType() const; - // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. - // Инициализировать данные по присланным. - virtual bool Init( const MbAttribute & ) ; - virtual void GetProperties( MbProperties & ); // выдать свойства объекта - - virtual MbePrompt GetPropertyName() ; - - /** - \brief \ru Получить данные. \en Get data. \~ - \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ - \param[out] oLast - \ru Фамилия. \en Last name. \~ - \param[out] oFirst - \ru Имя. \en First name. \~ - \param[out] oMid - \ru Итератор для вставки всех строк, соответствующих отчеству/средним именам. \en Insert iterator for middle names. \~ - \param[out] oPre - \ru Итератор для вставки всех строк, соответствующих титулов предшествующих. \en Insert iterator for prefix titles. \~ - \param[out] oSuf - \ru Итератор для вставки всех строк, соответствующих титулов завершающих. \en Insert iterator for suffix titles. \~ - \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - template< typename OutMid, typename OutPre, typename OutSuf > - void GetData( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, - OutMid oMid, OutPre oPre, OutSuf oSuf, - c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const; - - - /** - \brief \ru Получить данные. \en Get data. \~ - \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ - \param[out] oLast - \ru Фамилия. \en Last name. \~ - \param[out] oFirst - \ru Имя. \en First name. \~ - \param[out] oMid - \ru Итератор для вставки всех строк, соответствующих отчеству/средним именам. \en Insert iterator for middle names. \~ - \param[out] oPre - \ru Итератор для вставки всех строк, соответствующих титулов предшествующих. \en Insert iterator for prefix titles. \~ - \param[out] oSuf - \ru Итератор для вставки всех строк, соответствующих титулов завершающих. \en Insert iterator for suffix titles. \~ - \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - template< typename OutMid, typename OutPre, typename OutSuf > - void GetPOData( std::string& oPersonId, std::string& oLast, std::string& oFirst, - OutMid oMid, OutPre oPre, OutSuf oSuf, - std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const; - - /** - \brief \ru Получить полное имя с префиксами и суффиксами. \en full name with prefixes and suffixes. \~ - */ - c3d::string_t NameOneLine() const; - - /** - \brief \ru Получить данные организации. \en Get organization data. \~ - \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - void GetOrganization( c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const; - - - /** - \brief \ru Получить данные организации. \en Get organization data. \~ - \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - void GetOrganizationInfo( std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const; - - /** - \brief \ru Задать данные лица. \en Set person's data. \~ - \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ - \param[in] oLast - \ru Фамилия. \en Last name. \~ - \param[in] oFirst - \ru Имя. \en First name. \~ - \param[in] firstMid - \ru Итератор первой строки, соответствующей отчеству/средним именам. \en First iterator for middle names. \~ - \param[in] lastMid - \ru Итератор за последней строкой, соответствующей отчеству/средним именам. \en Next after last iterator for middle names. \~ - \param[in] firstPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en First iterator for prefix titles. \~ - \param[in] lastPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en Next after last iterator for prefix titles. \~ - \param[in] firstSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en First iterator for suffix titles. \~ - \param[in] lastSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en Next after last iterator for suffix titles. \~ - */ - template< typename InMid, typename InPre, typename InSuf > - void SetPerson( const c3d::string_t& oPersonId, const c3d::string_t& oLast, const c3d::string_t& oFirst, - InMid firstMid, InMid lastMid, - InPre firstPre, InPre lastPre, - InSuf firstSuf, InSuf lastSuf ); - - /** - \brief \ru Задать данные лица. \en Set person's data. \~ - \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ - \param[in] oLast - \ru Фамилия. \en Last name. \~ - \param[in] oFirst - \ru Имя. \en First name. \~ - \param[in] firstMid - \ru Итератор первой строки, соответствующей отчеству/средним именам. \en First iterator for middle names. \~ - \param[in] lastMid - \ru Итератор за последней строкой, соответствующей отчеству/средним именам. \en Next after last iterator for middle names. \~ - \param[in] firstPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en First iterator for prefix titles. \~ - \param[in] lastPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en Next after last iterator for prefix titles. \~ - \param[in] firstSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en First iterator for suffix titles. \~ - \param[in] lastSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en Next after last iterator for suffix titles. \~ - */ - template< typename InMid, typename InPre, typename InSuf > - void SetPersonInfo( const std::string& oPersonId, const std::string& oLast, const std::string& oFirst, - InMid firstMid, InMid lastMid, - InPre firstPre, InPre lastPre, - InSuf firstSuf, InSuf lastSuf ); - - /** - \brief \ru Задать данные организации. \en Set organization's data. \~ - \param[in] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[in] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[in] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - void SetOrganization( const c3d::string_t& initOrgId, const c3d::string_t& initOrgLabel, const c3d::string_t& initOrgDesc ); - - /** - \brief \ru Задать данные организации. \en Set organization's data. \~ - \param[in] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ - \param[in] oOrgLabel - \ru Название организации. \en Label of the organization. \~ - \param[in] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ - */ - void SetOrganizationInfo( const std::string& initOrgId, const std::string& initOrgLabel, const std::string& initOrgDesc ); - - /** - \brief \ru Задать данные лица и организации в упрощенной форме. \en Set person's and organization's simplified data. \~ - \param[in] person - \ru Фамилия автора. \en Author's second name. \~ - \param[in] organization - \ru Название организации. \en Label of the organization. \~ - */ - void SetPersonOrganization( const c3d::string_t& person, const c3d::string_t& organization ); - - /** - \brief \ru Задать данные лица и организации в упрощенной форме. \en Set person's and organization's simplified data. \~ - \param[in] person - \ru Фамилия автора. \en Author's second name. \~ - \param[in] organization - \ru Название организации. \en Label of the organization. \~ - */ - void SetPersonOrganizationInfo( const std::string& person, const std::string& organization ); - - /// \ru Добавить роль автора. \en Add person's role. - inline void AddRole( const c3d::string_t& role ) { roles.insert( role ); } - - /// \ru Добавить роль автора. \en Add person's role. - inline void AddToRoles( const std::string& role ) { roles.insert( c3d::ToC3Dstring( role ) ); } - - /// \ru Получить роли автора. \en Get person's roles. - template< typename T > void GetRoles( T dest ) const { std::copy( roles.begin(), roles.end(), dest ); } - - /// \ru Добавить роли к приёмнику. \en Add person's roles to destination. - template< typename T > void AddRolesTo( T dest ) const; - -private: - MbPersonOrganizationInfo & operator = ( const MbPersonOrganizationInfo & ); // forbidden - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPersonOrganizationInfo ) // Атрибуты писать ни к чему, они создаются только для конвертирования -}; - -IMPL_PERSISTENT_OPS( MbPersonOrganizationInfo ) - -//------------------------------------------------------------------------------ -/** \brief \ru Данные об изделии. \en Product data. -*/ -// --- -class MATH_CLASS MbProductInfo : public MbProductAttribute -{ - c3d::string_t id; ///< \ru Идентификатор. \en Identifier. - c3d::string_t name; ///< \ru Название. \en Name. - c3d::string_t description; ///< \ru Описание. \en Description. - bool isAssembly; ///< \ru Является ли сборочной единицей. \en If the product is an assembly. - -protected : - // Объявление (перегрузка) конструктора копирования без реализации, чтобы не было копирования по умолчанию. - MbProductInfo( const MbProductInfo & ); -public : - MbProductInfo( c3d::StringTCRef initId, c3d::StringTCRef initName, c3d::StringTCRef initDesc, bool isAssm ); - - MbProductInfo( const TCHAR* initId, const TCHAR* initName, TCHAR* initDesc, bool isAssm ); - - MbProductInfo( bool isAssm, const std::string & initId, const std::string & initName, const std::string & initDesc ); - // Деструктор. - virtual ~MbProductInfo(); - -public : - // Выдать подтип атрибута (временно). - virtual MbeAttributeType AttributeType() const; - // Сделать копию элемента. - virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const ; - virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. - // Инициализировать данные по присланным. - virtual bool Init( const MbAttribute & ) ; - virtual void GetProperties( MbProperties & ); // выдать свойства объекта - virtual size_t SetProperties( const MbProperties & ); // Установить свойства объекта. - - virtual MbePrompt GetPropertyName() ; - - const c3d::string_t& GetId() const; ///< \ru Получить идентификатор. \en Get id. - - const c3d::string_t& GetName() const; ///< \ru Получить наименование. \en Get name. - - const c3d::string_t& GetDescription() const; ///< \ru Получить описание. \en Get description. - - /// \ru Получить данные. \en Get data. - void GetData( c3d::string_t & oId, c3d::string_t & oName, c3d::string_t & oDesc ) const; - - /// \ru Получить данные. \en Get data. - void GetDataStd( std::string & oId, std::string & oName, std::string & oDesc ) const; - - /// \ru Задать название. \en Set the name of the product. - void SetNameC3D( const c3d::string_t& oName ); - - /// \ru Задать наименование. \en Set the designation of the product. - void SetId( const std::string& oId ); - /// \ru Задать название. \en Set the name of the product. - void SetName( const std::string& iName ); - /// \ru Задать описание. \en Set the description of the product. - void SetDescription( const std::string& oDesc ); - - /// \ru Является ли изделие сборочной единицей. \en If the product is an assembly. - bool IsAssembly() const; - -private: - MbProductInfo & operator = ( const MbProductInfo & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProductInfo ) // Атрибуты писать ни к чему, они создаются только для конвертирования -}; - -IMPL_PERSISTENT_OPS( MbProductInfo ) - -//////////////////////////////////////////////////////////////////////////////// -// -// Класс Лицо и организация. -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -// Получить данные -// --- -template< typename OutMid, typename OutPre, typename OutSuf > -void MbPersonOrganizationInfo::GetData( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, - OutMid oMid, OutPre oPre, OutSuf oSuf, - c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const { - oPersonId = personId; - oLast = lastName; - oFirst = firstName; - std::copy( middleNames.begin(), middleNames.end(), oMid ); - std::copy( prefixTitles.begin(), prefixTitles.end(), oPre ); - std::copy( suffixTitles.begin(), suffixTitles.end(), oSuf ); - oOrgId = orgId; - oOrgLabel = orgLabel; - oOrgDesc = orgDescription; -} - - -//------------------------------------------------------------------------------ -// Получить данные -// --- -template< typename OutMid, typename OutPre, typename OutSuf > -void MbPersonOrganizationInfo::GetPOData( std::string& oPersonId, std::string& oLast, std::string& oFirst, - OutMid oMid, OutPre oPre, OutSuf oSuf, - std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const { - oPersonId = c3d::ToSTDstring( personId ); - oLast = c3d::ToSTDstring( lastName ); - oFirst = c3d::ToSTDstring( firstName ); - std::list< std::string > tmp; - for( std::list::const_iterator itr = middleNames.begin(); itr != middleNames.end(); ++itr ) - tmp.push_back( c3d::ToSTDstring( *itr ) ); - std::copy( tmp.begin(), tmp.end(), oMid ); - tmp.clear(); - for( std::list::const_iterator itr = prefixTitles.begin(); itr != prefixTitles.end(); ++itr ) - tmp.push_back( c3d::ToSTDstring( *itr ) ); - std::copy( tmp.begin(), tmp.end(), oPre ); - tmp.clear(); - for( std::list::const_iterator itr = suffixTitles.begin(); itr != suffixTitles.end(); ++itr ) - tmp.push_back( c3d::ToSTDstring( *itr ) ); - std::copy( tmp.begin(), tmp.end(), oSuf ); - oOrgId = c3d::ToSTDstring( orgId ); - oOrgLabel = c3d::ToSTDstring( orgLabel ); - oOrgDesc = c3d::ToSTDstring( orgDescription ); -} - - -//------------------------------------------------------------------------------ -// Задать данные лица -// --- -template< typename InMid, typename InPre, typename InSuf > -void MbPersonOrganizationInfo::SetPerson( const c3d::string_t& oPersonId, const c3d::string_t& oLast, const c3d::string_t& oFirst, - InMid firstMid, InMid lastMid, - InPre firstPre, InPre lastPre, - InSuf firstSuf, InSuf lastSuf ) { - personId = oPersonId; - lastName = oLast; - firstName = oFirst; - middleNames.assign( firstMid, lastMid ); - prefixTitles.assign( firstPre, lastPre ); - suffixTitles.assign( firstSuf, lastSuf ); -} - - -//------------------------------------------------------------------------------ -// Задать данные лица -// --- -template< typename InMid, typename InPre, typename InSuf > -void MbPersonOrganizationInfo::SetPersonInfo( const std::string& oPersonId, const std::string& oLast, const std::string& oFirst, - InMid firstMid, InMid lastMid, - InPre firstPre, InPre lastPre, - InSuf firstSuf, InSuf lastSuf ) { - personId = c3d::ToC3Dstring( oPersonId ); - lastName = c3d::ToC3Dstring( oLast ); - firstName = c3d::ToC3Dstring( oFirst ); - std::list< c3d::string_t > tmp; - for( InMid itr = firstMid; itr != lastMid; ++itr ) - tmp.push_back( c3d::ToC3Dstring( *itr ) ); - middleNames.swap( tmp ); - tmp.clear(); - for( InPre itr = firstPre; itr != lastPre; ++itr ) - tmp.push_back( c3d::ToC3Dstring( *itr ) ); - prefixTitles.swap(tmp); - tmp.clear(); - for( InSuf itr = firstSuf; itr != lastSuf; ++itr ) - tmp.push_back( c3d::ToC3Dstring( *itr ) ); - suffixTitles.swap(tmp); -} - - -//------------------------------------------------------------------------------ -// Добавить роли к приёмнику. -// --- -template< typename T > -void MbPersonOrganizationInfo::AddRolesTo( T dest ) const { - std::list tmp; - for( std::set::const_iterator itr = roles.begin(); itr != roles.end(); ++itr ) - tmp.push_back( c3d::ToSTDstring( *itr ) ); - std::copy( tmp.begin(), tmp.end(), dest ); -} - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибуты изделий. + \en Product attributes. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifndef __ATTR_PRODUCT_H +#define __ATTR_PRODUCT_H + + +//------------------------------------------------------------------------------ +/** \brief \ru Родительский класс атрибутов изделий. + \en Base calss of product attributes. +*/ +// --- +class MATH_CLASS MbProductAttribute : public MbAttribute { +protected : + MbProductAttribute(); // \ru Конструктор. \en Constructor. +public : + // \ru Деструктор. \en Destructor. + virtual ~MbProductAttribute(); + +public : + virtual MbeAttributeType AttributeFamily() const; + // Выдать подтип атрибута (временно). + virtual MbeAttributeType AttributeType() const = 0; + // Сделать копию элемента. + virtual MbAttribute & Duplicate( MbRegDuplicate * = 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; + + virtual MbePrompt GetPropertyName() = 0; + + // Действия при изменении владельца, не связанное с другими действиями. + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // Действия при конвертации владельца. + virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // Действия при трансформировании владельца. + virtual void OnTransformOwner( const MbAttributeContainer & owner, const MbMatrix3D &, MbRegTransform * = NULL ); + // Действия при перемещении владельца. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // Действия при вращении владельца. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // Действия при копировании владельца. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + // Действия при объединении владельца. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // Действия при замене владельца. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // Действия при разделении владельца. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // Действия при удалении владельца. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + +DECLARE_PERSISTENT_CLASS( MbProductAttribute ) +OBVIOUS_PRIVATE_COPY( MbProductAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbProductAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru Сведения о лице в организации. + \en Information related to a person and the organization he/she in. +*/ +// --- +class MATH_CLASS MbPersonOrganizationInfo : public MbProductAttribute { + c3d::string_t personId; ///< \ru Идентификатор лица. \en Identifier of the person. + c3d::string_t lastName; ///< \ru Фамилия. \en Last name. + c3d::string_t firstName; ///< \ru Имя. \en First name. + std::list middleNames; ///< \ru Отчество/средние имена. \en Middle names. + std::list prefixTitles; ///< \ru Титулы предшествующие. \en Prefix titles. + std::list suffixTitles; ///< \ru Титулы завершающие. \en Suffix titles. + c3d::string_t orgId; ///< \ru Идентификатор организации. \en Identifier of the organization. + c3d::string_t orgLabel; ///< \ru Название организации. \en Label of the organization. + c3d::string_t orgDescription; ///< \ru Описание организации. \en Description of the organization. + std::set roles; ///< \ru Роли лица по отношению к изделию. \en The person's roles concerning a product. +protected : + // Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. + MbPersonOrganizationInfo( const MbPersonOrganizationInfo & ); +public : + // Конструктор без параметров для наследников. + MbPersonOrganizationInfo(); + // Деструктор. + virtual ~MbPersonOrganizationInfo(); + +public : + // Выдать подтип атрибута (временно). + virtual MbeAttributeType AttributeType() const; + // Сделать копию элемента. + virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const; + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. + // Инициализировать данные по присланным. + virtual bool Init( const MbAttribute & ) ; + virtual void GetProperties( MbProperties & ); // выдать свойства объекта + + virtual MbePrompt GetPropertyName() ; + + /** + \brief \ru Получить полное имя с префиксами и суффиксами. \en Get full name with prefixes and suffixes. \~ + */ + c3d::string_t NameOneLine() const; + + /** + \brief \ru Получить полное название организации. \en Get full name of organization. \~ + */ + c3d::string_t OrganizationOneLine() const; + + /** + \brief \ru Задать данные организации. \en Set organization's data. \~ + \param[in] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[in] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[in] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + void SetOrganization( const c3d::string_t& initOrgId, const c3d::string_t& initOrgLabel, const c3d::string_t& initOrgDesc ); + + /** + \brief \ru Получить данные организации. \en Get organization data. \~ + \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + void GetOrganizationDetails( c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const; + + + /** + \brief \ru Задать данные лица и организации в упрощенной форме. \en Set person's and organization's simplified data. \~ + \param[in] person - \ru Фамилия автора. \en Author's second name. \~ + \param[in] organization - \ru Название организации. \en Label of the organization. \~ + */ + void SetPersonOrganization( const c3d::string_t& person, const c3d::string_t& organization ); + + /// \ru Добавить роль автора. \en Add person's role. + inline void AddRole( const c3d::string_t& role ) { roles.insert( role ); } + + /// \ru Добавить роль автора. \en Add person's role. + inline void AddToRoles( const std::string& role ) { roles.insert( c3d::ToC3Dstring( role ) ); } + + /// \ru Получить роли автора. \en Get person's roles. + template< typename T > void GetRoles( T dest ) const { std::copy( roles.begin(), roles.end(), dest ); } + + /// \ru Добавить роли к приёмнику. \en Add person's roles to destination. + template< typename T > void AddRolesTo( T dest ) const; + + + /** + \brief \ru Выдать данные лица. \en Swap person's data. \~ + \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[in] oLast - \ru Фамилия. \en Last name. \~ + \param[in] oFirst - \ru Имя. \en First name. \~ + \param[in] oMiddles - \ru Список отчеств/средних имен. \en List of middle names. \~ + \param[in] oPrefixes - \ru Список титулов предшествующих. \en List of prefix titles. \~ + \param[in] oSuffixed - \ru Список титулов завершающих. \en List of suffix titles. \~ + */ + void GetPersonDetails( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, + std::list& oMiddles, + std::list& oPrefixes, + std::list& oSuffixed ) const; + + /** + \brief \ru Обменять данные лица. \en Swap person's data. \~ + \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[in] oLast - \ru Фамилия. \en Last name. \~ + \param[in] oFirst - \ru Имя. \en First name. \~ + \param[in] oMiddles - \ru Список отчеств/средних имен. \en List of middle names. \~ + \param[in] oPrefixes - \ru Список титулов предшествующих. \en List of prefix titles. \~ + \param[in] oSuffixed - \ru Список титулов завершающих. \en List of suffix titles. \~ + */ + void SwapPersonDetails( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, + std::list& oMiddles, + std::list& oPrefixes, + std::list& oSuffixed ); + + + /** + \brief \ru Задать данные лица. \en Set person's data. \~ + \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[in] oLast - \ru Фамилия. \en Last name. \~ + \param[in] oFirst - \ru Имя. \en First name. \~ + \param[in] firstMid - \ru Итератор первой строки, соответствующей отчеству/средним именам. \en First iterator for middle names. \~ + \param[in] lastMid - \ru Итератор за последней строкой, соответствующей отчеству/средним именам. \en Next after last iterator for middle names. \~ + \param[in] firstPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en First iterator for prefix titles. \~ + \param[in] lastPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en Next after last iterator for prefix titles. \~ + \param[in] firstSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en First iterator for suffix titles. \~ + \param[in] lastSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en Next after last iterator for suffix titles. \~ + */ + template< typename InMid, typename InPre, typename InSuf > + DEPRECATE_DECLARE void SetPerson( const c3d::string_t& oPersonId, const c3d::string_t& oLast, const c3d::string_t& oFirst, + InMid firstMid, InMid lastMid, + InPre firstPre, InPre lastPre, + InSuf firstSuf, InSuf lastSuf ); + + /** + \brief \ru Получить данные. \en Get data. \~ + \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[out] oLast - \ru Фамилия. \en Last name. \~ + \param[out] oFirst - \ru Имя. \en First name. \~ + \param[out] oMid - \ru Итератор для вставки всех строк, соответствующих отчеству/средним именам. \en Insert iterator for middle names. \~ + \param[out] oPre - \ru Итератор для вставки всех строк, соответствующих титулов предшествующих. \en Insert iterator for prefix titles. \~ + \param[out] oSuf - \ru Итератор для вставки всех строк, соответствующих титулов завершающих. \en Insert iterator for suffix titles. \~ + \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + template< typename OutMid, typename OutPre, typename OutSuf > + DEPRECATE_DECLARE void GetData( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, + OutMid oMid, OutPre oPre, OutSuf oSuf, + c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const; + + /** + \brief \ru Задать данные лица. \en Set person's data. \~ + \param[in] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[in] oLast - \ru Фамилия. \en Last name. \~ + \param[in] oFirst - \ru Имя. \en First name. \~ + \param[in] firstMid - \ru Итератор первой строки, соответствующей отчеству/средним именам. \en First iterator for middle names. \~ + \param[in] lastMid - \ru Итератор за последней строкой, соответствующей отчеству/средним именам. \en Next after last iterator for middle names. \~ + \param[in] firstPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en First iterator for prefix titles. \~ + \param[in] lastPre - \ru Итератор первой строки, соответствующей титулам предшествующих. \en Next after last iterator for prefix titles. \~ + \param[in] firstSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en First iterator for suffix titles. \~ + \param[in] lastSuf - \ru Итератор первой строки, соответствующей титулам завершающих. \en Next after last iterator for suffix titles. \~ + */ + template< typename InMid, typename InPre, typename InSuf > + DEPRECATE_DECLARE void SetPersonInfo( const std::string& oPersonId, const std::string& oLast, const std::string& oFirst, + InMid firstMid, InMid lastMid, + InPre firstPre, InPre lastPre, + InSuf firstSuf, InSuf lastSuf ); + + + /** + \brief \ru Получить данные. \en Get data. \~ + \param[out] oPersonId - \ru Идентификатор лица. \en Identifier of the person. \~ + \param[out] oLast - \ru Фамилия. \en Last name. \~ + \param[out] oFirst - \ru Имя. \en First name. \~ + \param[out] oMid - \ru Итератор для вставки всех строк, соответствующих отчеству/средним именам. \en Insert iterator for middle names. \~ + \param[out] oPre - \ru Итератор для вставки всех строк, соответствующих титулов предшествующих. \en Insert iterator for prefix titles. \~ + \param[out] oSuf - \ru Итератор для вставки всех строк, соответствующих титулов завершающих. \en Insert iterator for suffix titles. \~ + \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + template< typename OutMid, typename OutPre, typename OutSuf > + DEPRECATE_DECLARE void GetPOData( std::string& oPersonId, std::string& oLast, std::string& oFirst, + OutMid oMid, OutPre oPre, OutSuf oSuf, + std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const; + + + /** + \brief \ru Получить данные организации. \en Get organization data. \~ + \param[out] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[out] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[out] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + DEPRECATE_DECLARE void GetOrganizationInfo( std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const; + + + /** + \brief \ru Задать данные организации. \en Set organization's data. \~ + \param[in] oOrgId - \ru Идентификатор организации. \en Identifier of the organization. \~ + \param[in] oOrgLabel - \ru Название организации. \en Label of the organization. \~ + \param[in] oOrgDesc - \ru Описание организации. \en Description of the organization. \~ + */ + DEPRECATE_DECLARE void SetOrganizationInfo( const std::string& initOrgId, const std::string& initOrgLabel, const std::string& initOrgDesc ); + + + /** + \brief \ru Задать данные лица и организации в упрощенной форме. \en Set person's and organization's simplified data. \~ + \param[in] person - \ru Фамилия автора. \en Author's second name. \~ + \param[in] organization - \ru Название организации. \en Label of the organization. \~ + */ + DEPRECATE_DECLARE void SetPersonOrganizationInfo( const std::string& person, const std::string& organization ); + + +private: + MbPersonOrganizationInfo & operator = ( const MbPersonOrganizationInfo & ); // forbidden + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPersonOrganizationInfo ) // Атрибуты писать ни к чему, они создаются только для конвертирования +}; + +IMPL_PERSISTENT_OPS( MbPersonOrganizationInfo ) + +//------------------------------------------------------------------------------ +/** \brief \ru Данные об изделии. \en Product data. +*/ +// --- +class MATH_CLASS MbProductInfo : public MbProductAttribute +{ + c3d::string_t id; ///< \ru Идентификатор. \en Identifier. + c3d::string_t name; ///< \ru Название. \en Name. + c3d::string_t description; ///< \ru Описание. \en Description. + bool isAssembly; ///< \ru Является ли сборочной единицей. \en If the product is an assembly. + +protected : + // Объявление (перегрузка) конструктора копирования без реализации, чтобы не было копирования по умолчанию. + MbProductInfo( const MbProductInfo & ); +public : + MbProductInfo( c3d::StringTCRef initId, c3d::StringTCRef initName, c3d::StringTCRef initDesc, bool isAssm ); + + MbProductInfo( const TCHAR* initId, const TCHAR* initName, TCHAR* initDesc, bool isAssm ); + + MbProductInfo( bool isAssm, const std::string & initId, const std::string & initName, const std::string & initDesc ); + // Деструктор. + virtual ~MbProductInfo(); + +public : + // Выдать подтип атрибута (временно). + virtual MbeAttributeType AttributeType() const; + // Сделать копию элемента. + virtual MbAttribute & Duplicate( MbRegDuplicate * = NULL ) const ; + virtual bool IsSame( const MbAttribute &, double accuracy ) const; // Определить, являются ли объекты равными. + // Инициализировать данные по присланным. + virtual bool Init( const MbAttribute & ) ; + virtual void GetProperties( MbProperties & ); // выдать свойства объекта + virtual size_t SetProperties( const MbProperties & ); // Установить свойства объекта. + + virtual MbePrompt GetPropertyName() ; + + const c3d::string_t& GetId() const; ///< \ru Получить идентификатор. \en Get id. + + const c3d::string_t& GetName() const; ///< \ru Получить наименование. \en Get name. + + const c3d::string_t& GetDescription() const; ///< \ru Получить описание. \en Get description. + + /// \ru Получить данные. \en Get data. + void GetData( c3d::string_t & oId, c3d::string_t & oName, c3d::string_t & oDesc ) const; + + /// \ru Получить данные. \en Get data. + void GetDataStd( std::string & oId, std::string & oName, std::string & oDesc ) const; + + /// \ru Задать название. \en Set the name of the product. + void SetNameC3D( const c3d::string_t& oName ); + + /// \ru Задать наименование. \en Set the designation of the product. + void SetId( const std::string& oId ); + /// \ru Задать название. \en Set the name of the product. + void SetName( const std::string& iName ); + /// \ru Задать описание. \en Set the description of the product. + void SetDescription( const std::string& oDesc ); + + /// \ru Является ли изделие сборочной единицей. \en If the product is an assembly. + bool IsAssembly() const; + +private: + MbProductInfo & operator = ( const MbProductInfo & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProductInfo ) // Атрибуты писать ни к чему, они создаются только для конвертирования +}; + +IMPL_PERSISTENT_OPS( MbProductInfo ) + +//////////////////////////////////////////////////////////////////////////////// +// +// Класс Лицо и организация. +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +// Получить данные +// --- +template< typename OutMid, typename OutPre, typename OutSuf > +void MbPersonOrganizationInfo::GetData( c3d::string_t& oPersonId, c3d::string_t& oLast, c3d::string_t& oFirst, + OutMid oMid, OutPre oPre, OutSuf oSuf, + c3d::string_t& oOrgId, c3d::string_t& oOrgLabel, c3d::string_t& oOrgDesc ) const { + oPersonId = personId; + oLast = lastName; + oFirst = firstName; + std::copy( middleNames.begin(), middleNames.end(), oMid ); + std::copy( prefixTitles.begin(), prefixTitles.end(), oPre ); + std::copy( suffixTitles.begin(), suffixTitles.end(), oSuf ); + oOrgId = orgId; + oOrgLabel = orgLabel; + oOrgDesc = orgDescription; +} + + +//------------------------------------------------------------------------------ +// Получить данные +// --- +template< typename OutMid, typename OutPre, typename OutSuf > +void MbPersonOrganizationInfo::GetPOData( std::string& oPersonId, std::string& oLast, std::string& oFirst, + OutMid oMid, OutPre oPre, OutSuf oSuf, + std::string& oOrgId, std::string& oOrgLabel, std::string& oOrgDesc ) const { + oPersonId = c3d::ToSTDstring( personId ); + oLast = c3d::ToSTDstring( lastName ); + oFirst = c3d::ToSTDstring( firstName ); + std::list< std::string > tmp; + for( std::list::const_iterator itr = middleNames.begin(); itr != middleNames.end(); ++itr ) + tmp.push_back( c3d::ToSTDstring( *itr ) ); + std::copy( tmp.begin(), tmp.end(), oMid ); + tmp.clear(); + for( std::list::const_iterator itr = prefixTitles.begin(); itr != prefixTitles.end(); ++itr ) + tmp.push_back( c3d::ToSTDstring( *itr ) ); + std::copy( tmp.begin(), tmp.end(), oPre ); + tmp.clear(); + for( std::list::const_iterator itr = suffixTitles.begin(); itr != suffixTitles.end(); ++itr ) + tmp.push_back( c3d::ToSTDstring( *itr ) ); + std::copy( tmp.begin(), tmp.end(), oSuf ); + oOrgId = c3d::ToSTDstring( orgId ); + oOrgLabel = c3d::ToSTDstring( orgLabel ); + oOrgDesc = c3d::ToSTDstring( orgDescription ); +} + + +//------------------------------------------------------------------------------ +// Задать данные лица +// --- +template< typename InMid, typename InPre, typename InSuf > +void MbPersonOrganizationInfo::SetPerson( const c3d::string_t& oPersonId, const c3d::string_t& oLast, const c3d::string_t& oFirst, + InMid firstMid, InMid lastMid, + InPre firstPre, InPre lastPre, + InSuf firstSuf, InSuf lastSuf ) { + personId = oPersonId; + lastName = oLast; + firstName = oFirst; + middleNames.assign( firstMid, lastMid ); + prefixTitles.assign( firstPre, lastPre ); + suffixTitles.assign( firstSuf, lastSuf ); +} + + +//------------------------------------------------------------------------------ +// Задать данные лица +// --- +template< typename InMid, typename InPre, typename InSuf > +void MbPersonOrganizationInfo::SetPersonInfo( const std::string& oPersonId, const std::string& oLast, const std::string& oFirst, + InMid firstMid, InMid lastMid, + InPre firstPre, InPre lastPre, + InSuf firstSuf, InSuf lastSuf ) { + personId = c3d::ToC3Dstring( oPersonId ); + lastName = c3d::ToC3Dstring( oLast ); + firstName = c3d::ToC3Dstring( oFirst ); + std::list< c3d::string_t > tmp; + for( InMid itr = firstMid; itr != lastMid; ++itr ) + tmp.push_back( c3d::ToC3Dstring( *itr ) ); + middleNames.swap( tmp ); + tmp.clear(); + for( InPre itr = firstPre; itr != lastPre; ++itr ) + tmp.push_back( c3d::ToC3Dstring( *itr ) ); + prefixTitles.swap(tmp); + tmp.clear(); + for( InSuf itr = firstSuf; itr != lastSuf; ++itr ) + tmp.push_back( c3d::ToC3Dstring( *itr ) ); + suffixTitles.swap(tmp); +} + + +//------------------------------------------------------------------------------ +// Добавить роли к приёмнику. +// --- +template< typename T > +void MbPersonOrganizationInfo::AddRolesTo( T dest ) const { + std::list tmp; + for( std::set::const_iterator itr = roles.begin(); itr != roles.end(); ++itr ) + tmp.push_back( c3d::ToSTDstring( *itr ) ); + std::copy( tmp.begin(), tmp.end(), dest ); +} + + #endif // __ATTR_PRODUCT_H \ No newline at end of file diff --git a/C3d/Include/attr_registry.h b/C3d/Include/attr_registry.h index c593e39..b704e3c 100644 --- a/C3d/Include/attr_registry.h +++ b/C3d/Include/attr_registry.h @@ -1,91 +1,91 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Инстанс определения атрибута. - \en Attribute definition instance. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_REGISTRY_H -#define __ATTR_REGISTRY_H - - -#include -#include -#include -#include - - -class IAttrDefinition; - - -//------------------------------------------------------------------------------ -/** \brief \ru Идентификатор пользовательского атрибута. - \en Identifier of external attribute. \~ - \details \ru Идентификатор пользовательского атрибута. - \en Identifier of external attribute. \~ - \ingroup Model_Attributes - */ -// KVT class MbUserAttribType -// KVT { -// KVT public: -// KVT uint subtype1; -// KVT uint subtype2; -// KVT uint subtype3; -// KVT -// KVT public: -// KVT MbUserAttribType() -// KVT : subtype1( 0 ), subtype2( 0 ), subtype3( 0 ) {} -// KVT MbUserAttribType( uint type1, uint type2, uint type3 ) -// KVT : subtype1( type1 ), subtype2( type2 ), subtype3( type3 ) {} -// KVT MbUserAttribType( const MbUserAttribType & other ) -// KVT : subtype1( other.subtype1 ), subtype2( other.subtype2 ), subtype3( other.subtype3 ) {} -// KVT -// KVT bool operator == ( const MbUserAttribType & other ) const -// KVT { return subtype1 == other.subtype1 && subtype2 == other.subtype2 && subtype3 == other.subtype3; } -// KVT bool operator < ( const MbUserAttribType & other ) const -// KVT { -// KVT if (subtype1 != other.subtype1) -// KVT return subtype1 < other.subtype1; -// KVT else if (subtype2 != other.subtype2) -// KVT return subtype2 < other.subtype2; -// KVT else if (subtype3 != other.subtype3) -// KVT return subtype3 < other.subtype3; -// KVT -// KVT return false; -// KVT } -// KVT -// KVT private: -// KVT void operator = ( const MbUserAttribType & ); // \ru Не реализовано \en Not implemented -// KVT }; - -typedef MbUuid MbUserAttribType; - -//------------------------------------------------------------------------------ -/** \brief \ru Инстанс определения атрибута. - \en Attribute definition instance. \~ - \ingroup Model_Attributes - */ -class MATH_CLASS AttrDefInstance -{ -private: - MbUserAttribType id_; -public: - AttrDefInstance( const MbUserAttribType & id ); - virtual ~AttrDefInstance(); - -public: - virtual IAttrDefinition * GetAttrDefinition() = 0; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти определение пользовательского атрибута. - \en Find an external attribute definition. \~ - \ingroup Model_Attributes -*/ -MATH_FUNC (IAttrDefinition *) GetUserAttrDefinition( const MbUserAttribType & id ); - - -#endif // __ATTR_REGISTRY_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Инстанс определения атрибута. + \en Attribute definition instance. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_REGISTRY_H +#define __ATTR_REGISTRY_H + + +#include +#include +#include +#include + + +class IAttrDefinition; + + +//------------------------------------------------------------------------------ +/** \brief \ru Идентификатор пользовательского атрибута. + \en Identifier of external attribute. \~ + \details \ru Идентификатор пользовательского атрибута. + \en Identifier of external attribute. \~ + \ingroup Model_Attributes + */ +// KVT class MbUserAttribType +// KVT { +// KVT public: +// KVT uint subtype1; +// KVT uint subtype2; +// KVT uint subtype3; +// KVT +// KVT public: +// KVT MbUserAttribType() +// KVT : subtype1( 0 ), subtype2( 0 ), subtype3( 0 ) {} +// KVT MbUserAttribType( uint type1, uint type2, uint type3 ) +// KVT : subtype1( type1 ), subtype2( type2 ), subtype3( type3 ) {} +// KVT MbUserAttribType( const MbUserAttribType & other ) +// KVT : subtype1( other.subtype1 ), subtype2( other.subtype2 ), subtype3( other.subtype3 ) {} +// KVT +// KVT bool operator == ( const MbUserAttribType & other ) const +// KVT { return subtype1 == other.subtype1 && subtype2 == other.subtype2 && subtype3 == other.subtype3; } +// KVT bool operator < ( const MbUserAttribType & other ) const +// KVT { +// KVT if (subtype1 != other.subtype1) +// KVT return subtype1 < other.subtype1; +// KVT else if (subtype2 != other.subtype2) +// KVT return subtype2 < other.subtype2; +// KVT else if (subtype3 != other.subtype3) +// KVT return subtype3 < other.subtype3; +// KVT +// KVT return false; +// KVT } +// KVT +// KVT private: +// KVT void operator = ( const MbUserAttribType & ); // \ru Не реализовано \en Not implemented +// KVT }; + +typedef MbUuid MbUserAttribType; + +//------------------------------------------------------------------------------ +/** \brief \ru Инстанс определения атрибута. + \en Attribute definition instance. \~ + \ingroup Model_Attributes + */ +class MATH_CLASS AttrDefInstance +{ +private: + MbUserAttribType id_; +public: + AttrDefInstance( const MbUserAttribType & id ); + virtual ~AttrDefInstance(); + +public: + virtual IAttrDefinition * GetAttrDefinition() = 0; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти определение пользовательского атрибута. + \en Find an external attribute definition. \~ + \ingroup Model_Attributes +*/ +MATH_FUNC (IAttrDefinition *) GetUserAttrDefinition( const MbUserAttribType & id ); + + +#endif // __ATTR_REGISTRY_H diff --git a/C3d/Include/attr_selected.h b/C3d/Include/attr_selected.h index 2ae80b1..da48371 100644 --- a/C3d/Include/attr_selected.h +++ b/C3d/Include/attr_selected.h @@ -1,154 +1,154 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибуты. Селектированность. Видимость. Изменённость. - \en Attributes. Selection. Visibility. Modification. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_SELECTED_H -#define __ATTR_SELECTED_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Селектированность. - \en Selection. \~ - \details \ru Селектированность. \n - \en Selection. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbSelected : public MbElementaryAttribute { -protected : - bool selected; ///< \ru Селектированность. \en Selection. - -protected : - /// \ru Конструктор копирования. \en Copy-constructor. - MbSelected( const MbSelected & init ); -public : - /// \ru Конструктор. \en Constructor. - MbSelected( bool init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbSelected(); - - // \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 by given attribute. - - /// \ru Установить селектированность. \en Set selection. - void Init( bool init ) { selected = init; } - /// \ru Дать селектированность. \en Get selection. - bool Selected() const { return selected; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbSelected & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSelected ) - -}; // MbSelected - -IMPL_PERSISTENT_OPS( MbSelected ) - -//------------------------------------------------------------------------------ -/** \brief \ru Видимость. - \en Visibility. \~ - \details \ru Видимость. \n - \en Visibility. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbVisible : public MbElementaryAttribute { -protected : - bool visible; ///< \ru Видимость. \en Visibility. - -protected : - /// \ru Конструктор копирования. \en Copy-constructor. - MbVisible( const MbVisible & init ); -public : - /// \ru Конструктор. \en Constructor. - MbVisible( bool init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbVisible(); - - // \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 by given attribute. - - /// \ru Установить видимость. \en Set visibility. - void Init( bool init ) { visible = init; } - /// \ru Дать видимость. \en Get visibility. - bool Visible() const { return visible; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbVisible & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVisible ) - -}; // MbVisible - -IMPL_PERSISTENT_OPS( MbVisible ) - -//------------------------------------------------------------------------------ -/** \brief \ru Изменённость. - \en Modification. \~ - \details \ru Изменённость. \n - \en Modification. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbChanged : public MbElementaryAttribute { -protected : - bool changed; ///< \ru Изменённость. \en Modification. - -protected : - /// \ru Конструктор копирования. \en Copy-constructor. - MbChanged( const MbChanged & init ); -public : - /// \ru Конструктор. \en Constructor. - MbChanged( bool init ); - /// \ru Деструктор. \en Destructor. - virtual ~MbChanged(); - - // \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 by given attribute. - - /// \ru Установить изменённость. \en Set modification. - void Init( bool init ) { changed = init; } - /// \ru Дать изменённость. \en Get modification. - bool Changed() const { return changed; } - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -private: - void operator = ( const MbChanged & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChanged ) - -}; // MbChanged - -IMPL_PERSISTENT_OPS( MbChanged ) - -#endif // __ATTR_SELECTED_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибуты. Селектированность. Видимость. Изменённость. + \en Attributes. Selection. Visibility. Modification. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_SELECTED_H +#define __ATTR_SELECTED_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Селектированность. + \en Selection. \~ + \details \ru Селектированность. \n + \en Selection. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbSelected : public MbElementaryAttribute { +protected : + bool selected; ///< \ru Селектированность. \en Selection. + +protected : + /// \ru Конструктор копирования. \en Copy-constructor. + MbSelected( const MbSelected & init ); +public : + /// \ru Конструктор. \en Constructor. + MbSelected( bool init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbSelected(); + + // \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 by given attribute. + + /// \ru Установить селектированность. \en Set selection. + void Init( bool init ) { selected = init; } + /// \ru Дать селектированность. \en Get selection. + bool Selected() const { return selected; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbSelected & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSelected ) + +}; // MbSelected + +IMPL_PERSISTENT_OPS( MbSelected ) + +//------------------------------------------------------------------------------ +/** \brief \ru Видимость. + \en Visibility. \~ + \details \ru Видимость. \n + \en Visibility. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbVisible : public MbElementaryAttribute { +protected : + bool visible; ///< \ru Видимость. \en Visibility. + +protected : + /// \ru Конструктор копирования. \en Copy-constructor. + MbVisible( const MbVisible & init ); +public : + /// \ru Конструктор. \en Constructor. + MbVisible( bool init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbVisible(); + + // \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 by given attribute. + + /// \ru Установить видимость. \en Set visibility. + void Init( bool init ) { visible = init; } + /// \ru Дать видимость. \en Get visibility. + bool Visible() const { return visible; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbVisible & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVisible ) + +}; // MbVisible + +IMPL_PERSISTENT_OPS( MbVisible ) + +//------------------------------------------------------------------------------ +/** \brief \ru Изменённость. + \en Modification. \~ + \details \ru Изменённость. \n + \en Modification. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbChanged : public MbElementaryAttribute { +protected : + bool changed; ///< \ru Изменённость. \en Modification. + +protected : + /// \ru Конструктор копирования. \en Copy-constructor. + MbChanged( const MbChanged & init ); +public : + /// \ru Конструктор. \en Constructor. + MbChanged( bool init ); + /// \ru Деструктор. \en Destructor. + virtual ~MbChanged(); + + // \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 by given attribute. + + /// \ru Установить изменённость. \en Set modification. + void Init( bool init ) { changed = init; } + /// \ru Дать изменённость. \en Get modification. + bool Changed() const { return changed; } + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +private: + void operator = ( const MbChanged & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChanged ) + +}; // MbChanged + +IMPL_PERSISTENT_OPS( MbChanged ) + +#endif // __ATTR_SELECTED_H diff --git a/C3d/Include/attr_stamprib_attribut.h b/C3d/Include/attr_stamprib_attribute.h similarity index 94% rename from C3d/Include/attr_stamprib_attribut.h rename to C3d/Include/attr_stamprib_attribute.h index 16752b1..2798adc 100644 --- a/C3d/Include/attr_stamprib_attribut.h +++ b/C3d/Include/attr_stamprib_attribute.h @@ -1,93 +1,93 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибут ребра жесткости листового тела. - \en Attribute of reinforsed rib of sheet solid. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_STAMPRIB_ATTRIBUTE_H -#define __ATTR_STAMPRIB_ATTRIBUTE_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Атрибут ребра жесткости листового тела. - \en Attribute of reinforsed rib of sheet solid. \~ - \details \ru Атрибут ребра жесткости листового тела. Двумерный контур ребра - жесткости и локальная система координат, в плоскости XY которой - расположен двумерный контур содержатся в MbGeomAttribute. - \en Attribute of reinforsed rib of sheet solid. Two-dimensional contour - of a rib and a local coordinate system the two-dimensional contour - is located in XY plane of are stored in MbGeomAttribute \n \~ - \ingroup Model_Attributes - */ -class MATH_CLASS MbStampRibAttribute : public MbGeomAttribute -{ -protected : - size_t index; ///< \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. \en Index of a segment in the contour at which the inclination direction will be set. - SheetRibValues pars; ///< \ru Параметры операции. \en The operation parameters. - MbSNameMaker names; ///< \ru Именователь операции. \en An object defining names generation in the operation. - MbVector3D bendNorm; ///< \ru Нормаль поверхности сгиба (только для внутреннего использования). \en A normal to bend surface (for internal usage only). - MbCartPoint3D bendPoint; ///< \ru Точка на оси сгиба сгиба (только для внутреннего использования). \en A point on bend axis (for internal usage only). -private: - // \ru Конструктор копирования. \en Copy constructor. - MbStampRibAttribute( const MbStampRibAttribute & init, MbRegDuplicate * iReg ); -public : - /// \ru Конструктор. \en Constructor. - MbStampRibAttribute( const MbSpaceItem & item, MbeCreatorType t, size_t index, const SheetRibValues & pars, const MbSNameMaker & n, bool keepItem); - /// \ru Конструктор. \en Constructor. - MbStampRibAttribute( const MbSpaceItem & item, MbeCreatorType t, size_t index, const SheetRibValues & pars, const MbSNameMaker & n, bool keepItem, const c3d::string_t & itemPrompt ); - /// \ru Деструктор. \en Destructor. - virtual ~MbStampRibAttribute(); - -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; - // \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 & matr, MbRegTransform * iReg ); - // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D & to, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * iReg ); - // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. - virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - - virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. - 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. - /// \ru Дать индекс сегмента в контуре. \en Get index of a segment in the contour. - const size_t & GetIndex() const { return index; } - /// \ru Дать параметры операции. \en Get operation parameters. - const SheetRibValues & GetRibValues() const { return pars; } - /// \ru Дать именователь операции. \en Get an object defining a name of the operation. - const MbSNameMaker & GetNameMaker() const { return names; } - /// \ru Дать нормаль к поверхности сгиба. \en Get normal to bend surface. - const MbVector3D & GetBendNormal() const { return bendNorm; } - /// \ru Установить нормаль к поверхности сгиба. \en Set normal to bend surface. - void SetBendNormal( const MbVector3D & n ) { bendNorm = n; } - /// \ru Дать точку на оси сгиба. \en Get point on bend axis. - const MbCartPoint3D & GetBendPoint() const { return bendPoint; } - /// \ru Установить точку на оси сгиба. \en Set point on bend axis. - void SetBendPoint( const MbCartPoint3D & p ) { bendPoint = p; } -DECLARE_PERSISTENT_CLASS( MbStampRibAttribute ) -OBVIOUS_PRIVATE_COPY( MbStampRibAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbStampRibAttribute ) - -#endif // __ATTR_STAMPRIB_ATTRIBUTE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибут ребра жесткости листового тела. + \en Attribute of reinforsed rib of sheet solid. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_STAMPRIB_ATTRIBUTE_H +#define __ATTR_STAMPRIB_ATTRIBUTE_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Атрибут ребра жесткости листового тела. + \en Attribute of reinforsed rib of sheet solid. \~ + \details \ru Атрибут ребра жесткости листового тела. Двумерный контур ребра + жесткости и локальная система координат, в плоскости XY которой + расположен двумерный контур содержатся в MbGeomAttribute. + \en Attribute of reinforsed rib of sheet solid. Two-dimensional contour + of a rib and a local coordinate system the two-dimensional contour + is located in XY plane of are stored in MbGeomAttribute \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbStampRibAttribute : public MbGeomAttribute +{ +protected : + size_t index; ///< \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. \en Index of a segment in the contour at which the inclination direction will be set. + SheetRibValues pars; ///< \ru Параметры операции. \en The operation parameters. + MbSNameMaker names; ///< \ru Именователь операции. \en An object defining names generation in the operation. + MbVector3D bendNorm; ///< \ru Нормаль поверхности сгиба (только для внутреннего использования). \en A normal to bend surface (for internal usage only). + MbCartPoint3D bendPoint; ///< \ru Точка на оси сгиба сгиба (только для внутреннего использования). \en A point on bend axis (for internal usage only). +private: + // \ru Конструктор копирования. \en Copy constructor. + MbStampRibAttribute( const MbStampRibAttribute & init, MbRegDuplicate * iReg ); +public : + /// \ru Конструктор. \en Constructor. + MbStampRibAttribute( const MbSpaceItem & item, MbeCreatorType t, size_t index, const SheetRibValues & pars, const MbSNameMaker & n, bool keepItem); + /// \ru Конструктор. \en Constructor. + MbStampRibAttribute( const MbSpaceItem & item, MbeCreatorType t, size_t index, const SheetRibValues & pars, const MbSNameMaker & n, bool keepItem, const c3d::string_t & itemPrompt ); + /// \ru Деструктор. \en Destructor. + virtual ~MbStampRibAttribute(); + +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; + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = NULL ); + // \ru Выполнить действия при объединении владельца. \en Perform actions when merging the owner. + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + + virtual void GetCharValue( TCHAR * v ) const; // \ru Выдать строковое значение свойства. \en Get a string value of the property. + 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. + /// \ru Дать индекс сегмента в контуре. \en Get index of a segment in the contour. + const size_t & GetIndex() const { return index; } + /// \ru Дать параметры операции. \en Get operation parameters. + const SheetRibValues & GetRibValues() const { return pars; } + /// \ru Дать именователь операции. \en Get an object defining a name of the operation. + const MbSNameMaker & GetNameMaker() const { return names; } + /// \ru Дать нормаль к поверхности сгиба. \en Get normal to bend surface. + const MbVector3D & GetBendNormal() const { return bendNorm; } + /// \ru Установить нормаль к поверхности сгиба. \en Set normal to bend surface. + void SetBendNormal( const MbVector3D & n ) { bendNorm = n; } + /// \ru Дать точку на оси сгиба. \en Get point on bend axis. + const MbCartPoint3D & GetBendPoint() const { return bendPoint; } + /// \ru Установить точку на оси сгиба. \en Set point on bend axis. + void SetBendPoint( const MbCartPoint3D & p ) { bendPoint = p; } +DECLARE_PERSISTENT_CLASS( MbStampRibAttribute ) +OBVIOUS_PRIVATE_COPY( MbStampRibAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbStampRibAttribute ) + +#endif // __ATTR_STAMPRIB_ATTRIBUTE_H diff --git a/C3d/Include/attr_user_attribut.h b/C3d/Include/attr_user_attribute.h similarity index 87% rename from C3d/Include/attr_user_attribut.h rename to C3d/Include/attr_user_attribute.h index 8e24113..e986818 100644 --- a/C3d/Include/attr_user_attribut.h +++ b/C3d/Include/attr_user_attribute.h @@ -1,426 +1,412 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Пользовательские атрибуты. - \en User attributes. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTR_USER_ATTRIBUT_H -#define __ATTR_USER_ATTRIBUT_H - - -#include -#include -#include -#include -#include -#include -#include - -class MATH_CLASS MbExternalAttribute; -class MATH_CLASS MbUserAttribute; -class MATH_CLASS MbFixAttrSet; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс определения атрибута. - \en Attribute definition interface. \~ - \details \ru Интерфейс определения атрибута. Определение атрибута - объект используемый - для преобразования пользовательских внесистемных атрибутов в пользовательские системные, - а так же для разборки пользовательских системных атрибутов - на составные части - другие атрибуты системные атрибуты, и обратной сборки. - \en Attribute definition interface. Attribute definition - the object used - for converting user external attributes to user system attributes - and for a disassembly of user system attributes - to their components - other system attributes, and for reassembly. \~ - \ingroup Model_Attributes - */ -class IAttrDefinition -{ -public: - /// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. - virtual MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & source ) = 0; - - /// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. - virtual MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & source ) = 0; - - /// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. - virtual MbFixAttrSet * DisassembleUsetAttrib( const MbExternalAttribute & source ) = 0; - - /// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. - virtual bool ReassembleUsetAttrib ( const MbFixAttrSet & source, MbExternalAttribute & targer ) = 0; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Шаблон "определения" пользовательского атрибута. - \en A template of user attribute definition. \~ - \details \ru Шаблонный класс "Определения" пользовательского атрибута - используется для создания - стандартных определений, с предопределенным функционалом. - \en Template class "Definition" of user attribute - used for creation - of standard definitions with predefined functionality. \~ - \ingroup Model_Attributes - */ -template -class UserAttrDefinition : public IAttrDefinition -{ -public: - /// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. - virtual MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & source ); - - /// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. - virtual MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & source ); - - /// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. - virtual MbFixAttrSet * DisassembleUsetAttrib( const MbExternalAttribute & source ); - - /// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. - virtual bool ReassembleUsetAttrib( const MbFixAttrSet & source, MbExternalAttribute & targer ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Пользовательский системный атрибут. - \en User system attribute. \~ - \details \ru Пользовательский системный атрибут. \n - \en User system attribute. \n \~ - \ingroup Model_Attributes - */ -class MATH_CLASS MbUserAttribute : public MbAttribute, public MbSyncItem { - typedef std_unique_ptr UniqueMembufPtr; -protected : - MbUserAttribType userType_; ///< \ru Тип пользовательского атрибута. \en Type of user attribute. - c3d::string_t prompt_; ///< \ru Строка описания. \en String of description. -private: - SPtr extAttr; - mutable UniqueMembufPtr userBuf; - -private: // public: // You must inherit from MbExternalAttribute only!!! - /// \ru Конструктор. \en Constructor. - MbUserAttribute( const TCHAR * prompt, const MbUserAttribType & id ); - -public: - virtual MbeAttributeType AttributeFamily() const; // \ru Дать тип атрибута. \en Get type of an attribute. - virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. - - /// \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 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. - - // \ru Выполнить действия при изменении владельца не связанное с другими действиями \en Perform actions which are not associated with other actions when changing the owner - virtual void OnChangeOwner( const MbAttributeContainer & owner ); - - // \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 & matr, MbRegTransform * iReg ); - - // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D & to, MbRegTransform * iReg = NULL ); - - // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - - // \ru Выполнить действия при копировании владельца \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * iReg ); - - // \ru Выполнить действия при объединении владельца \en Perform actions when merging the owner. - virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - - // \ru Выполнить действия при замене владельца. \en Perform actions when replacing the owner. - virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - - // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. - virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); - - // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. - virtual void OnDeleteOwner( const MbAttributeContainer & owner ); - - /// \ru Выдать подсказку. \en Get a hint. - const TCHAR * GetPrompt() const; - /// \ru Выдать идентификатор хранимого атрибута. \en Get identifier of stored attribute. - void GetUserAttribId( MbUserAttribType & attrId ) const; - - /// \ru Установить пользовательские данные. \en Set user data. - void SetUserData( const char * extAttrMemory ); - /// \ru Установить пользовательские данные. \en Set user data. - void SetUserData( const std::vector & extAttrData ); - /// \ru Получить пользовательские данные. \en Get user data. - bool GetUserData( membuf & memBuf ) const; - /// \ru Создать пользовательский внесистемный атрибут по пользовательским данным. \en Make a user external attribute using user data. - bool MakeExternalAttribute( bool keepExisting ); - /// \ru Обновить пользовательские данные по внесистемному атрибуту пользователя. \en Update user data using the user external attribute. - bool UpdateByExternalAttribute() const; - - /// \ru Выдать пользовательский внесистемный атрибут. \en Get a user external attribute. - const MbExternalAttribute * GetExternalAttribute() const { return extAttr; } - /// \ru Установить пользовательский внесистемный атрибут. \en Set a user external attribute. - bool SetExternalAttribute( MbExternalAttribute * ); - /// \ru Установить пользовательский внесистемный атрибут (его копию). \en Set a user external attribute (сopy). - void SetExternalAttribute( const MbExternalAttribute & ); - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - - template - friend MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExternalAttribute & ); - -protected: - virtual ~MbUserAttribute(); // Use AddRef/Release or smart pointer SPtr to destruct it correctly. - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserAttribute ) -OBVIOUS_PRIVATE_COPY( MbUserAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbUserAttribute ) - -class MATH_CLASS MbFixAttrSet; - - -//------------------------------------------------------------------------------ -/** \brief \ru Пользовательский внесистемный атрибут - базовый класс. - \en User external attribute - the base class. \~ - \details \ru Пользовательский внесистемный атрибут - базовый класс. \n - \en User external attribute - the base class. \n \~ - \ingroup Model_Attributes - */ -class MATH_CLASS MbExternalAttribute : public MbAttribute -{ -public : - /// \ru Конструктор. \en Constructor. - MbExternalAttribute(); - /// \ru Деструктор. \en Destructor. - virtual ~MbExternalAttribute(); - - virtual MbeAttributeType AttributeFamily() const; // \ru Дать тип атрибута. \en Get type of an attribute. - virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. - /// \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 bool IsSame( const MbAttribute &, double accuracy ) const = 0; // \ru Определить, являются ли объекты равными. \en Determine whether objects are equal. - virtual bool Init( const MbAttribute & attr ) = 0; // \ru Инициализировать данные по присланным. \en Initialize data. - - // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. - virtual void OnChangeOwner( const MbAttributeContainer & owner ); - // \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 & matr, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. - virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D & to, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. - virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D & axis, double angle, MbRegTransform * iReg = NULL ); - // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. - virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * iReg = 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. - virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); - // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. - virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); - // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. - virtual void OnDeleteOwner( const MbAttributeContainer & owner ); - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. - -protected: - static MbFixAttrSet * CreateFixAttrSet( const MbUserAttribType &, c3d::AttrVector & ); - -OBVIOUS_PRIVATE_COPY( MbExternalAttribute ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Фиксированный набор атрибутов - \en Fixed set of attributes. \~ - \details \ru Набор атрибутов, состав которого нельзя изменить, но никто не запрещает - менять значение самих атрибутов. - \en A set of attributes the structure of which cannot be changed, but it is possible - to change values of the attributes. \~ - \ingroup Model_Attributes -*/ -class MATH_CLASS MbFixAttrSet -{ -private: - MbUserAttribType userAttrId; ///< \ru Идентификатор соответствующего пользовательского атрибута. \en Identifier of the corresponding external attribute. - c3d::AttrVector attributes; ///< \ru Атрибуты. \en Attributes. - -private: - /// \ru Конструктор. \en Constructor. - MbFixAttrSet( c3d::AttrVector & attrs ); -public: - /// \ru Деструктор. \en Destructor. - ~MbFixAttrSet() { std::for_each( attributes.begin(), attributes.end(), ReleaseItem ); } - -public: - /// \ru Выдать идентификатор атрибута. \en Get attribute identifier. - const MbUserAttribType & GetUserAttrId() const; - - /// \ru Установить атрибуты. \en Set attributes. - void SetAttribute ( size_t index, const MbAttribute & attrib ); - /// \ru Выдать атрибуты. \en Get attributes. - const MbAttribute & GetAttribute ( size_t index, const MbAttribute & attrib ) const; - - // \ru Выдать количество атрибутов. \en Get the number of attributes. - size_t AttributesCount() const { return attributes.size(); } - - // \ru Доступ хотелось бы ограничить только функцией. \en Access should be constrained only by a function. - // static MbFixAttrSet * MbExternalAttribute::CreateFixAttrSet( const MbUserAttribType & attrId, std::vector & attrs ); - friend class MbExternalAttribute; - -OBVIOUS_PRIVATE_COPY( MbFixAttrSet ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Шаблон явления "Определения" пользовательского атрибута. - \en A template of "Definition" phenomenon of user attribute. \~ - \ingroup Model_Attributes - */ -template -class UserAttrDefinitionInstance : public AttrDefInstance -{ -private: - AttrDefClass * attrDef; ///< \ru "Определение" пользовательского атрибута. \en "Definition" of user attribute. - -public: - /// \ru Конструктор. \en Constructor. - UserAttrDefinitionInstance( const MbUserAttribType & type ); - /// \ru Деструктор. \en Destructor. - virtual ~UserAttrDefinitionInstance(); - -public: - // \ru Дать "определение" пользовательского атрибута. \en Get a "definition" of user attribute. - virtual IAttrDefinition * GetAttrDefinition(); -}; - - -//------------------------------------------------------------------------------ -/// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. -// --- -template -MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExternalAttribute & source ) -{ - MbUserAttribType attrId( source.AttrTypeEx() ); - - MbUserAttribute * resAttr = new MbUserAttribute( _T("AttrClass"), attrId ); - resAttr->InitActions( source ); - { - const char * charBuf = NULL; - size_t memLen = 0; - { - membuf memBuf; - { - const AttrClass * attrPtr = static_cast(&source); - writer out( memBuf, io::out ); - if ( out.good() ) - out << attrPtr; - } - memBuf.closeBuff(); // before memBuf.getMemLen!!! - - memLen = memBuf.getMemLen(); - charBuf = new char[memLen]; - memBuf.toMemory( charBuf, memLen ); - } - resAttr->SetUserData( charBuf ); - delete [] charBuf; - } - - return resAttr; -} - - -//------------------------------------------------------------------------------ -/// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. -// --- -template -MbExternalAttribute * UserAttrDefinition::AdvanceUserAttrib( const MbUserAttribute & source ) -{ - AttrClass * resAttr = NULL; - MbUserAttribType attrId; - source.GetUserAttribId( attrId ); - { - membuf memBuf; - { - bool canRead = true; - if ( !source.GetUserData( memBuf ) ) { - canRead = false; - if ( source.UpdateByExternalAttribute() ) { - canRead = source.GetUserData( memBuf ); - } - } - if ( canRead ) { - reader in( memBuf, io::in ); - if ( in.good() ) - in >> resAttr; - } - } - memBuf.closeBuff(); - } - return resAttr; -} - - -//------------------------------------------------------------------------------ -/// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. -// --- -template -MbFixAttrSet * UserAttrDefinition::DisassembleUsetAttrib( const MbExternalAttribute & /*source*/ ) { - return NULL; -} - - -//------------------------------------------------------------------------------ -/// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. -// --- -template -bool UserAttrDefinition::ReassembleUsetAttrib( const MbFixAttrSet & /*source*/, MbExternalAttribute & /*targer*/ ) { - return false; -} - - -//------------------------------------------------------------------------------ -// \ru Конструктор. \en Constructor. -// --- -template -UserAttrDefinitionInstance::UserAttrDefinitionInstance(const MbUserAttribType & type) - : AttrDefInstance( type ) - , attrDef( NULL ) -{ -} - - -//------------------------------------------------------------------------------ -// \ru Деструктор. \en Destructor. -// --- -template -UserAttrDefinitionInstance::~UserAttrDefinitionInstance() -{ - if ( attrDef != NULL ) - delete attrDef; -} - - -//------------------------------------------------------------------------------ -// \ru Дать "определение" пользовательского атрибута. \en Get a "definition" of user attribute. -// --- -template -IAttrDefinition * UserAttrDefinitionInstance::GetAttrDefinition() -{ - if ( attrDef == NULL ) - attrDef = new AttrDefClass(); - return attrDef; -} - - -#endif // __ATTR_USER_ATTRIBUT_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Пользовательские атрибуты. + \en User attributes. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTR_USER_ATTRIBUT_H +#define __ATTR_USER_ATTRIBUT_H + + +#include +#include +#include +#include +#include +#include +#include + +class MATH_CLASS MbExternalAttribute; +class MATH_CLASS MbUserAttribute; +class MATH_CLASS MbFixAttrSet; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс определения атрибута. + \en Attribute definition interface. \~ + \details \ru Интерфейс определения атрибута. Определение атрибута - объект используемый + для преобразования пользовательских внесистемных атрибутов в пользовательские системные, + а так же для разборки пользовательских системных атрибутов + на составные части - другие атрибуты системные атрибуты, и обратной сборки. + \en Attribute definition interface. Attribute definition - the object used + for converting user external attributes to user system attributes + and for a disassembly of user system attributes + to their components - other system attributes, and for reassembly. \~ + \ingroup Model_Attributes + */ +class IAttrDefinition +{ +public: + /// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. + virtual MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & source ) = 0; + + /// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. + virtual MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & source ) = 0; + + /// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. + virtual MbFixAttrSet * DisassembleUserAttrib( const MbExternalAttribute & source ) = 0; + + /// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. + virtual bool ReassembleUserAttrib ( const MbFixAttrSet & source, MbExternalAttribute & target ) = 0; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Шаблон "определения" пользовательского атрибута. + \en A template of user attribute definition. \~ + \details \ru Шаблонный класс "Определения" пользовательского атрибута - используется для создания + стандартных определений, с предопределенным функционалом. + \en Template class "Definition" of user attribute - used for creation + of standard definitions with predefined functionality. \~ + \ingroup Model_Attributes + */ +template +class UserAttrDefinition : public IAttrDefinition +{ +public: + /// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. + virtual MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & source ); + + /// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. + virtual MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & source ); + + /// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. + virtual MbFixAttrSet * DisassembleUserAttrib( const MbExternalAttribute & source ); + + /// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. + virtual bool ReassembleUserAttrib( const MbFixAttrSet & source, MbExternalAttribute & target ); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Пользовательский системный атрибут. + \en User system attribute. \~ + \details \ru Пользовательский системный атрибут. \n + \en User system attribute. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbUserAttribute : public MbAttribute, public MbSyncItem { + typedef std_unique_ptr UniqueMembufPtr; +protected : + MbUserAttribType userType_; ///< \ru Тип пользовательского атрибута. \en Type of user attribute. + c3d::string_t prompt_; ///< \ru Строка описания. \en String of description. +private: + SPtr extAttr; + mutable UniqueMembufPtr userBuf; + +private: // public: // You must inherit from MbExternalAttribute only!!! + /// \ru Конструктор. \en Constructor. + MbUserAttribute( const TCHAR *, const MbUserAttribType & ); + +public: + virtual MbeAttributeType AttributeFamily() const; // \ru Дать тип атрибута. \en Get type of an attribute. + virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. + + /// \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 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. + + // \ru Выполнить действия при изменении владельца не связанное с другими действиями \en Perform actions which are not associated with other actions when changing the owner + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = 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. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + + /// \ru Выдать подсказку. \en Get a hint. + const TCHAR * GetPrompt() const; + /// \ru Выдать идентификатор хранимого атрибута. \en Get identifier of stored attribute. + void GetUserAttribId( MbUserAttribType & attrId ) const; + + /// \ru Установить пользовательские данные. \en Set user data. + void SetUserData( const char * extAttrMemory ); + /// \ru Установить пользовательские данные. \en Set user data. + void SetUserData( const std::vector & extAttrData ); + /// \ru Получить пользовательские данные. \en Get user data. + bool GetUserData( membuf & ) const; + /// \ru Создать пользовательский внесистемный атрибут по пользовательским данным. \en Make a user external attribute using user data. + bool MakeExternalAttribute( bool keepExisting ); + /// \ru Обновить пользовательские данные по внесистемному атрибуту пользователя. \en Update user data using the user external attribute. + bool UpdateByExternalAttribute() const; + + /// \ru Выдать пользовательский внесистемный атрибут. \en Get a user external attribute. + const MbExternalAttribute * GetExternalAttribute() const { return extAttr; } + /// \ru Установить пользовательский внесистемный атрибут. \en Set a user external attribute. + bool SetExternalAttribute( MbExternalAttribute * ); + /// \ru Установить пользовательский внесистемный атрибут (его копию). \en Set a user external attribute (copy). + void SetExternalAttribute( const MbExternalAttribute & ); + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + + //warning: dependent nested name specifier 'UserAttrDefinition::' for friend class declaration is not supported; turning off access control for 'MbUserAttribute' + //template + //friend MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExternalAttribute & ); + + template + friend class UserAttrDefinition; + +protected: + virtual ~MbUserAttribute(); // Use AddRef/Release or smart pointer SPtr to destruct it correctly. + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserAttribute ) +OBVIOUS_PRIVATE_COPY( MbUserAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbUserAttribute ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Пользовательский внесистемный атрибут - базовый класс. + \en User external attribute - the base class. \~ + \details \ru Пользовательский внесистемный атрибут - базовый класс. \n + \en User external attribute - the base class. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbExternalAttribute : public MbAttribute +{ +public : + /// \ru Конструктор. \en Constructor. + MbExternalAttribute(); + /// \ru Деструктор. \en Destructor. + virtual ~MbExternalAttribute(); + + virtual MbeAttributeType AttributeFamily() const; // \ru Дать тип атрибута. \en Get type of an attribute. + virtual MbeAttributeType AttributeType() const; // \ru Выдать подтип атрибута. \en Get subtype of an attribute. + /// \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 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. + + // \ru Выполнить действия при изменении владельца, не связанное с другими действиями. \en Perform actions which are not associated with other actions when changing the owner. + virtual void OnChangeOwner( const MbAttributeContainer & owner ); + // \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 ); + // \ru Выполнить действия при перемещении владельца. \en Perform actions when moving the owner. + virtual void OnMoveOwner( const MbAttributeContainer & owner, const MbVector3D &, MbRegTransform * = NULL ); + // \ru Выполнить действия при вращении владельца. \en Perform actions when rotating the owner. + virtual void OnRotateOwner( const MbAttributeContainer & owner, const MbAxis3D &, double angle, MbRegTransform * = NULL ); + // \ru Выполнить действия при копировании владельца. \en Perform actions when copying the owner. + virtual void OnCopyOwner( const MbAttributeContainer & owner, MbAttributeContainer & other, MbRegDuplicate * = 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. + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ); + // \ru Выполнить действия при разделении владельца. \en Perform actions when splitting the owner. + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ); + // \ru Выполнить действия при удалении владельца. \en Perform actions when deleting the owner. + virtual void OnDeleteOwner( const MbAttributeContainer & owner ); + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual size_t SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. + +OBVIOUS_PRIVATE_COPY( MbExternalAttribute ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Фиксированный набор атрибутов + \en Fixed set of attributes. \~ + \details \ru Набор атрибутов, состав которого нельзя изменить, но никто не запрещает + менять значение самих атрибутов. + \en A set of attributes the structure of which cannot be changed, but it is possible + to change values of the attributes. \~ + \ingroup Model_Attributes +*/ +class MATH_CLASS MbFixAttrSet +{ +private: + MbUserAttribType userAttrId; ///< \ru Идентификатор соответствующего пользовательского атрибута. \en Identifier of the corresponding external attribute. + c3d::AttrVector attributes; ///< \ru Атрибуты. \en Attributes. + +private: + /// \ru Конструктор. \en Constructor. + MbFixAttrSet( c3d::AttrVector & ); +public: + /// \ru Деструктор. \en Destructor. + ~MbFixAttrSet() { std::for_each( attributes.begin(), attributes.end(), ReleaseItem ); } + +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); } + // \ru Выдать количество атрибутов. \en Get the number of attributes. + size_t AttributesCount() const { return attributes.size(); } + + friend class MbExternalAttribute; + +OBVIOUS_PRIVATE_COPY( MbFixAttrSet ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Шаблон явления "Определения" пользовательского атрибута. + \en A template of "Definition" phenomenon of user attribute. \~ + \ingroup Model_Attributes + */ +template +class UserAttrDefinitionInstance : public AttrDefInstance, public MbSyncItem +{ +private: + AttrDefClass * attrDef; ///< \ru "Определение" пользовательского атрибута. \en "Definition" of user attribute. + +public: + /// \ru Конструктор. \en Constructor. + UserAttrDefinitionInstance( const MbUserAttribType & ); + /// \ru Деструктор. \en Destructor. + virtual ~UserAttrDefinitionInstance(); + +public: + // \ru Дать "определение" пользовательского атрибута. \en Get a "definition" of user attribute. + virtual IAttrDefinition * GetAttrDefinition(); +}; + + +//------------------------------------------------------------------------------ +/// \ru Преобразовать из пользовательского в "системный". \en Convert user attribute to "system" one. +// --- +template +MbUserAttribute * UserAttrDefinition::ReduceUserAttrib( const MbExternalAttribute & source ) +{ + MbUserAttribType attrId( source.AttrTypeEx() ); + + MbUserAttribute * resAttr = new MbUserAttribute( _T("AttrClass"), attrId ); + resAttr->InitActions( source ); + { + const char * charBuf = NULL; + size_t memLen = 0; + { + membuf memBuf; + { + const AttrClass * attrPtr = static_cast(&source); + writer out( memBuf, io::out ); + if ( out.good() ) + out << attrPtr; + } + memBuf.closeBuff(); // before memBuf.getMemLen!!! + + memLen = memBuf.getMemLen(); + charBuf = new char[memLen]; + memBuf.toMemory( charBuf, memLen ); + } + resAttr->SetUserData( charBuf ); + delete [] charBuf; + } + + return resAttr; +} + + +//------------------------------------------------------------------------------ +/// \ru Преобразовать из "системного" в пользовательский. \en Convert "system" attribute to user one. +// --- +template +MbExternalAttribute * UserAttrDefinition::AdvanceUserAttrib( const MbUserAttribute & source ) +{ + AttrClass * resAttr = NULL; + MbUserAttribType attrId; + source.GetUserAttribId( attrId ); + { + membuf memBuf; + { + bool canRead = true; + if ( !source.GetUserData( memBuf ) ) { + canRead = false; + if ( source.UpdateByExternalAttribute() ) { + canRead = source.GetUserData( memBuf ); + } + } + if ( canRead ) { + reader in( memBuf, io::in ); + if ( in.good() ) + in >> resAttr; + } + } + memBuf.closeBuff(); + } + return resAttr; +} + + +//------------------------------------------------------------------------------ +/// \ru "Разобрать" на составляющие атрибуты. \en Disassemble on attributes. +// --- +template +MbFixAttrSet * UserAttrDefinition::DisassembleUserAttrib( const MbExternalAttribute & /*source*/ ) { + return NULL; +} + + +//------------------------------------------------------------------------------ +/// \ru "Собрать" из составляющих атрибутов. \en Reassemble from attributes. +// --- +template +bool UserAttrDefinition::ReassembleUserAttrib( const MbFixAttrSet & /*source*/, MbExternalAttribute & /*target*/ ) { + return false; +} + + +//------------------------------------------------------------------------------ +// \ru Конструктор. \en Constructor. +// --- +template +UserAttrDefinitionInstance::UserAttrDefinitionInstance( const MbUserAttribType & type ) + : AttrDefInstance( type ) + , attrDef( NULL ) +{ +} + + +//------------------------------------------------------------------------------ +// \ru Деструктор. \en Destructor. +// --- +template +UserAttrDefinitionInstance::~UserAttrDefinitionInstance() +{ + if ( attrDef != NULL ) + delete attrDef; +} + + +//------------------------------------------------------------------------------ +// \ru Дать "определение" пользовательского атрибута. \en Get a "definition" of user attribute. +// --- +template +IAttrDefinition * UserAttrDefinitionInstance::GetAttrDefinition() +{ + if ( attrDef == NULL ) { + ScopedLock ll( GetLock() ); + attrDef = new AttrDefClass(); + } + return attrDef; +} + + +#endif // __ATTR_USER_ATTRIBUT_H diff --git a/C3d/Include/attribute.h b/C3d/Include/attribute.h index 463a095..9c8e197 100644 --- a/C3d/Include/attribute.h +++ b/C3d/Include/attribute.h @@ -1,540 +1,553 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Атрибуты объекта. - \en Object attributes. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTRIBUTE_H -#define __ATTRIBUTE_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbVector3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbMatrix3D; -class MATH_CLASS MbProperties; -class MATH_CLASS MbAttributeContainer; -class MbRegDuplicate; -class MbRegTransform; - - -class MATH_CLASS MbAttribute; -namespace c3d // namespace C3D -{ -typedef SPtr AttrSPtr; -typedef SPtr ConstAttrSPtr; - -typedef std::vector AttrVector; -typedef std::vector ConstAttrVector; - -typedef std::vector AttrSPtrVector; -typedef std::vector ConstAttrSPtrVector; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы атрибутов. - \en Types of attributes. \~ - \details \ru Типы атрибутов объектов геометрической модели. - Атрибуты объектов группируются по семействам. - \en Types of geometric model objects attributes. - Objects attributes are grouped by families. \~ - \ingroup Model_Attributes - */ -enum MbeAttributeType -{ - at_Undefined = 0, ///< \ru Неопределенный - используется при поиске как "любой". \en Undefined - used as "any" in search. \n - - // \ru Типы простых атрибутов. \en Types of elementary attributes. - at_ElementaryAttribute = 101, ///< \ru Простой атрибут. \en Elementary attribute. - at_Identifier = 102, ///< \ru Идентификатор. \en Identifier. - at_Color = 103, ///< \ru Цвет. \en Color. - at_Width = 104, ///< \ru Ширина линий. \en Lines width. - at_Style = 105, ///< \ru Стиль линий. \en Lines style. - at_Visual = 106, ///< \ru Свойства для OpenGL. \en Properties for OpenGL. - at_Selected = 107, ///< \ru Селектированность. \en Selection. - at_Visible = 108, ///< \ru Видимость. \en Visibility. - at_WireCount = 109, ///< \ru Количество u-линий и v-линий отрисовочной сетки. \en The number of u-mesh and v-mesh drawing lines. \~ - at_Changed = 110, ///< \ru Изменённость. \en Modification. - at_Dencity = 111, ///< \ru Плотность. \en Density. - at_NameAttribute = 112, ///< \ru Топологическое имя. \en Topological name. - at_UpdateStamp = 113, ///< \ru Метка времени обновления. \en Stamp of update time. - at_Embodiment = 114, ///< \ru Признак исполнения (варианта реализации модели). \en Indication of embodiment (variant of model implementation). - at_Elasticity = 115, ///< \ru Механические характеристики: модуль Юнга и коэффициент Пуассана. \en Mechanical properties: Young's modulus and Poisson's ratio. - at_Strains = 116, ///< \ru Деформации. \en The strains. - at_ElementaryLast = 200, /// \ru Простые атрибуты вставлять перед этим значением. \en Elementary attributes should be inserted before this value. \n - - // \ru Типы обобщенных атрибутов. \en Types of common attributes. - at_CommonAttribute = 201, ///< \ru Обобщенный атрибут. \en Common attribute. - at_BoolAttribute = 202, ///< \ru Булев атрибут. \en Boolean attribute. - at_IntAttribute = 203, ///< \ru Целочисленный атрибут. \en Integer attribute. - at_DoubleAttribute = 204, ///< \ru Действительный атрибут. \en Double attribute. - at_StringAttribute = 205, ///< \ru Строковый атрибут. \en String attribute. - at_GeomAttribute = 206, ///< \ru Геометрический атрибут. \en Geometric attribute. \n - at_StampRibAttribute = 207, ///< \ru Атрибут ребра жесткости листового тела. \en Attribute of reinforcement rib of sheet solid. \n - at_Int64Attribute = 208, ///< \ru Атрибут int64. \en Int64 attribute. - at_BinaryAttribute = 209, ///< \ru Бинарный атрибут. \en Binary attribute. - - // \ru Типы связующих атрибутов. \en Types of linking attributes. - at_LinkingAttribute = 301, ///< \ru Связующий атрибут. \en Linking attribute. - at_AnchorAttribute = 302, ///< \ru Якорь. \en Anchor. \n - - // \ru Типы директивных атрибутов. \en Types of directive attributes. - at_DirectiveAttribute = 401, ///< \ru Директивный атрибут. \en Directive attribute. - at_KeepUniqueKey = 402, ///< \ru Поддерживать уникальность ключей. \en Support unique keys. \n - - // \ru Типы изделия. \en Types of product attributes. - at_ProductAttribute = 501, ///< \ru Атрибут конвертеров \en Converters attribute - at_ModelInfo = 502, ///< \ru Сведения о модели в целом. \en Information about model itself. - at_PersonOrganizationInfo = 503, ///< \ru Лицо и организация. \en Person and organization information. - at_ProductInfo = 504, ///< \ru Сведения об изделии. \en Product info. - at_STEPTextDescription = 505, ///< \ru Описание STEP. \en STEP description. - at_STEPReferenceHolder = 506, ///< \ru Обратная ссылка. \en Back reference. \n - - // \ru Типы пользовательских атрибутов. \en Types of user attributes. - at_UserAttribute = 601, ///< \ru Пользовательский атрибут. \en User attribute. - at_UserFirst = 602, ///< \ru Первый пользовательский атрибут. \en First user attribute. - at_UserLast = 900, ///< \ru Последний пользовательский атрибут. \en Last user attribute. \n - - // \ru Типы внешних (внесистемных) атрибутов. \en Types of external (off-system) attributes. - at_ExternalAttribute = 901, ///< \ru Внешний атрибут. \en External attribute. - at_ExternalAttributeImp = 902, ///< \ru Подтип - внешний атрибут \en Subtype - external attribute. - - at_FreeItem = 1000, ///< \ru Тип для прочих объектов. \en Type for the other objects. - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы контейнеров атрибутов. - \en Types of attribute containers. \~ - \details \ru Типы контейнеров атрибутов наследников контейнера атрибутов. - Каждый отдельный атрибут может содержать свой контейнер атрибутов. - \en Types of attribute containers which are inheritors of attribute container. - Each separate attribute may have its attribute container. \~ - \ingroup Model_Attributes - */ -enum MbeImplicationType -{ - ace_Attribute, ///< \ru Контейнер атрибутов, содержащий другие атрибуты. \en Attribute container which contains other attributes. - ace_ModelItem, ///< \ru Контейнер атрибутов объектов геометрической модели. \en Container of geometric model objects attributes. - ace_TopItem, ///< \ru Контейнер атрибутов именованных топологических объектов. \en Container of named topological objects attributes. - ace_MeshItem, ///< \ru Контейнер атрибутов сеточных примитивов. \en Container of mesh primitives attributes. - ace_Model, ///< \ru Контейнер атрибутов геометрической модели. \en Container of geometric model attributes. - ace_AttribContainer, ///< \ru Контейнер атрибутов. \en Attribute container. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Атрибуты объекта. - \en Object attributes. \~ - \details \ru Атрибуты содержат информацию, дополняющую описание геометрической формы объекта. - Атрибут не является неотъемлемой частью объекта, а является элементом данных, которыми может быть наделен объект.\n - Атрибуты являются агентами передачи данных геометрического ядра от одного приложения другому приложению.\n - Атрибуты могут быть следующих типов.\n - Простой атрибут - атрибут несущий простую, однозначно интерпретируемую, информацию, например, цвет, признак выбора.\n - Обобщенный атрибут - атрибут стандартного типа со строковым наименованием, - например, имя, целое число, вещественное число, строка, точка, вектор, указатель.\n - С помощью таких атрибутов приложения могут обмениваться какой либо специфичной информацией - без необходимости разработки дополнительных комплексных атрибутов.\n - Комплексный атрибут - атрибут состоящий из предопределенного набора данных, - описывающих природу атрибута и его смысловую нагрузку, а так же способ его интерпретации. - Такими атрибутами могут описываться некоторые ограничения или простые зависимости а так же аннотационные объекты.\n - Директивный атрибут - атрибут определяющий предназначения объекта или действия которые необходимо с ним произвести, - например атрибут "вычитание" подразумевает что некое тело предназначено для вычитания из другого тела, - и не важно из какого. - Связующий атрибут - атрибут предназначенный для связи объекта геометрического ядра с абстрактным контейнером данных, - то есть набором данных, формат и смысловая нагрузка которых не может быть описана в рамках других атрибутов.\n - \en Attributes contain information supplementing description of object geometric shape. - Attribute is not an intrinsic part of the object, but it is an element of data which the object may contain. \n - Attributes are geometric kernel agents for transferring data from one application to another. \n - The possible types of attributes are the following. \n - Elementary attribute - an attribute which reflects simple and clearly interpreted information, for example, color or selection attribute.\n - Common attribute - attribute of standard type with string naming, - for example: name, integer value, double value, string, point, vector, pointer. \n - Applications may communicate any specific information using such attributes - without necessity of additional complex attributes developing. \n - Complex attribute - an attribute which consists of predefined data set, - which describe a nature of attribute, its semantic meaning and a way of its interpretation. - Such attributes can describe some of constraints or simple dependences and annotation objects.\n - Directive attribute - an attribute defining the purpose of object or actions which should be performed with it, - for example, an attribute "subtraction" implies that one solid is purposed for subtraction from another, - no matter from what exactly. - Linking attribute - an attribute designed for linking of geometric kernel object with abstract container of data, - i.e. a set of data, which format and semantic meaning can not be described by other attributes. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbAttribute : public MbRefItem, - public TapeBase -{ -public: - /**\ru Поведение атрибута при изменении владельца, не связанном с другими описанными действия. - \en Behavior of attribute which is not associated with other described actions when changing the owner. \~ */ - enum OnChangeOwnerAction { - chn_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnChangeOwner. \en Behavior defined by the virtual function OnChangeOwner. - chn_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - chn_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - chn_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при перерождении объекта в другой объект. - \en Behavior of attribute when an object regenerates in other object. \~ */ - enum OnConvertOwnerAction { - cnv_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnConvertOwner. \en Behavior defined by the virtual function OnConvertOwner. - cnv_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - cnv_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - cnv_Copy, ///< \ru Скопировать атрибут и прицепить его копию к копии владельца. \en Copy an attribute and attach its copy to an owner copy. - cnv_Convert, ///< \ru Конвертировать атрибут и прицепить результат к копии владельца. \en Copy an attribute and attach the result to an owner copy. - cnv_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при преобразовании владельца (по матрице). - \en Behaviour of attribute when transforming the owner (by the matrix). \~ */ - enum OnTransformOwnerAction { - trn_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnTransformOwner. \en Behavior defined by the virtual function OnTransformOwner. - trn_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - trn_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - trn_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при копировании владельца. - \en Behaviour of attribute when copying the owner. \~ */ - enum OnCopyOwnerAction { - cpy_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnCopyOwner. \en Behavior defined by the virtual function OnCopyOwner. - cpy_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - cpy_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - cpy_Copy, ///< \ru Скопировать атрибут и прицепить его копию к копии владельца. \en Copy an attribute and attach its copy to an owner copy. - cpy_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при объединении владельца с другим объектом. - \en Behaviour of attribute when merging of the owner with another object. \~ */ - enum OnMergeOwnerAction { - mrg_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnMergeOwner. \en Behavior is defined by the virtual function OnMergeOwner. - mrg_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - mrg_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - mrg_KeepAll, ///< \ru Передать атрибут от поглощаемого объекта поглощающему объекту без замещения. \en Transmit attribute from absorbed object to absorbing object without replacing. - mrg_KeepRep, ///< \ru Передать атрибут от поглощаемого объекта поглощающему объекту с замещением. \en Transmit attribute from absorbed object to absorbing object with replacing. - mrg_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при замещении владельца с другим объектом. - \en Behavior of attribute when replacing the owner by another object. \~ */ - enum OnReplaceOwnerAction { - rep_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnReplaceOwner. \en Behavior is defined by the virtual function OnReplaceOwner. - rep_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - rep_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - rep_KeepAll, ///< \ru Передать атрибут от замещаемого объекта замещающему объекту без замещения. \en Transmit attribute from replaced object to substitutional object without replacing. - rep_KeepRep, ///< \ru Передать атрибут от замещаемого объекта замещающему объекту с замещением. \en Transmit attribute from replaced object to substitutional object with replacing. - rep_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при разделении владельца. - \en Behavior of attribute when splitting the owner. \~ */ - enum OnSplitOwnerAction { - spl_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnSplitOwner. \en Behavior is defined by the virtual function OnSplitOwner. - spl_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - spl_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. - spl_Copy, ///< \ru Размножить(скопировать) атрибут для каждого результата разбиения. \en Duplicate (copy) attribute for each result of splitting. - spl_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - - /**\ru Поведение атрибута при удалении владельца. - \en Behavior of attribute when deleting the owner. \~ */ - enum OnDeleteOwnerAction { - del_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnDeleteOwner. \en Behavior defined by the virtual function OnDeleteOwner. - del_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. - del_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). - }; - -private : - uint8 forChange; ///< \ru Поведение атрибута при изменении владельца. \en Behavior of attribute when changing the owner. - uint8 forConvert; ///< \ru Поведение атрибута при конвертации владельца. \en Behavior of attribute when converting the owner. - uint8 forTransform; ///< \ru Поведение атрибута при трансформировании владельца. \en Behavior of attribute when transforming the owner. - uint8 forCopy; ///< \ru Поведение атрибута при копировании владельца. \en Behavior of attribute when copying the owner. - uint8 forMerge; ///< \ru Поведение атрибута при объединении владельца. \en Behavior of attribute when merging the owner. - uint8 forReplace; ///< \ru Поведение атрибута при замене владельца. \en Behavior of attribute when replacing the owner. - uint8 forSplit; ///< \ru Поведение атрибута при разделении владельца. \en Behavior of attribute when splitting the owner. - uint8 forDelete; ///< \ru Поведение атрибута при удалении владельца. \en Behavior of attribute when deleting the owner. - bool freeable; ///< \ru Свободность атрибута. \en Attribute freeness - bool copyable; ///< \ru Разрешение копировать атрибут. \en Permission to copy attribute. - -protected : - /// \ru Конструктор без параметров для наследников. \en Constructor without parameters for inheritors. - MbAttribute(); -public : - /// \ru Деструктор. \en Destructor. - virtual ~MbAttribute(); - -public : - /** \ru \name Общие функции атрибутов - \en \name Common functions of attributes - \{ */ - /// \ru Выдать регистрационный тип (для копирования, дублирования). \en Get registrational type (for copying, duplication) - virtual MbeRefType RefType() const; - /// \ru Выдать тип контейнера атрибутов. \en Get attribute container type. - virtual MbeImplicationType ImplicationType() const; - /// \ru Выдать тип атрибута. \en Get attribute type. - virtual MbeAttributeType AttributeFamily() const = 0; - /// \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; - /** \brief \ru Определить, являются ли объекты равными. - \en Determine whether objects are equal. \~ - \details \ru Равными считаются однотипные объекты, все данные которых одинаковы (равны). - \en Objects of the same types with similar (equal) data are considered to be equal. \~ - \param[in] item - \ru Объект для сравнения. - \en Objects for comparison. \~ - \param[in] accuracy - \ru Точность сравнения. - \en The accuracy to compare. \~ - \return \ru Равны ли объекты. - \en Whether objects are equal. \~ - */ - virtual bool IsSame( const MbAttribute & item, double accuracy ) const = 0; - /// \ru Инициализировать данные по присланным. \en Initialize data. - virtual bool Init( const MbAttribute & ) = 0; - - /// \ru Проверить тип атрибута. \en Check an attribute type. - bool IsA( MbeAttributeType t ) const { return t == AttributeFamily(); } - /** \} */ - - /** \ru \name Действия над объектами геометрического ядра, влияющие на состояние атрибутов - \en \name Actions with objects of geometric kernel influencing on states of attributes. - \{ */ - /** \brief \ru Выполнить действия при изменении владельца, не связанное с другими действиями. - \en Perform actions which are not associated with other actions when changing the owner. \~ - \details \ru Действия при изменении владельца, не связанное с другими действиями. \n - Вызывается после изменения владеющего объекта при условии GetActionForChange() == chn_Self. - \en Actions which are not associated with other actions when changing the owner. \n - This function is called after changing the owning object in a case when GetActionForChange() == chn_Self. \~ */ - virtual void OnChangeOwner( const MbAttributeContainer & owner ) = 0; - - /**\ru Выполнить действия при конвертации владельца, \n - Вызывается после конвертирования владеющего объекта при условии GetActionForConvert() == cnv_Self. \n - В качестве входного параметра передается результат конвертирования объекта. - \en Perform actions when converting the owner, \n - This function is called after converting the owning object in a case when GetActionForConvert() == cnv_Self. \n - The result of object converting is passed as input parameter. \~ */ - virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; - - /**\ru Выполнить действия при трансформировании владельца, \n - Вызывается после трансформирования владеющего объекта при условии GetActionForTransform() == trn_Self. - В качестве входного параметра может передаваться регистратор трансформированных объектов. - \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 & matr, MbRegTransform * iReg = NULL ) = 0; - - /**\ru Выполнить действия при перемещении владельца. \n - Вызывается после перемещения владеющего объекта при условии GetActionForTransform() == trn_Self. - В качестве входного параметра может передаваться регистратор трансформированных объектов. - \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 & to, MbRegTransform * iReg = NULL ) = 0; - - /**\ru Выполнить действия при вращении владельца. \n - Вызывается после вращения владеющего объекта при условии GetActionForTransform() == trn_Self. - В качестве входного параметра может передаваться регистратор трансформированных объектов. - \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 & axis, double angle, MbRegTransform * iReg = NULL ) = 0; - - /**\ru Выполнить действия при копировании владельца. \n - Вызывается после копирования владеющего объекта при условии GetActionForCopy() == cpy_Self. \n - В качестве входных параметров передаются: копия владеющего объекта и регистратор скопированных объектов. - \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 * iReg = NULL ) = 0; - - /**\ru Выполнить действия при объединении владельца. \n - Вызывается перед слиянием владельца при условии GetActionForMerge() == mrg_Self. \n - В качестве входного параметра передается объект который будет поглощен. - \en Perform actions when merging the owner. \n - This function is called before merging the owner in a case when GetActionForMerge() == mrg_Self. \n - The object which will be absorbed is passed as input parameter. \~ */ - virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; - - /**\ru Выполнить действия при замене владельца. \n - Вызывается перед выполнением замены владельца при условии GetActionForReplace() == rep_Self. \n - В качестве входного параметра передается объект - заместитель. - \en Perform actions when replacing the owner. \n - This function is called before replacing the owner in a case when GetActionForReplace() == rep_Self. \n - The substitutional object is passed as input parameter. \~ */ - virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; - - /**\ru Выполнить действия при разделении владельца. \n - Вызывается после разбиения владеющего объекта при условии GetActionForSplit() == spl_Self. \n - В качестве входного параметра передается контейнер результатов разбиения. - \en Perform actions when splitting the owner. \n - This function is called after splitting the owning object in a case when GetActionForSplit() == spl_Self. \n - The container of splitting results is passed as input parameter. \~ */ - virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ) = 0; - - /**\ru Выполнить действия при удалении владельца. \n - Вызывается перед удалением объекта при условии GetActionForDelete() == spl_Self. - \en Perform actions when deleting the owner. \n - This function is called before deleting the owner in a case when GetActionForDelete() == spl_Self. \~ */ - virtual void OnDeleteOwner( const MbAttributeContainer & owner ) = 0; - /** \} */ - - /// \ru Выдать поведение атрибута при изменении владельца. \en Get behavior of attribute when changing the owner. - OnChangeOwnerAction GetActionForChange () const { return static_cast(forChange); } - /// \ru Выдать поведение атрибута при конвертации владельца. \en Get behavior of attribute when converting the owner. - OnConvertOwnerAction GetActionForConvert () const { return static_cast(forConvert); } - /// \ru Выдать поведение атрибута при трансформировании владельца. \en Get behavior of attribute when transforming the owner. - OnTransformOwnerAction GetActionForTransform() const { return static_cast(forTransform); } - /// \ru Выдать поведение атрибута при копировании владельца. \en Get behavior of attribute when copying the owner. - OnCopyOwnerAction GetActionForCopy () const { return static_cast(forCopy); } - /// \ru Выдать поведение атрибута при объединении владельца. \en Get behavior of attribute when merging the owner. - OnMergeOwnerAction GetActionForMerge () const { return static_cast(forMerge); } - /// \ru Выдать поведение атрибута при замене владельца. \en Get behavior of attribute when replacing the owner. - OnReplaceOwnerAction GetActionForReplace () const { return static_cast(forReplace); } - /// \ru Выдать поведение атрибута при разделении владельца. \en Get behavior of attribute when splitting the owner. - OnSplitOwnerAction GetActionForSplit () const { return static_cast(forSplit); } - /// \ru Выдать поведение атрибута при удалении владельца. \en Get behavior of attribute when deleting the owner. - OnDeleteOwnerAction GetActionForDelete () const { return static_cast(forDelete); } - - /// \ru Задать поведение атрибута при изменении владельца. \en Set behavior of attribute when changing the owner. - void SetActionForChange ( OnChangeOwnerAction a ) { forChange = (uint8)a; } - /// \ru Задать поведение атрибута при конвертации владельца. \en Set behavior of attribute when converting the owner. - void SetActionForConvert ( OnConvertOwnerAction a ) { forConvert = (uint8)a; } - /// \ru Задать поведение атрибута при трансформировании владельца. \en Set behavior of attribute when transforming the owner. - void SetActionForTransform( OnTransformOwnerAction a ) { forTransform = (uint8)a; } - /// \ru Задать поведение атрибута при копировании владельца. \en Set behavior of attribute when copying the owner. - void SetActionForCopy ( OnCopyOwnerAction a ) { forCopy = (uint8)a; } - /// \ru Задать поведение атрибута при объедении владельца. \en Set behavior of attribute when merging the owner. - void SetActionForMerge ( OnMergeOwnerAction a ) { forMerge = (uint8)a; } - /// \ru Задать поведение атрибута при замене владельца. \en Set behavior of attribute when replacing the owner. - void SetActionForReplace ( OnReplaceOwnerAction a ) { forReplace = (uint8)a; } - /// \ru Задать поведение атрибута при разбиении владельца. \en Set behavior of attribute when splitting the owner. - void SetActionForSplit ( OnSplitOwnerAction a ) { forSplit = (uint8)a; } - /// \ru Задать поведение атрибута при удалении владельца. \en Set behavior of attribute when deleting the owner. - void SetActionForDelete ( OnDeleteOwnerAction a ) { forDelete = (uint8)a; } - - /// \ru Определить поведение атрибута по другому атрибуту. \en Define behavior of an attribute by another attribute. - void InitActions ( const MbAttribute & ); - - bool CanBeFree () const { return freeable; } - bool CanBeCopied() const { return copyable; } - - void SetCanBeFree ( bool b ) { freeable = b; } - void SetCanBeCopied( bool b ) { copyable = b; } - - /// \ru Выдать свойства объекта. \en Get properties of the object. - virtual void GetProperties( MbProperties & ); - /// \ru Установить свойства объекта. \en Set properties of object. - virtual size_t SetProperties( const MbProperties & ); - /// \ru Выдать заголовок свойства объекта. \en Get a name of object property. - virtual MbePrompt GetPropertyName() = 0; - - virtual bool IsFamilyRegistrable() const; - -DECLARE_PERSISTENT_CLASS( MbAttribute ) -OBVIOUS_PRIVATE_COPY( MbAttribute ) -}; - -IMPL_PERSISTENT_OPS( MbAttribute ) - -//------------------------------------------------------------------------------ -/** \brief \ru Объект для свойств. - \en Object for properties. \~ - \details \ru Объект для свойств. \n - \en Object for properties. \n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbAttributeAction : public MbRefItem { -private : - uint8 & forChange; ///< \ru Поведение атрибута при изменении владельца. \en Behavior of attribute when changing the owner. - uint8 & forConvert; ///< \ru Поведение атрибута при конвертации владельца. \en Behavior of attribute when converting the owner. - uint8 & forTransform; ///< \ru Поведение атрибута при трансформировании владельца. \en Behavior of attribute when transforming the owner. - uint8 & forCopy; ///< \ru Поведение атрибута при копировании владельца. \en Behavior of attribute when copying the owner. - uint8 & forMerge; ///< \ru Поведение атрибута при объединении владельца. \en Behavior of attribute when merging the owner. - uint8 & forReplace; ///< \ru Поведение атрибута при замене владельца. \en Behavior of attribute when replacing the owner. - uint8 & forSplit; ///< \ru Поведение атрибута при разделении владельца. \en Behavior of attribute when splitting the owner. - uint8 & forDelete; ///< \ru Поведение атрибута при удалении владельца. \en Behavior of attribute when deleting the owner. - bool & freeable; ///< \ru Свободность атрибута. \en Attribute freeness - bool & copyable; ///< \ru Разрешение копировать атрибут. \en Permission to copy attribute. - -public: - /// \ru Конструктор с параметрами. \en Constructor with parameters. - MbAttributeAction( uint8 & cha, uint8 & con, uint8 & tra, uint8 & cop, uint8 & mer, uint8 & rep, uint8 & spl, uint8 & del, - bool & fre, bool & cob ) - : MbRefItem() - , forChange( cha ) - , forConvert( con ) - , forTransform( tra ) - , forCopy( cop ) - , forMerge( mer ) - , forReplace( rep ) - , forSplit( spl ) - , forDelete( del ) - , freeable( fre ) - , copyable( cob ) {} - /// \ru Деструктор. \en Destructor. - ~MbAttributeAction() {} - -public: - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & ); - /// \ru Установить свойства объекта. \en Set properties of object. - void SetProperties( const MbProperties & ); - -OBVIOUS_PRIVATE_COPY( MbAttributeAction ) -}; - - -//------------------------------------------------------------------------------ -// \ru Системные строки атрибутов. \en System strings of attributes. -// --- -namespace c3d // namespace C3D -{ - /// \ru Подсказка для эквидистантной грани c нулевым значением эквидистанты. \en Hint for an offset face with the null value of offset. - const c3d::string_t str_ShellFace ( _T( "c3d_ShellFace" ) ); - /// \ru Подсказка для эквидистантной грани. \en Hint for an offset face. - const c3d::string_t str_OffsetFace ( _T( "c3d_OffsetFace" ) ); - /// \ru Подсказка для вскрываемой грани. \en Hint for an open face. - const c3d::string_t str_OpenFace ( _T( "c3d_OpenFace" ) ); - /// \ru Подсказка для доп.эквидистантного смещения слипшейся грани. \en Hint for an offset of a stuck face. - const c3d::string_t str_StuckOffset ( _T( "c3d_StuckOffset" ) ); - /// \ru Подсказка для удаляемой слипшейся грани. \en Hint for a deleted stuck face. - const c3d::string_t str_StuckDelete ( _T( "c3d_StuckDelete" ) ); - - /// \ru Подсказка для расшивки граней по ребру. \en Hint for separation neighbour faces by an edge. - const c3d::string_t str_UnstitchByEdge( _T( "c3d_UnstitchByEdge" ) ); - - /// \ru Подсказка для проверки идентификатора боковой грани. \en Hint for checking flank's identifier. - const c3d::string_t str_CheckFlankId ( _T( "c3d_CheckFlankId" ) ); - /// \ru Подсказка для порядкового номера оболочки. \en Hint for shell sequence number. - const c3d::string_t str_ShellSequenceNumber( _T( "c3d_ShellSequenceNumber" ) ); - - /// \ru Подсказка для сохраняемого объекта. \en Hint for kept object. - const c3d::string_t str_KeptObject ( _T( "c3d_KeptObject" ) ); - /// \ru Подсказка для удаляемого объекта. \en Hint for deleting object. - const c3d::string_t str_DeletingObject( _T( "c3d_DeletingObject" ) ); - /// \ru Подсказка для временного объекта. \en Hint for temporal object. - const c3d::string_t str_TemporalObject( _T( "c3d_TemporalObject" ) ); - - /**\ru Для плоской грани, сгибаемой в цилиндр - параметр u, который меньше соответствующего параметра любой точки грани, - сгибаемой в конус - угловой параметр луча, выходящего из начала координат плоскости параметров и не пересекающего контуры грани. - \en For a planar face bended in cylinder - u-parameter which is less than corresponding parameter of any point on the face, - bended in cone - angular parameter of the ray which goes out from the parameters plane origin and does not intersect contours of the face. \~*/ - const c3d::string_t str_BendMinAnlge ( _T( "BendMinAnlge" ) ); - /// \ru Для цилиндрической и конической грани параметр u, который меньше соответствующего параметра любой точки грани. \en For a cylindrical and conical face - parameter u which is less than corresponding parameter of any point on the face. - const c3d::string_t str_UnbendMinAngle( _T( "UnbendMinAngle" ) ); -} // namespace C3D - -#endif // __ATTRIBUTE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Атрибуты объекта. + \en Object attributes. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTRIBUTE_H +#define __ATTRIBUTE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbVector3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbMatrix3D; +class MATH_CLASS MbProperties; +class MATH_CLASS MbAttributeContainer; +class MbRegDuplicate; +class MbRegTransform; + + +class MATH_CLASS MbAttribute; +namespace c3d // namespace C3D +{ +typedef SPtr AttrSPtr; +typedef SPtr ConstAttrSPtr; + +typedef std::vector AttrVector; +typedef std::vector ConstAttrVector; + +typedef std::vector AttrSPtrVector; +typedef std::vector ConstAttrSPtrVector; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Типы атрибутов. + \en Types of attributes. \~ + \details \ru Типы атрибутов объектов геометрической модели. + Атрибуты объектов группируются по семействам. + \en Types of geometric model objects attributes. + Objects attributes are grouped by families. \~ + \ingroup Model_Attributes + */ +enum MbeAttributeType +{ + at_Undefined = 0, ///< \ru Неопределенный - используется при поиске как "любой". \en Undefined - used as "any" in search. \n + + // \ru Типы простых атрибутов. \en Types of elementary attributes. + at_ElementaryAttribute = 101, ///< \ru Простой атрибут. \en Elementary attribute. + at_Identifier = 102, ///< \ru Идентификатор. \en Identifier. + at_Color = 103, ///< \ru Цвет. \en Color. + at_Width = 104, ///< \ru Ширина линий. \en Lines width. + at_Style = 105, ///< \ru Стиль линий. \en Lines style. + at_Visual = 106, ///< \ru Свойства для OpenGL. \en Properties for OpenGL. + at_Selected = 107, ///< \ru Селектированность. \en Selection. + at_Visible = 108, ///< \ru Видимость. \en Visibility. + at_WireCount = 109, ///< \ru Количество u-линий и v-линий отрисовочной сетки. \en The number of u-mesh and v-mesh drawing lines. \~ + at_Changed = 110, ///< \ru Изменённость. \en Modification. + at_Dencity = 111, ///< \ru Плотность. \en Density. + at_NameAttribute = 112, ///< \ru Топологическое имя. \en Topological name. + at_UpdateStamp = 113, ///< \ru Метка времени обновления. \en Stamp of update time. + at_Embodiment = 114, ///< \ru Признак исполнения (варианта реализации модели). \en Indication of embodiment (variant of model implementation). + at_Elasticity = 115, ///< \ru Механические характеристики: модуль Юнга и коэффициент Пуассана. \en Mechanical properties: Young's modulus and Poisson's ratio. + at_Strains = 116, ///< \ru Деформации. \en The strains. + at_ElementaryLast = 200, ///< \ru Простые атрибуты вставлять перед этим значением. \en Elementary attributes should be inserted before this value. \n + + // \ru Типы обобщенных атрибутов. \en Types of common attributes. + at_CommonAttribute = 201, ///< \ru Обобщенный атрибут. \en Common attribute. + at_BoolAttribute = 202, ///< \ru Булев атрибут. \en Boolean attribute. + at_IntAttribute = 203, ///< \ru Целочисленный атрибут. \en Integer attribute. + at_DoubleAttribute = 204, ///< \ru Действительный атрибут. \en Double attribute. + at_StringAttribute = 205, ///< \ru Строковый атрибут. \en String attribute. + at_GeomAttribute = 206, ///< \ru Геометрический атрибут. \en Geometric attribute. \n + at_StampRibAttribute = 207, ///< \ru Атрибут ребра жесткости листового тела. \en Attribute of reinforcement rib of sheet solid. \n + at_Int64Attribute = 208, ///< \ru Атрибут int64. \en Int64 attribute. + at_BinaryAttribute = 209, ///< \ru Бинарный атрибут. \en Binary attribute. + at_SweptFlangeAttribute = 210, ///< \ru Атрибут отбортовки листового тела. \en Swept flange attribute of a sheet solid. \n + at_CommonLast = 300, ///< \ru Обобщенные атрибуты вставлять перед этим значением. \en Common attributes should be inserted before this value. \n + + // \ru Типы связующих атрибутов. \en Types of linking attributes. + at_LinkingAttribute = 301, ///< \ru Связующий атрибут. \en Linking attribute. + at_AnchorAttribute = 302, ///< \ru Якорь. \en Anchor. \n + + // \ru Типы директивных атрибутов. \en Types of directive attributes. + at_DirectiveAttribute = 401, ///< \ru Директивный атрибут. \en Directive attribute. + at_KeepUniqueKey = 402, ///< \ru Поддерживать уникальность ключей. \en Support unique keys. \n + + // \ru Типы изделия. \en Types of product attributes. + at_ProductAttribute = 501, ///< \ru Атрибут конвертеров \en Converters attribute + at_ModelInfo = 502, ///< \ru Сведения о модели в целом. \en Information about model itself. + at_PersonOrganizationInfo = 503, ///< \ru Лицо и организация. \en Person and organization information. + at_ProductInfo = 504, ///< \ru Сведения об изделии. \en Product info. + at_STEPTextDescription = 505, ///< \ru Описание STEP. \en STEP description. + at_STEPReferenceHolder = 506, ///< \ru Обратная ссылка. \en Back reference. \n + + // \ru Типы пользовательских атрибутов. \en Types of user attributes. + at_UserAttribute = 601, ///< \ru Пользовательский атрибут. \en User attribute. + at_UserFirst = 602, ///< \ru Первый пользовательский атрибут. \en First user attribute. + at_UserLast = 900, ///< \ru Последний пользовательский атрибут. \en Last user attribute. \n + + // \ru Типы внешних (внесистемных) атрибутов. \en Types of external (off-system) attributes. + at_ExternalAttribute = 901, ///< \ru Внешний атрибут. \en External attribute. + at_ExternalAttributeImp = 902, ///< \ru Подтип - внешний атрибут \en Subtype - external attribute. + + at_FreeItem = 1000, ///< \ru Тип для прочих объектов. \en Type for the other objects. + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Типы контейнеров атрибутов. + \en Types of attribute containers. \~ + \details \ru Типы контейнеров атрибутов наследников контейнера атрибутов. + Каждый отдельный атрибут может содержать свой контейнер атрибутов. + \en Types of attribute containers which are inheritors of attribute container. + Each separate attribute may have its attribute container. \~ + \ingroup Model_Attributes + */ +enum MbeImplicationType +{ + ace_Attribute, ///< \ru Контейнер атрибутов, содержащий другие атрибуты. \en Attribute container which contains other attributes. + ace_ModelItem, ///< \ru Контейнер атрибутов объектов геометрической модели. \en Container of geometric model objects attributes. + ace_TopItem, ///< \ru Контейнер атрибутов именованных топологических объектов. \en Container of named topological objects attributes. + ace_MeshItem, ///< \ru Контейнер атрибутов сеточных примитивов. \en Container of mesh primitives attributes. + ace_Model, ///< \ru Контейнер атрибутов геометрической модели. \en Container of geometric model attributes. + ace_AttribContainer, ///< \ru Контейнер атрибутов. \en Attribute container. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Атрибуты объекта. + \en Object attributes. \~ + \details \ru Атрибуты содержат информацию, дополняющую описание геометрической формы объекта. + Атрибут не является неотъемлемой частью объекта, а является элементом данных, которыми может быть наделен объект.\n + Атрибуты являются агентами передачи данных геометрического ядра от одного приложения другому приложению.\n + Атрибуты могут быть следующих типов.\n + Простой атрибут - атрибут несущий простую, однозначно интерпретируемую, информацию, например, цвет, признак выбора.\n + Обобщенный атрибут - атрибут стандартного типа со строковым наименованием, + например, имя, целое число, вещественное число, строка, точка, вектор, указатель.\n + С помощью таких атрибутов приложения могут обмениваться какой либо специфичной информацией + без необходимости разработки дополнительных комплексных атрибутов.\n + Комплексный атрибут - атрибут состоящий из предопределенного набора данных, + описывающих природу атрибута и его смысловую нагрузку, а так же способ его интерпретации. + Такими атрибутами могут описываться некоторые ограничения или простые зависимости а так же аннотационные объекты.\n + Директивный атрибут - атрибут определяющий предназначения объекта или действия которые необходимо с ним произвести, + например атрибут "вычитание" подразумевает что некое тело предназначено для вычитания из другого тела, + и не важно из какого. + Связующий атрибут - атрибут предназначенный для связи объекта геометрического ядра с абстрактным контейнером данных, + то есть набором данных, формат и смысловая нагрузка которых не может быть описана в рамках других атрибутов.\n + \en Attributes contain information supplementing description of object geometric shape. + Attribute is not an intrinsic part of the object, but it is an element of data which the object may contain. \n + Attributes are geometric kernel agents for transferring data from one application to another. \n + The possible types of attributes are the following. \n + Elementary attribute - an attribute which reflects simple and clearly interpreted information, for example, color or selection attribute.\n + Common attribute - attribute of standard type with string naming, + for example: name, integer value, double value, string, point, vector, pointer. \n + Applications may communicate any specific information using such attributes + without necessity of additional complex attributes developing. \n + Complex attribute - an attribute which consists of predefined data set, + which describe a nature of attribute, its semantic meaning and a way of its interpretation. + Such attributes can describe some of constraints or simple dependences and annotation objects.\n + Directive attribute - an attribute defining the purpose of object or actions which should be performed with it, + for example, an attribute "subtraction" implies that one solid is purposed for subtraction from another, + no matter from what exactly. + Linking attribute - an attribute designed for linking of geometric kernel object with abstract container of data, + i.e. a set of data, which format and semantic meaning can not be described by other attributes. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbAttribute : public MbRefItem, + public TapeBase +{ +public: + /**\ru Поведение атрибута при изменении владельца, не связанном с другими описанными действия. + \en Behavior of attribute which is not associated with other described actions when changing the owner. \~ */ + enum OnChangeOwnerAction { + chn_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnChangeOwner. \en Behavior defined by the virtual function OnChangeOwner. + chn_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + chn_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + chn_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при перерождении объекта в другой объект. + \en Behavior of attribute when an object regenerates in other object. \~ */ + enum OnConvertOwnerAction { + cnv_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnConvertOwner. \en Behavior defined by the virtual function OnConvertOwner. + cnv_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + cnv_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + cnv_Copy, ///< \ru Скопировать атрибут и прицепить его копию к копии владельца. \en Copy an attribute and attach its copy to an owner copy. + cnv_Convert, ///< \ru Конвертировать атрибут и прицепить результат к копии владельца. \en Copy an attribute and attach the result to an owner copy. + cnv_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при преобразовании владельца (по матрице). + \en Behaviour of attribute when transforming the owner (by the matrix). \~ */ + enum OnTransformOwnerAction { + trn_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnTransformOwner. \en Behavior defined by the virtual function OnTransformOwner. + trn_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + trn_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + trn_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при копировании владельца. + \en Behaviour of attribute when copying the owner. \~ */ + enum OnCopyOwnerAction { + cpy_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnCopyOwner. \en Behavior defined by the virtual function OnCopyOwner. + cpy_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + cpy_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + cpy_Copy, ///< \ru Скопировать атрибут и прицепить его копию к копии владельца. \en Copy an attribute and attach its copy to an owner copy. + cpy_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при объединении владельца с другим объектом. + \en Behaviour of attribute when merging of the owner with another object. \~ */ + enum OnMergeOwnerAction { + mrg_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnMergeOwner. \en Behavior is defined by the virtual function OnMergeOwner. + mrg_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + mrg_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + mrg_KeepAll, ///< \ru Передать атрибут от поглощаемого объекта поглощающему объекту без замещения. \en Transmit attribute from absorbed object to absorbing object without replacing. + mrg_KeepRep, ///< \ru Передать атрибут от поглощаемого объекта поглощающему объекту с замещением. \en Transmit attribute from absorbed object to absorbing object with replacing. + mrg_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при замещении владельца с другим объектом. + \en Behavior of attribute when replacing the owner by another object. \~ */ + enum OnReplaceOwnerAction { + rep_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnReplaceOwner. \en Behavior is defined by the virtual function OnReplaceOwner. + rep_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + rep_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + rep_KeepAll, ///< \ru Передать атрибут от замещаемого объекта замещающему объекту без замещения. \en Transmit attribute from replaced object to substitutional object without replacing. + rep_KeepRep, ///< \ru Передать атрибут от замещаемого объекта замещающему объекту с замещением. \en Transmit attribute from replaced object to substitutional object with replacing. + rep_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при разделении владельца. + \en Behavior of attribute when splitting the owner. \~ */ + enum OnSplitOwnerAction { + spl_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnSplitOwner. \en Behavior is defined by the virtual function OnSplitOwner. + spl_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + spl_Keep, ///< \ru Сохранить атрибут, т.е. ничего с ним не делать. \en Save attribute, i.e. do not do anything with it. + spl_Copy, ///< \ru Размножить(скопировать) атрибут для каждого результата разбиения. \en Duplicate (copy) attribute for each result of splitting. + spl_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + + /**\ru Поведение атрибута при удалении владельца. + \en Behavior of attribute when deleting the owner. \~ */ + enum OnDeleteOwnerAction { + del_Self = 0, ///< \ru Поведение, определяемое виртуальной функцией OnDeleteOwner. \en Behavior defined by the virtual function OnDeleteOwner. + del_Free, ///< \ru Освободить атрибут, если это возможно, в противном случае удалить. \en Free attribute if it is possible, otherwise delete it. + del_ActCount, ///< \ru Количество элементов в перечислении (добавлять перед данным значением). \en The number of elements in enumeration (add before the given value). + }; + +private : + uint8 forChange; ///< \ru Поведение атрибута при изменении владельца. \en Behavior of attribute when changing the owner. + uint8 forConvert; ///< \ru Поведение атрибута при конвертации владельца. \en Behavior of attribute when converting the owner. + uint8 forTransform; ///< \ru Поведение атрибута при трансформировании владельца. \en Behavior of attribute when transforming the owner. + uint8 forCopy; ///< \ru Поведение атрибута при копировании владельца. \en Behavior of attribute when copying the owner. + uint8 forMerge; ///< \ru Поведение атрибута при объединении владельца. \en Behavior of attribute when merging the owner. + uint8 forReplace; ///< \ru Поведение атрибута при замене владельца. \en Behavior of attribute when replacing the owner. + uint8 forSplit; ///< \ru Поведение атрибута при разделении владельца. \en Behavior of attribute when splitting the owner. + uint8 forDelete; ///< \ru Поведение атрибута при удалении владельца. \en Behavior of attribute when deleting the owner. + bool freeable; ///< \ru Свободность атрибута. \en Attribute freeness + bool copyable; ///< \ru Разрешение копировать атрибут. \en Permission to copy attribute. + +protected : + /// \ru Конструктор без параметров для наследников. \en Constructor without parameters for inheritors. + MbAttribute(); +public : + /// \ru Деструктор. \en Destructor. + virtual ~MbAttribute(); + +public : + /** \ru \name Общие функции атрибутов + \en \name Common functions of attributes + \{ */ + /// \ru Выдать регистрационный тип (для копирования, дублирования). \en Get registrational type (for copying, duplication) + virtual MbeRefType RefType() const; + /// \ru Выдать тип контейнера атрибутов. \en Get attribute container type. + virtual MbeImplicationType ImplicationType() const; + /// \ru Выдать тип атрибута. \en Get attribute type. + virtual MbeAttributeType AttributeFamily() const = 0; + /// \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; + /** \brief \ru Определить, являются ли объекты равными. + \en Determine whether objects are equal. \~ + \details \ru Равными считаются однотипные объекты, все данные которых одинаковы (равны). + \en Objects of the same types with similar (equal) data are considered to be equal. \~ + \param[in] item - \ru Объект для сравнения. + \en Objects for comparison. \~ + \param[in] accuracy - \ru Точность сравнения. + \en The accuracy to compare. \~ + \return \ru Равны ли объекты. + \en Whether objects are equal. \~ + */ + virtual bool IsSame( const MbAttribute & item, double accuracy ) const = 0; + /// \ru Инициализировать данные по присланным. \en Initialize data. + virtual bool Init( const MbAttribute & ) = 0; + + /// \ru Проверить тип атрибута. \en Check an attribute type. + bool IsA( MbeAttributeType t ) const { return t == AttributeFamily(); } + /** \} */ + + /** \ru \name Действия над объектами геометрического ядра, влияющие на состояние атрибутов + \en \name Actions with objects of geometric kernel influencing on states of attributes. + \{ */ + /** \brief \ru Выполнить действия при изменении владельца, не связанное с другими действиями. + \en Perform actions which are not associated with other actions when changing the owner. \~ + \details \ru Действия при изменении владельца, не связанное с другими действиями. \n + Вызывается после изменения владеющего объекта при условии GetActionForChange() == chn_Self. + \en Actions which are not associated with other actions when changing the owner. \n + This function is called after changing the owning object in a case when GetActionForChange() == chn_Self. \~ */ + virtual void OnChangeOwner( const MbAttributeContainer & owner ) = 0; + + /**\ru Выполнить действия при конвертации владельца, \n + Вызывается после конвертирования владеющего объекта при условии GetActionForConvert() == cnv_Self. \n + В качестве входного параметра передается результат конвертирования объекта. + \en Perform actions when converting the owner, \n + This function is called after converting the owning object in a case when GetActionForConvert() == cnv_Self. \n + The result of object converting is passed as input parameter. \~ */ + virtual void OnConvertOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; + + /**\ru Выполнить действия при трансформировании владельца, \n + Вызывается после трансформирования владеющего объекта при условии GetActionForTransform() == trn_Self. + В качестве входного параметра может передаваться регистратор трансформированных объектов. + \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; + + /**\ru Выполнить действия при перемещении владельца. \n + Вызывается после перемещения владеющего объекта при условии GetActionForTransform() == trn_Self. + В качестве входного параметра может передаваться регистратор трансформированных объектов. + \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; + + /**\ru Выполнить действия при вращении владельца. \n + Вызывается после вращения владеющего объекта при условии GetActionForTransform() == trn_Self. + В качестве входного параметра может передаваться регистратор трансформированных объектов. + \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; + + /**\ru Выполнить действия при копировании владельца. \n + Вызывается после копирования владеющего объекта при условии GetActionForCopy() == cpy_Self. \n + В качестве входных параметров передаются: копия владеющего объекта и регистратор скопированных объектов. + \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; + + /**\ru Выполнить действия при объединении владельца. \n + Вызывается перед слиянием владельца при условии GetActionForMerge() == mrg_Self. \n + В качестве входного параметра передается объект который будет поглощен. + \en Perform actions when merging the owner. \n + This function is called before merging the owner in a case when GetActionForMerge() == mrg_Self. \n + The object which will be absorbed is passed as input parameter. \~ */ + virtual void OnMergeOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; + + /**\ru Выполнить действия при замене владельца. \n + Вызывается перед выполнением замены владельца при условии GetActionForReplace() == rep_Self. \n + В качестве входного параметра передается объект - заместитель. + \en Perform actions when replacing the owner. \n + This function is called before replacing the owner in a case when GetActionForReplace() == rep_Self. \n + The substitutional object is passed as input parameter. \~ */ + virtual void OnReplaceOwner( const MbAttributeContainer & owner, MbAttributeContainer & other ) = 0; + + /**\ru Выполнить действия при разделении владельца. \n + Вызывается после разбиения владеющего объекта при условии GetActionForSplit() == spl_Self. \n + В качестве входного параметра передается контейнер результатов разбиения. + \en Perform actions when splitting the owner. \n + This function is called after splitting the owning object in a case when GetActionForSplit() == spl_Self. \n + The container of splitting results is passed as input parameter. \~ */ + virtual void OnSplitOwner( const MbAttributeContainer & owner, const std::vector & others ) = 0; + + /**\ru Выполнить действия при удалении владельца. \n + Вызывается перед удалением объекта при условии GetActionForDelete() == spl_Self. + \en Perform actions when deleting the owner. \n + This function is called before deleting the owner in a case when GetActionForDelete() == spl_Self. \~ */ + virtual void OnDeleteOwner( const MbAttributeContainer & owner ) = 0; + /** \} */ + + /// \ru Выдать поведение атрибута при изменении владельца. \en Get behavior of attribute when changing the owner. + OnChangeOwnerAction GetActionForChange () const { return static_cast(forChange); } + /// \ru Выдать поведение атрибута при конвертации владельца. \en Get behavior of attribute when converting the owner. + OnConvertOwnerAction GetActionForConvert () const { return static_cast(forConvert); } + /// \ru Выдать поведение атрибута при трансформировании владельца. \en Get behavior of attribute when transforming the owner. + OnTransformOwnerAction GetActionForTransform() const { return static_cast(forTransform); } + /// \ru Выдать поведение атрибута при копировании владельца. \en Get behavior of attribute when copying the owner. + OnCopyOwnerAction GetActionForCopy () const { return static_cast(forCopy); } + /// \ru Выдать поведение атрибута при объединении владельца. \en Get behavior of attribute when merging the owner. + OnMergeOwnerAction GetActionForMerge () const { return static_cast(forMerge); } + /// \ru Выдать поведение атрибута при замене владельца. \en Get behavior of attribute when replacing the owner. + OnReplaceOwnerAction GetActionForReplace () const { return static_cast(forReplace); } + /// \ru Выдать поведение атрибута при разделении владельца. \en Get behavior of attribute when splitting the owner. + OnSplitOwnerAction GetActionForSplit () const { return static_cast(forSplit); } + /// \ru Выдать поведение атрибута при удалении владельца. \en Get behavior of attribute when deleting the owner. + OnDeleteOwnerAction GetActionForDelete () const { return static_cast(forDelete); } + + /// \ru Задать поведение атрибута при изменении владельца. \en Set behavior of attribute when changing the owner. + void SetActionForChange ( OnChangeOwnerAction a ) { forChange = (uint8)a; } + /// \ru Задать поведение атрибута при конвертации владельца. \en Set behavior of attribute when converting the owner. + void SetActionForConvert ( OnConvertOwnerAction a ) { forConvert = (uint8)a; } + /// \ru Задать поведение атрибута при трансформировании владельца. \en Set behavior of attribute when transforming the owner. + void SetActionForTransform( OnTransformOwnerAction a ) { forTransform = (uint8)a; } + /// \ru Задать поведение атрибута при копировании владельца. \en Set behavior of attribute when copying the owner. + void SetActionForCopy ( OnCopyOwnerAction a ) { forCopy = (uint8)a; } + /// \ru Задать поведение атрибута при объедении владельца. \en Set behavior of attribute when merging the owner. + void SetActionForMerge ( OnMergeOwnerAction a ) { forMerge = (uint8)a; } + /// \ru Задать поведение атрибута при замене владельца. \en Set behavior of attribute when replacing the owner. + void SetActionForReplace ( OnReplaceOwnerAction a ) { forReplace = (uint8)a; } + /// \ru Задать поведение атрибута при разбиении владельца. \en Set behavior of attribute when splitting the owner. + void SetActionForSplit ( OnSplitOwnerAction a ) { forSplit = (uint8)a; } + /// \ru Задать поведение атрибута при удалении владельца. \en Set behavior of attribute when deleting the owner. + void SetActionForDelete ( OnDeleteOwnerAction a ) { forDelete = (uint8)a; } + + /// \ru Определить поведение атрибута по другому атрибуту. \en Define behavior of an attribute by another attribute. + void InitActions ( const MbAttribute & ); + + bool CanBeFree () const { return freeable; } + bool CanBeCopied() const { return copyable; } + + void SetCanBeFree ( bool b ) { freeable = b; } + void SetCanBeCopied( bool b ) { copyable = b; } + + /// \ru Выдать свойства объекта. \en Get properties of the object. + virtual void GetProperties( MbProperties & ); + /// \ru Установить свойства объекта. \en Set properties of object. + virtual size_t SetProperties( const MbProperties & ); + /// \ru Выдать заголовок свойства объекта. \en Get a name of object property. + virtual MbePrompt GetPropertyName() = 0; + + virtual bool IsFamilyRegistrable() const; + +DECLARE_PERSISTENT_CLASS( MbAttribute ) +OBVIOUS_PRIVATE_COPY( MbAttribute ) +}; + +IMPL_PERSISTENT_OPS( MbAttribute ) + +//------------------------------------------------------------------------------ +/** \brief \ru Объект для свойств. + \en Object for properties. \~ + \details \ru Объект для свойств. \n + \en Object for properties. \n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbAttributeAction : public MbRefItem { +private : + uint8 & forChange; ///< \ru Поведение атрибута при изменении владельца. \en Behavior of attribute when changing the owner. + uint8 & forConvert; ///< \ru Поведение атрибута при конвертации владельца. \en Behavior of attribute when converting the owner. + uint8 & forTransform; ///< \ru Поведение атрибута при трансформировании владельца. \en Behavior of attribute when transforming the owner. + uint8 & forCopy; ///< \ru Поведение атрибута при копировании владельца. \en Behavior of attribute when copying the owner. + uint8 & forMerge; ///< \ru Поведение атрибута при объединении владельца. \en Behavior of attribute when merging the owner. + uint8 & forReplace; ///< \ru Поведение атрибута при замене владельца. \en Behavior of attribute when replacing the owner. + uint8 & forSplit; ///< \ru Поведение атрибута при разделении владельца. \en Behavior of attribute when splitting the owner. + uint8 & forDelete; ///< \ru Поведение атрибута при удалении владельца. \en Behavior of attribute when deleting the owner. + bool & freeable; ///< \ru Свободность атрибута. \en Attribute freeness + bool & copyable; ///< \ru Разрешение копировать атрибут. \en Permission to copy attribute. + +public: + /// \ru Конструктор с параметрами. \en Constructor with parameters. + MbAttributeAction( uint8 & cha, uint8 & con, uint8 & tra, uint8 & cop, uint8 & mer, uint8 & rep, uint8 & spl, uint8 & del, + bool & fre, bool & cob ) + : MbRefItem() + , forChange( cha ) + , forConvert( con ) + , forTransform( tra ) + , forCopy( cop ) + , forMerge( mer ) + , forReplace( rep ) + , forSplit( spl ) + , forDelete( del ) + , freeable( fre ) + , copyable( cob ) {} + /// \ru Деструктор. \en Destructor. + ~MbAttributeAction() {} + +public: + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties & ); + /// \ru Установить свойства объекта. \en Set properties of object. + void SetProperties( const MbProperties & ); + +OBVIOUS_PRIVATE_COPY( MbAttributeAction ) +}; + + +//------------------------------------------------------------------------------ +// \ru Системные строки атрибутов. \en System strings of attributes. +// --- +namespace c3d // namespace C3D +{ + /// \ru Подсказка для эквидистантной грани c нулевым значением эквидистанты. \en Hint for an offset face with the null value of offset. + const_expr TCHAR c3dStr_ShellFace[] = _T( "c3d_ShellFace" ); + /// \ru Подсказка для эквидистантной грани. \en Hint for an offset face. + const_expr TCHAR c3dStr_OffsetFace[] = _T( "c3d_OffsetFace" ); + /// \ru Подсказка для вскрываемой грани. \en Hint for an open face. + const_expr TCHAR c3dStr_OpenFace[] = _T( "c3d_OpenFace" ); + /// \ru Подсказка для доп.эквидистантного смещения слипшейся грани. \en Hint for an offset of a stuck face. + const_expr TCHAR c3dStr_StuckOffset[] = _T( "c3d_StuckOffset" ); + /// \ru Подсказка для удаляемой слипшейся грани. \en Hint for a deleted stuck face. + const_expr TCHAR c3dStr_StuckDelete[] = _T( "c3d_StuckDelete" ); + + /// \ru Подсказка для расшивки граней по ребру. \en Hint for separation neighbour faces by an edge. + const_expr TCHAR c3dStr_UnstitchByEdge[] = _T( "c3d_UnstitchByEdge" ); + /// \ru Подсказка для проверки идентификатора боковой грани. \en Hint for checking flank's identifier. + const_expr TCHAR c3dStr_CheckFlankId[] = _T( "c3d_CheckFlankId" ); + /// \ru Подсказка для порядкового номера оболочки. \en Hint for shell sequence number. + const_expr TCHAR c3dStr_ShellSequenceNumber[] = _T( "c3d_ShellSequenceNumber" ); + /// \ru Подсказка для сохраняемого объекта. \en Hint for kept object. + const_expr TCHAR c3dStr_KeptObject[] = _T( "c3d_KeptObject" ); + /// \ru Подсказка для удаляемого объекта. \en Hint for deleting object. + const_expr TCHAR c3dStr_DeletingObject[] = _T( "c3d_DeletingObject" ); + /// \ru Подсказка для временного объекта. \en Hint for temporal object. + const_expr TCHAR c3dStr_TemporalObject[] = _T( "c3d_TemporalObject" ); + /// \ru Подсказка для временного маркера слитых атрибутов. \en Hint for a temporary marker of merged attributes. + const_expr TCHAR c3dStr_MergedStateMarker[] = _T( "c3d_MergedStateMarker" ); + + /**\ru Для плоской грани, сгибаемой в цилиндр - параметр u, который меньше соответствующего параметра любой точки грани, + сгибаемой в конус - угловой параметр луча, выходящего из начала координат плоскости параметров и не пересекающего контуры грани. + \en For a planar face bended in cylinder - u-parameter which is less than corresponding parameter of any point on the face, + bended in cone - angular parameter of the ray which goes out from the parameters plane origin and does not intersect contours of the face. \~*/ + const_expr TCHAR c3dStr_BendMinAnlge[] = _T( "BendMinAnlge" ); + /// \ru Для цилиндрической и конической грани параметр u, который меньше соответствующего параметра любой точки грани. \en For a cylindrical and conical face - parameter u which is less than corresponding parameter of any point on the face. + const_expr TCHAR c3dStr_UnbendMinAngle[] = _T( "UnbendMinAngle" ); + /// \ru Подсказка для продленной грани. \en Hint for extended face. + const_expr TCHAR c3dStr_ExtendedFace[] = _T( "c3d_ExtendedFace" ); + + /// \ru Подсказка для контрольного значения массы. \en Hint for the mass validation property. + const_expr TCHAR c3dStr_ValidationPropertyMassExchange[] = _T( "c3d_ValidationPropertyMassExchange" ); + /// \ru Подсказка для контрольного значения объёма. \en Hint for the volume validation property. + const_expr TCHAR c3dStr_ValidationPropertyVolumeExchange[] = _T( "c3d_ValidationPropertyVolumeExchange" ); + /// \ru Подсказка для контрольного значения площади поверхности. \en Hint for the surface area validation property. + const_expr TCHAR c3dStr_ValidationPropertySurfaceAreaExchange[] = _T( "c3d_ValidationPropertySurfaceAreaExchange" ); + /// \ru Подсказка для идентификатора элемента при обмене данными. \en Hint for the item identifier in model exchange operations. + const_expr TCHAR c3dStr_ItemIdentifierExchange[] = _T( "c3d_ItemIdentifierExchange" ); +} // namespace C3D + +#endif // __ATTRIBUTE_H diff --git a/C3d/Include/attribute_container.h b/C3d/Include/attribute_container.h index ffbd83f..ad82ea5 100644 --- a/C3d/Include/attribute_container.h +++ b/C3d/Include/attribute_container.h @@ -1,338 +1,339 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контейнер атрибутов. - \en An attribute container. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ATTRIBUTE_CONTAINER_H -#define __ATTRIBUTE_CONTAINER_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS reader; -class MATH_CLASS writer; -class MATH_CLASS MbVector3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbMatrix3D; -class MATH_CLASS MbAttribute; -class MATH_CLASS MbUserAttribute; -class MATH_CLASS MbExternalAttribute; -class MATH_CLASS MbProperties; -class MbRegDuplicate; -class MbRegTransform; - - -//------------------------------------------------------------------------------ -/** \brief \ru Контейнер атрибутов. - \en An attribute container. \~ - \details \ru Контейнер атрибутов. \n - От данного класса наследуются объекты модели геометрического ядра MbItem - и топологические объекты с именем MbTopologyItem .\n - Наследники данного класса содержат атрибуты.\n - Методами данного класса выполняются действия над атрибутами объектов геометрического ядра.\n - Атрибут может влиять на состояние атрибута через его владельца, - тo есть геометрическое ядро предусматривает возможность передачи атрибутам информации об изменениях - их владельцев посредством вызовов предопределенных функций у самого атрибута.\n - Кроме передачи самой информации об изменениях происходящих с владельцем, - предусмотрена возможность определять поведение атрибута при этих изменениях путем выбора - одного из предопределенных типов поведения на каждое изменения владельца.\n - Типы действий, влияющих на состояние атрибутов.\n - Копирование, например, при создании копии тела. Действие над атрибутом производится после копирования владеющего объекта.\n - Разделение, например, разделение грани на две части при вырезании. - Действие над атрибутом производится после разбиения владеющего объекта.\n - Слияние, например, слияние граней при булевых операциях. - Действие над атрибутом производится перед выполнением слияния объектов. - Обрабатываются атрибуты всех объектов, участвующих в слиянии.\n - Изменение, не связанное с разделением или слиянием. - Действие над атрибутом производится после изменения владеющего объекта.\n - Преобразование, например, поворот или параллельный перенос. - Действие над атрибутом производится после преобразования владеющего объекта.\n - Подмена, например замена одной грани тела на другую. Действие над атрибутом производится перед выполнением замены объектов. - Обрабатываются атрибуты всех объектов, участвующих в замене.\n - Удаление объекта. Действие над атрибутом производится перед удалением объекта.\n - \en An attribute container. \n - The inheritors of this class are: objects of geometric kernel model of type MbItem - and topological objects of type MbTopologyItem.\n - Inheritors of this class contain attributes.\n - Operations with attributes of geometric kernel objects are performed by methods of this class.\n - Attribute can affect attribute state using its owner, - i.e. geometric kernel provides an opportunity for transmission to attributes the information about changes - of their owners by calling the predefined functions of the attribute.\n - In addition to transfer of information about changes occurring with owner - provided a possibility to determine the behavior of attribute with these changes by selecting of - one of the predefined types of behavior for each changing of the owner.\n - Types of actions that affect the states of attributes.\n - Copying, for example, when creating a copy of solid. Action on attribute is performed after copying of owning object.\n - Splitting. For example, splitting of a face into two parts in cutting. - Action on attribute is performed after splitting of owning object.\n - Merging. For example, merging of faces in boolean operations. - Action on attribute is performed after merging of owning object.\n - Attributes of all objects involved in merging are processed.\n - Changing which is not associated with splitting or merging. - Action on attribute is performed after changing of owning object.\n - Transformation. For example, rotation or parallel translation. - Action on attribute is performed after transformation of owning object.\n - Replacement. For example, replacement of one face of a solid to another. Action on attribute is performed after replacement of objects. - Attributes of all objects involved in replacement are processed.\n - Deletion of an object. Action on attribute is performed after deletion of an object.\n \~ - \ingroup Model_Attributes -*/ -// --- -class MATH_CLASS MbAttributeContainer -{ -typedef MultiMap AttrMap_t; - -private: - AttrMap_t attributes; ///< \ru Множество атрибутов. \en Set of attributes. - -protected: - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - MbAttributeContainer( const MbAttributeContainer &, MbRegDuplicate * ); -public: - /// \ru Конструктор без параметров. \en Constructor without parameters. - MbAttributeContainer(); - /// \ru Конструктор по атрибуту. \en Constructor by attribute. - MbAttributeContainer( MbAttribute & ); - /// \ru Деструктор. \en Destructor. - virtual ~MbAttributeContainer(); - -public: - - /// \ru Выдать тип контейнера атрибутов. \en Get attribute container type. - virtual MbeImplicationType ImplicationType() const { return ace_AttribContainer; } - - /** \ru \name Общие функции над атрибутами - \en \name Common functions of attributes - \{ */ - /// \ru Cдублировать атрибуты присланного объекта, свои отпустить. \en Duplicate attributes of a given object, release existing attributes. - void AttributesAssign( const MbAttributeContainer & ); - /// \ru Выдать количество объектов. \en Get the number of objects. - size_t AttributesCount() const { return attributes.Count(); } - /// \ru Удалить все атрибуты из контейнера. \en Delete all attributes from container. - void RemoveAttributes(); - - /// \ru Добавить атрибут в контейнер. \en Add attribute in container. - MbAttribute * AddAttribute( MbAttribute *, bool checkSame = true ); - /// \ru Добавить атрибут в контейнер (всегда копирует атрибут). \en Add attribute in container (always copies the attribute). - MbAttribute * AddAttribute( const MbAttribute &, bool checkSame = true ); - /// \ru Выдать атрибуты заданного семейства. \en Get attributes of a given family. - void GetAttributes( c3d::AttrVector &, MbeAttributeType aFamily, MbeAttributeType subType ) const; - /// \ru Выдать атрибуты заданного типа. \en Get attributes of a given type. - void GetAttributes( c3d::AttrVector &, MbeAttributeType aType ) const; - /// \ru Выдать атрибуты по строке описания. \en Get attributes using sample of description string. - void GetCommonAttributes( c3d::AttrVector &, const c3d::string_t & samplePrompt, MbeAttributeType subType = at_Undefined ) const; - /// \ru Выдать строковые атрибуты по строке содержания. \en Get string attributes using sample of contents of the string. - void GetStringAttributes( c3d::AttrVector &, const c3d::string_t & sampleContent ) const; - - /// \ru Выдать атрибут заданного типа, если их несколько - то первый попавшийся. \en Get an attribute of a given type, the first one is returned if there are many. - //const MbAttribute * GetAttribute( MbeAttributeType subType ) const; - /// \ru Удалить атрибут из контейнера. \en Delete an attribute from container. - bool RemoveAttribute( const MbAttribute *, bool checkAccuracySame = false, double accuracy = LENGTH_EPSILON ); - /// \ru Удалить атрибуты заданного типа. \en Delete attributes of a given type. - bool RemoveAttributes( MbeAttributeType type, MbeAttributeType subType ); - - /// \ru Выдать простой атрибут данного подтипа. \en Get a simple attribute of a given subtype. - const MbAttribute * GetSimpleAttribute( MbeAttributeType ) const; - /// \ru Выдать простой атрибут данного подтипа. \en Get a simple attribute of a given subtype. - MbAttribute * SetSimpleAttribute( MbeAttributeType ); - /// \ru Установить простой атрибут данного подтипа. \en Set a simple attribute of a given subtype. - MbAttribute * SetSimpleAttribute( MbAttribute * simpAttr ); - /// \ru Установить простой атрибут данного подтипа (всегда копирует атрибут). \en Set a simple attribute of a given subtype (always copies the attribute). - MbAttribute * SetSimpleAttribute( const MbAttribute & simpAttr ); - /// \ru Удалить простой атрибут(один и более) данного подтипа. \en Delete simple attributes (one or more) of a given subtype. - void RemoveSimpleAttribute( MbeAttributeType ); - /// \ru Отдать простой атрибут данного подтипа. \en Detach a simple attribute of a given subtype. - MbAttribute * DetachSimpleAttribute( MbeAttributeType ); - - /// \ru Выдать пользовательский атрибут данного подтипа. \en Get a user attribute of a given subtype. - void GetUserAttributes( std::vector & attrs, const MbUserAttribType & type ) const; - /// \ru Удалить пользовательский атрибут (один и более) данного подтипа. \en Delete user attributes (one or more) of a given subtype. - void RemoveUserAttributes( const MbUserAttribType & type ); - /// \ru Отдать пользовательский атрибут данного подтипа. \en Detach a user attribute of a given subtype. - void DetachUserAttributes( std::vector & attrs, const MbUserAttribType & type ); - - /// \ru Преобразовать из пользовательского в "системный" \en Convert user attribute to "system" one - static MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & ); - /// \ru Преобразовать из "системного" в пользовательский \en Convert "system" attribute to user one - static MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & ); - - /// \ru Выполнить действия при изменении атрибутов. \en Perform actions when changing the attributes. - void AttributesChange (); - /// \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 ); - /// \ru Выполнить действия при перемещении атрибутов. \en Perform actions when moving the attributes. - void AttributesMove ( const MbVector3D &, MbRegTransform * = NULL ); - /// \ru Выполнить действия при вращении атрибутов. \en Perform actions when rotating the attributes. - void AttributesRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); - /// \ru Выполнить действия при копировании атрибутов. \en Perform actions when copying the attributes. - void AttributesCopy ( MbAttributeContainer & other, MbRegDuplicate * = NULL ) const; - /// \ru Выполнить действия при объединении атрибутов. \en Perform actions when merging the attributes. - void AttributesMerge ( MbAttributeContainer & other ); - /// \ru Выполнить действия при замене атрибутов. \en Perform actions when replacing the attributes. - void AttributesReplace( MbAttributeContainer & other ); - /// \ru Выполнить действия при разделении атрибутов. \en Perform actions when splitting the attributes. - void AttributesSplit ( const std::vector & others ); - /// \ru Выполнить действия при удалении атрибутов. \en Perform actions when deleting the attributes. - void AttributesDelete (); - /** \} */ - - /** \ru \name Функции простых атрибутов объекта. - \en \name Functions of object's simple attributes. - \{ */ - /// \ru Установить плотность объекта. \en Set density of an object. - void SetDensity( double ); - /// \ru Выдать плотность объекта. \en Get density of an object. - double GetDensity() const; - - /// \ru Установить визуальные свойства объекта. \en Set visual properties of the object. - void SetVisual( float a, float d, float sp, float sh, float t, float e ); - /** \brief \ru Выдать визуальные свойства объекта. - \en Get visual properties of the object. \~ - \details \ru Выдать визуальные свойства объекта. - \en Get visual properties of the object. \~ - \param[out] a - \ru Коэффициент общего фона (рассеянного освещения) - \en Coefficient of backlighting \~ - \param[out] d - \ru Коэффициент диффузного отражения - \en Coefficient of diffuse reflection \~ - \param[out] s - \ru Коэффициент зеркального отражения - \en Coefficient of specular reflection \~ - \param[out] h - \ru Блеск (показатель степени в законе зеркального отражения) - \en Shininess (index according to the law of specular reflection) \~ - \param[out] t - \ru Коэффициент непрозрачности - \en Coefficient of total reflection (opacity coefficient) \~ - \param[out] e - \ru Коэффициент излучения - \en Emissivity coefficient \~ - \return \ru true если есть такой атрибут \n false в противном случае - \en True if there is the attribute MbVisual \n otherwise false. \~ - */ - bool GetVisual( float & a, float & d, float & sp, float & sh, float & t, float & e ) const; - - /// \ru Есть ли у объекта свой цвет. \en . - - /** \brief \ru Есть ли у объекта свой цвет. - \en Whether the object is colored. \~ - \details \ru Есть ли у объекта свой цвет. - \en Whether the object is colored. \~ - \return \ru true если есть такой атрибут \n false в противном случае - \en True if there is the attribute MbColor \n otherwise false. \~ - */ - bool IsColored() const { return (GetSimpleAttribute( at_Color ) != NULL); } - /// \ru Изменить цвет объекта. \en Change color of the object. - void SetColor( uint32 ); - /// \ru Выдать цвет объекта. \en Get color of an object. - uint32 GetColor() const; - - /// \ru Установить толщину линий для отображения объекта. \en Set thickness of lines for object's representation. - void SetWidth( int ); - /// \ru Выдать толщину линий для отображения объекта. \en Get thickness of lines for object's representation. - int GetWidth() const; - - /// \ru Установить стиль линий для отображения объекта. \en Set style of lines for object's representation. - void SetStyle( int ); - /// \ru Выдать стиль линий для отображения объекта. \en Get style of lines for object's representation. - int GetStyle() const; - - /// \ru Выделить или не выделить объект. \en To allocate or not to allocate an object. - void SetSelected( bool s = true ); - /// \ru Выделен ли объект? \en Is the object selected. - bool IsSelected() const; - /// \ru Инвертировать выделение объекта. \en Invert object selection. - bool ReverseSelected(); - - /// \ru Задать: объект изменен или не изменён. \en Set: the object is changed or isn't changed. - void SetChanged( bool c = true ); - /// \ru Изменен ли объект? \en Is the object changed? - bool IsChanged() const; - - /// \ru Установить видимость. \en Set visibility. - void SetVisible( bool ); - /// \ru Видимый ли объект? \en Is the object visible? - bool IsVisible() const; - /// \ru Не видимый ли элемент? \en Is the object invisible? - bool IsInvisible() const; - /** \} */ - - /// \ru Прочитать атрибуты из потока. \en Read attributes from stream. - void AttributesRead ( reader & ); - /// \ru Записать атрибуты в поток. \en Writing attributes to stream. - void AttributesWrite( writer & ) const; - /// \ru Выдать свойства атрибутов. \en Get properties of attributes. - void GetProperties( MbProperties & ); - /// \ru Установить свойства атрибутов. \en Set properties of attributes. - void SetProperties( const MbProperties & ); - -OBVIOUS_PRIVATE_COPY( MbAttributeContainer ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить обобщенные атрибуты. - \en Get common attributes. \~ - \details \ru Получить обобщенные атрибуты. \n - \en Get common attributes. \n \~ - \param[in] attrItem - \ru Объект с атрибутами. - \en Object with attributes. \~ - \param[in] attrPrompt - \ru Подсказка атрибута для поиска. - \en Attribute prompt. \~ - \param[out] resAttrs - \ru Найденные атрибуты. - \en Found attributes. \~ - \result \ru Возвращает true, если что-то добавлено. - \en Returns 'true' if the something was got. \~ - \ingroup Model_Attributes -*/ -// --- -MATH_FUNC (bool) GetCommonAttributes( const MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt, c3d::ConstAttrVector & resAttrs ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Установить обобщенные атрибуты в целевой объект из объекта-источника. - \en Set common attributes in the destination object from the source object. \~ - \details \ru Установить обобщенные атрибуты в целевой объект из объекта-источника. \n - \en Set common attributes in the destination object from the source object. \n \~ - \param[in] srcItem - \ru Объект-источник. - \en The source object. \~ - \param[in] attrType - \ru Тип атрибута. - \en Attribute type. \~ - \param[in] attrPrompt - \ru Подсказка атрибута для поиска. - \en Attribute prompt. \~ - \param[out] dstItem - \ru Целевой объект. - \en The destination object. \~ - \param[in,out] bufAttrs - \ru Буферный массив атрибутов. - \en Buffer attributes vector. \~ - \result \ru Возвращает true, если что-то добавлено. - \en Returns 'true' if the something was added. \~ - \ingroup Model_Attributes -*/ -// --- -MATH_FUNC (bool) AddCommonAttributes( const MbAttributeContainer & srcItem, MbeAttributeType attrType, const c3d::string_t & attrPrompt, - MbAttributeContainer & dstItem, c3d::AttrVector * bufAttrs = NULL ); - -//------------------------------------------------------------------------------ -/** \brief \ru Удалить обобщенные атрибуты. - \en Delete common attributes. \~ - \details \ru Удалить обобщенные атрибуты. \n - \en Delete common attributes. \n \~ - \param[in] attrItem - \ru Объект с атрибутами. - \en Object with attributes. \~ - \param[in] attrPrompt - \ru Подсказка атрибута для поиска. - \en Attribute prompt. \~ - \result \ru Возвращает true, если что-то добавлено. - \en Returns 'true' if the something was deleted. \~ - \ingroup Model_Attributes -*/ -// --- -MATH_FUNC (bool) RemoveCommonAttributes( MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt ); - - -#endif // __ATTRIBUTE_CONTAINER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контейнер атрибутов. + \en An attribute container. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ATTRIBUTE_CONTAINER_H +#define __ATTRIBUTE_CONTAINER_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS reader; +class MATH_CLASS writer; +class MATH_CLASS MbVector3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbMatrix3D; +class MATH_CLASS MbAttribute; +class MATH_CLASS MbUserAttribute; +class MATH_CLASS MbExternalAttribute; +class MATH_CLASS MbProperties; +class MbRegDuplicate; +class MbRegTransform; + + +//------------------------------------------------------------------------------ +/** \brief \ru Контейнер атрибутов. + \en An attribute container. \~ + \details \ru Контейнер атрибутов. \n + От данного класса наследуются объекты модели геометрического ядра MbItem + и топологические объекты с именем MbTopologyItem .\n + Наследники данного класса содержат атрибуты.\n + Методами данного класса выполняются действия над атрибутами объектов геометрического ядра.\n + Атрибут может влиять на состояние атрибута через его владельца, + тo есть геометрическое ядро предусматривает возможность передачи атрибутам информации об изменениях + их владельцев посредством вызовов предопределенных функций у самого атрибута.\n + Кроме передачи самой информации об изменениях происходящих с владельцем, + предусмотрена возможность определять поведение атрибута при этих изменениях путем выбора + одного из предопределенных типов поведения на каждое изменения владельца.\n + Типы действий, влияющих на состояние атрибутов.\n + Копирование, например, при создании копии тела. Действие над атрибутом производится после копирования владеющего объекта.\n + Разделение, например, разделение грани на две части при вырезании. + Действие над атрибутом производится после разбиения владеющего объекта.\n + Слияние, например, слияние граней при булевых операциях. + Действие над атрибутом производится перед выполнением слияния объектов. + Обрабатываются атрибуты всех объектов, участвующих в слиянии.\n + Изменение, не связанное с разделением или слиянием. + Действие над атрибутом производится после изменения владеющего объекта.\n + Преобразование, например, поворот или параллельный перенос. + Действие над атрибутом производится после преобразования владеющего объекта.\n + Подмена, например замена одной грани тела на другую. Действие над атрибутом производится перед выполнением замены объектов. + Обрабатываются атрибуты всех объектов, участвующих в замене.\n + Удаление объекта. Действие над атрибутом производится перед удалением объекта.\n + \en An attribute container. \n + The inheritors of this class are: objects of geometric kernel model of type MbItem + and topological objects of type MbTopologyItem.\n + Inheritors of this class contain attributes.\n + Operations with attributes of geometric kernel objects are performed by methods of this class.\n + Attribute can affect attribute state using its owner, + i.e. geometric kernel provides an opportunity for transmission to attributes the information about changes + of their owners by calling the predefined functions of the attribute.\n + In addition to transfer of information about changes occurring with owner + provided a possibility to determine the behavior of attribute with these changes by selecting of + one of the predefined types of behavior for each changing of the owner.\n + Types of actions that affect the states of attributes.\n + Copying, for example, when creating a copy of solid. Action on attribute is performed after copying of owning object.\n + Splitting. For example, splitting of a face into two parts in cutting. + Action on attribute is performed after splitting of owning object.\n + Merging. For example, merging of faces in boolean operations. + Action on attribute is performed after merging of owning object.\n + Attributes of all objects involved in merging are processed.\n + Changing which is not associated with splitting or merging. + Action on attribute is performed after changing of owning object.\n + Transformation. For example, rotation or parallel translation. + Action on attribute is performed after transformation of owning object.\n + Replacement. For example, replacement of one face of a solid to another. Action on attribute is performed after replacement of objects. + Attributes of all objects involved in replacement are processed.\n + Deletion of an object. Action on attribute is performed after deletion of an object.\n \~ + \ingroup Model_Attributes +*/ +// --- +class MATH_CLASS MbAttributeContainer { +public: +typedef MultiMap AttrMap_t; +private: + AttrMap_t attributes; ///< \ru Множество атрибутов. \en Set of attributes. + +protected: + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + MbAttributeContainer( const MbAttributeContainer &, MbRegDuplicate * ); +public: + /// \ru Конструктор без параметров. \en Constructor without parameters. + MbAttributeContainer(); + /// \ru Конструктор по атрибуту. \en Constructor by attribute. + MbAttributeContainer( MbAttribute & ); + /// \ru Деструктор. \en Destructor. + virtual ~MbAttributeContainer(); + +public: + + /// \ru Выдать тип контейнера атрибутов. \en Get attribute container type. + virtual MbeImplicationType ImplicationType() const { return ace_AttribContainer; } + + /** \ru \name Общие функции над атрибутами + \en \name Common functions of attributes + \{ */ + /// \ru Cдублировать атрибуты присланного объекта, свои отпустить. \en Duplicate attributes of a given object, release existing attributes. + void AttributesAssign( const MbAttributeContainer & ); + /// \ru Выдать количество объектов. \en Get the number of objects. + size_t AttributesCount() const { return attributes.Count(); } + /// \ru Удалить все атрибуты из контейнера. \en Delete all attributes from container. + void RemoveAttributes( bool onDeleteOwner = false ); + + /// \ru Добавить атрибут в контейнер. \en Add attribute in container. + MbAttribute * AddAttribute( MbAttribute *, bool checkSame = true ); + /// \ru Добавить атрибут в контейнер (всегда копирует атрибут). \en Add attribute in container (always copies the attribute). + MbAttribute * AddAttribute( const MbAttribute &, bool checkSame = true ); + /// \ru Выдать атрибуты заданного семейства. \en Get attributes of a given family. + void GetAttributes( c3d::AttrVector &, MbeAttributeType aFamily, MbeAttributeType subType ) const; + /// \ru Выдать атрибуты заданного типа. \en Get attributes of a given type. + void GetAttributes( c3d::AttrVector &, MbeAttributeType aType ) const; + /// \ru Выдать атрибуты по строке описания. \en Get attributes using sample of description string. + void GetCommonAttributes( c3d::AttrVector &, const c3d::string_t & samplePrompt, MbeAttributeType subType = at_Undefined ) const; + /// \ru Выдать строковые атрибуты по строке содержания. \en Get string attributes using sample of contents of the string. + void GetStringAttributes( c3d::AttrVector &, const c3d::string_t & sampleContent ) const; + + /// \ru Выдать атрибут заданного типа, если их несколько - то первый попавшийся. \en Get an attribute of a given type, the first one is returned if there are many. + //const MbAttribute * GetAttribute( MbeAttributeType subType ) const; + /// \ru Удалить атрибут из контейнера. \en Delete an attribute from container. + bool RemoveAttribute( const MbAttribute *, bool checkAccuracySame = false, double accuracy = LENGTH_EPSILON ); + /// \ru Удалить атрибуты заданного типа. \en Delete attributes of a given type. + bool RemoveAttributes( MbeAttributeType type, MbeAttributeType subType ); + + /// \ru Выдать простой атрибут данного подтипа. \en Get a simple attribute of a given subtype. + const MbAttribute * GetSimpleAttribute( MbeAttributeType ) const; + /// \ru Выдать простой атрибут данного подтипа. \en Get a simple attribute of a given subtype. + MbAttribute * SetSimpleAttribute( MbeAttributeType ); + /// \ru Установить простой атрибут данного подтипа. \en Set a simple attribute of a given subtype. + MbAttribute * SetSimpleAttribute( MbAttribute * simpAttr ); + /// \ru Установить простой атрибут данного подтипа (всегда копирует атрибут). \en Set a simple attribute of a given subtype (always copies the attribute). + MbAttribute * SetSimpleAttribute( const MbAttribute & simpAttr ); + /// \ru Удалить простой атрибут(один и более) данного подтипа. \en Delete simple attributes (one or more) of a given subtype. + void RemoveSimpleAttribute( MbeAttributeType ); + /// \ru Отдать простой атрибут данного подтипа. \en Detach a simple attribute of a given subtype. + MbAttribute * DetachSimpleAttribute( MbeAttributeType ); + + /// \ru Выдать пользовательский атрибут данного подтипа. \en Get a user attribute of a given subtype. + void GetUserAttributes( std::vector & attrs, const MbUserAttribType & type ) const; + /// \ru Удалить пользовательский атрибут (один и более) данного подтипа. \en Delete user attributes (one or more) of a given subtype. + void RemoveUserAttributes( const MbUserAttribType & type ); + /// \ru Отдать пользовательский атрибут данного подтипа. \en Detach a user attribute of a given subtype. + void DetachUserAttributes( std::vector & attrs, const MbUserAttribType & type ); + + /// \ru Преобразовать из пользовательского в "системный" \en Convert user attribute to "system" one + static MbUserAttribute * ReduceUserAttrib ( const MbExternalAttribute & ); + /// \ru Преобразовать из "системного" в пользовательский \en Convert "system" attribute to user one + static MbExternalAttribute * AdvanceUserAttrib( const MbUserAttribute & ); + + /// \ru Выполнить действия при изменении атрибутов. \en Perform actions when changing the attributes. + void AttributesChange (); + /// \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 ); + /// \ru Выполнить действия при перемещении атрибутов. \en Perform actions when moving the attributes. + void AttributesMove ( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Выполнить действия при вращении атрибутов. \en Perform actions when rotating the attributes. + void AttributesRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + /// \ru Выполнить действия при копировании атрибутов. \en Perform actions when copying the attributes. + void AttributesCopy ( MbAttributeContainer & other, MbRegDuplicate * = NULL ) const; + /// \ru Выполнить действия при объединении атрибутов. \en Perform actions when merging the attributes. + void AttributesMerge ( MbAttributeContainer & other ); + /// \ru Выполнить действия при замене атрибутов. \en Perform actions when replacing the attributes. + void AttributesReplace( MbAttributeContainer & other ); + /// \ru Выполнить действия при разделении атрибутов. \en Perform actions when splitting the attributes. + void AttributesSplit ( const std::vector & others ); + /// \ru Выполнить действия при удалении атрибутов. \en Perform actions when deleting the attributes. + void AttributesDelete (); + /** \} */ + + /** \ru \name Функции простых атрибутов объекта. + \en \name Functions of object's simple attributes. + \{ */ + /// \ru Установить плотность объекта. \en Set density of an object. + void SetDensity( double ); + /// \ru Выдать плотность объекта. \en Get density of an object. + double GetDensity() const; + + /// \ru Установить визуальные свойства объекта. \en Set visual properties of the object. + void SetVisual( float a, float d, float sp, float sh, float t, float e ); + /** \brief \ru Выдать визуальные свойства объекта. + \en Get visual properties of the object. \~ + \details \ru Выдать визуальные свойства объекта. + \en Get visual properties of the object. \~ + \param[out] a - \ru Коэффициент общего фона (рассеянного освещения) + \en Coefficient of backlighting \~ + \param[out] d - \ru Коэффициент диффузного отражения + \en Coefficient of diffuse reflection \~ + \param[out] s - \ru Коэффициент зеркального отражения + \en Coefficient of specular reflection \~ + \param[out] h - \ru Блеск (показатель степени в законе зеркального отражения) + \en Shininess (index according to the law of specular reflection) \~ + \param[out] t - \ru Коэффициент непрозрачности + \en Coefficient of total reflection (opacity coefficient) \~ + \param[out] e - \ru Коэффициент излучения + \en Emissivity coefficient \~ + \return \ru true если есть такой атрибут \n false в противном случае + \en True if there is the attribute MbVisual \n otherwise false. \~ + */ + bool GetVisual( float & a, float & d, float & sp, float & sh, float & t, float & e ) const; + + /// \ru Есть ли у объекта свой цвет. \en . + + /** \brief \ru Есть ли у объекта свой цвет. + \en Whether the object is colored. \~ + \details \ru Есть ли у объекта свой цвет. + \en Whether the object is colored. \~ + \return \ru true если есть такой атрибут \n false в противном случае + \en True if there is the attribute MbColor \n otherwise false. \~ + */ + bool IsColored() const { return (GetSimpleAttribute( at_Color ) != NULL); } + /// \ru Изменить цвет объекта. \en Change color of the object. + void SetColor( uint32 ); + /// \ru Изменить цвет объекта (0-255). \en Change color of the object (0-255). + void SetColor( int R, int G, int B ); + /// \ru Выдать цвет объекта. \en Get color of an object. + uint32 GetColor() const; + + /// \ru Установить толщину линий для отображения объекта. \en Set thickness of lines for object's representation. + void SetWidth( int ); + /// \ru Выдать толщину линий для отображения объекта. \en Get thickness of lines for object's representation. + int GetWidth() const; + + /// \ru Установить стиль линий для отображения объекта. \en Set style of lines for object's representation. + void SetStyle( int ); + /// \ru Выдать стиль линий для отображения объекта. \en Get style of lines for object's representation. + int GetStyle() const; + + /// \ru Выделить или не выделить объект. \en To allocate or not to allocate an object. + void SetSelected( bool s = true ); + /// \ru Выделен ли объект? \en Is the object selected. + bool IsSelected() const; + /// \ru Инвертировать выделение объекта. \en Invert object selection. + bool ReverseSelected(); + + /// \ru Задать: объект изменен или не изменён. \en Set: the object is changed or isn't changed. + void SetChanged( bool c = true ); + /// \ru Изменен ли объект? \en Is the object changed? + bool IsChanged() const; + + /// \ru Установить видимость. \en Set visibility. + void SetVisible( bool ); + /// \ru Видимый ли объект? \en Is the object visible? + bool IsVisible() const; + /// \ru Не видимый ли элемент? \en Is the object invisible? + bool IsInvisible() const; + /** \} */ + + /// \ru Прочитать атрибуты из потока. \en Read attributes from stream. + void AttributesRead ( reader & ); + /// \ru Записать атрибуты в поток. \en Writing attributes to stream. + void AttributesWrite( writer & ) const; + /// \ru Выдать свойства атрибутов. \en Get properties of attributes. + void GetProperties( MbProperties & ); + /// \ru Установить свойства атрибутов. \en Set properties of attributes. + void SetProperties( const MbProperties & ); + +OBVIOUS_PRIVATE_COPY( MbAttributeContainer ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить обобщенные атрибуты. + \en Get common attributes. \~ + \details \ru Получить обобщенные атрибуты. \n + \en Get common attributes. \n \~ + \param[in] attrItem - \ru Объект с атрибутами. + \en Object with attributes. \~ + \param[in] attrPrompt - \ru Подсказка атрибута для поиска. + \en Attribute prompt. \~ + \param[out] resAttrs - \ru Найденные атрибуты. + \en Found attributes. \~ + \result \ru Возвращает true, если что-то добавлено. + \en Returns 'true' if the something was got. \~ + \ingroup Model_Attributes +*/ +// --- +MATH_FUNC (bool) GetCommonAttributes( const MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt, c3d::ConstAttrVector & resAttrs ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Установить обобщенные атрибуты в целевой объект из объекта-источника. + \en Set common attributes in the destination object from the source object. \~ + \details \ru Установить обобщенные атрибуты в целевой объект из объекта-источника. \n + \en Set common attributes in the destination object from the source object. \n \~ + \param[in] srcItem - \ru Объект-источник. + \en The source object. \~ + \param[in] attrType - \ru Тип атрибута. + \en Attribute type. \~ + \param[in] attrPrompt - \ru Подсказка атрибута для поиска. + \en Attribute prompt. \~ + \param[out] dstItem - \ru Целевой объект. + \en The destination object. \~ + \param[in,out] bufAttrs - \ru Буферный массив атрибутов. + \en Buffer attributes vector. \~ + \result \ru Возвращает true, если что-то добавлено. + \en Returns 'true' if the something was added. \~ + \ingroup Model_Attributes +*/ +// --- +MATH_FUNC (bool) AddCommonAttributes( const MbAttributeContainer & srcItem, MbeAttributeType attrType, const c3d::string_t & attrPrompt, + MbAttributeContainer & dstItem, c3d::AttrVector * bufAttrs = NULL ); + +//------------------------------------------------------------------------------ +/** \brief \ru Удалить обобщенные атрибуты. + \en Delete common attributes. \~ + \details \ru Удалить обобщенные атрибуты. \n + \en Delete common attributes. \n \~ + \param[in] attrItem - \ru Объект с атрибутами. + \en Object with attributes. \~ + \param[in] attrPrompt - \ru Подсказка атрибута для поиска. + \en Attribute prompt. \~ + \result \ru Возвращает true, если что-то добавлено. + \en Returns 'true' if the something was deleted. \~ + \ingroup Model_Attributes +*/ +// --- +MATH_FUNC (bool) RemoveCommonAttributes( MbAttributeContainer & attrItem, const c3d::string_t & attrPrompt ); + + +#endif // __ATTRIBUTE_CONTAINER_H diff --git a/C3d/Include/cdet_bool.h b/C3d/Include/cdet_bool.h index 15fbfbb..7ebfbb6 100644 --- a/C3d/Include/cdet_bool.h +++ b/C3d/Include/cdet_bool.h @@ -1,57 +1,57 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Расчет пересечений тел посредством аппарата булевой операции. - \en Calculation of intersections between solids using the boolean operations. \~ - -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __CDET_BOOL_H -#define __CDET_BOOL_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbSolid; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbCurveEdge; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Расчет пересечений тел посредством аппарата булевой операции. - \en Calculation of intersections between solids using the boolean operations. \~ - \details \ru Расчет пересечений тел посредством аппарата булевой операции. - \en Calculation of intersections between solids using the boolean operations. \~ \n - \param[in] solid1 - \ru Первое тело. \en The first solid. \~ - \param[in] solid2 - \ru Второе тело. \en The second solid. \~ - \param[out] edges - \ru Ребра пересечения тел. \en Intersection edges. \~ - \param[out] intersectedFaces - \ru Пары номеров пересекшихся граней. \n - - \en The couples of indeses intersected faces of the solids, \n - \param[out] touchedFaces - \ru Пары номеров касающихся граней с противоположно направленными нормалями. - \en The couples of indeses of contacted faces with oppositely directed normals. \~ - \param[out] similarFaces - \ru Пары номеров касающихся подобных граней, которые могут быть объединены. - \en The couples of indeses of relating to similar faces that can be combined. \~ - \return \ru Код результата операции. \en Operation result code. \~ - - \warning \ru Тела будут изменены операцией! Если требуется сохранить тела без изменений, - передавайте копии, сделанные помощью MbSolid::Duplicate(). - \en The solids will be modified by this operation! To keep the body intact, - give the copies made using MbSolid::Duplicate(). \~ - - \ingroup Collision_Detection -*/ -//--- -MATH_FUNC (MbResultType) InterferenceSolids( MbSolid & solid1, MbSolid & solid2, - std::vector * edges, - c3d::IndicesPairsVector * intersectedFaces, - c3d::IndicesPairsVector * similarFaces, - c3d::IndicesPairsVector * touchedFaces ); - - -#endif // __CDET_BOOL_H - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Расчет пересечений тел посредством аппарата булевой операции. + \en Calculation of intersections between solids using the boolean operations. \~ + +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __CDET_BOOL_H +#define __CDET_BOOL_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbSolid; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbCurveEdge; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Расчет пересечений тел посредством аппарата булевой операции. + \en Calculation of intersections between solids using the boolean operations. \~ + \details \ru Расчет пересечений тел посредством аппарата булевой операции. + \en Calculation of intersections between solids using the boolean operations. \~ \n + \param[in] solid1 - \ru Первое тело. \en The first solid. \~ + \param[in] solid2 - \ru Второе тело. \en The second solid. \~ + \param[out] edges - \ru Ребра пересечения тел. \en Intersection edges. \~ + \param[out] intersectedFaces - \ru Пары номеров пересекшихся граней. \n + - \en The couples of indeses intersected faces of the solids, \n + \param[out] touchedFaces - \ru Пары номеров касающихся граней с противоположно направленными нормалями. + \en The couples of indeses of contacted faces with oppositely directed normals. \~ + \param[out] similarFaces - \ru Пары номеров касающихся подобных граней, которые могут быть объединены. + \en The couples of indeses of relating to similar faces that can be combined. \~ + \return \ru Код результата операции. \en Operation result code. \~ + + \warning \ru Тела будут изменены операцией! Если требуется сохранить тела без изменений, + передавайте копии, сделанные помощью MbSolid::Duplicate(). + \en The solids will be modified by this operation! To keep the body intact, + give the copies made using MbSolid::Duplicate(). \~ + + \ingroup Collision_Detection +*/ +//--- +MATH_FUNC (MbResultType) InterferenceSolids( MbSolid & solid1, MbSolid & solid2, + std::vector * edges, + c3d::IndicesPairsVector * intersectedFaces, + c3d::IndicesPairsVector * similarFaces, + c3d::IndicesPairsVector * touchedFaces ); + + +#endif // __CDET_BOOL_H + diff --git a/C3d/Include/cdet_data.h b/C3d/Include/cdet_data.h index dcf6819..657ae38 100644 --- a/C3d/Include/cdet_data.h +++ b/C3d/Include/cdet_data.h @@ -25,8 +25,8 @@ class MbHRepSolid; //---------------------------------------------------------------------------------------- /// \ru Объект набора для контроля столкновений. \en Object of the set for collision detection. //--- -typedef MbHRepSolid * cdet_item; -typedef MbResultType cdet_result; ///< \ru Код результата контроля столкновений. \en Result code of collision queries. +typedef const MbHRepSolid * cdet_item; +typedef MbResultType cdet_result; ///< \ru Код результата контроля столкновений. \en Result code of collision queries. //---------------------------------------------------------------------------------------- // \ru Код результата контроля столкновений. \en Codes of collision detection. @@ -45,8 +45,8 @@ typedef const void * cdet_app_item; //---------------------------------------------------------------------------------------- // Constants //--- -const cdet_item CDET_NULL = NULL; ///< \ru Пустой объект набора для контроля столкновений. \en Empty object of the collision query set. -const cdet_app_item CDET_APP_NULL = NULL; ///< \ru "Нулевой" объект модели приложения. \en "Null object" of the client app. +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. //---------------------------------------------------------------------------------------- // Base class to implement collision query details @@ -77,8 +77,8 @@ struct cdet_query const MbRefItem * refItem; const MbMatrix3D * wMatrix; geom_element() - : appItem( NULL ) - , refItem( NULL ) + : appItem( C3D_NULL_PTR ) + , refItem( C3D_NULL_PTR ) , wMatrix( &MbMatrix3D::identity ) {} }; @@ -117,7 +117,7 @@ struct cdet_query_result: public cdet_query private: static cback_res QueryFunc( cdet_query * query, message code, cback_data & ) { - C3D_ASSERT( NULL != query ); + C3D_ASSERT( C3D_NULL_PTR != query ); cdet_query_result * q = static_cast( query ); switch( code ) { @@ -140,7 +140,6 @@ private: } }; - //---------------------------------------------------------------------------------------- // The structure queries first founded collision faces //--- @@ -163,7 +162,7 @@ private: { case CDET_QUERY_STARTED: // The collision query is started for all solids of the set { - q->first = q->second = NULL; + q->first = q->second = C3D_NULL_PTR; return CBACK_VOID; } case CDET_FINISHED: // A pair of solids is finished. @@ -310,6 +309,36 @@ private: OBVIOUS_PRIVATE_COPY( cdet_collided_faces ); }; +//---------------------------------------------------------------------------------------- +// +//--- +typedef enum +{ + CDET_EXAM_EnableComponentsOnly // Test collisions between components only. + , CDET_EXAM_Enabled // Enable the pair to test collisions. + , CDET_EXAM_Disabled // Reject the collision test of the pair. +} CDET_exam_status; + +//---------------------------------------------------------------------------------------- +// +//--- +struct CDET_item_data +{ + cdet_item comp; // Descriptor of the component owning the inctance. + cdet_item inst; // Descriptor of the instance. + cdet_app_item appItem; // Application pointer for the instance or the component. + CDET_item_data() + { + comp = inst = CDET_NULL; + appItem = CDET_APP_NULL; + } +}; + +//---------------------------------------------------------------------------------------- +// +//--- +typedef CDET_exam_status (*CDET_exam_func)( cdet_query *, const CDET_item_data &, const CDET_item_data & ); + /** \} */ // Collision_Detection class TapeBase; @@ -321,23 +350,40 @@ class MbFace; // --- class MbCollisionFace { - const MbFace * mathFace; - TapeBase * partFace; + cdet_item item; // The instance to witch the face belongs. + const MbFace * mathFace; // The topological face identified in the collision detection or proximity query. + TapeBase * partFace; // The face of the application representation. public: - MbCollisionFace( const MbFace &_mathFace ) : mathFace( &_mathFace ), partFace( NULL ) {} + MbCollisionFace( const MbFace & f ) + : item( CDET_NULL ) + , mathFace( &f ) + , partFace( C3D_NULL_PTR ) + {} - const MbFace & GetMathFace() const { return *mathFace; } + const MbFace & Face() const { return *mathFace; } + cdet_item Item() const { return item; } + const MbFace & GetMathFace() const { return *mathFace; } // \ru Установка объекта модели. \en Setting an object of model. - void SetCollisionFaceObject( TapeBase * _partFace ) { partFace = _partFace; } + void SetCollisionFaceObject( TapeBase * _partFace ) { partFace = _partFace; } + // \ru Выдача объекта модели. \en Getting an object of model. TapeBase * GetCollisionFaceObject() const { return partFace; } + // \ru Задать грань и компонент-вставку, которой принадлежит. \en Set a face and its component-instance. + MbCollisionFace & SetFace( const MbFace * f, cdet_item inst ) + { + mathFace = f; + item = inst; + return *this; + } + MbCollisionFace & operator = ( const MbCollisionFace & other ) { + item = other.item; mathFace = other.mathFace; - partFace = other.partFace; //CppCheck + partFace = other.partFace; return *this; } bool operator > ( const MbCollisionFace & other ) const { return mathFace > other.mathFace; } @@ -359,9 +405,11 @@ class MATH_CLASS MbProximityParameters SPtr plane; public: - MbCartPoint thePar1, thePar2; // \ru Пара точек близости, заданная в поверхностных координатах граненй. \en The points of the proximity specified in the surface coordinates of the faces. - double theDistance; // \ru Расстояние. \en Distance. - double upperDist; // \ru Верхняя оценка для поиска минимальной дистанции. \en The upper bound of the minimal distance estimation. + //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. + double upperDist; // \ru Верхняя оценка для поиска минимальной дистанции. \en The upper bound of the minimal distance estimation. public: MbProximityParameters(); @@ -379,12 +427,16 @@ public: const MbCollisionFace & FaceTwo() const { return *theFace2; } void SetFacePair( const MbFace &, const MbFace & ); + void SetFacePair( const MbFace *, cdet_item, const MbFace *, cdet_item ); private: MbProximityParameters( const MbProximityParameters & ); // not implemented MbProximityParameters & operator = ( const MbProximityParameters & ); // not implemented }; + + + #endif // __CDET_DATA_H // eof diff --git a/C3d/Include/cdet_utility.h b/C3d/Include/cdet_utility.h index fa39a1d..0d5e68d 100644 --- a/C3d/Include/cdet_utility.h +++ b/C3d/Include/cdet_utility.h @@ -10,13 +10,20 @@ #define __CDET_UTILITY_H #include +#include +class MtRefItem; class MbItem; class MbSolid; class MbAssembly; struct MbLumpAndFaces; class MbCollisionDetector; +/** + \addtogroup Collision_Detection + \{ +*/ + //---------------------------------------------------------------------------------------- /** \brief \ru Утилита расчета параметров пересечения и близости тел. \en Utility for calculation of intersection and proximity parameters of solids. \~ @@ -31,7 +38,6 @@ class MbCollisionDetector; 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. \~ - \ingroup Collision_Detection */ // --- class MATH_CLASS MbCollisionDetectionUtility @@ -84,12 +90,6 @@ public: public: // the functions below can be deprecated in future version. - /** - \brief \ru Добавить модель тела, как набор граней и решеток. - \en Add a solid data as a set of faces and the grids. \~ - \return \ru Индекс добавленной твердотельной модели. \en Index of added solid data. \~ - */ - size_t AddLump( const MbLumpAndFaces & ); /** \brief \ru Добавить модель тела, как набор граней и решеток. \en Add a solid data as a set of faces and the grids. \~ @@ -98,19 +98,41 @@ 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. size_t Count() const; - // Use AppItem() insead this - cdet_app_item Component( size_t solIdx ) const; /// \ru Номер твердотельной модели, зарегистрированной в детекторе. \en An index of solid model registered in the detector. size_t SolidIndex( cdet_item cItem ) const; - /// \ru Вычисление минимального расстояния между объектами (см.функцию SetDistanceComputationObjects(...)) \en Calculation of minimal distance between objects (see the function SetDistanceComputationObjects(...)) - cdet_result DistanceQuery( MbProximityParameters & minDist ) const; + /// \ru Вычисление минимального расстояния между объектами (см.функцию #SetDistanceTracking) \en Calculation of minimal distance between objects (see the function #SetDistanceTracking) + cdet_result DistanceQuery( MbProximityParameters & ) const; + /// \ru Вычисление минимального расстояния между объектами + cdet_result DistanceQuery( cdet_item, cdet_item, MbProximityParameters & ) const; /// \ru Выключить из рассмотрения все модели. \en Exclude all models from consideration. void FlushSolids(); - /// \ru Выдать иерархическое представление тела (NULL = отсутствие такового в списке). \en Get the hierarchical representation of the solid (NULL means that the solid is not in the list). + /// \ru Выдать иерархическое представление тела (CDET_NULL = отсутствие такового в списке). \en Get the hierarchical representation of the solid (CDET_NULL means that the solid is not in the list). cdet_item GetHRepSolid ( const MbLumpAndFaces & ) const; /// \ru Задать барьер для отличия касания от пересечения. \en Set the barrier for the difference between the touch and the intersection. void SetTouchTolerance( double lTol ); @@ -126,20 +148,22 @@ public: // the functions below can be deprecated in future version. // \ru Объявление конструктора копирования и оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration without implementation of the copy-constructor and assignment operator to prevent an assignment by default. OBVIOUS_PRIVATE_COPY( MbCollisionDetectionUtility ); -public: +public: /* + Deprecated and testing functions + */ + void SetCallback( CDET_exam_func ); + // Use AppItem() insead this + cdet_app_item Component( size_t solIdx ) const; // The func is deprecated. Instead, use CheckCollisions - cdet_result InterferenceDetect( void * formalPar = NULL ) const; + cdet_result InterferenceDetect( void * formalPar = C3D_NULL_PTR ) const; // The func is deprecated. Use SetDistanceTracking instead. void SetDistanceComputationObjects( const MbLumpAndFaces &, const MbLumpAndFaces & ); + // The func is deprecated. Use AddSolid/AddItem instead. + size_t AddLump( const MbLumpAndFaces & ); // For testing purposes bool IsEmpty( cdet_item ) const; // For testing purposes - cdet_item NewComponent( cdet_app_item ); - // For testing purposes - //cdet_item Component( cdet_item subItem ); - // For testing purposes - cdet_item AddInstance( cdet_item compItem, cdet_item subItem, const MbPlacement3D & ); - + const MtRefItem * _ComputeBVTree( cdet_item ); private: /* @@ -162,6 +186,30 @@ inline cdet_result MbCollisionDetectionUtility::CheckCollisions() return CheckCollisions( defaultQuery ); } +/// \ru Узел дерева объемов. \en A node of the bounding volume tree. +typedef const MtRefItem * cdet_bvt_node; +/// \ru Пустое дерево объемов. \en An empty bounding volume tree. +const cdet_bvt_node CDET_BVT_NULL = C3D_NULL_PTR; +/// \ru Пара ветвей поддерева объемов. \en A pair of branches of the bounding volume subtree. +typedef std::pair cdet_bvt_pair; + +//--------------------------------------------------------------------------------------- +/** + \brief \ru Получить левую и правую ветви поддерева объемов. + \en Get the left and the right branches of the bounding volume subtree. +*/ +//--- +MATH_FUNC(cdet_bvt_pair) BvtSubNodes( cdet_item, cdet_bvt_node ); + +//--------------------------------------------------------------------------------------- +/** \brief \ru Матрица получения ограничивающего параллелепипеда из единичного куба. + \en Transformation matrix yielding bounding parallelepiped from the unit cube. +*/ +//--- +MATH_FUNC(void) GetOrientedBox( cdet_item, cdet_bvt_node, MbMatrix3D & ); + #endif // __CDET_UTILITY_H +/** \} */ + // eof \ No newline at end of file diff --git a/C3d/Include/check_geometry.h b/C3d/Include/check_geometry.h index 65af3ec..4e9f4f6 100644 --- a/C3d/Include/check_geometry.h +++ b/C3d/Include/check_geometry.h @@ -30,7 +30,7 @@ \ingroup Algorithms_3D */ //--- -struct MATH_CLASS MbIntersectionData { +struct MATH_CLASS MbShellsIntersectionData { protected: c3d::EdgesSPtrVector edges; ///< \ru Ребра пересечения (владеет по счетчику ссылок). \en Intersection edges (owns by reference counter). c3d::IndicesVector faceIndices1; ///< \ru Номера касающихся граней первого тела. \en The numbers concerning faces of the first solid. @@ -45,28 +45,28 @@ protected: public: /// \ru Конструктор. \en Constructor. - MbIntersectionData(); + MbShellsIntersectionData(); /// \ru Конструктор по ребру. \en Constructor by an edge. - MbIntersectionData( const MbCurveEdge & ); + MbShellsIntersectionData( const MbCurveEdge & ); /// \ru Конструктор по ребрам. \en Constructor by edges. template - MbIntersectionData( const EdgesVector &, bool isSolidEdges ); + MbShellsIntersectionData( const EdgesVector &, bool isSolidEdges ); /// \ru Конструктор по ребрам. \en Constructor by edges. template - MbIntersectionData( const EdgesVector &, const FaceIndicesVector & faceNumbers1, const FaceIndicesVector & faceNumbers2 ); + MbShellsIntersectionData( const EdgesVector &, const FaceIndicesVector & faceNumbers1, const FaceIndicesVector & faceNumbers2 ); /// \ru Конструктор по ребрам. \en Constructor by edges. template - MbIntersectionData( const EdgesVector &, const c3d::IndicesPairsVector & faceNumbersPairs ); + MbShellsIntersectionData( const EdgesVector &, const c3d::IndicesPairsVector & faceNumbersPairs ); /// \ru Конструктор по телу. \en Constructor by a solid. - explicit MbIntersectionData( const MbSolid & ); + explicit MbShellsIntersectionData( const MbSolid & ); /// \ru Конструктор по точкам. \en Constructor by points. - explicit MbIntersectionData( const std::vector & ); + explicit MbShellsIntersectionData( const std::vector & ); /// \ru Конструктор по вершинам и флагу использования этих объектов, а не их копий. \en Constructor by vertices and by flag of use of these objects instead of their copies. - explicit MbIntersectionData( const c3d::ConstVerticesVector &, bool same ); + explicit MbShellsIntersectionData( const c3d::ConstVerticesVector &, bool same ); /// \ru Конструктор по вершинам и флагу использования этих объектов, а не их копий. \en Constructor by vertices and by flag of use of these objects instead of their copies. - explicit MbIntersectionData( const c3d::ConstVerticesSPtrVector &, bool same ); + explicit MbShellsIntersectionData( const c3d::ConstVerticesSPtrVector &, bool same ); /// \ru Деструктор. \en Destructor. - ~MbIntersectionData(); + ~MbShellsIntersectionData(); public: /// \ru Пересечение - есть тело. \en Intersection is a solid. @@ -105,7 +105,7 @@ public: /// \ru Получить набор точек касания. \en Get a set of touch points. const MbPointFrame * GetPointFrame() const { return pointFrame; } -OBVIOUS_PRIVATE_COPY( MbIntersectionData ) // \ru Не реализовано \en Not implemented +OBVIOUS_PRIVATE_COPY( MbShellsIntersectionData ) // \ru Не реализовано \en Not implemented }; @@ -113,7 +113,7 @@ OBVIOUS_PRIVATE_COPY( MbIntersectionData ) // \ru Не реализовано \e // \ru Конструктор по ребрам. \en Constructor by edges. //--- template -MbIntersectionData::MbIntersectionData( const EdgesVector & initEdges, bool isSolidEgdes ) +MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & initEdges, bool isSolidEgdes ) : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) @@ -140,9 +140,9 @@ MbIntersectionData::MbIntersectionData( const EdgesVector & initEdges, bool isSo // \ru Конструктор по ребрам. \en Constructor by edges. //--- template -MbIntersectionData::MbIntersectionData( const EdgesVector & initEdges, - const FaceIndicesVector & faceInds1, - const FaceIndicesVector & faceInds2 ) +MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & initEdges, + const FaceIndicesVector & faceInds1, + const FaceIndicesVector & faceInds2 ) : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) @@ -172,8 +172,8 @@ MbIntersectionData::MbIntersectionData( const EdgesVector & initEdges, // \ru Конструктор по ребрам. \en Constructor by edges. //--- template -MbIntersectionData::MbIntersectionData( const EdgesVector & initEdges, - const c3d::IndicesPairsVector & faceIndicesPairs ) +MbShellsIntersectionData::MbShellsIntersectionData( const EdgesVector & initEdges, + const c3d::IndicesPairsVector & faceIndicesPairs ) : edges ( ) , faceIndices1 ( ) , faceIndices2 ( ) @@ -209,7 +209,7 @@ MbIntersectionData::MbIntersectionData( const EdgesVector & initEdge // \ru Получить массив кривых пересечения. \en Get the intersection curve array. //--- template -void MbIntersectionData::GetCurves( EdgesVector & dstEdges ) const +void MbShellsIntersectionData::GetCurves( EdgesVector & dstEdges ) const { size_t addCnt = edges.size(); c3d::EdgeSPtr edge; @@ -226,7 +226,7 @@ void MbIntersectionData::GetCurves( EdgesVector & dstEdges ) const // \ru Получить номера касающихся граней первого/второго тела. \en Get numbers concerning faces of the first/second solid. //--- template -void MbIntersectionData::GetFaceNumbers( bool first, OutputIndicesVector & outputIndices ) const +void MbShellsIntersectionData::GetFaceNumbers( bool first, OutputIndicesVector & outputIndices ) const { const c3d::IndicesVector & faceIndices = first ? faceIndices1 : faceIndices2; size_t addCnt = faceIndices.size(); @@ -243,7 +243,7 @@ void MbIntersectionData::GetFaceNumbers( bool first, OutputIndicesVector & outpu // \ru Получить номера касающихся граней первого и второго тел. \en Get numbers concerning faces of the first and second solids. //--- template -void MbIntersectionData::GetFaceNumbersPairs( OutputIndicesPairsVector & outputIndicesPairs ) const +void MbShellsIntersectionData::GetFaceNumbersPairs( OutputIndicesPairsVector & outputIndicesPairs ) const { size_t addCnt = std_min( faceIndices1.size(), faceIndices2.size() ); if ( addCnt > 0 ) { @@ -272,14 +272,6 @@ void MbIntersectionData::GetFaceNumbersPairs( OutputIndicesPairsVector & outputI MATH_FUNC (bool) IsDegeneratedCurve( const MbCurve3D & curve, double eps ); -//------------------------------------------------------------------------------ -/// \ru Проверка на полное совпадение двух кривых пересечения поверхностей c метрической точностью lenEps \en Check for complete coincidence of two intersection curves of surfaces with metric tolerance lenEps -//--- -bool IsCoincidentCurves( const MbSurfaceIntersectionCurve & intCurve1, - const MbSurfaceIntersectionCurve & intCurve2, - double lenEps ); - - //------------------------------------------------------------------------------ /** \brief \ru Проверка оболочки тела на замкнутость. \en Check of solid's shell for closedness. \~ @@ -320,7 +312,7 @@ MATH_FUNC (bool) CheckSolidClosure( const MbSolid & solid ); /** \brief \ru Поиск краевых ребер замкнутой оболочки. \en Search for the boundary edges of a closed shell. \~ \details \ru Поиск краевых ребер замкнутой оболочки. \n - Краевое ребер - это ребро у которого нет ссылки на одну из смежных граней. \n + Краевое ребро - это ребро у которого нет ссылки на одну из смежных граней. \n Наличие краевых ребер замкнутой оболочки может приводит к отказу операций над оболочкой, если операцией будет затронута часть оболочки с краевыми ребрами. \n Наличие одиночных краевых ребер практически никак не влияет на правильность расчета МЦХ. diff --git a/C3d/Include/collection.h b/C3d/Include/collection.h index c77d996..57477b0 100644 --- a/C3d/Include/collection.h +++ b/C3d/Include/collection.h @@ -1,337 +1,337 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Коллекция элементов. - \en Collection of elements . \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __COLLECTION_H -#define __COLLECTION_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbMesh; -class MATH_CLASS MbGrid; - - -//------------------------------------------------------------------------------ -/** \brief \ru Коллекция элементов. - \en Collection of elements. \~ - \details \ru Коллекция элементов - это объект геометрической модели, наследник MbItem, являющийся - множеством элементов в трехмерном пространстве. \n - \en The collection of 3D elements is an object of geometric model (subclass MbItem) which is - the set of elements in 3D space. \n \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbCollection : public MbItem { -public: - /** \brief \ru Типы коллекций 3D объектов. - \en Types of 3D object collection. \~ -*/ -enum CollectionType { - coll_PointCloud = 0, ///< \ru Облако точек. \en The point cloud. - coll_Tessellation = 1, ///< \ru Триангуляция. \en The tessellation. - coll_Elements = 2, ///< \ru Набор элементов. \en Set of elements. - coll_Segmentation = 3, ///< \ru Сегментированная полигональная сетка. \en Segmented polygonal mesh. -}; - -private: - CollectionType type; ///< \ru Тип коллекции 3D объектов. \en Type of 3D object collection. - uint32 xSize; ///< \ru Количество объектов вдоль первой координаты. \en The number of objects along the first coordinate. - uint32 ySize; ///< \ru Количество объектов вдоль второй координаты. \en The number of objects along the second coordinate. - uint32 zSize; ///< \ru Количество объектов вдоль третьей координаты. \en The number of objects along the third coordinate. - std::vector points; ///< \ru Множество точек. \en Set of points. - std::vector normals; ///< \ru Множество нормалей в точках согласовано с множеством точек. \en Set of normals at control points is synchronized with the set of points. - std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. - std::vector triangles; ///< \ru Индексное множество треугольных пластин содержит номера элементов множества points и normals. \en Set of triangular plates contains numbers of elements of 'points' and 'normals' sets. - std::vector quadrangles; ///< \ru Индексное множество четырёхугольных пластин содержит номера элементов множества params и/или множеств points и normals. \en Set of quadrangular plates contains numbers of elements of 'params' set and/or of 'points' and 'normals' sets. - std::vector elements; ///< \ru Индексное множество объемных элементов содержит номера элементов множества points. \en Set of volume elements contains numbers of vertices of 'points' sets. - std::vector segments; ///< \ru Множество сегментов полигональной сетки. \en Set of segments of mesh. - - /** \brief \ru Габаритный куб объекта. - \en Bounding box of object. \~ - \details \ru Габаритный куб объекта рассчитывается только при запросе габарита объекта. Габаритный куб в конструкторе объекта и после модификации объекта принимает неопределенное значение. - \en Bounding box of object is calculated only at the request. Bounding box of object is undefined after object constructor and after object modifications \n \~ - */ - mutable MbCube cube; -private: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbCollection( const MbCollection & init ); - - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbCollection( const MbCollection &, MbRegDuplicate * ); -public: - /// \ru Конструктор. \en Constructor. - MbCollection(); - /// \ru Конструктор. \en Constructor. - MbCollection( const MbMesh & mesh ); - - /// \ru Деструктор. \en Destructor. - virtual ~MbCollection(); - -public: - VISITING_CLASS( MbCollection ); - - // \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 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. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. - virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - virtual MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create a custom 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 Create a polygonal object - a simplified copy of the given object. - virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; - // \ru Создать полигональный объект - упрощенную копию данного объекта. \en Create a polygonal object - a simplified copy of the given object. - MbGrid * CreateGrid() const; - - // \ru Создать сетки из четырехугольных пластин наружных стенок элементов. \en Create grids by quadrangular plates of the outside walls of elements. - void CreateGridsByElements( RPArray & grids_ ) const; - - // \ru Создать угловые точки и элементы. \en Create corner points and elements. - void CreateCornerPointsAndElements( SArray & points0, SArray & elements0 ) const; - - // \ru Создать сетки из по результатам сегментации. \en Create grids by segmentation results. - void CreateGridsBySegments( RPArray & grids_ ) const; - - /** \ru \name Общие функции коллекции. - \en \name Common functions of a collection. - \{ */ - - /// \ru Выдать количество точек. \en Get count of points. - size_t PointsCount() const { return points.size(); } - /// \ru Выдать количество нормалей. \en Get the number of normals. - size_t NormalsCount() const { return normals.size(); } - /// \ru Выдать количество значений. \en Get count of values. - size_t EscortsCount() const { return escorts.size(); } - /// \ru Выдать количество треугольников. \en Get the number of triangles. - size_t TrianglesCount() const { return triangles.size(); } - /// \ru Выдать количество четырехугольников. \en Get the number of quadrangles. - size_t QuadranglesCount() const { return quadrangles.size(); } - /// \ru Выдать количество объемных элементов. \en Get the number of elements of volume. - size_t ElementsCount() const { return elements.size(); } - /// \ru Выдать количество сегментов. \en Get the number of segments of mesh. - size_t SegmentsCount() const { return segments.size(); } - /// \ru Выдать количество триангуляций. \en Get the number of triangulations. - //size_t GridsCount() const { return grids.size(); } - ptrdiff_t PointsMaxIndex() const { ptrdiff_t c = points.size(); return ( c - 1 ); } - /// \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). - ptrdiff_t NormalsMaxIndex() const { ptrdiff_t c = normals.size(); return ( c - 1 ); } - - /// \ru Добавить в коллекцию точку и нормаль в точке. \en Add a point and normal at the point to collection. - void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ) { points.push_back(p3D); normals.push_back(n3D); cube.SetEmpty(); } - /// \ru Добавить в коллекцию точку. \en Add a point to collection. - void AddPoint ( const MbCartPoint3D & p3D ) { points.push_back(p3D); cube.SetEmpty(); } - /// \ru Добавить в коллекцию нормаль. \en Add a normal to collection. - void AddNormal( const MbVector3D & n3D ) { normals.push_back(n3D) ; } - /// \ru Добавить в коллекцию точки. \en Add points to collection. - void AddPoints ( const std::vector & pnts ) { points.insert(points.end(), pnts.begin(), pnts.end()); cube.SetEmpty(); } - /// \ru Добавить в коллекцию нормали. \en Add normals to collection. - void AddNormals( const SArray & nrms ) { normals.insert(normals.end(), nrms.begin(), nrms.end()); cube.SetEmpty(); } - /// \ru Добавить в коллекцию данных. \en Add scores to collection. - void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } - - /// \ru Добавить треугольник. \en Add a triangle. - void AddTriangle ( const MbTriangle & triangle ) { triangles.push_back( triangle ); } - /// \ru Добавить треугольник с заданными номерами вершин. \en Add a triangle by the given indices of vertices - void AddTriangle ( uint j0, uint j1, uint j2, bool o ) { MbTriangle t(j0,j1,j2,o); triangles.push_back( t ); } - /// \ru Добавить четырёхугольник. \en Add a quadrangle. - void AddQuadrangle( const MbQuadrangle & quadrangle ) { quadrangles.push_back( quadrangle ); } - /// \ru Добавить четырёхугольник с заданными номерами вершин. \en Add a quadrangle by the given indices of vertices. - void AddQuadrangle( uint j0, uint j1, uint j2, uint j3, bool o ) { MbQuadrangle t(j0,j1,j2,j3,o); quadrangles.push_back( t ); } - /// \ru Добавить объемный элемент. \en Add an element. - void AddElement( const MbElement & element ) { elements.push_back(element); } - /// \ru Добавить объемный элемент. \en Add an element. - void AddElement( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ) { - MbElement t( j0,j1,j2,j3,j4,j5,j6,j7 ); elements.push_back( t ); } - void AddSegment( const MbGridSegment & segment ) { segments.push_back( segment ); } - void AddSegment( const std::vector & initFaces ) { MbGridSegment seg( initFaces ); segments.push_back( seg ); } - /// \ru Добавить полигон. \en Add a polygon. - //void AddGrid( MbExactGrid & grd ) { grids.push_back( &grd ); } - - /// \ru Выдать индексы точек в массиве points для i-го треугольника (связанного или несвязанного). \en Get indices of points in 'points' array for i-th triangle (adjacent or non-adjacent). - bool GetTrianglePointIndex ( size_t i, uint & ind0, uint & ind1, uint & ind2 ) const; - /// \ru Выдать индексы точек в массиве points для i-го четырехугольника (связанного или несвязанного). \en Get indices of points in 'points' array for i-th quadrangle (adjacent or non-adjacent). - bool GetQuadranglePointIndex( size_t i, uint & ind0, uint & ind1, uint & ind2, uint & ind3 ) const; - /// \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). - bool GetTrianglePoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2 ) const; - /// \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). - bool GetTriangleNormals ( size_t i, MbVector3D &n0, MbVector3D &n1, MbVector3D &n2 ) const; - - /// \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). - bool GetQuadranglePoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p3 ) const; - /// \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). - bool GetQuadrangleNormals( size_t i, MbVector3D &n0, MbVector3D &n1, MbVector3D &n2, MbVector3D &n3 ) const; - - /// \ru Удалить точки. \en Delete points. - void PointsRemove() { points.clear(); - #ifdef STANDARD_C11 - points.shrink_to_fit(); - #endif - cube.SetEmpty(); } - /// \ru Удалить точку с заданным номером. \en Delete point by the given index. - void PointRemove ( size_t i ) { if ( i < points.size() ) points.erase( points.begin() + i ); cube.SetEmpty(); } - /// \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. - void NormalRemove( size_t i ) { if ( i < normals.size() ) normals.erase( normals.begin() + i ); } - - /// \ru Установить тип объекта. \en Set type. - void SetType( CollectionType t ) { type = t; } - /// \ru Выдать тип объекта. \en Get type. - CollectionType GetType() const { return type; } - /// \ru Установить количество объектов вдоль первой координаты. \en Set the number of objects along the first coordinate. - void SetXSize( uint32 n ) { xSize = n; } - /// \ru Установить количество объектов вдоль второй координаты. \en Set the number of objects along the cecond coordinate. - void SetYSize( uint32 n ) { ySize = n; } - /// \ru Установить количество объектов вдоль третьей координаты. \en Set the number of objects along the third coordinate. - void SetZSize( uint32 n ) { zSize = n; } - /// \ru Выдать количество объектов вдоль первой координаты. \en Get the number of objects along the first coordinate. - uint32 GetXSize() const { return xSize; } - /// \ru Выдать количество объектов вдоль второй координаты. \en Get the number of objects along the cecond coordinate. - uint32 GetYSize() const { return ySize; } - /// \ru Выдать количество объектов вдоль третьей координаты. \en Get the number of objects along the third coordinate. - uint32 GetZSize() const { return zSize; } - - /// \ru Выдать точку по её номеру. \en Get point by its index. - void GetPoint ( size_t i, MbCartPoint3D & p ) const { p = points[i]; } - /// \ru Выдать множество точек. \en Get set of points. - const std::vector & GetPoints ( ) const { return points; } - /// \ru Выдать нормаль по её номеру. \en Get normal by its index. - void GetNormal( size_t i, MbVector3D & n ) const { n = normals[i]; } - /// \ru Выдать множество нормалей. \en Get set of normals. - const std::vector & GetNormals( ) const { return normals; } - /// \ru Выдать точку по её номеру. \en Get point by its index. - double GetEscort( size_t i ) const { return escorts[i]; } - /// \ru Выдать элемент по его номеру. \en Get element by its index. - void GetElement( size_t i, MbElement & elem ) const { elem = elements[i]; } - /// \ru Выдать индексы точек в массиве points для i-го объемного элемента. \en Get indices of points in 'points' array for i-th element. - bool GetElementIndex( size_t i, uint & ind0, uint & ind1, uint & ind2, uint & ind3, uint & ind4, uint & ind5, uint & ind6, uint & ind7 ) const; - /// \ru Выдать для элемента с номером i точки вершин. \en Get points of vertices for i-th element. - bool GetElementPoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p3, - MbCartPoint3D &p4, MbCartPoint3D &p5, MbCartPoint3D &p6, MbCartPoint3D &p7 ) const; - /// \ru Выдать сегмент по его номеру. \en Get segment by its index. - void GetSegment( size_t i, MbGridSegment & seg ) const { seg = segments[i]; } - /// \ru Выдать точку с заданным номером. \en Get point by the given index. - const MbCartPoint3D & GetPoint ( size_t i ) const { return points[i]; } - /// \ru Выдать нормаль с заданным номером. \en Get normal by the given index. - const MbVector3D & GetNormal( size_t i ) const { return ( (normals.size() == 1) ? normals[0] : normals[i] ); } - /// \ru Выдать треугольник с номером i. \en Get i-th triangle. - const MbTriangle & GetTriangle ( size_t i ) const { return triangles[i]; } - /// \ru Выдать четырёхугольник с номером i. \en Get i-th quadrangle. - const MbQuadrangle & GetQuadrangle( size_t i ) const { return quadrangles[i]; } - /// \ru Выдать четырёхугольник с номером i. \en Get i-th quadrangle. - const MbElement & GetElement ( size_t i ) const { return elements[i]; } - /// \ru Выдать сегмент по его номеру. \en Get segment by its index. - const MbGridSegment & GetSegment( size_t i ) const { return segments[i]; } - /// \ru Выдать полигон с номером i. \en Get i-th polygon. - //const MbExactGrid & GetGrid ( size_t i ) const { return *grids[i]; } - - /// \ru Удалить все xтреугольники. \en Delete all triangles. - void TrianglesDelete() { triangles.clear(); } - /// \ru Удалить все четырехугольники. \en Delete all quadrangles. - void QuadranglesDelete() { quadrangles.clear(); } - /// \ru Удалить все объемные элементы. \en Delete all elements. - void ElementsDelete() { elements.clear(); } - /// \ru Удалить все сегменты. \en Delete all segments. - void SegmentsDelete() { segments.clear(); } - /// \ru Удалить все nhbfyuekzwbb. \en Delete all triangulations. - //void GridsDelete(); - - /// \ru Зарезервировать память для контейнеров. \en Reserve memory for some containers. - void ReservePointsNormals( size_t n ) { points.reserve( points.size() + n ); normals.reserve( normals.size() + n ); } - /// \ru Зарезервировать память для контейнера точек. \en Reserve memory for container of points. - void PointsReserve ( size_t n ) { points.reserve( points.size() + n ); } - /// \ru Зарезервировать память для контейнера нормалей. \en Reserve memory for container of normals. - void NormalsReserve ( size_t n ) { normals.reserve( normals.size() + n ); } - /// \ru Зарезервировать память для контейнера параметров. \en Reserve memory for container of elements. - /// \ru Зарезервировать память для контейнера параметров. \en Reserve memory for container of elements. - void EscordsReserve ( size_t n ) { escorts.reserve( escorts.size() + n ); } - /// \ru Зарезервировать память для контейнера треугольников. \en Reserve memory for container of triangles. - void TrianglesReserve ( size_t n ) { triangles.reserve( triangles.size() + n ); } - /// \ru Зарезервировать память для контейнера четырехугольников. \en Reserve memory for container of quadrangles. - void QuadranglesReserve( size_t n ) { quadrangles.reserve( quadrangles.size() + n ); } - /// \ru Зарезервировать память для контейнера элементов. \en Reserve memory for container of elements. - void ElementsReserve ( size_t n ) { elements.reserve( elements.size() + n ); } - /// \ru Зарезервировать память для контейнера сегментов. \en Reserve memory for container of segments. - void SegmentsReserve ( size_t n ) { segments.reserve( segments.size() + n ); } - /// \ru Зарезервировать память для контейнера полигонов. \en Reserve memory for container of grids. - //void GridReserve ( size_t n ) { grids.reserve( grids.size() + n ); } - - /// \ru Удалить всю триангуляцию без освобождения памяти, занятую контейнерами. \en Delete all triangulation without freeing the memory occupied by containers. - void Flush() { points.clear(); normals.clear(); escorts.clear(); - triangles.clear(); quadrangles.clear(); elements.clear(); segments.clear(); //grids.clear(); - cube.SetEmpty(); } - /// \ru Удалить всю триангуляцию и освободить память. \en Delete all triangulation and free the memory. - void HardFlush() { points.clear(); normals.clear(); escorts.clear(); - triangles.clear(); quadrangles.clear(); elements.clear(); segments.clear(); //grids.clear(); - #ifdef STANDARD_C11 - points.shrink_to_fit(); normals.shrink_to_fit(); escorts.shrink_to_fit(); - triangles.shrink_to_fit(); quadrangles.shrink_to_fit(); elements.shrink_to_fit(); segments.shrink_to_fit(); //grids.shrink_to_fit(); - #endif - cube.SetEmpty(); } - /// \ru Освободить лишнюю память. \en Free the unnecessary memory. - void Adjust() { - #ifdef STANDARD_C11 - points.shrink_to_fit(); normals.shrink_to_fit(); escorts.shrink_to_fit(); - triangles.shrink_to_fit(); quadrangles.shrink_to_fit(); elements.shrink_to_fit(); segments.shrink_to_fit(); //grids.shrink_to_fit(); - #endif - } - - /// \ru Инициализировать объект. \en Initialize object. - void Init( const MbCollection & init ); - /// \ru Инициализировать объект. \en Initialize object. - void Init( const MbGrid & init ); - /// \ru Инициализировать объект. \en Initialize object. - void Init( const MbMesh & init ); - - // \ru Выдать контейнер треугольников. \en Get the container of triangles. - template - void GetTriangles( TrianglesVector & tVector ) const { - tVector.reserve( tVector.size() + triangles.size() ); - for ( size_t i = 0, iCount = triangles.size(); i < iCount; i++ ) - tVector.push_back( triangles[i] ); - } - // \ru Выдать контейнер четырёхугольников. \en Get the container of quadrangles. - template - void GetQuadrangles( QuadranglesVector & qVector ) const { - qVector.reserve( qVector.size() + quadrangles.size() ); - for ( size_t i = 0, iCount = quadrangles.size(); i < iCount; i++ ) - qVector.push_back( quadrangles[i] ); - } - - /// \ru Преобразовать четырёхугольники в треугольники. \en Convert quadrangles to triangles. - void ConvertQuadranglesToTriangles(); - /// \ru Преобразовать все объекты в треугольники и уравнять число точек и нормалей. \en Convert all objects to triangles and equalize count of points and count of normals. - void ConvertAllToTriangles(); - /// \ru Удалить дублирующие с заданной точностью друг друга точки. \en Remove redundant points with a given tolerance (duplicates). - bool RemoveRedundantPoints( bool deleteNormals, double epsilon = LENGTH_EPSILON ); - - /** \} */ - private: - /// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbCollection & operator = ( const MbCollection & ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCollection ) -}; - -IMPL_PERSISTENT_OPS( MbCollection ) - -#endif // __COLLECTION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Коллекция элементов. + \en Collection of elements . \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __COLLECTION_H +#define __COLLECTION_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbMesh; +class MATH_CLASS MbGrid; + + +//------------------------------------------------------------------------------ +/** \brief \ru Коллекция элементов. + \en Collection of elements. \~ + \details \ru Коллекция элементов - это объект геометрической модели, наследник MbItem, являющийся + множеством элементов в трехмерном пространстве. \n + \en The collection of 3D elements is an object of geometric model (subclass MbItem) which is + the set of elements in 3D space. \n \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbCollection : public MbItem { +public: + /** \brief \ru Типы коллекций 3D объектов. + \en Types of 3D object collection. \~ +*/ +enum CollectionType { + coll_PointCloud = 0, ///< \ru Облако точек. \en The point cloud. + coll_Tessellation = 1, ///< \ru Триангуляция. \en The tessellation. + coll_Elements = 2, ///< \ru Набор элементов. \en Set of elements. + coll_Segmentation = 3, ///< \ru Сегментированная полигональная сетка. \en Segmented polygonal mesh. +}; + +private: + CollectionType type; ///< \ru Тип коллекции 3D объектов. \en Type of 3D object collection. + uint32 xSize; ///< \ru Количество объектов вдоль первой координаты. \en The number of objects along the first coordinate. + uint32 ySize; ///< \ru Количество объектов вдоль второй координаты. \en The number of objects along the second coordinate. + uint32 zSize; ///< \ru Количество объектов вдоль третьей координаты. \en The number of objects along the third coordinate. + std::vector points; ///< \ru Множество точек. \en Set of points. + std::vector normals; ///< \ru Множество нормалей в точках согласовано с множеством точек. \en Set of normals at control points is synchronized with the set of points. + std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. + std::vector triangles; ///< \ru Индексное множество треугольных пластин содержит номера элементов множества points и normals. \en Set of triangular plates contains numbers of elements of 'points' and 'normals' sets. + std::vector quadrangles; ///< \ru Индексное множество четырёхугольных пластин содержит номера элементов множества params и/или множеств points и normals. \en Set of quadrangular plates contains numbers of elements of 'params' set and/or of 'points' and 'normals' sets. + std::vector elements; ///< \ru Индексное множество объемных элементов содержит номера элементов множества points. \en Set of volume elements contains numbers of vertices of 'points' sets. + std::vector segments; ///< \ru Множество сегментов полигональной сетки. \en Set of segments of mesh. + + /** \brief \ru Габаритный куб объекта. + \en Bounding box of object. \~ + \details \ru Габаритный куб объекта рассчитывается только при запросе габарита объекта. Габаритный куб в конструкторе объекта и после модификации объекта принимает неопределенное значение. + \en Bounding box of object is calculated only at the request. Bounding box of object is undefined after object constructor and after object modifications \n \~ + */ + mutable MbCube cube; +private: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbCollection( const MbCollection & init ); + + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbCollection( const MbCollection &, MbRegDuplicate * ); +public: + /// \ru Конструктор. \en Constructor. + MbCollection(); + /// \ru Конструктор. \en Constructor. + MbCollection( const MbMesh & mesh ); + + /// \ru Деструктор. \en Destructor. + virtual ~MbCollection(); + +public: + VISITING_CLASS( MbCollection ); + + // \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 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. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. + virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + virtual MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create a custom 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 Create a polygonal object - a simplified copy of the given object. + virtual MbItem * CreateMesh( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * iReg ) const; + // \ru Создать полигональный объект - упрощенную копию данного объекта. \en Create a polygonal object - a simplified copy of the given object. + MbGrid * CreateGrid() const; + + // \ru Создать сетки из четырехугольных пластин наружных стенок элементов. \en Create grids by quadrangular plates of the outside walls of elements. + void CreateGridsByElements( RPArray & grids_ ) const; + + // \ru Создать угловые точки и элементы. \en Create corner points and elements. + void CreateCornerPointsAndElements( SArray & points0, SArray & elements0 ) const; + + // \ru Создать сетки из по результатам сегментации. \en Create grids by segmentation results. + void CreateGridsBySegments( RPArray & grids_ ) const; + + /** \ru \name Общие функции коллекции. + \en \name Common functions of a collection. + \{ */ + + /// \ru Выдать количество точек. \en Get count of points. + size_t PointsCount() const { return points.size(); } + /// \ru Выдать количество нормалей. \en Get the number of normals. + size_t NormalsCount() const { return normals.size(); } + /// \ru Выдать количество значений. \en Get count of values. + size_t EscortsCount() const { return escorts.size(); } + /// \ru Выдать количество треугольников. \en Get the number of triangles. + size_t TrianglesCount() const { return triangles.size(); } + /// \ru Выдать количество четырехугольников. \en Get the number of quadrangles. + size_t QuadranglesCount() const { return quadrangles.size(); } + /// \ru Выдать количество объемных элементов. \en Get the number of elements of volume. + size_t ElementsCount() const { return elements.size(); } + /// \ru Выдать количество сегментов. \en Get the number of segments of mesh. + size_t SegmentsCount() const { return segments.size(); } + /// \ru Выдать количество триангуляций. \en Get the number of triangulations. + //size_t GridsCount() const { return grids.size(); } + ptrdiff_t PointsMaxIndex() const { ptrdiff_t c = points.size(); return ( c - 1 ); } + /// \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). + ptrdiff_t NormalsMaxIndex() const { ptrdiff_t c = normals.size(); return ( c - 1 ); } + + /// \ru Добавить в коллекцию точку и нормаль в точке. \en Add a point and normal at the point to collection. + void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ) { points.push_back(p3D); normals.push_back(n3D); cube.SetEmpty(); } + /// \ru Добавить в коллекцию точку. \en Add a point to collection. + void AddPoint ( const MbCartPoint3D & p3D ) { points.push_back(p3D); cube.SetEmpty(); } + /// \ru Добавить в коллекцию нормаль. \en Add a normal to collection. + void AddNormal( const MbVector3D & n3D ) { normals.push_back(n3D) ; } + /// \ru Добавить в коллекцию точки. \en Add points to collection. + void AddPoints ( const std::vector & pnts ) { points.insert(points.end(), pnts.begin(), pnts.end()); cube.SetEmpty(); } + /// \ru Добавить в коллекцию нормали. \en Add normals to collection. + void AddNormals( const SArray & nrms ) { normals.insert(normals.end(), nrms.begin(), nrms.end()); cube.SetEmpty(); } + /// \ru Добавить в коллекцию данных. \en Add scores to collection. + void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } + + /// \ru Добавить треугольник. \en Add a triangle. + void AddTriangle ( const MbTriangle & triangle ) { triangles.push_back( triangle ); } + /// \ru Добавить треугольник с заданными номерами вершин. \en Add a triangle by the given indices of vertices + void AddTriangle ( uint j0, uint j1, uint j2, bool o ) { MbTriangle t(j0,j1,j2,o); triangles.push_back( t ); } + /// \ru Добавить четырёхугольник. \en Add a quadrangle. + void AddQuadrangle( const MbQuadrangle & quadrangle ) { quadrangles.push_back( quadrangle ); } + /// \ru Добавить четырёхугольник с заданными номерами вершин. \en Add a quadrangle by the given indices of vertices. + void AddQuadrangle( uint j0, uint j1, uint j2, uint j3, bool o ) { MbQuadrangle t(j0,j1,j2,j3,o); quadrangles.push_back( t ); } + /// \ru Добавить объемный элемент. \en Add an element. + void AddElement( const MbElement & element ) { elements.push_back(element); } + /// \ru Добавить объемный элемент. \en Add an element. + void AddElement( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ) { + MbElement t( j0,j1,j2,j3,j4,j5,j6,j7 ); elements.push_back( t ); } + void AddSegment( const MbGridSegment & segment ) { segments.push_back( segment ); } + void AddSegment( const std::vector & initFaces ) { MbGridSegment seg( initFaces ); segments.push_back( seg ); } + /// \ru Добавить полигон. \en Add a polygon. + //void AddGrid( MbExactGrid & grd ) { grids.push_back( &grd ); } + + /// \ru Выдать индексы точек в массиве points для i-го треугольника (связанного или несвязанного). \en Get indices of points in 'points' array for i-th triangle (adjacent or non-adjacent). + bool GetTrianglePointIndex ( size_t i, uint & ind0, uint & ind1, uint & ind2 ) const; + /// \ru Выдать индексы точек в массиве points для i-го четырехугольника (связанного или несвязанного). \en Get indices of points in 'points' array for i-th quadrangle (adjacent or non-adjacent). + bool GetQuadranglePointIndex( size_t i, uint & ind0, uint & ind1, uint & ind2, uint & ind3 ) const; + /// \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). + bool GetTrianglePoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2 ) const; + /// \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). + bool GetTriangleNormals ( size_t i, MbVector3D &n0, MbVector3D &n1, MbVector3D &n2 ) const; + + /// \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). + bool GetQuadranglePoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p3 ) const; + /// \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). + bool GetQuadrangleNormals( size_t i, MbVector3D &n0, MbVector3D &n1, MbVector3D &n2, MbVector3D &n3 ) const; + + /// \ru Удалить точки. \en Delete points. + void PointsRemove() { points.clear(); + #ifdef C3D_STANDARD_CXX_11_PARTIAL + points.shrink_to_fit(); + #endif + cube.SetEmpty(); } + /// \ru Удалить точку с заданным номером. \en Delete point by the given index. + void PointRemove ( size_t i ) { if ( i < points.size() ) points.erase( points.begin() + i ); cube.SetEmpty(); } + /// \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. + void NormalRemove( size_t i ) { if ( i < normals.size() ) normals.erase( normals.begin() + i ); } + + /// \ru Установить тип объекта. \en Set type. + void SetType( CollectionType t ) { type = t; } + /// \ru Выдать тип объекта. \en Get type. + CollectionType GetType() const { return type; } + /// \ru Установить количество объектов вдоль первой координаты. \en Set the number of objects along the first coordinate. + void SetXSize( uint32 n ) { xSize = n; } + /// \ru Установить количество объектов вдоль второй координаты. \en Set the number of objects along the cecond coordinate. + void SetYSize( uint32 n ) { ySize = n; } + /// \ru Установить количество объектов вдоль третьей координаты. \en Set the number of objects along the third coordinate. + void SetZSize( uint32 n ) { zSize = n; } + /// \ru Выдать количество объектов вдоль первой координаты. \en Get the number of objects along the first coordinate. + uint32 GetXSize() const { return xSize; } + /// \ru Выдать количество объектов вдоль второй координаты. \en Get the number of objects along the cecond coordinate. + uint32 GetYSize() const { return ySize; } + /// \ru Выдать количество объектов вдоль третьей координаты. \en Get the number of objects along the third coordinate. + uint32 GetZSize() const { return zSize; } + + /// \ru Выдать точку по её номеру. \en Get point by its index. + void GetPoint ( size_t i, MbCartPoint3D & p ) const { p = points[i]; } + /// \ru Выдать множество точек. \en Get set of points. + const std::vector & GetPoints ( ) const { return points; } + /// \ru Выдать нормаль по её номеру. \en Get normal by its index. + void GetNormal( size_t i, MbVector3D & n ) const { n = normals[i]; } + /// \ru Выдать множество нормалей. \en Get set of normals. + const std::vector & GetNormals( ) const { return normals; } + /// \ru Выдать точку по её номеру. \en Get point by its index. + double GetEscort( size_t i ) const { return escorts[i]; } + /// \ru Выдать элемент по его номеру. \en Get element by its index. + void GetElement( size_t i, MbElement & elem ) const { elem = elements[i]; } + /// \ru Выдать индексы точек в массиве points для i-го объемного элемента. \en Get indices of points in 'points' array for i-th element. + bool GetElementIndex( size_t i, uint & ind0, uint & ind1, uint & ind2, uint & ind3, uint & ind4, uint & ind5, uint & ind6, uint & ind7 ) const; + /// \ru Выдать для элемента с номером i точки вершин. \en Get points of vertices for i-th element. + bool GetElementPoints ( size_t i, MbCartPoint3D &p0, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p3, + MbCartPoint3D &p4, MbCartPoint3D &p5, MbCartPoint3D &p6, MbCartPoint3D &p7 ) const; + /// \ru Выдать сегмент по его номеру. \en Get segment by its index. + void GetSegment( size_t i, MbGridSegment & seg ) const { seg = segments[i]; } + /// \ru Выдать точку с заданным номером. \en Get point by the given index. + const MbCartPoint3D & GetPoint ( size_t i ) const { return points[i]; } + /// \ru Выдать нормаль с заданным номером. \en Get normal by the given index. + const MbVector3D & GetNormal( size_t i ) const { return ( (normals.size() == 1) ? normals[0] : normals[i] ); } + /// \ru Выдать треугольник с номером i. \en Get i-th triangle. + const MbTriangle & GetTriangle ( size_t i ) const { return triangles[i]; } + /// \ru Выдать четырёхугольник с номером i. \en Get i-th quadrangle. + const MbQuadrangle & GetQuadrangle( size_t i ) const { return quadrangles[i]; } + /// \ru Выдать четырёхугольник с номером i. \en Get i-th quadrangle. + const MbElement & GetElement ( size_t i ) const { return elements[i]; } + /// \ru Выдать сегмент по его номеру. \en Get segment by its index. + const MbGridSegment & GetSegment( size_t i ) const { return segments[i]; } + /// \ru Выдать полигон с номером i. \en Get i-th polygon. + //const MbExactGrid & GetGrid ( size_t i ) const { return *grids[i]; } + + /// \ru Удалить все xтреугольники. \en Delete all triangles. + void TrianglesDelete() { triangles.clear(); } + /// \ru Удалить все четырехугольники. \en Delete all quadrangles. + void QuadranglesDelete() { quadrangles.clear(); } + /// \ru Удалить все объемные элементы. \en Delete all elements. + void ElementsDelete() { elements.clear(); } + /// \ru Удалить все сегменты. \en Delete all segments. + void SegmentsDelete() { segments.clear(); } + /// \ru Удалить все nhbfyuekzwbb. \en Delete all triangulations. + //void GridsDelete(); + + /// \ru Зарезервировать память для контейнеров. \en Reserve memory for some containers. + void ReservePointsNormals( size_t n ) { points.reserve( points.size() + n ); normals.reserve( normals.size() + n ); } + /// \ru Зарезервировать память для контейнера точек. \en Reserve memory for container of points. + void PointsReserve ( size_t n ) { points.reserve( points.size() + n ); } + /// \ru Зарезервировать память для контейнера нормалей. \en Reserve memory for container of normals. + void NormalsReserve ( size_t n ) { normals.reserve( normals.size() + n ); } + /// \ru Зарезервировать память для контейнера параметров. \en Reserve memory for container of elements. + /// \ru Зарезервировать память для контейнера параметров. \en Reserve memory for container of elements. + void EscordsReserve ( size_t n ) { escorts.reserve( escorts.size() + n ); } + /// \ru Зарезервировать память для контейнера треугольников. \en Reserve memory for container of triangles. + void TrianglesReserve ( size_t n ) { triangles.reserve( triangles.size() + n ); } + /// \ru Зарезервировать память для контейнера четырехугольников. \en Reserve memory for container of quadrangles. + void QuadranglesReserve( size_t n ) { quadrangles.reserve( quadrangles.size() + n ); } + /// \ru Зарезервировать память для контейнера элементов. \en Reserve memory for container of elements. + void ElementsReserve ( size_t n ) { elements.reserve( elements.size() + n ); } + /// \ru Зарезервировать память для контейнера сегментов. \en Reserve memory for container of segments. + void SegmentsReserve ( size_t n ) { segments.reserve( segments.size() + n ); } + /// \ru Зарезервировать память для контейнера полигонов. \en Reserve memory for container of grids. + //void GridReserve ( size_t n ) { grids.reserve( grids.size() + n ); } + + /// \ru Удалить всю триангуляцию без освобождения памяти, занятую контейнерами. \en Delete all triangulation without freeing the memory occupied by containers. + void Flush() { points.clear(); normals.clear(); escorts.clear(); + triangles.clear(); quadrangles.clear(); elements.clear(); segments.clear(); //grids.clear(); + cube.SetEmpty(); } + /// \ru Удалить всю триангуляцию и освободить память. \en Delete all triangulation and free the memory. + void HardFlush() { points.clear(); normals.clear(); escorts.clear(); + triangles.clear(); quadrangles.clear(); elements.clear(); segments.clear(); //grids.clear(); + #ifdef C3D_STANDARD_CXX_11_PARTIAL + points.shrink_to_fit(); normals.shrink_to_fit(); escorts.shrink_to_fit(); + triangles.shrink_to_fit(); quadrangles.shrink_to_fit(); elements.shrink_to_fit(); segments.shrink_to_fit(); //grids.shrink_to_fit(); + #endif + cube.SetEmpty(); } + /// \ru Освободить лишнюю память. \en Free the unnecessary memory. + void Adjust() { + #ifdef C3D_STANDARD_CXX_11_PARTIAL + points.shrink_to_fit(); normals.shrink_to_fit(); escorts.shrink_to_fit(); + triangles.shrink_to_fit(); quadrangles.shrink_to_fit(); elements.shrink_to_fit(); segments.shrink_to_fit(); //grids.shrink_to_fit(); + #endif + } + + /// \ru Инициализировать объект. \en Initialize object. + void Init( const MbCollection & init ); + /// \ru Инициализировать объект. \en Initialize object. + void Init( const MbGrid & init ); + /// \ru Инициализировать объект. \en Initialize object. + void Init( const MbMesh & init ); + + // \ru Выдать контейнер треугольников. \en Get the container of triangles. + template + void GetTriangles( TrianglesVector & tVector ) const { + tVector.reserve( tVector.size() + triangles.size() ); + for ( size_t i = 0, iCount = triangles.size(); i < iCount; i++ ) + tVector.push_back( triangles[i] ); + } + // \ru Выдать контейнер четырёхугольников. \en Get the container of quadrangles. + template + void GetQuadrangles( QuadranglesVector & qVector ) const { + qVector.reserve( qVector.size() + quadrangles.size() ); + for ( size_t i = 0, iCount = quadrangles.size(); i < iCount; i++ ) + qVector.push_back( quadrangles[i] ); + } + + /// \ru Преобразовать четырёхугольники в треугольники. \en Convert quadrangles to triangles. + void ConvertQuadranglesToTriangles(); + /// \ru Преобразовать все объекты в треугольники и уравнять число точек и нормалей. \en Convert all objects to triangles and equalize count of points and count of normals. + void ConvertAllToTriangles(); + /// \ru Удалить дублирующие с заданной точностью друг друга точки. \en Remove redundant points with a given tolerance (duplicates). + bool RemoveRedundantPoints( bool deleteNormals, double epsilon = LENGTH_EPSILON ); + + /** \} */ + private: + /// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbCollection & operator = ( const MbCollection & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCollection ) +}; + +IMPL_PERSISTENT_OPS( MbCollection ) + +#endif // __COLLECTION_H diff --git a/C3d/Include/comanager.h b/C3d/Include/comanager.h index f493bf7..c96969e 100644 --- a/C3d/Include/comanager.h +++ b/C3d/Include/comanager.h @@ -1,59 +1,59 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Модуль: COMANAGER - \en Module: COMANAGER. \~ - \details \ru Цель: Менеджер геометрических ограничений для MbModel - \en Target: Geometric constraints manager for MbModel \~ - -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __COMANAGER_H -#define __COMANAGER_H -// -#include -#include -// constraints -#include "gce_api.h" - - - -class GcFormerImpl; -class MbConstraint; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Менеджер для взаимодействия с решателем \en Manager of interactions with the solver -// -////////////////////////////////////////////////////////////////////////////////////////// - -class MATH_CLASS ConstraintManager2D -{ - GCE_system m_gcSolver; - GcFormerImpl & m_gcFormer; - -public: - ConstraintManager2D(); - ~ConstraintManager2D(); - -public: - /// \ru Добавить ограничение в решатель \en Add a constraint to the solver - bool AddConstraint( const MbConstraint & ); - /// \ru Рассчитать систему ограничений \en Compute a system of constraints - bool Evaluate(); - /// \ru Применить решение \en Apply the solution - void ApplySolution(); - /// \ru Очистить весь контекст решателя \en Clear the whole context of the solver - void Clear(); - -private: - ConstraintManager2D( const ConstraintManager2D & ); - ConstraintManager2D & operator = ( const ConstraintManager2D & ); -}; - -#endif // __COMANAGER_H - - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Модуль: COMANAGER + \en Module: COMANAGER. \~ + \details \ru Цель: Менеджер геометрических ограничений для MbModel + \en Target: Geometric constraints manager for MbModel \~ + +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __COMANAGER_H +#define __COMANAGER_H +// +#include +#include +// constraints +#include "gce_api.h" + + + +class GcFormerImpl; +class MbConstraint; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Менеджер для взаимодействия с решателем \en Manager of interactions with the solver +// +////////////////////////////////////////////////////////////////////////////////////////// + +class MATH_CLASS ConstraintManager2D +{ + GCE_system m_gcSolver; + GcFormerImpl & m_gcFormer; + +public: + ConstraintManager2D(); + ~ConstraintManager2D(); + +public: + /// \ru Добавить ограничение в решатель \en Add a constraint to the solver + bool AddConstraint( const MbConstraint & ); + /// \ru Рассчитать систему ограничений \en Compute a system of constraints + bool Evaluate(); + /// \ru Применить решение \en Apply the solution + void ApplySolution(); + /// \ru Очистить весь контекст решателя \en Clear the whole context of the solver + void Clear(); + +private: + ConstraintManager2D( const ConstraintManager2D & ); + ConstraintManager2D & operator = ( const ConstraintManager2D & ); +}; + +#endif // __COMANAGER_H + + // eof \ No newline at end of file diff --git a/C3d/Include/constraint.h b/C3d/Include/constraint.h index d096cee..b15f24f 100644 --- a/C3d/Include/constraint.h +++ b/C3d/Include/constraint.h @@ -1,229 +1,237 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Геометрическое ограничение. - \en Geometric constraint. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONSTRAINT_H -#define __CONSTRAINT_H - -#include -#include -#include -#include -#include - -struct CNodeIterator; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Аргумент геометрического ограничения. - \en An argument of geometric constraint. \~ - \details \ru Аргумент ограничений со связанным элементом, указателем на геометрический - объект, содержащий элемент, и указателем на сборку, содержащую объект. - \en An argument of constraints with connected element, the geometric object - containing the element, and the assembly containing the object.\~ - \ingroup Model_Items -*/ -//--- -class MATH_CLASS MtGeomArgument -{ -private: - SPtr propItem; ///< \ru Элемент объекта, непосредственно выбранный для связи. \en The element of geom object which constraints are connected to. - SimpleName propName; ///< \ru Имя связываемого элемента. \en Name of a connected element. - uint32 hash; ///< \ru Имя объекта сборки или подсборки, содержащего объект связи с ограничением. \en Hash code of the path from the root to the item. - SPtr item; ///< \ru Объект сборки или подсборки, содержащий объект связи с ограничением. \en Assembly object that hosts geom entity connected to constraint. - const MbAssembly * root; ///< \ru Сборка, содержащая объект с ограничением. \en The assembly that hosts geom object with entity connected to constraint. - -public: - static const MtGeomArgument null; ///< \ru Пустой аргумент. \en An empty argument. - -public: - MtGeomArgument( const MbRefItem * p, const MbItem * h ); - MtGeomArgument( const MtGeomArgument & ); - MtGeomArgument() : propItem( NULL ), propName( UNDEFINED_SNAME ) - , hash( UNDEFINED_SNAME ), item( NULL ), root( NULL ) {} - -public: - /** \brief \ru Получить непосредственный объект сборки, содержащий ссылочный объект. - \en Get immediate object of the assembly containing the reference object. - \param trans - \ru Матрица ссылочного объекта в системе координат непосредственного объекта сборки. - - \en Matrix from the reference object to the sub-item of the assembly. \~ - */ - const MbItem * SubItemOf( const MbAssembly *, MbMatrix3D & trans ) const; - /// \ru Объект геометрической модели, владеющий аргументом. \en Geometry model object which is a host of an argument. - const MbItem * HostItem() const { return item; } - /// \ru Аргумент ограничения, заданный в ЛСК хозяина. \en Geometric constraint argument given in the host's LCS. - const MbRefItem * PropItem() const { return propItem; } - /// \ru Выдать значение геометрии аргумента, заданное в ЛСК хозяина. \en Get geometric value of argument given in the host LCS. - MtGeomVariant PropGeom() const; - /// \ru Выдать хэш-имя объекта. \en Get a hash name of the object. - SimpleName PropName() const; - /// \ru Равны ли объекты? \en Are objects equal? \~ - bool IsSame( const MtGeomArgument & r ) const { - return ( (propItem == r.propItem) && (propName == r.propName) && (item == r.item) && (hash == r.hash) ); - } - /// \ru Равны ли ссылкпи на объект модели? \en Are the references to the model object equal? \~ - bool IsSameItemReference( const MtGeomArgument & r ) const { // MtItemReference - return ( (hash == r.hash) && (item == r.item) && (root == r.root) ); - } - /// \ru Оператор равенства объектов. \en Objects equality operator. \~ - bool operator == ( const MtGeomArgument & ) const; - /// \ru Оператор копирования. \en Copy operator. \~ - MtGeomArgument & operator = ( const MtGeomArgument & ); - -KNOWN_OBJECTS_RW_REF_OPERATORS( MtGeomArgument ) // Serializing into a file format -}; // MtGeomArgument - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Геометрическое ограничение. - \en Geometric constraint. \~ - \details \ru Этот класс представляет все виды ограничений, включая геометрические и - размерные отношения между объектами модели. - \en This class represents all kinds of constraints of assembly, including - geometrical and dimensional relationships between the model objects. \~ - \ingroup Model_Items -*/ -//--- -class MATH_CLASS MtGeomConstraint -{ -private: - const ItConstraintItem * m_cItem; ///< \ru Указатель на реализацию геометрического ограничения. \en Pointer to geometric constraint implementation. \~ - std::vector m_arguments; ///< \ru Аргументы геометрического ограничения. \en The arguments of geometric constraint. \~ - SPtr m_mesh; ///< \ru Объект для демонстрации геометрического ограничения. \en The draw object of geometric constraint. \~ - -public: - MtGeomConstraint( const MtGeomConstraint & ); - ~MtGeomConstraint(); - -public: - /// \ru Возвращает true, если ограничение не действительно. \en Return true if the constraint is invalid. - bool IsNull() const { return m_cItem == NULL; } - /// \ru Тип сопряжения (геометрического ограничения). \en Type of geometric constraint. - MtMateType ConstraintType() const; - /// \ru Текущее значение размера. \en Current value of the dimension. - double DimValue() const; - /// \ru Создать полигональный объект для отображения геометрических ограничений. \en Create a polygonal object for visualization. - bool CreateMesh( const MbAssembly & assem, const MbStepData & stepData, const MbFormNote & note, double meshUnit, uint32 color ); - /// \ru Выдать указатель на объект для демонстрации геометрического ограничения. \en Get a pointer to draw object of geometric constraint. - const MbItem * GetMesh() const { return m_mesh.get(); } - - // \ru Объявление оператора присваивания. \en Declaration of the assignment operator. - MtGeomConstraint & operator = (const MtGeomConstraint & arg ); - -protected: - friend class MbConstraintSystem; - friend class MtConstraintIter; - /// \ru Выдать указатель на реализацию геометрического ограничения. \en Get a pointer to geometric constraint implementation. \~ - const ItConstraintItem * ConstraintItem() const { return m_cItem; } - - MtGeomConstraint( const ItConstraintItem * cItem, const MtGeomArgument & a1, const MtGeomArgument & a2 ); - MtGeomConstraint( const MbConstraintSystem &, const ItConstraintItem * cItem ); -}; // MtGeomConstraint - - -//---------------------------------------------------------------------------------------- -/// \ru Итератор обходящий ограничения сборки. \en Iterator traversing assembly constraints. -//--- -class MATH_CLASS MtConstraintIter -{ -private: - CNodeIterator * m_cIter; - const MbConstraintSystem * m_gcSystem; - -public: - MtConstraintIter(); - MtConstraintIter( const MtConstraintIter & ); - MtConstraintIter & operator = ( const MtConstraintIter & ); - ~MtConstraintIter(); - -public: - MtGeomConstraint Get() const; - MtConstraintIter & Set( const MbConstraintSystem *, CNodeIterator & ); - const MtConstraintIter & Next(); - bool EqualTo( const MtConstraintIter & ) const; - -public: - //operator CNodeIterator& () { return *impl; } - MtGeomConstraint operator*() const { return Get(); } - // prefix operator - const MtConstraintIter & operator++() { return Next(); } - bool operator ==( const MtConstraintIter & iter ) const { return EqualTo( iter ); } - bool operator !=( const MtConstraintIter & iter ) const { return !EqualTo( iter ); } - -}; // MtConstraintIter - - -//---------------------------------------------------------------------------------------- -/// \ru Обработчик события, связанные с решением сборки. \en The event handles related to solving the assembly. -//--- -struct MATH_CLASS ItAssemblyReactor -{ -public: - /// \ru Захватить сборкой объект для дальнейшей работы. \en Capture the reactor instance by the assembly for further work. - virtual void Capture( const MbAssembly * ) = 0; - /// \ru Отпустить сборкой объект, прекратить работать с ним. \en Release this instance by the assembly, stop working with it. - virtual void Release() = 0; - /// \ru Геометрический решатель не пытался удовлетворить ограничение. \en This called when geometric solver failed to try for constraint satisfaction. - virtual void EvaluationFailed( const MbAssembly * ) const {} - /// \ru Геометрический решатель нашел новую позицию под-объекта сборки. \en The geometric solver found a new position of a constrained sub-object belonging the assembly. - virtual void PositionChanged( const MbAssembly *, const MbItem * /*subItem*/ ) const {} - -protected: - ~ItAssemblyReactor() {} -}; // ItAssemblyReactor - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Интерфейс для системы ограничения импорта сборки из приложения. - \en The user defined interface for import constraint system of an assembly from CAD application. -*/ -//--- -struct MATH_CLASS ItAssemblyImportData -{ -protected: - ~ItAssemblyImportData() {} - -public: - /// \ru Импорт системы ограничений сборки. \en Import a constraint system of the assembly. - virtual bool ImportCSystem( const MbAssembly &, GCM_system & ) const = 0; - /// \ru Получить дескриптор элемента сборки в системе ограничений. \en Get a descriptor of assembly sub-item which used in the constraint system. - virtual MtGeomId GeomId( const MbAssembly &, const MbItem * ) const = 0; - /// \ru Получить объект модели, являющийся аргументом геометрического ограничения. \en Get the model object that is the argument of the geometric constraint. - virtual MtGeomArgument GeomSubItem( const MtArgument & ) const { return MtGeomArgument(); } - /// \ru Получить объект модели, являющийся аргументом геометрического ограничения. \en Get the model object that is the argument of the geometric constraint. - virtual MtGeomArgument GeomSubItem( MtGeomId ) const { return MtGeomArgument(); } -}; //ItAssemblyImportData - -//---------------------------------------------------------------------------------------- -/// \ru Оператор равенства объектов. \en Objects equality operator. \~ -//--- -inline bool MtGeomArgument::operator == ( const MtGeomArgument & r ) const -{ - if ( propItem != r.propItem ) - return false; - if ( propName != r.propName ) - return false; - if ( (item == r.item) && (hash == r.hash) ) - return true; - if ( (hash == r.hash) && (root == r.root) ) - return true; - return false; -} - -//---------------------------------------------------------------------------------------- -/// \ru Оператор копирования. \en Copy operator. \~ -//--- -inline MtGeomArgument & MtGeomArgument::operator = ( const MtGeomArgument & arg ) -{ - propItem = arg.propItem; - propName = arg.propName; - hash = arg.hash; - item = arg.item; - root = arg.root; - return *this; -} - -#endif // __CONSTRAINT_H +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Геометрическое ограничение. + \en Geometric constraint. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONSTRAINT_H +#define __CONSTRAINT_H + +#include +#include +#include +#include +#include + +struct CNodeIterator; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Аргумент геометрического ограничения. + \en An argument of geometric constraint. \~ + \details \ru Аргумент ограничений со связанным элементом, указателем на геометрический + объект, содержащий элемент, и указателем на сборку, содержащую объект. + \en An argument of constraints with connected element, the geometric object + containing the element, and the assembly containing the object.\~ + \ingroup Model_Items +*/ +//--- +class MATH_CLASS MtGeomArgument +{ +private: + SPtr propItem; ///< \ru Элемент объекта, непосредственно выбранный для связи. \en The element of geom object which constraints are connected to. + SimpleName propName; ///< \ru Имя связываемого элемента. \en Name of a connected element. + SimpleName hash; ///< \ru Имя объекта сборки или подсборки, содержащего объект связи с ограничением. \en Hash code of the path from the root to the item. + SPtr item; ///< \ru Объект сборки или подсборки, содержащий объект связи с ограничением. \en Assembly object that hosts geom entity connected to constraint. + const MbAssembly * root; ///< \ru Сборка, содержащая объект с ограничением. \en The assembly that hosts geom object with entity connected to constraint. + +public: + static const MtGeomArgument null; ///< \ru Пустой аргумент. \en An empty argument. + +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 ) {} + +public: + /** \brief \ru Получить непосредственный объект сборки, содержащий ссылочный объект. + \en Get immediate object of the assembly containing the reference object. + \param trans - \ru Матрица ссылочного объекта в системе координат непосредственного объекта сборки. + - \en Matrix from the reference object to the sub-item of the assembly. \~ + */ + const MbItem * SubItemOf( const MbAssembly *, MbMatrix3D & trans ) const; + /// \ru Объект геометрической модели, владеющий аргументом. \en Geometry model object which is a host of an argument. + const MbItem * HostItem() const { return item; } + /// \ru Аргумент ограничения, заданный в ЛСК хозяина. \en Geometric constraint argument given in the host's LCS. + const MbRefItem * PropItem() const { return propItem; } + ///< \ru Выдать имя связываемого элемента. \en Get name of a connected element. + SimpleName GetPropName() const { return propName; } + ///< \ru Выдать имя объекта сборки или подсборки, содержащего объект связи с ограничением. \en Get hash code of the path from the root to the item. + SimpleName GetHash() const { return hash; } + ///< \ru Выдать сборку, содержащую объект с ограничением. \en Get assembly that hosts geom object with entity connected to constraint. + const MbAssembly * GetRoot() const { return root; } + /// \ru Выдать значение геометрии аргумента, заданное в ЛСК хозяина. \en Get geometric value of argument given in the host LCS. + MtGeomVariant PropGeom() const; + /// \ru Выдать хэш-имя объекта. \en Get a hash name of the object. + SimpleName PropName() const; + /// \ru Равны ли объекты? \en Are objects equal? \~ + bool IsSame( const MtGeomArgument & r ) const { + return ( (propItem == r.propItem) && (propName == r.propName) && (item == r.item) && (hash == r.hash) ); + } + /// \ru Равны ли ссылкпи на объект модели? \en Are the references to the model object equal? \~ + bool IsSameItemReference( const MtGeomArgument & r ) const { // MtItemReference + return ( (hash == r.hash) && (item == r.item) && (root == r.root) ); + } + /// \ru Оператор равенства объектов. \en Objects equality operator. \~ + bool operator == ( const MtGeomArgument & ) const; + /// \ru Оператор копирования. \en Copy operator. \~ + MtGeomArgument & operator = ( const MtGeomArgument & ); + +KNOWN_OBJECTS_RW_REF_OPERATORS( MtGeomArgument ) // Serializing into a file format +}; // MtGeomArgument + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Геометрическое ограничение. + \en Geometric constraint. \~ + \details \ru Этот класс представляет все виды ограничений, включая геометрические и + размерные отношения между объектами модели. + \en This class represents all kinds of constraints of assembly, including + geometrical and dimensional relationships between the model objects. \~ + \ingroup Model_Items +*/ +//--- +class MATH_CLASS MtGeomConstraint +{ +private: + const ItConstraintItem * m_cItem; ///< \ru Указатель на реализацию геометрического ограничения. \en Pointer to geometric constraint implementation. \~ + std::vector m_arguments; ///< \ru Аргументы геометрического ограничения. \en The arguments of geometric constraint. \~ + SPtr m_mesh; ///< \ru Объект для демонстрации геометрического ограничения. \en The draw object of geometric constraint. \~ + +public: + MtGeomConstraint( const MtGeomConstraint & ); + ~MtGeomConstraint(); + +public: + /// \ru Возвращает true, если ограничение не действительно. \en Return true if the constraint is invalid. + bool IsNull() const { return m_cItem == NULL; } + /// \ru Тип сопряжения (геометрического ограничения). \en Type of geometric constraint. + MtMateType ConstraintType() const; + /// \ru Текущее значение размера. \en Current value of the dimension. + double DimValue() const; + /// \ru Создать полигональный объект для отображения геометрических ограничений. \en Create a polygonal object for visualization. + bool CreateMesh( const MbAssembly & assem, const MbStepData & stepData, const MbFormNote & note, double meshUnit, uint32 color ); + /// \ru Выдать указатель на реализацию геометрического ограничения. \en Get a pointer to geometric constraint implementation. \~ + const ItConstraintItem * ConstraintItem() const { return m_cItem; } + /// \ru Выдать аргументы геометрического ограничения. \en Get arguments of geometric constraint. \~ + const std::vector & GeomArguments() const { return m_arguments; } + /// \ru Выдать указатель на объект для демонстрации геометрического ограничения. \en Get a pointer to draw object of geometric constraint. \~ + const MbItem * GetMesh() const { return m_mesh.get(); } + + // \ru Объявление оператора присваивания. \en Declaration of the assignment operator. + MtGeomConstraint & operator = (const MtGeomConstraint & arg ); + +protected: + friend class MbConstraintSystem; + friend class MtConstraintIter; + + MtGeomConstraint( const ItConstraintItem * cItem, const MtGeomArgument & a1, const MtGeomArgument & a2 ); + MtGeomConstraint( const MbConstraintSystem &, const ItConstraintItem * cItem ); +}; // MtGeomConstraint + + +//---------------------------------------------------------------------------------------- +/// \ru Итератор обходящий ограничения сборки. \en Iterator traversing assembly constraints. +//--- +class MATH_CLASS MtConstraintIter +{ +private: + CNodeIterator * m_cIter; + const MbConstraintSystem * m_gcSystem; + +public: + MtConstraintIter(); + MtConstraintIter( const MtConstraintIter & ); + MtConstraintIter & operator = ( const MtConstraintIter & ); + ~MtConstraintIter(); + +public: + MtGeomConstraint Get() const; + MtConstraintIter & Set( const MbConstraintSystem *, CNodeIterator & ); + const MtConstraintIter & Next(); + bool EqualTo( const MtConstraintIter & ) const; + +public: + //operator CNodeIterator& () { return *impl; } + MtGeomConstraint operator*() const { return Get(); } + // prefix operator + const MtConstraintIter & operator++() { return Next(); } + bool operator ==( const MtConstraintIter & iter ) const { return EqualTo( iter ); } + bool operator !=( const MtConstraintIter & iter ) const { return !EqualTo( iter ); } + +}; // MtConstraintIter + + +//---------------------------------------------------------------------------------------- +/// \ru Обработчик события, связанные с решением сборки. \en The event handles related to solving the assembly. +//--- +struct MATH_CLASS ItAssemblyReactor +{ +public: + /// \ru Захватить сборкой объект для дальнейшей работы. \en Capture the reactor instance by the assembly for further work. + virtual void Capture( const MbAssembly * ) = 0; + /// \ru Отпустить сборкой объект, прекратить работать с ним. \en Release this instance by the assembly, stop working with it. + virtual void Release() = 0; + /// \ru Геометрический решатель не пытался удовлетворить ограничение. \en This called when geometric solver failed to try for constraint satisfaction. + virtual void EvaluationFailed( const MbAssembly * ) const {} + /// \ru Геометрический решатель нашел новую позицию под-объекта сборки. \en The geometric solver found a new position of a constrained sub-object belonging the assembly. + virtual void PositionChanged( const MbAssembly *, const MbItem * /*subItem*/ ) const {} + +protected: + ~ItAssemblyReactor() {} +}; // ItAssemblyReactor + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Интерфейс для системы ограничения импорта сборки из приложения. + \en The user defined interface for import constraint system of an assembly from CAD application. +*/ +//--- +struct MATH_CLASS ItAssemblyImportData +{ +protected: + ~ItAssemblyImportData() {} + +public: + /// \ru Импорт системы ограничений сборки. \en Import a constraint system of the assembly. + virtual bool ImportCSystem( const MbAssembly &, GCM_system & ) const = 0; + /// \ru Получить дескриптор элемента сборки в системе ограничений. \en Get a descriptor of assembly sub-item which used in the constraint system. + virtual MtGeomId GeomId( const MbAssembly &, const MbItem * ) const = 0; + /// \ru Получить объект модели, являющийся аргументом геометрического ограничения. \en Get the model object that is the argument of the geometric constraint. + virtual MtGeomArgument GeomSubItem( const MtArgument & ) const { return MtGeomArgument(); } + /// \ru Получить объект модели, являющийся аргументом геометрического ограничения. \en Get the model object that is the argument of the geometric constraint. + virtual MtGeomArgument GeomSubItem( MtGeomId ) const { return MtGeomArgument(); } +}; //ItAssemblyImportData + +//---------------------------------------------------------------------------------------- +/// \ru Оператор равенства объектов. \en Objects equality operator. \~ +//--- +inline bool MtGeomArgument::operator == ( const MtGeomArgument & r ) const +{ + if ( propItem != r.propItem ) + return false; + if ( propName != r.propName ) + return false; + if ( (item == r.item) && (hash == r.hash) ) + return true; + if ( (hash == r.hash) && (root == r.root) ) + return true; + return false; +} + +//---------------------------------------------------------------------------------------- +/// \ru Оператор копирования. \en Copy operator. \~ +//--- +inline MtGeomArgument & MtGeomArgument::operator = ( const MtGeomArgument & arg ) +{ + propItem = arg.propItem; + propName = arg.propName; + hash = arg.hash; + item = arg.item; + root = arg.root; + return *this; +} + +#endif // __CONSTRAINT_H diff --git a/C3d/Include/constraint_item.h b/C3d/Include/constraint_item.h index 916663d..5f48735 100644 --- a/C3d/Include/constraint_item.h +++ b/C3d/Include/constraint_item.h @@ -1,255 +1,255 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Двухмерные геометрические ограничения для объектов C3D-модели - \en 2D-constraints between geometric objects of C3D-model. - \~ - \attention \ru Данный файл содержит типы данных и вызовы, предназначенные для тестирования - и отладки, поэтому могут быть изменены или удалены из API C3D Kernel без - предупреждения. Для применения функциональности решателя двухмерных ограничений - рекомендуется реализация собственного модуля встраивания в приложение на - основе интерфейсов gce_api.h и gce_types.h. - - \en This file contains data types and calls for testing and debugging, so they - can be modified or removed from the C3D Kernel API without notice. To use - the 2D constraint solver, it is recommended to implement a custom embedding module - based on th interfaces gce_api.h and gce_types.h. - \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONSTRAINT_ITEM_H -#define __CONSTRAINT_ITEM_H - - -#include -#include -#include -#include -#include -#include - - -//---------------------------------------------------------------------------------------- -/// \ru Кодировка геометрического примитива \en Geometric primitive encoding -//--- -struct GeomCode -{ - enum Type - { - // \ru Словарь примитивов плоскости (соответствует словарю решателя; типы геометрических подмножеств плоскости) \en Plane primitive dictionary (corresponds to the solver dictionary; types of geometric subsets of plane) - NULL_GEOM, ///< \ru пустое геометрическое множество \en empty geometric set - POINT, ///< \ru Точка: элемент плоскости \en Point: element of the plane - PROPER_POINT = POINT, ///< \ru Контрольная точка по индексу \en Control point by index - LINE, ///< \ru Прямая \en Line - CIRCLE, - ELLIPSE, - SPLINE, - PARAMETRIC, ///< \ru Неподвижная параметрическая кривая \en Fixed parametric curve - - // \ru Дифференциация подтипов точки \en Differentiation of subtypes of the point - FIRST_END, ///< \ru Начальная точка кривой \en Start point of a curve - SECOND_END, ///< \ru Конечная точка кривой \en End point of a curve - MIDDLE_POINT, ///< \ru Средняя точка кривой \en Middle point of a curve - CENTRE_POINT, ///< \ru Центральная точка эллипса \en Central point of an ellipse - SPLINE_POINT, ///< \ru Контрольная точка сплайна по индексу \en Control point of a spline by index - Q1_POINT, ///< \ru Квадрантная точка на 3 ч \en Quadrant point at 3 o'clock - Q2_POINT, ///< \ru Квадрантная точка на 12 ч \en Quadrant point at 12 o'clock - Q3_POINT, ///< \ru Квадрантная точка на 9 ч \en Quadrant point at 9 o'clock - Q4_POINT, ///< \ru Квадрантная точка на 6 ч \en Quadrant point at 6 o'clock - - // \ru Размеры \en Sizes - /* - LINEAR_DIM, - ANGULAR_DIM, - */ - }; - Type type; ///< \ru Тип геометрии объекта модели (из словаря типов, поддерживаемых решателем) \en Type of geometry of a model object (from dictionary of types supported by the solver) - size_t index; ///< \ru Номер примитива для данного объекта модели (кодируется в индивидуальных адаптерах) \en Number of a primitive for a given object of the model (encoded in individual adapters) - - GeomCode( GeomCode::Type t ) : type(t),index(0) {} - bool operator != ( const GeomCode & g ) const { return type != g.type || index != g.index; } - GeomCode & operator = ( const Type & gType ) { type = gType; index = 0; return *this; } -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Аргумент ограничения (или геометрический примитив решателя) \en Argument of constraint (or geometric primitive of the solver) -/**\ru Этот тип: - 1) Кодирует информацию о геометрии, которая является аргументом для ограничений; - 2) соответствует одному из примитивных типов словаря решателя - - Словарь примитивов решателя: точка, прямая, окружность, эллипс, сплайн. - \en This type: - 1) Encodes the information about the geometry which is the argument for constraints; - 2) Corresponds to one of primitive types of the solver dictionary - - The solver primitives dictionary: point, line, circle, ellipse, spline. \~ - -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -class MATH_CLASS GcArgument { -public: - typedef MbRefItem * ParObject; ///< \ru Ассоциированный тип: владелец примитива, которого он содержит, как свою составную часть \en Associated type: primitives owner which contain the primitive as a component - -public: - GeomCode m_geom; ///< \ru Тип геометрии объекта модели (из словаря типов, поддерживаемых решателем) \en Type of geometry of a model object (from dictionary of types supported by the solver) - c3d::RefItemSPtr m_item; ///< \ru Объект модели \en The model object - -public: - GcArgument() : m_geom(GeomCode::NULL_GEOM), m_item() {} - GcArgument( GeomCode type, MbRefItem & item ) : m_geom(type), m_item(&item) {} - GcArgument( const GcArgument & ag ) : m_geom(ag.m_geom), m_item(ag.m_item) {} - GcArgument & operator = ( const GcArgument & g ) { m_geom = g.m_geom; m_item = g.m_item; return *this; } - bool operator != ( const GcArgument & g ) const { return m_item.get() != g.m_item.get() && m_geom != g.m_geom; } -}; - -//---------------------------------------------------------------------------------------- -// -//--- -inline GcArgument::ParObject Owner( GcArgument & g ) { return g.m_item; } -inline GcArgument::ParObject Owner( const GcArgument & g ) { return g.m_item; } - -//---------------------------------------------------------------------------------------- -/// \ru Параметры размерного ограничения \en Parameters of size constraint -//--- -struct DimParameters -{ - double dimValue; - double dirAngle; ///< \ru Угол для направленного размера \en Angle for a directed size -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Элементарное ограничение \en Elementary constraint -/**\ru Элементарное ограничение соответствует типам ограничений из словаря решателя и не более того. - Ограничения более сложных типов описываются набором классов MbConstraint. - \en Elementary constraint corresponds to the types of constraints from the dictionary of the solver and nothing more. - Constraints of more complex types are described by a set of classes MbConstraint. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -class MATH_CLASS MbConstraint -{ -public: - typedef GcArgument Argument; ///< \ru Тип аргумента ограничения \en Type of argument of the constraint - typedef std::vector arg_list; - typedef arg_list::const_iterator arg_iter; - typedef std::pair arg_iter_pair; - static const Argument null_arg; - -private: - constraint_type m_type; ///< \ru Тип ограничения из словаря решателя \en Type of the argument of the solver dictionary - arg_list m_args; ///< \ru Аргументы ограничения (примитивы из словаря решателя) \en Arguments of the constraint (primitives from the solver dictionary) - DimParameters m_pars; ///< \ru Параметры размера (можно считать тоже аргументом, но представлен другим типом) \en Parameters of size (it can be considered as an argument but it is represented by another type) - -public: - MbConstraint( constraint_type, const Argument &, const Argument & ); // \ru Бинарное ограничение \en Binary constraint - MbConstraint( const MbConstraint & ); - -public: - const Argument & GetGeom( size_t nb ) const { --nb; return nb < m_args.size() ? m_args[nb] : null_arg; } - constraint_type Type() const { return m_type; } - arg_iter_pair Arguments() const { return arg_iter_pair( m_args.begin(), m_args.end() ); } - - /* - bool operator < ( const MbConstraint & c ) const; - bool operator == ( const MbConstraint & c ) const; - */ - -public: - MbConstraint & operator = ( const MbConstraint & ); -}; - - -//---------------------------------------------------------------------------------------- -/// \ru Формирователь модели в решателе \en Generator of a model in the solver -//--- -/* struct GcFormer -{ - // \ru Геометрические объекты \en Geometric objects - virtual bool Point( const GcArgument & ) = 0; - virtual bool Line( const GcArgument & ) = 0; - virtual bool LineSeg( const GcArgument &, const GcArgument & ) = 0; - virtual bool Circle( const MbRefItem &, const MbCartPoint &, double ) = 0; - virtual bool Circle( const GcArgument & ) = 0; - - // \ru Геометрические ограничения \en Geometric constraints - virtual bool Coincidence( const GcArgument &, const GcArgument & ) = 0; - virtual bool Incidence( const GcArgument &, const GcArgument & ) = 0; - virtual bool Vertical( const GcArgument &, const GcArgument & ) = 0; - virtual bool Horizontal( const GcArgument &, const GcArgument & ) = 0; - - // \ru Размерные ограничения \en Dimensional constraints - virtual bool LinearDimension( const MbConstraint & ) = 0; -}; -*/ - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Ограничение модели \en Model constraints -// -////////////////////////////////////////////////////////////////////////////////////////// - -class MbConstraintItem: public TapeBase - , public MtRefItem -{ - MbConstraint m_arg; - -public: - MbConstraintItem(); - MbConstraintItem( const MbConstraint & c ) : MtRefItem(), m_arg(c) {} - constraint_type GceType() const { return m_arg.Type(); } - const MbConstraint & GceConstraint() const { return m_arg; } - - virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const - { - C3D_ASSERT_UNCONDITIONAL( false ); // Неполная реализация класса - return ClassDescriptor( ::pureName(typeid(*this).name()), Math::MathID() ); - } -}; - - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Размерное ограничение \en Dimensional constraint -// -////////////////////////////////////////////////////////////////////////////////////////// - -class MbDimensional: public MbConstraintItem -{ - MbCartPoint legendPos; ///< \ru Положение размерной надписи в ЛСК размера \en Position of a dimension legend in LCS of the dimension - -private: - /// \ru Выдать ЛСК размера \en Get LCS of the dimension - virtual void GetPlacement( MbPlacement & ) const; -}; - -////////////////////////////////////////////////////////////////////////////////////////// -// -/// \ru Система геометрических ограничений \en Geometric constraints system -// -////////////////////////////////////////////////////////////////////////////////////////// - -class MATH_CLASS MbConstraintSystem2D -{ - typedef SPtr ConstraintPtr; - std::vector myConstraints; - -public: - MbConstraintSystem2D(); - ~MbConstraintSystem2D(); - -public: - void AddConstraint( SPtr ); -}; - - -#endif // __CONSTRAINT_ITEM_H - - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Двухмерные геометрические ограничения для объектов C3D-модели + \en 2D-constraints between geometric objects of C3D-model. + \~ + \attention \ru Данный файл содержит типы данных и вызовы, предназначенные для тестирования + и отладки, поэтому могут быть изменены или удалены из API C3D Kernel без + предупреждения. Для применения функциональности решателя двухмерных ограничений + рекомендуется реализация собственного модуля встраивания в приложение на + основе интерфейсов gce_api.h и gce_types.h. + + \en This file contains data types and calls for testing and debugging, so they + can be modified or removed from the C3D Kernel API without notice. To use + the 2D constraint solver, it is recommended to implement a custom embedding module + based on th interfaces gce_api.h and gce_types.h. + \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __CONSTRAINT_ITEM_H +#define __CONSTRAINT_ITEM_H + + +#include +#include +#include +#include +#include +#include + + +//---------------------------------------------------------------------------------------- +/// \ru Кодировка геометрического примитива \en Geometric primitive encoding +//--- +struct GeomCode +{ + enum Type + { + // \ru Словарь примитивов плоскости (соответствует словарю решателя; типы геометрических подмножеств плоскости) \en Plane primitive dictionary (corresponds to the solver dictionary; types of geometric subsets of plane) + NULL_GEOM, ///< \ru пустое геометрическое множество \en empty geometric set + POINT, ///< \ru Точка: элемент плоскости \en Point: element of the plane + PROPER_POINT = POINT, ///< \ru Контрольная точка по индексу \en Control point by index + LINE, ///< \ru Прямая \en Line + CIRCLE, + ELLIPSE, + SPLINE, + PARAMETRIC, ///< \ru Неподвижная параметрическая кривая \en Fixed parametric curve + + // \ru Дифференциация подтипов точки \en Differentiation of subtypes of the point + FIRST_END, ///< \ru Начальная точка кривой \en Start point of a curve + SECOND_END, ///< \ru Конечная точка кривой \en End point of a curve + MIDDLE_POINT, ///< \ru Средняя точка кривой \en Middle point of a curve + CENTRE_POINT, ///< \ru Центральная точка эллипса \en Central point of an ellipse + SPLINE_POINT, ///< \ru Контрольная точка сплайна по индексу \en Control point of a spline by index + Q1_POINT, ///< \ru Квадрантная точка на 3 ч \en Quadrant point at 3 o'clock + Q2_POINT, ///< \ru Квадрантная точка на 12 ч \en Quadrant point at 12 o'clock + Q3_POINT, ///< \ru Квадрантная точка на 9 ч \en Quadrant point at 9 o'clock + Q4_POINT, ///< \ru Квадрантная точка на 6 ч \en Quadrant point at 6 o'clock + + // \ru Размеры \en Sizes + /* + LINEAR_DIM, + ANGULAR_DIM, + */ + }; + Type type; ///< \ru Тип геометрии объекта модели (из словаря типов, поддерживаемых решателем) \en Type of geometry of a model object (from dictionary of types supported by the solver) + size_t index; ///< \ru Номер примитива для данного объекта модели (кодируется в индивидуальных адаптерах) \en Number of a primitive for a given object of the model (encoded in individual adapters) + + GeomCode( GeomCode::Type t ) : type(t),index(0) {} + bool operator != ( const GeomCode & g ) const { return type != g.type || index != g.index; } + GeomCode & operator = ( const Type & gType ) { type = gType; index = 0; return *this; } +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Аргумент ограничения (или геометрический примитив решателя) \en Argument of constraint (or geometric primitive of the solver) +/**\ru Этот тип: + 1) Кодирует информацию о геометрии, которая является аргументом для ограничений; + 2) соответствует одному из примитивных типов словаря решателя + + Словарь примитивов решателя: точка, прямая, окружность, эллипс, сплайн. + \en This type: + 1) Encodes the information about the geometry which is the argument for constraints; + 2) Corresponds to one of primitive types of the solver dictionary + + The solver primitives dictionary: point, line, circle, ellipse, spline. \~ + +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +class MATH_CLASS GcArgument { +public: + typedef MbRefItem * ParObject; ///< \ru Ассоциированный тип: владелец примитива, которого он содержит, как свою составную часть \en Associated type: primitives owner which contain the primitive as a component + +public: + GeomCode m_geom; ///< \ru Тип геометрии объекта модели (из словаря типов, поддерживаемых решателем) \en Type of geometry of a model object (from dictionary of types supported by the solver) + c3d::RefItemSPtr m_item; ///< \ru Объект модели \en The model object + +public: + GcArgument() : m_geom(GeomCode::NULL_GEOM), m_item() {} + GcArgument( GeomCode type, MbRefItem & item ) : m_geom(type), m_item(&item) {} + GcArgument( const GcArgument & ag ) : m_geom(ag.m_geom), m_item(ag.m_item) {} + GcArgument & operator = ( const GcArgument & g ) { m_geom = g.m_geom; m_item = g.m_item; return *this; } + bool operator != ( const GcArgument & g ) const { return m_item.get() != g.m_item.get() && m_geom != g.m_geom; } +}; + +//---------------------------------------------------------------------------------------- +// +//--- +inline GcArgument::ParObject Owner( GcArgument & g ) { return g.m_item; } +inline GcArgument::ParObject Owner( const GcArgument & g ) { return g.m_item; } + +//---------------------------------------------------------------------------------------- +/// \ru Параметры размерного ограничения \en Parameters of size constraint +//--- +struct DimParameters +{ + double dimValue; + double dirAngle; ///< \ru Угол для направленного размера \en Angle for a directed size +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Элементарное ограничение \en Elementary constraint +/**\ru Элементарное ограничение соответствует типам ограничений из словаря решателя и не более того. + Ограничения более сложных типов описываются набором классов MbConstraint. + \en Elementary constraint corresponds to the types of constraints from the dictionary of the solver and nothing more. + Constraints of more complex types are described by a set of classes MbConstraint. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +class MATH_CLASS MbConstraint +{ +public: + typedef GcArgument Argument; ///< \ru Тип аргумента ограничения \en Type of argument of the constraint + typedef std::vector arg_list; + typedef arg_list::const_iterator arg_iter; + typedef std::pair arg_iter_pair; + static const Argument null_arg; + +private: + constraint_type m_type; ///< \ru Тип ограничения из словаря решателя \en Type of the argument of the solver dictionary + arg_list m_args; ///< \ru Аргументы ограничения (примитивы из словаря решателя) \en Arguments of the constraint (primitives from the solver dictionary) + DimParameters m_pars; ///< \ru Параметры размера (можно считать тоже аргументом, но представлен другим типом) \en Parameters of size (it can be considered as an argument but it is represented by another type) + +public: + MbConstraint( constraint_type, const Argument &, const Argument & ); // \ru Бинарное ограничение \en Binary constraint + MbConstraint( const MbConstraint & ); + +public: + const Argument & GetGeom( size_t nb ) const { --nb; return nb < m_args.size() ? m_args[nb] : null_arg; } + constraint_type Type() const { return m_type; } + arg_iter_pair Arguments() const { return arg_iter_pair( m_args.begin(), m_args.end() ); } + + /* + bool operator < ( const MbConstraint & c ) const; + bool operator == ( const MbConstraint & c ) const; + */ + +public: + MbConstraint & operator = ( const MbConstraint & ); +}; + + +//---------------------------------------------------------------------------------------- +/// \ru Формирователь модели в решателе \en Generator of a model in the solver +//--- +/* struct GcFormer +{ + // \ru Геометрические объекты \en Geometric objects + virtual bool Point( const GcArgument & ) = 0; + virtual bool Line( const GcArgument & ) = 0; + virtual bool LineSeg( const GcArgument &, const GcArgument & ) = 0; + virtual bool Circle( const MbRefItem &, const MbCartPoint &, double ) = 0; + virtual bool Circle( const GcArgument & ) = 0; + + // \ru Геометрические ограничения \en Geometric constraints + virtual bool Coincidence( const GcArgument &, const GcArgument & ) = 0; + virtual bool Incidence( const GcArgument &, const GcArgument & ) = 0; + virtual bool Vertical( const GcArgument &, const GcArgument & ) = 0; + virtual bool Horizontal( const GcArgument &, const GcArgument & ) = 0; + + // \ru Размерные ограничения \en Dimensional constraints + virtual bool LinearDimension( const MbConstraint & ) = 0; +}; +*/ + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Ограничение модели \en Model constraints +// +////////////////////////////////////////////////////////////////////////////////////////// + +class MbConstraintItem: public TapeBase + , public MtRefItem +{ + MbConstraint m_arg; + +public: + MbConstraintItem(); + MbConstraintItem( const MbConstraint & c ) : MtRefItem(), m_arg(c) {} + constraint_type GceType() const { return m_arg.Type(); } + const MbConstraint & GceConstraint() const { return m_arg; } + + virtual ClassDescriptor GetClassDescriptor( const VersionContainer & ) const + { + C3D_ASSERT_UNCONDITIONAL( false ); // Неполная реализация класса + return ClassDescriptor( ::pureName(typeid(*this).name()), Math::MathID() ); + } +}; + + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Размерное ограничение \en Dimensional constraint +// +////////////////////////////////////////////////////////////////////////////////////////// + +class MbDimensional: public MbConstraintItem +{ + MbCartPoint legendPos; ///< \ru Положение размерной надписи в ЛСК размера \en Position of a dimension legend in LCS of the dimension + +private: + /// \ru Выдать ЛСК размера \en Get LCS of the dimension + virtual void GetPlacement( MbPlacement & ) const; +}; + +////////////////////////////////////////////////////////////////////////////////////////// +// +/// \ru Система геометрических ограничений \en Geometric constraints system +// +////////////////////////////////////////////////////////////////////////////////////////// + +class MATH_CLASS MbConstraintSystem2D +{ + typedef SPtr ConstraintPtr; + std::vector myConstraints; + +public: + MbConstraintSystem2D(); + ~MbConstraintSystem2D(); + +public: + void AddConstraint( SPtr ); +}; + + +#endif // __CONSTRAINT_ITEM_H + + // eof \ No newline at end of file diff --git a/C3d/Include/contour_graph.h b/C3d/Include/contour_graph.h index 993e2bf..2fb9573 100644 --- a/C3d/Include/contour_graph.h +++ b/C3d/Include/contour_graph.h @@ -370,7 +370,7 @@ public: \param[in] m - \ru Направление обхода.\n Имеет значение знак числа m:\n если m > 0, то обход против часовой стрелки,\n - если m < 0, то по часовой стрелки. + если m < 0, то по часовой стрелке. \en The traversal direction.\n Has a value of sign of number m:\n if m > 0, then traversal is counterclockwise,\n diff --git a/C3d/Include/conv_annotation_item.h b/C3d/Include/conv_annotation_item.h index 999dfb1..c3c8dbf 100644 --- a/C3d/Include/conv_annotation_item.h +++ b/C3d/Include/conv_annotation_item.h @@ -9,16 +9,18 @@ #ifndef __CONV_ANNOTATION_ITEM_H #define __CONV_ANNOTATION_ITEM_H - +#include #include -#include #include -#include -#include -#include +#include + #include #include +class MbLineSegment3D; +class MbArc3D; +class MbItem; +class MbPlaneItem; //------------------------------------------------------------------------------ /** \brief \ru Тип элемента аннотации. @@ -182,7 +184,7 @@ enum MbeDefinedDimensionSymbol { dds_RegardlessOfFeatureSize, ///< \ru . \en . dds_Straightness, ///< \ru Допуск прямолинейности. \en Straightness. dds_Symmetry, ///< \ru Допуск симметричности. \en .Symmetry - dds_TotlaRunout, ///< \ru Допуск полного радиального (либо торцевого) биения. \en TotlaRunout. + dds_TotlaRunout, ///< \ru Допуск полного радиального (либо торцевого) биения. \en Full radial (or face) runout tolerance. }; @@ -393,7 +395,7 @@ struct MaTerminatorSymbol { \en Curve and terminators. \~ */ class CONV_CLASS MaDecoratedCurve : public MbRefItem { - c3d::SpaceCurveSPtr curve; + SPtr curve; std::vector< MaTerminatorSymbol > terminators; MbeDecoratedCurveRole curveType; public: @@ -401,7 +403,7 @@ public: MaDecoratedCurve( const MaDecoratedCurve& ); ///< \ru Конструктор копирования. \en Copy constructor. const MaDecoratedCurve& operator= ( const MaDecoratedCurve& ); ///< \ru Оператор присваивания. \en Assignment operator. - c3d::SpaceCurveSPtr GetCurve() const; ///< \ru Получить кривую. \en Get curve. + 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. @@ -409,6 +411,7 @@ public: 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. }; @@ -450,6 +453,15 @@ public: /// \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 ); @@ -498,6 +510,27 @@ protected: 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 Размер - родоначальник классов для размеров различных типов. @@ -524,7 +557,7 @@ public: virtual Mae_AnnotationType Type() const; /// \ru Получить размерную кривую. \en Get the dimensional curve. - MbCurve3D* GetDimensionCurve(); + MbCurve3D* GetDimensionCurve() const; /// \ru Задать номинал. \en Set a value. void SetValue( double v ); @@ -551,9 +584,9 @@ public: */ bool AddTerminator( const MaTerminatorSymbol& init ); /// \ru Получить первый законцовочный символ. \en Get the first terminator. - bool GetFirstTerminator( MaTerminatorSymbol& first ); + bool GetFirstTerminator( MaTerminatorSymbol& first ) const; /// \ru Получить второй законцовочный символ. \en Get the second terminator. - bool GetSecondTerminator( MaTerminatorSymbol& second ); + bool GetSecondTerminator( MaTerminatorSymbol& second ) const; void InitValueTerminators( const MaDimension& init ); protected: @@ -595,9 +628,9 @@ public: const MbRefItem * GetBindTarget(); /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D* GetProjectionBase(); + MbLineSegment3D* GetProjectionBase() const; /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. - MbLineSegment3D* GetProjectionTarget(); + MbLineSegment3D* GetProjectionTarget() const; /// \ru Задать кривую, вдоль которой провдится измерение. \en Set the curve the measurement is performed along. void SetPath( MbCurve3D* inPath ); @@ -645,9 +678,9 @@ public: const MbRefItem * GetBindTarget(); /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase(); + MbLineSegment3D * GetProjectionBase() const; /// \ru Получить проекционную кривую ко второму объекту привязки. \en Get the projection curve to the second binding object. - MbLineSegment3D * GetProjectionTarget(); + 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. @@ -684,7 +717,7 @@ public: /// \ru Получить базовый объект привязки. \en Get the base binding object. const MbRefItem * GetBindBase(); /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase(); + MbLineSegment3D * GetProjectionBase() const; /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); @@ -723,9 +756,9 @@ public: const MbRefItem * GetBindBase(); /// \ru Получить проекционную кривую к базовому объекту привязки. \en Get projection curve to the base binding object. - MbLineSegment3D * GetProjectionBase(); + MbLineSegment3D * GetProjectionBase() const; /// \ru Получить вторую проекционную кривую к объекту привязки. \en Get the first projection curve to the binding object. - MbLineSegment3D * GetProjectionTarget(); + MbLineSegment3D * GetProjectionTarget() const; /// \ru Создать дубликат и трансформировать его согласно матрице. \en Create a replica then transform it. virtual SPtr ShallowDuplicateTransform( const MbMatrix3D& ); diff --git a/C3d/Include/conv_binary_object.h b/C3d/Include/conv_binary_object.h new file mode 100644 index 0000000..16290a0 --- /dev/null +++ b/C3d/Include/conv_binary_object.h @@ -0,0 +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; } +}; + + +#endif \ No newline at end of file diff --git a/C3d/Include/conv_error_result.h b/C3d/Include/conv_exchange_settings.h similarity index 50% rename from C3d/Include/conv_error_result.h rename to C3d/Include/conv_exchange_settings.h index e8ad6ae..d0c1ab9 100644 --- a/C3d/Include/conv_error_result.h +++ b/C3d/Include/conv_exchange_settings.h @@ -1,25 +1,24 @@ //////////////////////////////////////////////////////////////////////////////// /** \file - \brief \ru Перечисления, используемые при импорте и экспорте. - \en Enumerations for import/export operations.\~ - \details \ru Определены перечисления, определяющие результат конвертирования, - разрешение на чтение и запись различных объектов и передаваемых черезх конвертер строк. - \en Converting result, objects and properties filters, special strings - of enumerations are defined.\~ + \brief \ru Настройки импорта и экспорта. + \en Settings of import and export procedure. \~ + \details \ru Интерфейс настроек и предопределённая реализация ConvConvertorProperty3D. + \en Interface of settings and pre-defined implementation ConvConvertorProperty3D. \~ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __CONV_ERROR_RESULT_H -#define __CONV_ERROR_RESULT_H - - -#include +#ifndef __CONV_MODEL_PROPERTIES_H +#define __CONV_MODEL_PROPERTIES_H +#include +#include +#include +#include //------------------------------------------------------------------------------ /** \brief \ru Константы единиц измерения. - \en Length units constants.\~ +\en Length units constants.\~ \ingroup Data_Interface */ // --- @@ -37,7 +36,7 @@ //------------------------------------------------------------------------------ /** \brief \ru Прикладной протокол. - \en Applied protocol.\~ +\en Applied protocol.\~ \ingroup Data_Interface */ // --- @@ -58,51 +57,24 @@ enum MbeImpExpFormat { //------------------------------------------------------------------------------ -/** \brief \ru Обменный формат модели. - \en Model exchange format.\~ +/** \brief \ru Индексы строк, передаваемых через конвертер. +\en Indices of strings, transmitted through converter.\~ \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. +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.\~ +\en Indeces, which filter imported/exported objects or properties.\~ \ingroup Data_Interface */ // --- @@ -137,59 +109,17 @@ enum MbeIOPermiss { 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 Indeхes 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_END ///< \ru Для удобства перебора. \en For lookup only. -}; - - -//------------------------------------------------------------------------------ -/** \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 Representation of exported text.\~ -\ingroup Data_Exchange -*/ -// --- -enum eTextForm { - exf_TextOnly, ///< \ru Только текст. \en Text only. - exf_GeometryOnly, ///< \ru Только геометрия. \en Geometry only. -}; - - //------------------------------------------------------------------------------ /** \brief \ru Тип сообщения об ошибке при выводе в лог. - \en Type of a log message.\~ +\en Type of a log message.\~ \ingroup Data_Exchange */ // --- @@ -204,7 +134,7 @@ enum eMsgType { //------------------------------------------------------------------------------ /** \brief \ru Код подробного сообщения об ошибке при выводе в лог. - \en The key of a detailed log message.\~ +\en The key of a detailed log message.\~ \ingroup Data_Interface */ // --- @@ -288,8 +218,10 @@ enum eMsgDetail { 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. @@ -303,12 +235,15 @@ enum eMsgDetail { 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. @@ -321,54 +256,247 @@ enum eMsgDetail { //------------------------------------------------------------------------------ -/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения конвертации данных. - \en Identifiers of the execution progress indicator messages converters data exchange \~ -\ingroup Data_Exchange +/** \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 */ -//--- -enum MbeProgBarId_Converters { - pbarId_Cnv_Beg = pbarId_PointsSurface_End + 1, +class IConvertorProperty3D { +public : + virtual ~IConvertorProperty3D() {} - 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... +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; - pbarId_Cnv_End, -}; + /** \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 audit the translation. + virtual bool TotalAudit() { return false; } + + /// \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; } +}; // IConvertorProperty3D //------------------------------------------------------------------------------ -/** \brief \ru Идентификаторы сообщений индикатора прогресса выполнения триангуляции при выполнении конвертации данных. - \en Identifiers of the execution progress indicator messages triangulation. \~ -\ingroup Data_Exchange +/** \brief \ru Предопределённая реализация интерфейса свойств конвертера. + \en Pre-defined implementation of converter's properties. \~ +\ingroup Exchange_Interface */ -//--- -enum MbeProgBarId_Triangulation { - pbarId_Triangulation_Beg = pbarId_Cnv_End + 1, +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 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. - pbarId_Calc_Triangulation, // \ru Расчет триангуляции \en Calculating of triangulation +public: - pbarId_Triangulation_End, -}; + 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(); + /// \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; } + + OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D ) + +}; // IConvertorProperty3D -//------------------------------------------------------------------------------ -/** \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 +#endif // __CONV_MODEL_PROPERTIES_H diff --git a/C3d/Include/conv_model_document.h b/C3d/Include/conv_model_document.h new file mode 100644 index 0000000..b58bca4 --- /dev/null +++ b/C3d/Include/conv_model_document.h @@ -0,0 +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 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; + +}; + + +#endif // __CONV_MODEL_DOCUMENT_H \ No newline at end of file diff --git a/C3d/Include/conv_i_converter.h b/C3d/Include/conv_model_exchange.h similarity index 65% rename from C3d/Include/conv_i_converter.h rename to C3d/Include/conv_model_exchange.h index d899345..b1d4550 100644 --- a/C3d/Include/conv_i_converter.h +++ b/C3d/Include/conv_model_exchange.h @@ -1,154 +1,367 @@ //////////////////////////////////////////////////////////////////////////////// /** \file - \brief \ru Интерфейсы конвертера. - \en Interfaces of the converter. \~ - + \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 -#include -#include - - -class IProgressIndicator; -struct IScaleRequestor; -class ItModelDocument; -class MATH_CLASS MbRefItem; -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbModel; +#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 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 +/** \brief \ru Результат конвертирования. +\en Result of converting operation. +\ingroup Data_Interface */ -class IConvertorProperty3D { -public : - virtual ~IConvertorProperty3D() {} +// --- +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. +}; -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. \~ + +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 */ - virtual bool EnableAutoStitch( double& /*stitchPrecision*/ ) const = 0; + CONV_FUNC (MbeConvResType) ImportFromFile( MbModel & model, + const path_string & fileName, + IConvertorProperty3D * prop = C3D_NULL_PTR, + IProgressIndicator * indicator = C3D_NULL_PTR ); - /** \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. \~ + + /** \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 */ - virtual double LengthUnitsFactor() const { return LENGTH_UNIT_MM; } + CONV_FUNC (MbeConvResType) ImportFromFile( c3d::ItemSPtr& item, + const path_string& filePath, + IConvertorProperty3D* prop = C3D_NULL_PTR, + IProgressIndicator* indicator = C3D_NULL_PTR ); - - /** \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. \~ + /** \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 */ - virtual double AppLengthUnitsFactor() const { return LENGTH_UNIT_MM; } + CONV_FUNC (MbeConvResType) ImportFromFile( ItModelDocument & mDoc, + const path_string & filePath, + IConvertorProperty3D * prop = C3D_NULL_PTR, + IProgressIndicator * indicator = C3D_NULL_PTR ); - /** \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. \~ + /** \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 */ - virtual void LogReport( ptrdiff_t id, eMsgType msgType, eMsgDetail msgText ) = 0; + CONV_FUNC (MbeConvResType) ExportIntoFile( MbModel & model, + const path_string & filePath, + IConvertorProperty3D * prop = C3D_NULL_PTR, + IProgressIndicator * indicator = C3D_NULL_PTR ); -// /** \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 audit the translation. - virtual bool TotalAudit() { return false; } + /** \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 ); - /// \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; } -}; // IConvertorProperty3D + /** \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; + } + }; +}; //------------------------------------------------------------------------------ @@ -500,6 +713,42 @@ public: */ 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 @@ -511,6 +760,13 @@ public: 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. \~ @@ -773,75 +1029,6 @@ CONV_FUNC (MbeConvResType ) ASCIIPointCloudWrite( IConvertorProperty3D & prop, I namespace c3d { - - /** \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 = 0, - IProgressIndicator * indicator = 0 ); - - /** \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, - IProgressIndicator * indicator ); - - /** \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 = 0, - IProgressIndicator * indicator = 0 ); /** \brief \ru Импортировать данные из буфера в модель. \en Import data from buffer into model. \~ @@ -861,12 +1048,36 @@ namespace c3d { \en Code of the operation termination. \~ \ingroup Exchange_Interface */ - CONV_FUNC (MbeConvResType) ImportFromBuffer( MbModel & model, - const char * data, - size_t length, - MbeModelExchangeFormat modelFormat, - IConvertorProperty3D * prop = 0, - IProgressIndicator * indicator = 0 ); + 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. \~ @@ -886,13 +1097,38 @@ namespace c3d { \en Code of the operation termination. \~ \ingroup Exchange_Interface */ - CONV_FUNC (MbeConvResType) ExportIntoBuffer( MbModel & model, - MbeModelExchangeFormat modelFormat, - char *& data, - size_t & length, - IConvertorProperty3D * prop = 0, - IProgressIndicator * indicator = 0 ); -}; + 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); + +} /** \} */ diff --git a/C3d/Include/conv_model_properties.h b/C3d/Include/conv_model_properties.h deleted file mode 100644 index 39b2f00..0000000 --- a/C3d/Include/conv_model_properties.h +++ /dev/null @@ -1,712 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Интерфейсы, используемые при импорте и экспорте. - \en Interfaces used for import and export. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CONV_MODEL_PROPERTIES_H -#define __CONV_MODEL_PROPERTIES_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbItem; -class MATH_CLASS MbName; -class ItModelAssembly; -class ItModelPart; - - -/** \brief \ru Контейнер объектов аннотации. - \en Container of annotation objects. \~ -\ingroup Exchange_Base -*/ -typedef std::vector vector_of_annotation; - - -/** \brief \ru Ассоциация наборов аннотационных объектов элементам со счётчиком ссылок. - \en Association of sets of annotation objects with elements with reference counter. \~ -\ingroup Exchange_Base -*/ -typedef std::map< SPtr, vector_of_annotation > map_of_visual_items; - - -/** \brief \ru Контейнер текстовых блоков. - \en Container of text blocks. \~ -\ingroup Exchange_Base -*/ -typedef std::vector< SPtr > vector_of_text; - - -//------------------------------------------------------------------------------ -/** \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 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 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( vector_of_annotation &, eTextForm ) const = 0; - - /// \ru Задать технические требования. \en Set technical requirements. - virtual void SetRequirements( const vector_of_annotation & ) = 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 SPtr CreateAssembly( const MbPlacement3D &place, const std::vector< SPtr > & 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 SPtr CreatePart( const MbPlacement3D &place, const std::vector< SPtr > & 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 SPtr 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 SPtr 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 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 SPtr 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 SPtr 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( std::vector< SPtr > & 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 std::vector< SPtr > & 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 vector_of_annotation GetAnnotationItems( eTextForm, bool ) const { return vector_of_annotation(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D - virtual vector_of_annotation GetAnnotationItems( eTextForm ) const { return vector_of_annotation(); }; // Будет удалена после её реализации на стороне 3D - - /** \brief \ru Задать элементы аннотации в сборке. - \en Set elements of annotation in the assembly. \~ - \param[in] sourceDim - \ru Элементы аннотации - \en Elements of annotation. \~ - */ - virtual void SetAnnotationItems( const vector_of_annotation & ) = 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 SPtr 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 SPtr 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( std::vector< SPtr > & 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 std::vector< SPtr > & 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 vector_of_annotation GetAnnotationItems( eTextForm, bool ) const { return vector_of_annotation(); }; // Реализация будет удалена после того, как она будет осуществлена на стороне 3D - virtual vector_of_annotation GetAnnotationItems( eTextForm ) const { return vector_of_annotation(); }; // Будет удалена после её реализации на стороне 3D - - - /** \brief \ru Задать элементы аннотации в детали. - \en Set elements of annotation in the part. \~ - \param[in] sourceDim - \ru Элементы аннотации - \en Elements of annotation. \~ - */ - virtual void SetAnnotationItems( const vector_of_annotation & ) = 0; - -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс документа модели сборки или детали. - \en Interface of document of an assembly model or a part model. \~ -\ingroup Exchange_Interface -*/ -// --- -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 SPtr CreateAssembly( const std::vector< SPtr > & 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 SPtr CreatePart( const std::vector< SPtr > & 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 SPtr 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 SPtr 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 Implementation of model document which has regular structure. \~ -\ingroup Exchange_Interface -*/ -// --- -class CONV_CLASS C3dModelDocument: public ItModelDocument { - - SPtr part; ///< \ru Представление в виде детали. \en Representation as detail. - SPtr assembly; ///< \ru Представление в виде сборки. \en Representation as assembly. - map_of_visual_items visualItems; ///< \ru Элементы аннотации. \en Annotation items. - c3d::ItemSPtr rawContent; -public: - - virtual ~C3dModelDocument(); ///< \ru Деструктор. \en Descructor. - - // Является ли сборкой. - virtual bool IsAssembly() const; - // Пуст ли. - virtual bool IsEmpty() const; - // Задать модель напрямую. - virtual void SetContent( MbItem* /*content*/); - // Выдать модель напрямую. - virtual MbItem * GetContent(); - // Создать сборку. - virtual SPtr CreateAssembly( const std::vector< SPtr > & componentItems, const c3d::string_t& fileName ); - // Создать деталь. - virtual SPtr CreatePart( const std::vector< SPtr > & componentItems, const c3d::string_t& fileName ); - // Выдать сборку. - virtual SPtr GetInstanceAssembly( ); - // Выдать деталь. - virtual SPtr 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 Зарегистрировать элемент аннотации. \en Register annotation object. - void RegisterAnnotation( c3d::ItemSPtr component, const vector_of_annotation& annotation, const vector_of_annotation& requirements ); -}; - - -typedef C3dModelDocument RegularModelDocument; -typedef C3dModelDocument ConvModelDocument; - - -//------------------------------------------------------------------------------ -/** \brief \ru Упрощенная реализация интерфейса свойств конвертера. - \en Simple 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 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(); - /// \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; } - - OBVIOUS_PRIVATE_COPY( ConvConvertorProperty3D ) - -}; // IConvertorProperty3D - - - -#endif // __CONV_MODEL_PROPERTIES_H diff --git a/C3d/Include/conv_predefined.h b/C3d/Include/conv_predefined.h new file mode 100644 index 0000000..bec7f66 --- /dev/null +++ b/C3d/Include/conv_predefined.h @@ -0,0 +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, +}; + + +#endif // __CONV_ERROR_RESULT_H \ No newline at end of file diff --git a/C3d/Include/conv_topo_mesh.h b/C3d/Include/conv_topo_mesh.h new file mode 100644 index 0000000..d5e2ad9 --- /dev/null +++ b/C3d/Include/conv_topo_mesh.h @@ -0,0 +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 diff --git a/C3d/Include/cr_attribute_provider.h b/C3d/Include/cr_attribute_provider.h index a242ca2..086e2e3 100644 --- a/C3d/Include/cr_attribute_provider.h +++ b/C3d/Include/cr_attribute_provider.h @@ -1,153 +1,153 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поставщик атрибутов для топологических объектов. - \en Topological objects attributes provider. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_ATTRIBURE_PROVIDER_H -#define __CR_ATTRIBURE_PROVIDER_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbNamedAttributeContainer; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поставщик атрибутов для топологических объектов. - \en Topological objects attributes provider. \~ - \details \ru Поставщик атрибутов для топологических объектов создаёт атрибуты для журнала построений. \n - \en Topological objects attributes provider creates attributes for history tree. \n \~ - \ingroup Model_Creators - */ -class MATH_CLASS MbAttributeProvider : public MbCreator -{ -private: - struct NamedAttrCondDuplicator - { - public: - MbAttributeProvider & target_; - NamedAttrCondDuplicator( MbAttributeProvider & target ) : target_(target) {} - void operator () ( MbNamedAttributeContainer * source ); - private: - void operator = ( const NamedAttrCondDuplicator & ); - }; - - struct NamedAttrCondComparer - { - public: - MbName target_; - NamedAttrCondComparer( const MbName & target ) : target_(target) {} - bool operator () ( MbNamedAttributeContainer * source ); - private: - void operator = ( const NamedAttrCondComparer & ); - }; - - struct NamedAttrCondSetter - { - public: - MbFaceShell & target_; - NamedAttrCondSetter( MbFaceShell & target ) : target_(target) {} - void operator () ( MbNamedAttributeContainer * source ); - private: - void operator = ( const NamedAttrCondSetter & ); - }; - - typedef std::vector::iterator ContIter; - -private: - std::vector attrConts; // \ru Передаваемые атрибуты \en Attributes to pass - -public: - MbAttributeProvider( const MbSNameMaker & n ); - ~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 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 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. - - // \ru Добавить отдельный атрибут (забрать во владение) \en Add a separate attribute. - void AddAttribute( const MbName & name, MbAttribute * attr ); - // \ru Добавить контейнер атрибутов (забрать во владение) \en Add an attribute container. - void AddNamedCont( MbNamedAttributeContainer * attr ); - // \ru Добавить контейнер атрибутов (сделать себе копию) \en Add an attribute container (make a copy). - void AddNamedCont( MbNamedAttributeContainer & attr ); - -protected: - MbAttributeProvider( const MbAttributeProvider & ); - void operator = ( const MbAttributeProvider & ); // \ru Не реализовано \en Not implemented - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAttributeProvider ) -}; - -IMPL_PERSISTENT_OPS( MbAttributeProvider ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Контейнер атрибутов. - \en Attribute container. \~ - \details \ru Контейнер атрибутов для одного топологического объекта. \n - \en An attribute container for a topological object. \n \~ - \ingroup Model_Attributes - */ -class MATH_CLASS MbNamedAttributeContainer -{ - typedef c3d::AttrVector::iterator AttrIter; - -private: - MbName target; // \ru Имя топологического объекта, которому будут отданы хранимые атрибуты. \en Name of the topological object the stored attributes will be passed to. - c3d::AttrVector attributes; // \ru Передаваемые атрибуты. \en Attributes to pass. - -public: - MbNamedAttributeContainer( const MbName & ); - virtual ~MbNamedAttributeContainer(); - -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; - /// \ru Дать количество атрибутов. \en Get the attributes count. - size_t AttributesCount() const { return attributes.size(); } - /// \ru Добавить атрибут. \en Add an attribute. - void AddAttribute( MbAttribute & ) ; - const MbAttribute * _GetAttribute( size_t k ) const { return attributes[k]; } - -public: - /// \ru Дать имя топологического объекта. \en Get the topological object name. - const MbName & GetName() const { return target; } - - /// \ru Читать из потока. \en Read from stream. - void ReadAttrCont ( reader & ); - /// \ru Записать в поток. \en Write to stream. - void WriteAttrCont( writer & ) const; - - virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. - -protected: - MbNamedAttributeContainer( const MbNamedAttributeContainer & ); - void operator = ( const MbNamedAttributeContainer & ); // \ru Не реализовано \en Not implemented -}; - - -#endif // __CR_ATTRIBURE_PROVIDER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поставщик атрибутов для топологических объектов. + \en Topological objects attributes provider. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_ATTRIBURE_PROVIDER_H +#define __CR_ATTRIBURE_PROVIDER_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbNamedAttributeContainer; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поставщик атрибутов для топологических объектов. + \en Topological objects attributes provider. \~ + \details \ru Поставщик атрибутов для топологических объектов создаёт атрибуты для журнала построений. \n + \en Topological objects attributes provider creates attributes for history tree. \n \~ + \ingroup Model_Creators + */ +class MATH_CLASS MbAttributeProvider : public MbCreator +{ +private: + struct NamedAttrCondDuplicator + { + public: + MbAttributeProvider & target_; + NamedAttrCondDuplicator( MbAttributeProvider & target ) : target_(target) {} + void operator () ( MbNamedAttributeContainer * source ); + private: + void operator = ( const NamedAttrCondDuplicator & ); + }; + + struct NamedAttrCondComparer + { + public: + MbName target_; + NamedAttrCondComparer( const MbName & target ) : target_(target) {} + bool operator () ( MbNamedAttributeContainer * source ); + private: + void operator = ( const NamedAttrCondComparer & ); + }; + + struct NamedAttrCondSetter + { + public: + MbFaceShell & target_; + NamedAttrCondSetter( MbFaceShell & target ) : target_(target) {} + void operator () ( MbNamedAttributeContainer * source ); + private: + void operator = ( const NamedAttrCondSetter & ); + }; + + typedef std::vector::iterator ContIter; + +private: + std::vector attrConts; // \ru Передаваемые атрибуты \en Attributes to pass + +public: + MbAttributeProvider( const MbSNameMaker & n ); + ~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 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 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. + + // \ru Добавить отдельный атрибут (забрать во владение) \en Add a separate attribute. + void AddAttribute( const MbName & name, MbAttribute * attr ); + // \ru Добавить контейнер атрибутов (забрать во владение) \en Add an attribute container. + void AddNamedCont( MbNamedAttributeContainer * attr ); + // \ru Добавить контейнер атрибутов (сделать себе копию) \en Add an attribute container (make a copy). + void AddNamedCont( MbNamedAttributeContainer & attr ); + +protected: + MbAttributeProvider( const MbAttributeProvider & ); + void operator = ( const MbAttributeProvider & ); // \ru Не реализовано \en Not implemented + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbAttributeProvider ) +}; + +IMPL_PERSISTENT_OPS( MbAttributeProvider ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Контейнер атрибутов. + \en Attribute container. \~ + \details \ru Контейнер атрибутов для одного топологического объекта. \n + \en An attribute container for a topological object. \n \~ + \ingroup Model_Attributes + */ +class MATH_CLASS MbNamedAttributeContainer +{ + typedef c3d::AttrVector::iterator AttrIter; + +private: + MbName target; // \ru Имя топологического объекта, которому будут отданы хранимые атрибуты. \en Name of the topological object the stored attributes will be passed to. + c3d::AttrVector attributes; // \ru Передаваемые атрибуты. \en Attributes to pass. + +public: + MbNamedAttributeContainer( const MbName & ); + virtual ~MbNamedAttributeContainer(); + +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; + /// \ru Дать количество атрибутов. \en Get the attributes count. + size_t AttributesCount() const { return attributes.size(); } + /// \ru Добавить атрибут. \en Add an attribute. + void AddAttribute( MbAttribute & ) ; + const MbAttribute * _GetAttribute( size_t k ) const { return attributes[k]; } + +public: + /// \ru Дать имя топологического объекта. \en Get the topological object name. + const MbName & GetName() const { return target; } + + /// \ru Читать из потока. \en Read from stream. + void ReadAttrCont ( reader & ); + /// \ru Записать в поток. \en Write to stream. + void WriteAttrCont( writer & ) const; + + virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual void SetProperties( const MbProperties & ); // \ru Установить свойства объекта. \en Set properties of the object. + +protected: + MbNamedAttributeContainer( const MbNamedAttributeContainer & ); + void operator = ( const MbNamedAttributeContainer & ); // \ru Не реализовано \en Not implemented +}; + + +#endif // __CR_ATTRIBURE_PROVIDER_H diff --git a/C3d/Include/cr_connecting_curve.h b/C3d/Include/cr_connecting_curve.h index 58e90f9..f9c196b 100644 --- a/C3d/Include/cr_connecting_curve.h +++ b/C3d/Include/cr_connecting_curve.h @@ -1,182 +1,196 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель кривой сопряжения двух кривых. - \en Constructor of curve connecting two curves. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_CONNECTING_CURVE_H -#define __CR_CONNECTING_CURVE_H - - -#include - - -class MATH_CLASS MbCartPoint; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; -class MATH_CLASS MbElementarySurface; -class MATH_CLASS MbEdge; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель кривой сопряжения двух кривых. - \en Constructor of curve connecting two curves. \~ - \details \ru Строитель кривой сопряжения двух кривых.\n - \en Constructor of curve connecting two curves.\n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbConnectingCurveCreator : public MbCreator { -private: - MbCurve3D * curve1; ///< \ru Первая скругляемая кривая \en The first curve to connect - MbCurve3D * curve2; ///< \ru Вторая скругляемая кривая \en The second curve to connect - double init1; ///< \ru Исходное приближение параметра первой скругляемой кривой (для ft_Fillet и ft_OnSurface) \en The initial approximation of parameter of the first curve to be connected (for ft_Fillet and ft_OnSurface) - double init2; ///< \ru Исходное приближение параметра второй скругляемой кривой (для ft_Fillet и ft_OnSurface) \en The initial approximation of parameter of the second curve to be connected (for ft_Fillet and ft_OnSurface) - double param1; ///< \ru Параметр точки стыковки первой скругляемой кривой (кроме ft_Double) \en Connection point parameter of the first curve (except ft_Double) - double param2; ///< \ru Параметр точки стыковки второй скругляемой кривой (кроме ft_Double) \en Connection point parameter of the second curve (except ft_Double) - double radius1; ///< \ru Исходное приближение радиуса (кроме ft_Bridge, для ft_Double - радиус скругления первого участка, для ft_Spline - tension) \en The initial approximation of radius (except ft_Bridge, for ft_Double - the first segment fillet radius, for ft_Spline - tension) - double radius2; ///< \ru Результат расчета радиуса (кроме ft_Bridge, для ft_Double - радиус скругления второго участка, для ft_Spline - tension) \en The radius calculation result (except ft_Bridge, for ft_Double - the second segment fillet radius, for ft_Spline - tension) - bool sense1; ///< \ru Совпадение направления кривой скругления и первой кривой (кроме ft_Spline, для ft_Double - начало/конец кривой) \en Coincidence of the connecting curve direction and the first curve (except ft_Spline, for ft_Double - start/end point of the curve) - bool sense2; ///< \ru Совпадение направления кривой скругления и второй кривой (кроме ft_Spline, для ft_Double - начало/конец кривой) \en Coincidence of the connecting curve direction and the second curve (except ft_Spline, for ft_Double - start/end point of the curve) - MbeMatingType mating1; ///< \ru Тип сопряжения с первой кривой (для ft_Spline) \en Type of mating with the first curve (for ft_Spline) - MbeMatingType mating2; ///< \ru Тип сопряжения со второй кривой (для ft_Spline) \en Type of mating with the second curve (for ft_Spline) - MbeConnectingType type; ///< \ru Тип скругления (обычное или на поверхности) \en Connection type (ordinary or on a surface) - -protected: - MbConnectingCurveCreator( const MbConnectingCurveCreator & , MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbConnectingCurveCreator( const MbConnectingCurveCreator & ); // \ru Не реализовано \en Not implemented - MbConnectingCurveCreator(); // \ru Не реализовано \en Not implemented - -public: - MbConnectingCurveCreator( const MbSNameMaker & n, - const MbCurve3D & c1, double t1, double p1, double r1, bool s1, MbeMatingType m1, - const MbCurve3D & c2, double t2, double p2, double r2, bool s2, MbeMatingType m2, MbeConnectingType t ); - -public : - virtual ~MbConnectingCurveCreator(); - - // \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 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 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 - 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 Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateSpaceCurve( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); - - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbConnectingCurveCreator & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConnectingCurveCreator ) -}; - -IMPL_PERSISTENT_OPS( MbConnectingCurveCreator ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создание строителя скругления двух кривых. - \en Create two curves fillet constructor. \~ - \details \ru Создание строителя скругления двух кривых.\n - \en Create two curves fillet constructor.\n \~ - \param[in] curve1 - \ru Кривая 1. - \en Curve 1. \~ - \param[in] curve2 - \ru Кривая 2. - \en Curve 2. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCreator *) CreateFilletEdge( const MbCurve3D & curve1, double & t1, - const MbCurve3D & curve2, double & t2, - double & radius, bool sense, - MbeConnectingType type, - const MbSNameMaker & names, - MbResultType & res, - bool & unchanged, // \ru Для ft_Fillet и ft_OnSurface \en For ft_Fillet and ft_OnSurface - MbElementarySurface *& surface, // \ru Для ft_Fillet и ft_OnSurface \en For ft_Fillet and ft_OnSurface - MbEdge *& edge ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создание строителя сопряжения двух кривых сплайном. - \en Create constructor of two curves connection by a spline. \~ - \details \ru Создание строителя сопряжения двух кривых сплайном.\n - \en Create constructor of two curves connection by a spline.\n \~ - \param[in] curve1 - \ru Кривая 1. - \en Curve 1. \~ - \param[in] curve2 - \ru Кривая 2. - \en Curve 2. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCreator *) CreateSplineEdge( const MbCurve3D & curve1, double t1, MbeMatingType mating1, - const MbCurve3D & curve2, double t2, MbeMatingType mating2, - double tension1, double tension2, - const MbSNameMaker & names, - MbResultType & res, - MbEdge *& edge ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создание строителя сопряжения концов двух кривых составной кривой плавного соединения. - \en Create a constructor of conjugation of two curves end points by a composite curve of smooth connection. \~ - \details \ru Создание строителя сопряжения концов двух кривых составной кривой плавного соединения.\n - \en Create a constructor of conjugation of two curves end points by a composite curve of smooth connection.\n \~ - \param[in] curve1 - \ru Кривая 1. - \en Curve 1. \~ - \param[in] curve2 - \ru Кривая 2. - \en Curve 2. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCreator *) CreateConnectingEdge( const MbCurve3D & curve1, bool isBegin1, double radius1, - const MbCurve3D & curve2, bool isBegin2, double radius2, - const MbSNameMaker & names, - MbResultType & res, - MbEdge *& edge ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Cоздание строителя сопряжения двух кривых кубическим сплайном Эрмита (кривой-мостиком). - \en Create a constructor of two curves conjugation by a cubic Hermite spline (transition curve). \~ - \details \ru Cоздание строителя сопряжения двух кривых кубическим сплайном Эрмита (кривой-мостиком).\n - \en Create a constructor of two curves conjugation by a cubic Hermite spline (transition curve).\n \~ - \param[in] curve1 - \ru Кривая 1. - \en Curve 1. \~ - \param[in] curve2 - \ru Кривая 2. - \en Curve 2. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Curve3D_Modeling -*/ -// --- -MATH_FUNC (MbCreator *) CreateBridgeEdge( const MbCurve3D & curve1, double t1, bool sense1, - const MbCurve3D & curve2, double t2, bool sense2, - const MbSNameMaker & names, - MbResultType & res, - MbEdge *& edge ); - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель кривой сопряжения двух кривых. + \en Constructor of curve connecting two curves. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_CONNECTING_CURVE_H +#define __CR_CONNECTING_CURVE_H + + +#include + + +class MATH_CLASS MbCartPoint; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; +class MATH_CLASS MbElementarySurface; +class MATH_CLASS MbEdge; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель кривой сопряжения двух кривых. + \en Constructor of curve connecting two curves. \~ + \details \ru Строитель кривой сопряжения двух кривых.\n + \en Constructor of curve connecting two curves.\n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbConnectingCurveCreator : public MbCreator { +private: + MbCurve3D * curve1; ///< \ru Первая скругляемая кривая \en The first curve to connect + MbCurve3D * curve2; ///< \ru Вторая скругляемая кривая \en The second curve to connect + double init1; ///< \ru Исходное приближение параметра первой скругляемой кривой (для ft_Fillet и ft_OnSurface) \en The initial approximation of parameter of the first curve to be connected (for ft_Fillet and ft_OnSurface) + double init2; ///< \ru Исходное приближение параметра второй скругляемой кривой (для ft_Fillet и ft_OnSurface) \en The initial approximation of parameter of the second curve to be connected (for ft_Fillet and ft_OnSurface) + double param1; ///< \ru Параметр точки стыковки первой скругляемой кривой (кроме ft_Double) \en Connection point parameter of the first curve (except ft_Double) + double param2; ///< \ru Параметр точки стыковки второй скругляемой кривой (кроме ft_Double) \en Connection point parameter of the second curve (except ft_Double) + double radius1; ///< \ru Исходное приближение радиуса (кроме ft_Bridge, для ft_Double - радиус скругления первого участка, для ft_Spline - tension) \en The initial approximation of radius (except ft_Bridge, for ft_Double - the first segment fillet radius, for ft_Spline - tension) + double radius2; ///< \ru Результат расчета радиуса (кроме ft_Bridge, для ft_Double - радиус скругления второго участка, для ft_Spline - tension) \en The radius calculation result (except ft_Bridge, for ft_Double - the second segment fillet radius, for ft_Spline - tension) + bool sense1; ///< \ru Совпадение направления кривой скругления и первой кривой (кроме ft_Spline, для ft_Double - начало/конец кривой) \en Coincidence of the connecting curve direction and the first curve (except ft_Spline, for ft_Double - start/end point of the curve) + bool sense2; ///< \ru Совпадение направления кривой скругления и второй кривой (кроме ft_Spline, для ft_Double - начало/конец кривой) \en Coincidence of the connecting curve direction and the second curve (except ft_Spline, for ft_Double - start/end point of the curve) + MbeMatingType mating1; ///< \ru Тип сопряжения с первой кривой (для ft_Spline) \en Type of mating with the first curve (for ft_Spline) + MbeMatingType mating2; ///< \ru Тип сопряжения со второй кривой (для ft_Spline) \en Type of mating with the second curve (for ft_Spline) + MbeConnectingType type; ///< \ru Тип скругления (обычное или на поверхности) \en Connection type (ordinary or on a surface) + +protected: + MbConnectingCurveCreator( const MbConnectingCurveCreator & , MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + MbConnectingCurveCreator( const MbConnectingCurveCreator & ); // \ru Не реализовано \en Not implemented + MbConnectingCurveCreator(); // \ru Не реализовано \en Not implemented + +public: + MbConnectingCurveCreator( const MbSNameMaker & n, + const MbCurve3D & c1, double t1, double p1, double r1, bool s1, MbeMatingType m1, + const MbCurve3D & c2, double t2, double p2, double r2, bool s2, MbeMatingType m2, MbeConnectingType t ); + +public : + virtual ~MbConnectingCurveCreator(); + + // \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 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 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 + 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 Построить кривую по журналу построения \en Create a curve from the history tree + virtual bool CreateSpaceCurve( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbConnectingCurveCreator & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConnectingCurveCreator ) +}; + +IMPL_PERSISTENT_OPS( MbConnectingCurveCreator ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создание строителя скругления двух кривых. + \en Create two curves fillet constructor. \~ + \details \ru Создание строителя скругления двух кривых.\n + \en Create two curves fillet constructor.\n \~ + \param[in] curve1 - \ru Кривая 1. + \en Curve 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 соединения с кривой соединения. + \en A point parameter on curve 2 of connection with fillet curve. \~ + \param[in/out] radius - \ru Радиус дуги или цилиндра. + \en The radius of an arc or a cylinder. \~ + \param[in] type - \ru Тип скругления. + \en The fillet type. \~ + \param[in] names - \ru Именователь построенного ребра. + \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). \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCreator *) CreateFilletEdge( const MbCurve3D & curve1, double & t1, + const MbCurve3D & curve2, double & t2, + double & radius, bool sense, + MbeConnectingType type, + const MbSNameMaker & names, + MbResultType & res, + bool & unchanged, // \ru Для ft_Fillet и ft_OnSurface \en For ft_Fillet and ft_OnSurface + MbElementarySurface *& surface, // \ru Для ft_Fillet и ft_OnSurface \en For ft_Fillet and ft_OnSurface + MbEdge *& edge ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создание строителя сопряжения двух кривых сплайном. + \en Create constructor of two curves connection by a spline. \~ + \details \ru Создание строителя сопряжения двух кривых сплайном.\n + \en Create constructor of two curves connection by a spline.\n \~ + \param[in] curve1 - \ru Кривая 1. + \en Curve 1. \~ + \param[in] curve2 - \ru Кривая 2. + \en Curve 2. \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCreator *) CreateSplineEdge( const MbCurve3D & curve1, double t1, MbeMatingType mating1, + const MbCurve3D & curve2, double t2, MbeMatingType mating2, + double tension1, double tension2, + const MbSNameMaker & names, + MbResultType & res, + MbEdge *& edge ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создание строителя сопряжения концов двух кривых составной кривой плавного соединения. + \en Create a constructor of conjugation of two curves end points by a composite curve of smooth connection. \~ + \details \ru Создание строителя сопряжения концов двух кривых составной кривой плавного соединения.\n + \en Create a constructor of conjugation of two curves end points by a composite curve of smooth connection.\n \~ + \param[in] curve1 - \ru Кривая 1. + \en Curve 1. \~ + \param[in] curve2 - \ru Кривая 2. + \en Curve 2. \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCreator *) CreateConnectingEdge( const MbCurve3D & curve1, bool isBegin1, double radius1, + const MbCurve3D & curve2, bool isBegin2, double radius2, + const MbSNameMaker & names, + MbResultType & res, + MbEdge *& edge ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Cоздание строителя сопряжения двух кривых кубическим сплайном Эрмита (кривой-мостиком). + \en Create a constructor of two curves conjugation by a cubic Hermite spline (transition curve). \~ + \details \ru Cоздание строителя сопряжения двух кривых кубическим сплайном Эрмита (кривой-мостиком).\n + \en Create a constructor of two curves conjugation by a cubic Hermite spline (transition curve).\n \~ + \param[in] curve1 - \ru Кривая 1. + \en Curve 1. \~ + \param[in] curve2 - \ru Кривая 2. + \en Curve 2. \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Curve3D_Modeling +*/ +// --- +MATH_FUNC (MbCreator *) CreateBridgeEdge( const MbCurve3D & curve1, double t1, bool sense1, + const MbCurve3D & curve2, double t2, bool sense2, + const MbSNameMaker & names, + MbResultType & res, + MbEdge *& edge ); + + #endif // __CR_CONNECTING_CURVE_H \ No newline at end of file diff --git a/C3d/Include/cr_duplication_solid.h b/C3d/Include/cr_duplication_solid.h index 0207d16..5a81df9 100644 --- a/C3d/Include/cr_duplication_solid.h +++ b/C3d/Include/cr_duplication_solid.h @@ -1,103 +1,104 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель размноженого набора граней. - \en Constructor of duplication face sets . \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef CR_ELEMENTARY_SOLID_H -#define CR_ELEMENTARY_SOLID_H - - -#include -#include - - -class MATH_CLASS MbFaceShell; -class MbRegTransform; -class MbRegDuplicate; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель размноженого набора граней. - \en Constructor of duplication face sets . \~ - \details \ru Строитель выполняет размножение тела согласно параметрам и объединяет копии в одно тело\n - \en Creator makes duplication of face sets accordind to parameters and unite its into a single face set\~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbDuplicationSolid : public MbCreator { -protected: - DuplicationValues * parameters; ///< \ru Параметры размножения. \en Parameters of duplication. - -public: - /// \ru Конструктор по параметрам. \en Constructor by parameters. - MbDuplicationSolid( const DuplicationValues & p, const MbSNameMaker & n ); -private: - MbDuplicationSolid( const MbDuplicationSolid & init, MbRegDuplicate *ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbDuplicationSolid( const MbDuplicationSolid & init ); -public: - virtual~MbDuplicationSolid(); - - /** \ru \name Общие функции строителя оболочки. - \en \name Common functions of the shell creator. - \{ */ - /// \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 & 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 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 - - 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 bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - /** \} */ - -private : -// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbDuplicationSolid & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDuplicationSolid ) -}; // MbDuplicationSolid - -IMPL_PERSISTENT_OPS( MbDuplicationSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создать оболочку размножения исходной оболочки. - \en Create a shell of duplication of original shell. \~ - \details \ru По данной оболочке и параметрам размножения построить оболочку как результат объединения копий.\n - Одновременно с построением оболочки функция создаёт её строитель. \n - \en For a given shell and duplication parameters construct a shell as a result of a union of copies. \n - The function simultaneously constructs the shell and creates its constructor.\~ - \param[in] solid - \ru Исходная оболочка. - \en Original face set. \~ - \param[in] params - \ru Параметры размножения. - \en Parameters of duplication. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] duplSolid - \ru Построенный набор граней. - \en Constructed set of faces. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \result \ru Возвращает строитель, если операция была выполнена успешно. - \en Returns the constructor if the operation has been successfully performed. \~ - \ingroup Solid_Modeling -*/ -MATH_FUNC (MbCreator *) CreateDuplication( const MbFaceShell & solid, - const DuplicationValues & params, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // CR_ELEMENTARY_SOLID_H \ No newline at end of file +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель размноженного набора граней. + \en Constructor of duplication face sets . \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef CR_DUPLICATION_SOLID_H +#define CR_DUPLICATION_SOLID_H + + +#include +#include + + +class MATH_CLASS MbFaceShell; +class MbRegTransform; +class MbRegDuplicate; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель размноженного набора граней. + \en Constructor of duplication face sets . \~ + \details \ru Строитель выполняет размножение тела согласно параметрам и объединяет копии в одно тело\n + \en Creator makes duplication of face sets according to parameters and unite its into a single face set\~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbDuplicationSolid : public MbCreator { +protected: + DuplicationValues * parameters; ///< \ru Параметры размножения. \en Parameters of duplication. + +public: + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MbDuplicationSolid( const DuplicationValues &, const MbSNameMaker & ); +private: + MbDuplicationSolid( const MbDuplicationSolid &, MbRegDuplicate * ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbDuplicationSolid( const MbDuplicationSolid & ); +public: + virtual~MbDuplicationSolid(); + + /** \ru \name Общие функции строителя оболочки. + \en \name Common functions of the shell creator. + \{ */ + /// \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 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 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 bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + /** \} */ + +private : +// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbDuplicationSolid & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbDuplicationSolid ) +}; // MbDuplicationSolid + +IMPL_PERSISTENT_OPS( MbDuplicationSolid ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать оболочку размножения исходной оболочки. + \en Create a shell of duplication of original shell. \~ + \details \ru По данной оболочке и параметрам размножения построить оболочку как результат объединения копий.\n + Одновременно с построением оболочки функция создаёт её строитель. \n + \en For a given shell and duplication parameters construct a shell as a result of a union of copies. \n + The function simultaneously constructs the shell and creates its constructor.\~ + \param[in] solid - \ru Исходная оболочка. + \en Original face set. \~ + \param[in] params - \ru Параметры размножения. + \en Parameters of duplication. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] duplSolid - \ru Построенный набор граней. + \en Constructed set of faces. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \result \ru Возвращает строитель, если операция была выполнена успешно. + \en Returns the constructor if the operation has been successfully performed. \~ + \ingroup Solid_Modeling +*/ +MATH_FUNC (MbCreator *) CreateDuplication( const MbFaceShell & solid, + const DuplicationValues & params, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // CR_DUPLICATION_SOLID_H \ No newline at end of file diff --git a/C3d/Include/cr_elementary_solid.h b/C3d/Include/cr_elementary_solid.h index 1879a6f..43f630c 100644 --- a/C3d/Include/cr_elementary_solid.h +++ b/C3d/Include/cr_elementary_solid.h @@ -48,12 +48,21 @@ 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. public : /** \brief \ru Конструктор. \en Constructor. \~ - \details \ru Конструктор по точкам и типу тела. - \en Constructor by points and a type of a solid. \~ + \details \ru Конструктор по точкам и типу тела. При этом, по массиву точек тела и его типу наполняются соответствующие его параметры. + \en Constructor by points and type of solid. + At the same time, the corresponding parameters are filled in by the array of points of the body and its type. \~ \param[in] pnts - \ru Опорные точки. \n pnts[0] определяет начало локальной системы координат. \n @@ -89,17 +98,8 @@ public : \en An object defining names generation in the operation. \~ */ template - MbElementarySolid( const Points & pnts, ElementaryShellType t, const MbSNameMaker & n ) - : MbCreator( n ) - , points ( ) - , type ( t ) - { - size_t cnt = pnts.size(); - points.reserve( cnt ); - for ( size_t k = 0; k < cnt; ++k ) { - points.push_back( pnts[k] ); - } - } + MbElementarySolid( const Points & pnts, ElementaryShellType t, const MbSNameMaker & n ); + private : MbElementarySolid( const MbElementarySolid &, MbRegDuplicate * iReg ); // \ru Конструктор копирования с регистратором \en Copy-constructor with the registrator @@ -183,7 +183,7 @@ IMPL_PERSISTENT_OPS( MbElementarySolid ) */ // --- MATH_FUNC (MbCreator *) CreateElementary( const SArray & points, - ElementaryShellType t, + const ElementaryShellType t, const MbSNameMaker & n, MbResultType & res, MbFaceShell *& shell ); diff --git a/C3d/Include/cr_extension_shell.h b/C3d/Include/cr_extension_shell.h index 01a0f35..a906d9e 100644 --- a/C3d/Include/cr_extension_shell.h +++ b/C3d/Include/cr_extension_shell.h @@ -1,123 +1,121 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение удлинённой грани оболочки. - \en Construction of an extended face of a shell. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_EXTENSION_SHELL_H -#define __CR_EXTENSION_SHELL_H - - -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель удлинённой грани оболочки. - \en Constructor of an extended face of a shell. \~ - \details \ru Строитель удлинённой грани оболочки. Удлинение может быть выполнено следующими способами. - Может быть ублинена на заданное расстояние указанная грань. - К указанной грани может быть добавлена гладко стыкующаяся с ней грань. - К указанной грани может быть добавлена грань, полученная выдавливанием крайнего ребра в заданном направлении. - \en Constructor of an extended face of a shell. Extension can be performed in the following ways: - The specified faces can be extended on the given distance. - A smoothly connected face can be added to the given face. - A face obtained by extrusion of boundary edge in the given direction can be added to the specified face. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbExtensionShell : public MbCreator { -protected : - MbItemIndex faceIndex; ///< \ru Идентификатор удлиняемой грани в оболочке. \en Identifier of a shell face to extend. - SArray edgeIndexes; ///< \ru Идентификаторы ребер в грани. \en Identifier of edges in the face. - ExtensionValues parameters; ///< \ru Параметры построения удлинённой оболочки. \en Parameters of the extended shell construction. - -public : - MbExtensionShell( const MbItemIndex & fInd, const SArray & inds, - const ExtensionValues & p, const MbSNameMaker & n ); -private : - MbExtensionShell( const MbExtensionShell &, MbRegDuplicate * ireg ); -public : - virtual ~MbExtensionShell(); - - // \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 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 - - 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 - - // \ru Общие функции твердого тела \en Common functions of solid solid - - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( ExtensionValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const ExtensionValues & params ) { parameters = params; } - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExtensionShell ) -OBVIOUS_PRIVATE_COPY( MbExtensionShell ) -}; // MbExtensionShell - -IMPL_PERSISTENT_OPS( MbExtensionShell ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить удлинённую грань оболочки. - \en Construct the extended face of a shell. \~ - \details \ru Построить удлинённую грань оболочки. Удлинение может быть выполнено следующими способами. - Может быть ублинена на заданное расстояние указанная грань. - К указанной грани может быть добавлена гладко стыкующаяся с ней грань. - К указанной грани может быть добавлена грань, полученная выдавливанием крайнего ребра в заданном направлении. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct the extended face of a shell. Extension can be performed in the following ways: - The specified faces can be extended on the given distance. - A smoothly connected face can be added to the given face. - A face obtained by extrusion of a boundary edge in the given direction can be added to the specified face. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] solid - \ru Исходная оболочка. - \en The initial shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the initial shell. \~ - \param[in] face - \ru Удлиняемая грагнь. - \en Face to extend. \~ - \param[in] edges - \ru Крайние рёбра удлиняемой грани. - \en Boundary edges of a face to extend. \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] operNames - \ru Именователь граней. - \en An object for naming faces. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateExtensionShell( MbFaceShell * solid, - MbeCopyMode sameShell, - MbFace & face, - const RPArray & edges, - const ExtensionValues & parameters, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_EXTENSION_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение удлинённой грани оболочки. + \en Construction of an extended face of a shell. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_EXTENSION_SHELL_H +#define __CR_EXTENSION_SHELL_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель удлинённой грани оболочки. + \en Constructor of an extended face of a shell. \~ + \details \ru Строитель удлинённой грани оболочки. Удлинение может быть выполнено следующими способами. + Может быть удлинена на заданное расстояние указанная грань. + К указанной грани может быть добавлена гладко стыкующаяся с ней грань. + К указанной грани может быть добавлена грань, полученная выдавливанием крайнего ребра в заданном направлении. + \en Constructor of an extended face of a shell. Extension can be performed in the following ways: + The specified faces can be extended on the given distance. + A smoothly connected face can be added to the given face. + A face obtained by extrusion of boundary edge in the given direction can be added to the specified face. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbExtensionShell : public MbCreator { +protected : + std::vector facesIndex; ///< \ru Идентификаторы удлиняемых граней в оболочке. \en Identifier of a shell faces to extend. + ExtensionValues parameters; ///< \ru Параметры построения удлинённой оболочки. \en Parameters of the extended shell construction. + +public : + MbExtensionShell( const std::vector & fInd, + const ExtensionValues & p, const MbSNameMaker & n ); +private : + MbExtensionShell( const MbExtensionShell &, MbRegDuplicate * ireg ); +public : + virtual ~MbExtensionShell(); + + // \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 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 + + 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 + + // \ru Общие функции твердого тела \en Common functions of solid solid + + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( ExtensionValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const ExtensionValues & params ) { parameters = params; } + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExtensionShell ) +OBVIOUS_PRIVATE_COPY( MbExtensionShell ) +}; // MbExtensionShell + + +IMPL_PERSISTENT_OPS( MbExtensionShell ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить удлинённую грань оболочки. + \en Construct the extended face of a shell. \~ + \details \ru Построить удлинённую грань оболочки. Удлинение может быть выполнено следующими способами. + Может быть удлинена на заданное расстояние указанная грань. + К указанной грани может быть добавлена гладко стыкующаяся с ней грань. + К указанной грани может быть добавлена грань, полученная выдавливанием крайнего ребра в заданном направлении. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct the extended face of a shell. An extension can be performed in the following ways: + The specified faces can be extended on the given distance. + A smoothly connected face can be added to the given face. + A face obtained by extrusion of a boundary edge in the given direction can be added to the specified face. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] solid - \ru Исходная оболочка. + \en The initial shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the initial shell. \~ + \param[in] edges - \ru Множество краевых ребер, через которые выполняется продление. + \en An array of boundary edges through which to extend the face. \~ + \param[in] parameters - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] operNames - \ru Именователь граней. + \en An object for naming faces. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateExtensionShell( MbFaceShell * solid, + MbeCopyMode sameShell, + const RPArray & edges, + const ExtensionValues & parameters, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_EXTENSION_SHELL_H diff --git a/C3d/Include/cr_fillet_solid.h b/C3d/Include/cr_fillet_solid.h index 90bbb6a..b12681a 100644 --- a/C3d/Include/cr_fillet_solid.h +++ b/C3d/Include/cr_fillet_solid.h @@ -36,6 +36,7 @@ struct MATH_CLASS MbEdgeFunction; class MATH_CLASS MbFilletSolid : public MbSmoothSolid { public : RPArray functions; ///< \ru Функции изменения радиусов сопряжения. \en Functions of changing conjugation radii. + RPArray slideways; ///< \ru Опорные кривые сопряжения. \en Supporting curves of conjugation. SArray boundaries; ///< \ru Номера граней для обрезки краёв скругления / фаски. \en Indices of faces for trimming the fillet / chamfer boundaries. SArray vertices; ///< \ru Номера скругляемых вершин. \en Indices of vertices to fillet. CornerValues cornerData; ///< \ru Параметры скругления вершин. \en Parameters of vertices fillet. @@ -43,6 +44,7 @@ public : public : MbFilletSolid( SArray & inds, RPArray & funcs, + RPArray & slids, SArray & bounds, SArray & verts, const SmoothValues & params, @@ -68,6 +70,7 @@ public : virtual MbePrompt GetPropertyName(); // \ru Выдать заголовок свойства объекта. \en Get a name of object property. virtual bool IsSame( const MbCreator & other, 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 & init ); // \ru Сделать равным. \en Make equal. // \ru Общие функции твердого тела \en Common functions of solid @@ -85,6 +88,7 @@ private : IMPL_PERSISTENT_OPS( MbFilletSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку со cкруглением ребeр. \en Create a shell with edges fillet. \~ diff --git a/C3d/Include/cr_intersection_curve.h b/C3d/Include/cr_intersection_curve.h index dc2e656..b9eacc6 100644 --- a/C3d/Include/cr_intersection_curve.h +++ b/C3d/Include/cr_intersection_curve.h @@ -1,73 +1,73 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель кривой пересечения. - \en Intersection curve constructor. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_INTERSECTION_CURVE_H -#define __CR_INTERSECTION_CURVE_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель кривой пересечения. - \en Intersection curve constructor. \~ - \details \ru Строитель кривой пересечения.\n - \en Intersection curve constructor.\n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbIntCurveCreator : public MbCreator { -private: - RPArray creators1; // \ru Журнал построения первой оболочки. \en The first shell history tree. - RPArray creators2; // \ru Журнал построения второй оболочки. \en The second shell history tree. - -protected: - MbIntCurveCreator( const MbIntCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbIntCurveCreator( const MbIntCurveCreator & ); // \ru Не реализовано \en Not implemented - MbIntCurveCreator(); // \ru Не реализовано \en Not implemented -public: - MbIntCurveCreator( const RPArray & creators1, bool same1, - const RPArray & creators2, bool same2, - const MbSNameMaker & snMaker ); -public: - virtual ~MbIntCurveCreator(); - - // \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 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 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 - 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 Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); - - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbIntCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) -}; - -IMPL_PERSISTENT_OPS( MbIntCurveCreator ) - -#endif // __CR_INTERSECTION_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель кривой пересечения. + \en Intersection curve constructor. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_INTERSECTION_CURVE_H +#define __CR_INTERSECTION_CURVE_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель кривой пересечения. + \en Intersection curve constructor. \~ + \details \ru Строитель кривой пересечения.\n + \en Intersection curve constructor.\n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbIntCurveCreator : public MbCreator { +private: + RPArray creators1; // \ru Журнал построения первой оболочки. \en The first shell history tree. + RPArray creators2; // \ru Журнал построения второй оболочки. \en The second shell history tree. + +protected: + MbIntCurveCreator( const MbIntCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + MbIntCurveCreator( const MbIntCurveCreator & ); // \ru Не реализовано \en Not implemented + MbIntCurveCreator(); // \ru Не реализовано \en Not implemented +public: + MbIntCurveCreator( const RPArray & creators1, bool same1, + const RPArray & creators2, bool same2, + const MbSNameMaker & snMaker ); +public: + virtual ~MbIntCurveCreator(); + + // \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 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 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 + 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 Построить кривую по журналу построения \en Create a curve from the history tree + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbIntCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbIntCurveCreator ) +}; + +IMPL_PERSISTENT_OPS( MbIntCurveCreator ) + +#endif // __CR_INTERSECTION_CURVE_H diff --git a/C3d/Include/cr_join_shell.h b/C3d/Include/cr_join_shell.h index dd25c8b..b8a3999 100644 --- a/C3d/Include/cr_join_shell.h +++ b/C3d/Include/cr_join_shell.h @@ -1,239 +1,239 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение оболочки соединения. - \en Construction of a join shell. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_JOIN_SHELL_H -#define __CR_JOIN_SHELL_H - - -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки соединения. - \en Constructor of a join shell. \~ - \details \ru Строитель оболочки, соединяющей две грани по двум кривым на них. \n - \en Constructor of a shell joining two faces by two curves on them. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbJoinShell : public MbCreator { -protected: - MbCurve3D * curve1; ///< \ru Первая образующая кривая. \en The first generating curve. - MbCurve3D * curve2; ///< \ru Вторая образующая кривая. \en The second generating curve. - JoinSurfaceValues parameters; ///< \ru Параметры поверхности соединения. \en Parameters of a join surface. -public : - MbJoinShell( MbCurve3D & c1, MbCurve3D & c2, const JoinSurfaceValues & p, const MbSNameMaker & n ); -private : - MbJoinShell( const MbJoinShell & init, MbRegDuplicate * ireg ); -public : - virtual ~MbJoinShell(); - - // \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 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 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 - 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. - - // \ru Общие функции твердого тела \en Common functions of solid solid - - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); ///< \ru Построение \en Construction - - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( JoinSurfaceValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const JoinSurfaceValues & params ) { parameters = params; } - - const MbCurve3D & GetCurve( ptrdiff_t num ) const; - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinShell ) -OBVIOUS_PRIVATE_COPY( MbJoinShell ) -}; - -IMPL_PERSISTENT_OPS( MbJoinShell ) - -//------------------------------------------------------------------------------ -/* \brief \ru Проверить необходимость модификации второй кривой. - \en Check if a modification of the second curve is necessary. \~ - \details \ru Проверить необходимость модификации второй кривой для построения оболочки соединения на этих кривых. \n - \en Check whether a modification of the second curve is necessary for construction of a join shell on these curves. \n \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \param[out] isInverted1 - \ru Была ли первая кривая инвертирована. - \en Whether the first curve was inverted. \~ - \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. - \en Whether the beginning of the first curve was shifted. \~ - \param[in] version - \ru Версия построения. - \en The version of construction. \~ - \result \ru Возвращает построенную оболочку. - \en Returns the constructed shell. \~ - \ingroup Model_Creators -*/ -//--- -void CheckJoinedShellCurve( const MbCurve3D & curve1, - const MbCurve3D & curve2, - bool & isInverted1, - bool & isShifted1, - VERSION version ); - - -//------------------------------------------------------------------------------ -/* \brief \ru Построить кривую по набору рёбер. - \en Construct a curve given a set of edges. \~ - \details \ru Построить кривую по набору рёбер для поверхности соединения. - \en Construct a curve given a set of edges for a join surface. \~ - \param[in] edges - \ru Набор ребер. - \en A set of edges. \~ - \param[in] orients - \ru Ориентация рёбер набора. - \en Orientation of edges from the set. \~ - \param[in] matr - \ru Матрица преобразования рёбер набора. - \en Transformation matrix of edges from the set. \~ - \param[out] res - \ru Код результата построения. - \en Construction result code. \~ - \result \ru Возвращает построенную кривую. - \en Returns the constructed curve. \~ - \ingroup Model_Creators -*/ -//--- -MbCurve3D * CreateJoinedShellCurve( const RPArray & edges, - const SArray & orients, - const MbMatrix3D & matr, - MbResultType & res ); - - -//------------------------------------------------------------------------------ -/* \brief \ru Построить оболочку соединения. - \en Construct a join shell. \~ - \details \ru Построить оболочку, соединяющую две грани по двум кривым на них. \n - \en Construct a shell joining two faces by two curves on them. \n \~ - \param[in] curve1 - \ru Кривая на первой соединяемой поверхности. - \en A curve on the first surface to join. \~ - \param[in] curve2 - \ru Кривая на второй соединяемой поверхности. - \en A curve on the second surface to join. \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] names - \ru Именователь граней. - \en An object for naming faces. \~ - \param[in] isPhantom - \ru Режим создания фантома. - \en Create in the phantom mode. \~ - \param[out] res - \ru Код результата построения. - \en Construction result code. \~ - \result \ru Возвращает построенную оболочку. - \en Returns the constructed shell. \~ - \ingroup Model_Creators -*/ -// --- -MbFaceShell * MakeJoinShell( MbSurfaceCurve & curve1, - MbSurfaceCurve & curve2, - JoinSurfaceValues & parameters, - const MbSNameMaker & names, - bool isPhantom, - MbResultType & res ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку соединения. - \en Construct a join shell. \~ - \details \ru Построить оболочку, соединяющую две грани по двум кривым на них. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell joining two faces by two curves on them. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] curve1 - \ru Кривая на первой соединяемой поверхности. - \en A curve on the first surface to join. \~ - \param[in] curve2 - \ru Кривая на второй соединяемой поверхности. - \en A curve on the second surface to join. \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] names - \ru Именователь граней. - \en An object for naming faces. \~ - \param[out] res - \ru Код результата построения. - \en Construction result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateJoinShell( MbSurfaceCurve & curve1, - MbSurfaceCurve & curve2, - JoinSurfaceValues & parameters, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку соединения. - \en Construct a join shell. \~ - \details \ru Построить оболочку соединения по двум наборам ребер. - Рёбра двух наборов определяют набор граней соединения, каждая из которых побстроена по двум кривым. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell of join given two sets of edges. - Edges of two sets define a set of join faces each of which is constructed by two curves. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] edges1 - \ru Первый набор ребер. - \en The first set of edges. \~ - \param[in] orients1 - \ru Ориентация рёбер первого набора. - \en Orientation of edges from the first set. \~ - \param[in] edges2 - \ru Второй набор ребер. - \en The second set of edges. \~ - \param[in] orients2 - \ru Ориентация рёбер второго набора. - \en Orientation of edges of the second set. \~ - \param[in] matr1 - \ru Матрица преобразования рёбер первого набора. - \en Transformation matrix of edges from the first set. \~ - \param[in] matr2 - \ru Матрица преобразования рёбер второго набора. - \en Transformation matrix of edges from the second set. \~ - \param[in] parameters - \ru Параметры построения. - \en Parameters of a shell creation. \~ - \param[in] names - \ru Именователь граней. - \en An object for naming faces. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \param[in] isPhantom - \ru Режим создания фантома. - \en Create in the phantom mode. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateJoinShell( const RPArray & edges1, - const SArray & orients1, - const RPArray & edges2, - const SArray & orients2, - const MbMatrix3D & matr1, - const MbMatrix3D & matr2, - JoinSurfaceValues & parameters, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell, - bool isPhantom ); - - -#endif // __CR_JOIN_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение оболочки соединения. + \en Construction of a join shell. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_JOIN_SHELL_H +#define __CR_JOIN_SHELL_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки соединения. + \en Constructor of a join shell. \~ + \details \ru Строитель оболочки, соединяющей две грани по двум кривым на них. \n + \en Constructor of a shell joining two faces by two curves on them. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbJoinShell : public MbCreator { +protected: + MbCurve3D * curve1; ///< \ru Первая образующая кривая. \en The first generating curve. + MbCurve3D * curve2; ///< \ru Вторая образующая кривая. \en The second generating curve. + JoinSurfaceValues parameters; ///< \ru Параметры поверхности соединения. \en Parameters of a join surface. +public : + MbJoinShell( MbCurve3D & c1, MbCurve3D & c2, const JoinSurfaceValues & p, const MbSNameMaker & n ); +private : + MbJoinShell( const MbJoinShell & init, MbRegDuplicate * ireg ); +public : + virtual ~MbJoinShell(); + + // \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 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 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 + 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. + + // \ru Общие функции твердого тела \en Common functions of solid solid + + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); ///< \ru Построение \en Construction + + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( JoinSurfaceValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const JoinSurfaceValues & params ) { parameters = params; } + + const MbCurve3D & GetCurve( ptrdiff_t num ) const; + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinShell ) +OBVIOUS_PRIVATE_COPY( MbJoinShell ) +}; + +IMPL_PERSISTENT_OPS( MbJoinShell ) + +//------------------------------------------------------------------------------ +/* \brief \ru Проверить необходимость модификации второй кривой. + \en Check if a modification of the second curve is necessary. \~ + \details \ru Проверить необходимость модификации второй кривой для построения оболочки соединения на этих кривых. \n + \en Check whether a modification of the second curve is necessary for construction of a join shell on these curves. \n \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \param[out] isInverted1 - \ru Была ли первая кривая инвертирована. + \en Whether the first curve was inverted. \~ + \param[out] isShifted1 - \ru Было ли смещено начало второй кривой. + \en Whether the beginning of the first curve was shifted. \~ + \param[in] version - \ru Версия построения. + \en The version of construction. \~ + \result \ru Возвращает построенную оболочку. + \en Returns the constructed shell. \~ + \ingroup Model_Creators +*/ +//--- +void CheckJoinedShellCurve( const MbCurve3D & curve1, + const MbCurve3D & curve2, + bool & isInverted1, + bool & isShifted1, + VERSION version ); + + +//------------------------------------------------------------------------------ +/* \brief \ru Построить кривую по набору рёбер. + \en Construct a curve given a set of edges. \~ + \details \ru Построить кривую по набору рёбер для поверхности соединения. + \en Construct a curve given a set of edges for a join surface. \~ + \param[in] edges - \ru Набор ребер. + \en A set of edges. \~ + \param[in] orients - \ru Ориентация рёбер набора. + \en Orientation of edges from the set. \~ + \param[in] matr - \ru Матрица преобразования рёбер набора. + \en Transformation matrix of edges from the set. \~ + \param[out] res - \ru Код результата построения. + \en Construction result code. \~ + \result \ru Возвращает построенную кривую. + \en Returns the constructed curve. \~ + \ingroup Model_Creators +*/ +//--- +MbCurve3D * CreateJoinedShellCurve( const RPArray & edges, + const SArray & orients, + const MbMatrix3D & matr, + MbResultType & res ); + + +//------------------------------------------------------------------------------ +/* \brief \ru Построить оболочку соединения. + \en Construct a join shell. \~ + \details \ru Построить оболочку, соединяющую две грани по двум кривым на них. \n + \en Construct a shell joining two faces by two curves on them. \n \~ + \param[in] curve1 - \ru Кривая на первой соединяемой поверхности. + \en A curve on the first surface to join. \~ + \param[in] curve2 - \ru Кривая на второй соединяемой поверхности. + \en A curve on the second surface to join. \~ + \param[in] parameters - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] names - \ru Именователь граней. + \en An object for naming faces. \~ + \param[in] isPhantom - \ru Режим создания фантома. + \en Create in the phantom mode. \~ + \param[out] res - \ru Код результата построения. + \en Construction result code. \~ + \result \ru Возвращает построенную оболочку. + \en Returns the constructed shell. \~ + \ingroup Model_Creators +*/ +// --- +MbFaceShell * MakeJoinShell( MbSurfaceCurve & curve1, + MbSurfaceCurve & curve2, + JoinSurfaceValues & parameters, + const MbSNameMaker & names, + bool isPhantom, + MbResultType & res ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку соединения. + \en Construct a join shell. \~ + \details \ru Построить оболочку, соединяющую две грани по двум кривым на них. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell joining two faces by two curves on them. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] curve1 - \ru Кривая на первой соединяемой поверхности. + \en A curve on the first surface to join. \~ + \param[in] curve2 - \ru Кривая на второй соединяемой поверхности. + \en A curve on the second surface to join. \~ + \param[in] parameters - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] names - \ru Именователь граней. + \en An object for naming faces. \~ + \param[out] res - \ru Код результата построения. + \en Construction result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateJoinShell( MbSurfaceCurve & curve1, + MbSurfaceCurve & curve2, + JoinSurfaceValues & parameters, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку соединения. + \en Construct a join shell. \~ + \details \ru Построить оболочку соединения по двум наборам ребер. + Рёбра двух наборов определяют набор граней соединения, каждая из которых побстроена по двум кривым. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell of join given two sets of edges. + Edges of two sets define a set of join faces each of which is constructed by two curves. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] edges1 - \ru Первый набор ребер. + \en The first set of edges. \~ + \param[in] orients1 - \ru Ориентация рёбер первого набора. + \en Orientation of edges from the first set. \~ + \param[in] edges2 - \ru Второй набор ребер. + \en The second set of edges. \~ + \param[in] orients2 - \ru Ориентация рёбер второго набора. + \en Orientation of edges of the second set. \~ + \param[in] matr1 - \ru Матрица преобразования рёбер первого набора. + \en Transformation matrix of edges from the first set. \~ + \param[in] matr2 - \ru Матрица преобразования рёбер второго набора. + \en Transformation matrix of edges from the second set. \~ + \param[in] parameters - \ru Параметры построения. + \en Parameters of a shell creation. \~ + \param[in] names - \ru Именователь граней. + \en An object for naming faces. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \param[in] isPhantom - \ru Режим создания фантома. + \en Create in the phantom mode. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateJoinShell( const RPArray & edges1, + const SArray & orients1, + const RPArray & edges2, + const SArray & orients2, + const MbMatrix3D & matr1, + const MbMatrix3D & matr2, + JoinSurfaceValues & parameters, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell, + bool isPhantom ); + + +#endif // __CR_JOIN_SHELL_H diff --git a/C3d/Include/cr_median_shell.h b/C3d/Include/cr_median_shell.h index 57af1ed..edda9cf 100644 --- a/C3d/Include/cr_median_shell.h +++ b/C3d/Include/cr_median_shell.h @@ -1,115 +1,118 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение срединной оболочки между гранями тела. - \en Construction of a median shell between faces of solid. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_MEDIAN_SHELL_H -#define __CR_MEDIAN_SHELL_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MedianShellFaces; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель срединной оболочки тела. - \en Constructor of a median shell of solid. \~ - \details \ru Строитель осуществляет построение срединной оболочки между выбранными парами граней тела. - Поверхности выбранные граней должны быть эквидистантны по отношению друг к другу. \n - \en Constructor performs the building of a median shell between suitable selected face pairs of solid. - Suitable face pairs should be equidistant from each other. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbMedianShell : public MbCreator { -private : - MedianShellFaces faces; ///< \ru Выбранные грани. \en Selected faces . - MedianShellValues parameters; ///< \ru Параметры срединной оболочки. \en Parameters of median shell. - -public: - /// \ru Конструктор по выбранным граням и параметрам срединной оболочки. \en Constructor by selected faces and parameters of median shell. - MbMedianShell( const MedianShellFaces & faces, const MedianShellValues & params, const MbSNameMaker & snMaker ); - /// \ru Деструктор. \en Destructor. - virtual ~MbMedianShell(); - -private: - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - MbMedianShell( const MbMedianShell &, MbRegDuplicate * ); - -public: - virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element - virtual MbCreator & Duplicate( MbRegDuplicate * = 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 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 Construction of a shell from the given data - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - - /// \ru Дать параметры. \en Get the parameters. - void GetParameters( MedianShellValues & params ) const { params = parameters; } - /// \ru Установить параметры. \en Set the parameters. - void SetParameters( const MedianShellValues & params ) { parameters = params; } - - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMedianShell ) -OBVIOUS_PRIVATE_COPY( MbMedianShell ) -}; - -IMPL_PERSISTENT_OPS( MbMedianShell ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить срединную оболочку между выбранными парами граней тела. - \en Build a median shell between selected faces of solid. \~ - \details \ru Построить срединную оболочку между выбранными парами граней тела. - Выбранные грани должны быть эквидистантны по отношению друг к другу. - Грани должны принадлежать одному и тому же телу. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Build a median shell between suitable selected face pairs of solid. - Suitable face pairs should be offset from each other. - The faces must belong to the same body. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] solid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] faces - \ru Выбранные пары граней. - \en Selected face pairs. \~ - \param[in] parameters - \ru Параметры операции. - \en Parameters of operation. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенная срединная оболочка. - \en Constructed median shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateMedianShell( const MbFaceShell & solid, - const std::vector & faceIndexes, - const MedianShellValues & parameters, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение срединной оболочки между гранями тела. + \en Construction of a median shell between faces of solid. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_MEDIAN_SHELL_H +#define __CR_MEDIAN_SHELL_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MedianShellFaces; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель срединной оболочки тела. + \en Constructor of a median shell of solid. \~ + \details \ru Строитель осуществляет построение срединной оболочки между выбранными парами граней тела. + Поверхности выбранные граней должны быть эквидистантны по отношению друг к другу. \n + \en Constructor performs the building of a median shell between suitable selected face pairs of solid. + Suitable face pairs should be equidistant from each other. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbMedianShell : public MbCreator { +private : + MedianShellFaces faces; ///< \ru Выбранные грани. \en Selected faces . + MedianShellValues parameters; ///< \ru Параметры срединной оболочки. \en Parameters of median shell. + +public: + /// \ru Конструктор по выбранным граням и параметрам срединной оболочки. \en Constructor by selected faces and parameters of median shell. + MbMedianShell( const MedianShellFaces & faces, const MedianShellValues & params, const MbSNameMaker & snMaker ); + /// \ru Деструктор. \en Destructor. + virtual ~MbMedianShell(); + +private: + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + MbMedianShell( const MbMedianShell &, MbRegDuplicate * ); + +public: + virtual MbeCreatorType IsA() const; // \ru Тип элемента \en Type of element + virtual MbCreator & Duplicate( MbRegDuplicate * = 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 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 Construction of a shell from the given data + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + + /// \ru Дать параметры. \en Get the parameters. + void GetParameters( MedianShellValues & params ) const { params = parameters; } + /// \ru Установить параметры. \en Set the parameters. + void SetParameters( const MedianShellValues & params ) { parameters = params; } + + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMedianShell ) +OBVIOUS_PRIVATE_COPY( MbMedianShell ) +}; + +IMPL_PERSISTENT_OPS( MbMedianShell ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить срединную оболочку между выбранными парами граней тела. + \en Build a median shell between selected faces of solid. \~ + \details \ru Построить срединную оболочку между выбранными парами граней тела. + Выбранные грани должны быть эквидистантны по отношению друг к другу. + Грани должны принадлежать одному и тому же телу. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Build a median shell between suitable selected face pairs of solid. + Suitable face pairs should be offset from each other. + The faces must belong to the same body. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] solid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] faces - \ru Выбранные пары граней. + \en Selected face pairs. \~ + \param[in] parameters - \ru Параметры операции. + \en Parameters of operation. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] medianFaces - \ru Множество граней для создания срединной оболочки. + \en Set of faces for build a median shell. \~ + \param[out] shell - \ru Построенная срединная оболочка. + \en Constructed median shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateMedianShell( const MbFaceShell & solid, + const c3d::IndicesPairsVector & faceIndexes, + const MedianShellValues & parameters, + const MbSNameMaker & operNames, + MbResultType & res, + MedianShellFaces & medianFaces, + MbFaceShell *& shell ); + + #endif // __CR_MEDIAN_SHELL_H \ No newline at end of file diff --git a/C3d/Include/cr_mesh_shell.h b/C3d/Include/cr_mesh_shell.h index 3a2cef5..5b59c37 100644 --- a/C3d/Include/cr_mesh_shell.h +++ b/C3d/Include/cr_mesh_shell.h @@ -1,103 +1,103 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение оболочки на сетке кривых. - \en Construction of a shell from a mesh of curves. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_MESH_SHELL_H -#define __CR_MESH_SHELL_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbFaceShell; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки на сетке кривых. - \en Constructor of a shell from a mesh of curves. \~ - \details \ru Строитель оболочки на сетке кривых, образованной двумя сечействами кривых. \n - \en Constructor of a shell from a mesh of curves formed by two sets of curves. \n \~ - \ingroup Model_Creators -*/ -//--- -class MATH_CLASS MbMeshShell : public MbCreator { -private : - MeshSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. - mutable bool changed; ///< \ru Флаг изменения параметров. \en Flag of parameters modification. -private: - /// \ru Конструктор копирования. \en Copy-constructor. - MbMeshShell( const MbMeshShell & obj, MbRegDuplicate * ireg ); -public: - /// \ru Конструктор по параметрам операции и именователю на оригиналах кривых и копиях поверхностей. \en Constructor by operation parameters and name-maker for original curves and copies of surfaces. - MbMeshShell( const MeshSurfaceValues & pars, const MbSNameMaker & n ); - virtual ~MbMeshShell(); - -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 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 MbePrompt GetPropertyName(); ///< \ru Выдать заголовок свойства объекта \en Get name of object property - virtual void GetProperties( MbProperties & ); ///< \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties & ); ///< \ru Записать свойства объекта \en Write 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. - -public: - /// \ru Построение оболочки \en Creation of a shell - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MeshSurfaceValues & params ) const; - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MeshSurfaceValues & params ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMeshShell ) -OBVIOUS_PRIVATE_COPY( MbMeshShell ) -}; // MbMeshShell - -IMPL_PERSISTENT_OPS( MbMeshShell ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку на сетке кривых. - \en Construct a shell from a mesh of curves. \~ - \details \ru Построить оболочку на сетке кривых, образованной двумя сечействами кривых. \n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Create a shell from a mesh of curves formed by two sets of curves. \n - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] parameters - \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. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateMeshShell( MeshSurfaceValues & parameters, - const MbSNameMaker & operNames, - bool isPhantom, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_MESH_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение оболочки на сетке кривых. + \en Construction of a shell from a mesh of curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_MESH_SHELL_H +#define __CR_MESH_SHELL_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbFaceShell; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки на сетке кривых. + \en Constructor of a shell from a mesh of curves. \~ + \details \ru Строитель оболочки на сетке кривых, образованной двумя сечействами кривых. \n + \en Constructor of a shell from a mesh of curves formed by two sets of curves. \n \~ + \ingroup Model_Creators +*/ +//--- +class MATH_CLASS MbMeshShell : public MbCreator { +private : + MeshSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. + mutable bool changed; ///< \ru Флаг изменения параметров. \en Flag of parameters modification. +private: + /// \ru Конструктор копирования. \en Copy-constructor. + MbMeshShell( const MbMeshShell & obj, MbRegDuplicate * ireg ); +public: + /// \ru Конструктор по параметрам операции и именователю на оригиналах кривых и копиях поверхностей. \en Constructor by operation parameters and name-maker for original curves and copies of surfaces. + MbMeshShell( const MeshSurfaceValues & pars, const MbSNameMaker & n ); + virtual ~MbMeshShell(); + +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 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 MbePrompt GetPropertyName(); ///< \ru Выдать заголовок свойства объекта \en Get name of object property + virtual void GetProperties( MbProperties & ); ///< \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); ///< \ru Записать свойства объекта \en Write 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. + +public: + /// \ru Построение оболочки \en Creation of a shell + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MeshSurfaceValues & params ) const; + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MeshSurfaceValues & params ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMeshShell ) +OBVIOUS_PRIVATE_COPY( MbMeshShell ) +}; // MbMeshShell + +IMPL_PERSISTENT_OPS( MbMeshShell ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку на сетке кривых. + \en Construct a shell from a mesh of curves. \~ + \details \ru Построить оболочку на сетке кривых, образованной двумя сечействами кривых. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Create a shell from a mesh of curves formed by two sets of curves. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] parameters - \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. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateMeshShell( MeshSurfaceValues & parameters, + const MbSNameMaker & operNames, + bool isPhantom, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_MESH_SHELL_H diff --git a/C3d/Include/cr_modified_nurbs_.h b/C3d/Include/cr_modified_nurbs_.h index c499843..7e5ca95 100644 --- a/C3d/Include/cr_modified_nurbs_.h +++ b/C3d/Include/cr_modified_nurbs_.h @@ -1,217 +1,217 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель оболочки c деформируемыми гранями. - \en Constructor of a shell with deformable faces. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_MODIFIED_NURBS_H -#define __CR_MODIFIED_NURBS_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки c деформируемыми гранями. - \en Constructor of a shell with deformable faces. \~ - \details \ru Строитель оболочки, выполняющий замену поверхностей указанных граней деформируемыми поверхностями. \n - \en Constructor of a shell performing replacement of the surfaces of the specified faces with deformable surfaces. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbModifiedNurbsItem : public MbCreator { -protected: - NurbsValues parameters; ///< \ru Параметры модифицированных поверхностей. \en Parameters of modified surfaces. - SArray itemIndices; ///< \ru Идентификаторы модифицируемых граней. \en Identifiers of faces being modified. - RPArray surfaces; ///< \ru Множество поверхностей модифицированных граней. \en A set of surfaces of the modified faces. - -public: // \ru конструктор по параметрам \en constructor by parameters - MbModifiedNurbsItem( const NurbsValues & p, const SArray & faces, - RPArray & surfs, const MbSNameMaker & names ); -private: // \ru конструктор дублирующий \en duplication constructor - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbModifiedNurbsItem( const MbModifiedNurbsItem & init ); - MbModifiedNurbsItem( const MbModifiedNurbsItem & init, MbRegDuplicate * ireg ); - -public: // \ru деструктор \en destructor - virtual ~MbModifiedNurbsItem(); - -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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - - /// \ru Построение оболочки. \en creation of a shell - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell - // \ru Выдать базовые объекты. \en Get basis objects. - virtual void GetBasisItems( RPArray & s ); - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( NurbsValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const NurbsValues & params ) { parameters = params; } - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbModifiedNurbsItem & ); - void SurfacesFree(); // \ru Удалить поверхности \en Delete the surfaces - void SurfacesAddRef(); // \ru Учесть поверхности \en Consider the surfaces - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbModifiedNurbsItem ) -}; - -IMPL_PERSISTENT_OPS( MbModifiedNurbsItem ) - -//------------------------------------------------------------------------------ -/** \brief \ru Модификатор оболочки c деформируемой гранью. - \en Modifier of a shell with a deformable face. \~ - \details \ru Модификатор оболочки выполняет деформацию поверхности указанной грани. - Указанная грань должна быть дефолрмируемой. \n - \en Modifier of a shell performs deformation of a surface of the specified face. - The specified face should be deformable. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbNurbsModification : public MbCreator { -protected: - MbItemIndex faceIndex; ///< \ru Идентификатор деформируемой грани. \en Identifier of the deformable face. - MbSurface * faceSurface; ///< \ru Поверхность деформируемой грани. \en Surface of the deformable face. - Array2 fixedPoints; ///< \ru Матрица положений неизменяемых контрольных точек модифицируемой поверхности. \en Matrix of positions of the invariant control points of the modifiable surface. - -public: // \ru конструктор по параметрам \en constructor by parameters - MbNurbsModification( const MbItemIndex & index, MbSurface & fSurface, Array2 & fPoints, - const MbSNameMaker & names ); -private: // \ru конструктор дублирующий \en duplication constructor - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbNurbsModification( const MbNurbsModification & init ); - MbNurbsModification( const MbNurbsModification & init, MbRegDuplicate * ireg ); - -public: // \ru деструктор \en destructor - virtual ~MbNurbsModification(); - -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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - - /// \ru построение оболочки \en creation of a shell - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell - // \ru Выдать базовые объекты. \en Get basis objects. - virtual void GetBasisItems( RPArray & s ); - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbNurbsModification & ); // \ru не реализован!!! \en not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsModification ) -}; - -IMPL_PERSISTENT_OPS( MbNurbsModification ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку c деформируемыми гранями. - \en Construct a shell with deformable faces. \~ - \details \ru Построить оболочку c заменjq указанных граней исходной оболочки деформируемыми гранями. - Поверхности выбранных граней аппроксимируются NURBS поверхностями или - деформируемыми поверхностями для последующего редактирования. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell with replacement of the specified faces of the source shell with deformable faces. - Surfaces of the selected faces are approximated with NURBS surfaces or - deformable surfaces for the further editing. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] outer - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the source shell. \~ - \param[in] parameters - \ru Параметры модификации. - \en Parameters of the modification. \~ - \param[in] faces - \ru Изменяемые грани тела. - \en Faces to be modified. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] res - \ru Код результата операции выдавливания. - \en The extrusion operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateModifiedNurbsItem( MbFaceShell * outer, - MbeCopyMode sameShell, - const NurbsValues & parameters, - const RPArray & faces, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку, в которой деформирована указанная грань. - \en Construct a shell in which the specified face is deformed. \~ - \details \ru Построить оболочку, в которой деформирована указанная грань путём - подстановки контрольных точек присланной NURBS-поверхности с фиксацией указанных точек.\n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell in which the specified face is deformed by - replacement of the control points of the given NURBS surface with fixing the specified points.\n - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] outer - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the source shell. \~ - \param[in] face - \ru Деформируемая грань оболочки. - \en Deformable face of the shell. \~ - \param[in] faceSurface - \ru Новая деформируемая поверхность для грани. - \en The new deformable surface of the face. \~ - \param[in] fixedPoints - \ru Матрица положений неизменяемых контрольных точек деформируемой поверхности (false). - \en Matrix of positions of invariant control points of the deformable surface (false). \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] res - \ru Код результата операции выдавливания. - \en The extrusion operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateNurbsModification( MbFaceShell * outer, - MbeCopyMode sameShell, - MbFace * face, - MbSurface & faceSurface, - Array2 & fixedPoints, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_MODIFIED_NURBS_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель оболочки c деформируемыми гранями. + \en Constructor of a shell with deformable faces. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_MODIFIED_NURBS_H +#define __CR_MODIFIED_NURBS_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки c деформируемыми гранями. + \en Constructor of a shell with deformable faces. \~ + \details \ru Строитель оболочки, выполняющий замену поверхностей указанных граней деформируемыми поверхностями. \n + \en Constructor of a shell performing replacement of the surfaces of the specified faces with deformable surfaces. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbModifiedNurbsItem : public MbCreator { +protected: + NurbsValues parameters; ///< \ru Параметры модифицированных поверхностей. \en Parameters of modified surfaces. + SArray itemIndices; ///< \ru Идентификаторы модифицируемых граней. \en Identifiers of faces being modified. + RPArray surfaces; ///< \ru Множество поверхностей модифицированных граней. \en A set of surfaces of the modified faces. + +public: // \ru конструктор по параметрам \en constructor by parameters + MbModifiedNurbsItem( const NurbsValues & p, const SArray & faces, + RPArray & surfs, const MbSNameMaker & names ); +private: // \ru конструктор дублирующий \en duplication constructor + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbModifiedNurbsItem( const MbModifiedNurbsItem & init ); + MbModifiedNurbsItem( const MbModifiedNurbsItem & init, MbRegDuplicate * ireg ); + +public: // \ru деструктор \en destructor + virtual ~MbModifiedNurbsItem(); + +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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + + /// \ru Построение оболочки. \en creation of a shell + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell + // \ru Выдать базовые объекты. \en Get basis objects. + virtual void GetBasisItems( RPArray & s ); + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( NurbsValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const NurbsValues & params ) { parameters = params; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbModifiedNurbsItem & ); + void SurfacesFree(); // \ru Удалить поверхности \en Delete the surfaces + void SurfacesAddRef(); // \ru Учесть поверхности \en Consider the surfaces + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbModifiedNurbsItem ) +}; + +IMPL_PERSISTENT_OPS( MbModifiedNurbsItem ) + +//------------------------------------------------------------------------------ +/** \brief \ru Модификатор оболочки c деформируемой гранью. + \en Modifier of a shell with a deformable face. \~ + \details \ru Модификатор оболочки выполняет деформацию поверхности указанной грани. + Указанная грань должна быть дефолрмируемой. \n + \en Modifier of a shell performs deformation of a surface of the specified face. + The specified face should be deformable. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbNurbsModification : public MbCreator { +protected: + MbItemIndex faceIndex; ///< \ru Идентификатор деформируемой грани. \en Identifier of the deformable face. + MbSurface * faceSurface; ///< \ru Поверхность деформируемой грани. \en Surface of the deformable face. + Array2 fixedPoints; ///< \ru Матрица положений неизменяемых контрольных точек модифицируемой поверхности. \en Matrix of positions of the invariant control points of the modifiable surface. + +public: // \ru конструктор по параметрам \en constructor by parameters + MbNurbsModification( const MbItemIndex & index, MbSurface & fSurface, Array2 & fPoints, + const MbSNameMaker & names ); +private: // \ru конструктор дублирующий \en duplication constructor + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbNurbsModification( const MbNurbsModification & init ); + MbNurbsModification( const MbNurbsModification & init, MbRegDuplicate * ireg ); + +public: // \ru деструктор \en destructor + virtual ~MbNurbsModification(); + +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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + + /// \ru построение оболочки \en creation of a shell + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell + // \ru Выдать базовые объекты. \en Get basis objects. + virtual void GetBasisItems( RPArray & s ); + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbNurbsModification & ); // \ru не реализован!!! \en not implemented!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsModification ) +}; + +IMPL_PERSISTENT_OPS( MbNurbsModification ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку c деформируемыми гранями. + \en Construct a shell with deformable faces. \~ + \details \ru Построить оболочку c заменой указанных граней исходной оболочки деформируемыми гранями. + Поверхности выбранных граней аппроксимируются NURBS поверхностями или + деформируемыми поверхностями для последующего редактирования. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell with replacement of the specified faces of the source shell with deformable faces. + Surfaces of the selected faces are approximated with NURBS surfaces or + deformable surfaces for the further editing. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] outer - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] parameters - \ru Параметры модификации. + \en Parameters of the modification. \~ + \param[in] faces - \ru Изменяемые грани тела. + \en Faces to be modified. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] res - \ru Код результата операции выдавливания. + \en The extrusion operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateModifiedNurbsItem( MbFaceShell * outer, + MbeCopyMode sameShell, + const NurbsValues & parameters, + const RPArray & faces, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку, в которой деформирована указанная грань. + \en Construct a shell in which the specified face is deformed. \~ + \details \ru Построить оболочку, в которой деформирована указанная грань путём + подстановки контрольных точек присланной NURBS-поверхности с фиксацией указанных точек.\n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell in which the specified face is deformed by + replacement of the control points of the given NURBS surface with fixing the specified points.\n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] outer - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] face - \ru Деформируемая грань оболочки. + \en Deformable face of the shell. \~ + \param[in] faceSurface - \ru Новая деформируемая поверхность для грани. + \en The new deformable surface of the face. \~ + \param[in] fixedPoints - \ru Матрица положений неизменяемых контрольных точек деформируемой поверхности (false). + \en Matrix of positions of invariant control points of the deformable surface (false). \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] res - \ru Код результата операции выдавливания. + \en The extrusion operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateNurbsModification( MbFaceShell * outer, + MbeCopyMode sameShell, + MbFace * face, + MbSurface & faceSurface, + Array2 & fixedPoints, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_MODIFIED_NURBS_H diff --git a/C3d/Include/cr_nurbs3d.h b/C3d/Include/cr_nurbs3d.h index d5dbc14..48ba21e 100644 --- a/C3d/Include/cr_nurbs3d.h +++ b/C3d/Include/cr_nurbs3d.h @@ -1,129 +1,129 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель пространственного сплайна с сопряжениями. - \en Constructor of the spatial spline with tangents. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_NURBS3D_H -#define __CR_NURBS3D_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель пространственного сплайна. - \en Spatial spline constructor. \~ - \details \ru Строитель пространственного сплайна.\n - \en Spatial spline constructor.\n \~ - \ingroup Model_Creators -*/ -// --- -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 - -protected: - MbNurbs3DCreator( const MbNurbs3DCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbNurbs3DCreator( const MbNurbs3DCreator & ); // \ru Не реализовано \en Not implemented - MbNurbs3DCreator(); // \ru Не реализовано \en Not implemented -public: - MbNurbs3DCreator( const SArray & spacePnts, bool throughPnts, - MbeSplineParamType paramType, size_t degree, bool closed, - const SArray * weights, - const SArray * knots, - const RPArray< MbPntMatingData > & 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 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 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 - 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 Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); - - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbNurbs3DCreator & ); // \ru Не реализовано!!! \en Not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) -}; - -IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создать пространственный сплайн через точки и с сопряжениями. - \en Create a spatial spline through points and with the given tangents. \~ - \details \ru Создать пространственный сплайн через точки и с сопряжениями - Если есть сопряжения, то количество сопряжений д.б. равно количеству точек. - Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве. - \en Create a spatial spline through points with tangents - If the tangents are specified, then the number of tangents should be equal to the number of points. - The missing tangents should be represented as the null pointers in the array. \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать пространственный сплайн по точкам и сопряжениями. - \en Create a spatial spline from points and tangents. \~ - \details \ru Создать пространственный сплайн по точкам и сопряжениями.\n - \en Create a spatial spline from points and tangents.\n \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Curve3D_Modeling -*/ -//--- -MATH_FUNC (MbCreator *) CreateSplineBy( const SArray & points, // \ru Точки \en Points - 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 - const MbSNameMaker & snMaker, // \ru Именователь \en An object for naming the new objects - MbResultType & resType, - MbCurve3D *& resCurve ); - - -#endif // __CR_NURBS3D_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель пространственного сплайна с сопряжениями. + \en Constructor of the spatial spline with tangents. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_NURBS3D_H +#define __CR_NURBS3D_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель пространственного сплайна. + \en Spatial spline constructor. \~ + \details \ru Строитель пространственного сплайна.\n + \en Spatial spline constructor.\n \~ + \ingroup Model_Creators +*/ +// --- +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 + +protected: + MbNurbs3DCreator( const MbNurbs3DCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + MbNurbs3DCreator( const MbNurbs3DCreator & ); // \ru Не реализовано \en Not implemented + MbNurbs3DCreator(); // \ru Не реализовано \en Not implemented +public: + MbNurbs3DCreator( const SArray & spacePnts, bool throughPnts, + MbeSplineParamType paramType, size_t degree, bool closed, + const SArray * weights, + const SArray * knots, + const RPArray< MbPntMatingData > & 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 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 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 + 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 Построить кривую по журналу построения \en Create a curve from the history tree + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbNurbs3DCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbs3DCreator ) +}; + +IMPL_PERSISTENT_OPS( MbNurbs3DCreator ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создать пространственный сплайн через точки и с сопряжениями. + \en Create a spatial spline through points and with the given tangents. \~ + \details \ru Создать пространственный сплайн через точки и с сопряжениями + Если есть сопряжения, то количество сопряжений д.б. равно количеству точек. + Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве. + \en Create a spatial spline through points with tangents + If the tangents are specified, then the number of tangents should be equal to the number of points. + The missing tangents should be represented as the null pointers in the array. \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать пространственный сплайн по точкам и сопряжениями. + \en Create a spatial spline from points and tangents. \~ + \details \ru Создать пространственный сплайн по точкам и сопряжениями.\n + \en Create a spatial spline from points and tangents.\n \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Curve3D_Modeling +*/ +//--- +MATH_FUNC (MbCreator *) CreateSplineBy( const SArray & points, // \ru Точки \en Points + 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 + const MbSNameMaker & snMaker, // \ru Именователь \en An object for naming the new objects + MbResultType & resType, + MbCurve3D *& resCurve ); + + +#endif // __CR_NURBS3D_H diff --git a/C3d/Include/cr_nurbs_surfaces_shell.h b/C3d/Include/cr_nurbs_surfaces_shell.h index 623ab2c..02a0ede 100644 --- a/C3d/Include/cr_nurbs_surfaces_shell.h +++ b/C3d/Include/cr_nurbs_surfaces_shell.h @@ -1,73 +1,73 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Создание оболочки из нурбс-поверхностей -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __NURBS_SURFACES_SHELL_H -#define __NURBS_SURFACES_SHELL_H - -#include -#include -#include - - -class MATH_CLASS MbCreator; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbFaceShell; -struct NurbsSurfaceValues; -class IProgressIndicator; - - -//------------------------------------------------------------------------------ -/** \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. \~ - \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. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbFaceShell *) CreateNurbsSurfacesShell( NurbsSurfaceValues & params, - const MbSNameMaker & operNames, - bool isPhantom, - MbResultType & res, - IProgressIndicator * = 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. \~ - \param[in] shell - \ru Оболочка, построенная по заданным параметрам. - \en The shell constructed by given parameters. \~ - \param[out] indicator - \ru Индикатор хода построения позволяющий прервать построение. - \en Construction process indicator which allow to interrupt the construction. \~ - \result \ru Возвращает код результата операции. - \en Returns operation result code. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbResultType) CheckNurbsSurfacesShell( const NurbsSurfaceValues & params, - const MbFaceShell & shell, - IProgressIndicator * = NULL ); - - -#endif // __NURBS_SURFACES_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +// +// Создание оболочки из нурбс-поверхностей +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __NURBS_SURFACES_SHELL_H +#define __NURBS_SURFACES_SHELL_H + +#include +#include +#include + + +class MATH_CLASS MbCreator; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFaceShell; +struct NurbsSurfaceValues; +class IProgressIndicator; + + +//------------------------------------------------------------------------------ +/** \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. \~ + \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. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbFaceShell *) CreateNurbsSurfacesShell( NurbsSurfaceValues & params, + const MbSNameMaker & operNames, + bool isPhantom, + MbResultType & res, + IProgressIndicator * = 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. \~ + \param[in] shell - \ru Оболочка, построенная по заданным параметрам. + \en The shell constructed by given parameters. \~ + \param[out] indicator - \ru Индикатор хода построения позволяющий прервать построение. + \en Construction process indicator which allow to interrupt the construction. \~ + \result \ru Возвращает код результата операции. + \en Returns operation result code. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbResultType) CheckNurbsSurfacesShell( const NurbsSurfaceValues & params, + const MbFaceShell & shell, + IProgressIndicator * = 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 32516a7..6cec11e 100644 --- a/C3d/Include/cr_nurbs_surfaces_solid.h +++ b/C3d/Include/cr_nurbs_surfaces_solid.h @@ -1,116 +1,116 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение оболочки из NURBS-поверхностей. - \en Construction of a sell from NURBS-surfaces. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_NURBS_SURFACES_SOLID_H -#define __CR_NURBS_SURFACES_SOLID_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbCreator; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbFaceShell; -struct MATH_CLASS NurbsSurfaceValues; -class IProgressIndicator; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из NURBS-поверхностей. - \en Constructor of a shell from NURBS-surfaces. \~ - \details \ru Строитель оболочки из NURBS-поверхностей MbSplineSurface. - Аббревиатура NURBS получена из первых букв словосочетания Non-Uniform Rational B-Spline. - \en Constructor of a shell from NURBS-surfaces MbSplineSurface. - Abbreviation of NURBS is obtained from the first letters of "Non-Uniform Rational B-Spline" phrase. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbNurbsSurfacesSolid : public MbCreator { -protected: - NurbsSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. - mutable bool changed; ///< \ru Флаг изменения параметров. \en Flag of parameters modification. - -public: - // \ru конструктор, копирующий параметры \en constructor copying the parameters - MbNurbsSurfacesSolid( const NurbsSurfaceValues & params, const MbSNameMaker & names ); -private: - MbNurbsSurfacesSolid( const MbNurbsSurfacesSolid &, MbRegDuplicate * ireg ); -public: - // \ru деструктор \en destructor - ~MbNurbsSurfacesSolid(); - -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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - -public: - /// \ru построение оболочки \en creation of a shell - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( NurbsSurfaceValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const NurbsSurfaceValues & params ) { parameters = params; } - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsSurfacesSolid ) -OBVIOUS_PRIVATE_COPY( MbNurbsSurfacesSolid ) -}; - -IMPL_PERSISTENT_OPS( MbNurbsSurfacesSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку из NURBS-поверхностей. - \en Construct a shell from NURBS-surfaces. \~ - \details \ru Построить оболочку из NURBS-поверхностей MbSplineSurface. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell from NURBS-surfaces MbSplineSurface. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] parameters - \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. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateNurbsShell( NurbsSurfaceValues & parameters, - const MbSNameMaker & operNames, - bool isPhantom, - MbResultType & res, - MbFaceShell *& shell, - IProgressIndicator * indicator = NULL ); - - -#endif // __CR_NURBS_SURFACES_SOLID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение оболочки из NURBS-поверхностей. + \en Construction of a sell from NURBS-surfaces. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_NURBS_SURFACES_SOLID_H +#define __CR_NURBS_SURFACES_SOLID_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbCreator; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFaceShell; +struct MATH_CLASS NurbsSurfaceValues; +class IProgressIndicator; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из NURBS-поверхностей. + \en Constructor of a shell from NURBS-surfaces. \~ + \details \ru Строитель оболочки из NURBS-поверхностей MbSplineSurface. + Аббревиатура NURBS получена из первых букв словосочетания Non-Uniform Rational B-Spline. + \en Constructor of a shell from NURBS-surfaces MbSplineSurface. + Abbreviation of NURBS is obtained from the first letters of "Non-Uniform Rational B-Spline" phrase. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbNurbsSurfacesSolid : public MbCreator { +protected: + NurbsSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. + mutable bool changed; ///< \ru Флаг изменения параметров. \en Flag of parameters modification. + +public: + // \ru конструктор, копирующий параметры \en constructor copying the parameters + MbNurbsSurfacesSolid( const NurbsSurfaceValues & params, const MbSNameMaker & names ); +private: + MbNurbsSurfacesSolid( const MbNurbsSurfacesSolid &, MbRegDuplicate * ireg ); +public: + // \ru деструктор \en destructor + ~MbNurbsSurfacesSolid(); + +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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData3D & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + +public: + /// \ru построение оболочки \en creation of a shell + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + virtual void Refresh( MbFaceShell & outer ); ///< \ru обновить форму оболочки \en update shape of the shell + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( NurbsSurfaceValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const NurbsSurfaceValues & params ) { parameters = params; } + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbNurbsSurfacesSolid ) +OBVIOUS_PRIVATE_COPY( MbNurbsSurfacesSolid ) +}; + +IMPL_PERSISTENT_OPS( MbNurbsSurfacesSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку из NURBS-поверхностей. + \en Construct a shell from NURBS-surfaces. \~ + \details \ru Построить оболочку из NURBS-поверхностей MbSplineSurface. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell from NURBS-surfaces MbSplineSurface. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] parameters - \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. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateNurbsShell( NurbsSurfaceValues & parameters, + const MbSNameMaker & operNames, + bool isPhantom, + MbResultType & res, + MbFaceShell *& shell, + IProgressIndicator * indicator = NULL ); + + +#endif // __CR_NURBS_SURFACES_SOLID_H diff --git a/C3d/Include/cr_offset_curve.h b/C3d/Include/cr_offset_curve.h index 6e3952c..7cfd3fc 100644 --- a/C3d/Include/cr_offset_curve.h +++ b/C3d/Include/cr_offset_curve.h @@ -1,167 +1,167 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель эквидистантной кривой. - \en Offset curve constructor. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_OFFSET_CURVE_H -#define __CR_OFFSET_CURVE_H - - -#include -#include -#include - - -class MATH_CLASS MbCurve3D; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель эквидистантной кривой. - \en Offset curve constructor. \~ - \details \ru Строитель эквидистантной кривой.\n - \en Offset curve constructor.\n \~ - \ingroup Model_Creators -*/ -// --- -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). - - // \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. - - // \ru Дополнительные параметры (эквидистанта на поверхности грани оболочки) \en Auxiliary parameters (offset on the shell face surface) - 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 ); -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 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 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 - 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 size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. - virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. - 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 ); - - /** \} */ - -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 ) -}; - -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 Постранственная кривая, к которой строится эквидистантная. - \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[out] resCurve - \ru Эквидистантная кривая. - \en The offset curve. \~ - \return \ru Возвращает строитель. - \en Returns the constructor. \~ - \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 ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать офсетную кривую по поверхностной кривой и значению смещения. - \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[out] resCurves - \ru Множество эквидистантных кривых. - \en Offset curve array. \~ - \return \ru Возвращает строитель. - \en Returns the constructor. \~ - \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 ); - - -#endif // __CR_OFFSET_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель эквидистантной кривой. + \en Offset curve constructor. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_OFFSET_CURVE_H +#define __CR_OFFSET_CURVE_H + + +#include +#include +#include + + +class MATH_CLASS MbCurve3D; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель эквидистантной кривой. + \en Offset curve constructor. \~ + \details \ru Строитель эквидистантной кривой.\n + \en Offset curve constructor.\n \~ + \ingroup Model_Creators +*/ +// --- +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). + + // \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. + + // \ru Дополнительные параметры (эквидистанта на поверхности грани оболочки) \en Auxiliary parameters (offset on the shell face surface) + 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 ); +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 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 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 + 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 size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. + virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. + 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 ); + + /** \} */ + +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 ) +}; + +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 Постранственная кривая, к которой строится эквидистантная. + \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[out] resCurve - \ru Эквидистантная кривая. + \en The offset curve. \~ + \return \ru Возвращает строитель. + \en Returns the constructor. \~ + \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 ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать офсетную кривую по поверхностной кривой и значению смещения. + \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[out] resCurves - \ru Множество эквидистантных кривых. + \en Offset curve array. \~ + \return \ru Возвращает строитель. + \en Returns the constructor. \~ + \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 ); + + +#endif // __CR_OFFSET_CURVE_H diff --git a/C3d/Include/cr_patch_creator.h b/C3d/Include/cr_patch_creator.h index 185a412..249e62f 100644 --- a/C3d/Include/cr_patch_creator.h +++ b/C3d/Include/cr_patch_creator.h @@ -32,23 +32,23 @@ class MATH_CLASS MbFaceShell; // --- class MATH_CLASS MbPatchCreator : public MbCreator { protected: - RPArray initCurves; ///< \ru Кривые, определяющие края заплатки. \en Curves determining the boundaries of a patch. - PatchValues parameters; ///< \ru Параметры построения заплатки. \en Parameters of patch construction. + RPArray initCurves; ///< \ru Кривые, определяющие края заплатки. \en Curves determining the boundaries of a patch. + PatchValues parameters; ///< \ru Параметры построения заплатки. \en Parameters of patch construction. /// \ru Cледующие данные имеются только, если обрабатываются ребра. \en The following data are defined only when edges are being processed. - SArray orientations; ///< \ru Ориентация кривых для замыкания в цепь. \en Orientation of curves for enclosing into a chain. - SArray tolerances; ///< \ru Толерантности стыков кривых для замыкания в цепь. \en Tolerances of joints of curves for enclosing into a chain. - SArray surfInds; ///< \ru Номер поверхности кривой пересечения, отвечающей существующей грани. \en Number of surface of the intersection curve corresponding to the existent face. + SArray orientations; ///< \ru Ориентация кривых для замыкания в цепь. \en Orientation of curves for enclosing into a chain. + SArray tolerances; ///< \ru Толерантности стыков кривых для замыкания в цепь. \en Tolerances of joints of curves for enclosing into a chain. + SArray surfInds; ///< \ru Номер поверхности кривой пересечения, отвечающей существующей грани. \en Number of surface of the intersection curve corresponding to the existent face. private : MbPatchCreator( const MbPatchCreator &, MbRegDuplicate * ireg ); public : - MbPatchCreator( const RPArray & curves, - const PatchValues & params, - const MbSNameMaker & n, - const SArray * surfInds, - const SArray * orientations, - const SArray * tolerances ); + MbPatchCreator( const RPArray & curves, + const PatchValues & params, + const MbSNameMaker & n, + const SArray * surfInds, + const SArray * orientations, + const SArray * tolerances ); virtual ~MbPatchCreator(); // \ru Общие функции математического объекта \en Common functions of the mathematical object diff --git a/C3d/Include/cr_projection_curve.h b/C3d/Include/cr_projection_curve.h index 23ea950..0fcbee4 100644 --- a/C3d/Include/cr_projection_curve.h +++ b/C3d/Include/cr_projection_curve.h @@ -1,86 +1,86 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель проволочного каркаса из проекционных кривых. - \en Projection wireframe constructor. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_PROJECTION_CURVE_H -#define __CR_PROJECTION_CURVE_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель проволочного каркаса из проекционных кривых. - \en Projection wireframe constructor. \~ - \details \ru Строитель проволочного каркаса из проекционных кривых.\n - \en Projection wireframe constructor.\n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbProjCurveCreator : public MbCreator { -private: - MbWireFrame * wireFrame; // \ru Проецируемый проволочный каркас. \en Wireframe to project. - RPArray shellCreators; // \ru Протокол построения оболочки, на которую выполняется проецирование \en History tree of the shell the projection is performed onto - MbVector3D dir; // \ru Вектор направления (если нулевой, то проекция по нормали) \en Direction vector (if zero, the normal projection) - bool createExact; // \ru Создавать проекционную кривую при необходимости \en Create the projection curve if necessary - bool truncateByBounds; // \ru Усечь границами \en Truncate by bounds - -protected: - MbProjCurveCreator( const MbProjCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbProjCurveCreator( const MbProjCurveCreator & ); // \ru Не реализовано \en Not implemented - MbProjCurveCreator(); // \ru Не реализовано \en Not implemented -public: - MbProjCurveCreator( const MbCurve3D & curve, - const RPArray & shellCreators, bool sameCreators, - const MbVector3D * dir, bool exact, bool truncate, - const MbSNameMaker & snMaker ); - - MbProjCurveCreator( const MbWireFrame &wf, const bool sameWire, - const RPArray & shellCreators, bool sameCreators, - const MbVector3D * dir, bool exact, bool truncate, - const MbSNameMaker & snMaker ); -public: - virtual ~MbProjCurveCreator(); - - // \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 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 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 - 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 size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. - virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. - 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 ); - - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbProjCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProjCurveCreator ) -}; - -IMPL_PERSISTENT_OPS( MbProjCurveCreator ) - -#endif // __CR_PROJECTION_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель проволочного каркаса из проекционных кривых. + \en Projection wireframe constructor. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_PROJECTION_CURVE_H +#define __CR_PROJECTION_CURVE_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель проволочного каркаса из проекционных кривых. + \en Projection wireframe constructor. \~ + \details \ru Строитель проволочного каркаса из проекционных кривых.\n + \en Projection wireframe constructor.\n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbProjCurveCreator : public MbCreator { +private: + MbWireFrame * wireFrame; // \ru Проецируемый проволочный каркас. \en Wireframe to project. + RPArray shellCreators; // \ru Протокол построения оболочки, на которую выполняется проецирование \en History tree of the shell the projection is performed onto + MbVector3D dir; // \ru Вектор направления (если нулевой, то проекция по нормали) \en Direction vector (if zero, the normal projection) + bool createExact; // \ru Создавать проекционную кривую при необходимости \en Create the projection curve if necessary + bool truncateByBounds; // \ru Усечь границами \en Truncate by bounds + +protected: + MbProjCurveCreator( const MbProjCurveCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + MbProjCurveCreator( const MbProjCurveCreator & ); // \ru Не реализовано \en Not implemented + MbProjCurveCreator(); // \ru Не реализовано \en Not implemented +public: + MbProjCurveCreator( const MbCurve3D & curve, + const RPArray & shellCreators, bool sameCreators, + const MbVector3D * dir, bool exact, bool truncate, + const MbSNameMaker & snMaker ); + + MbProjCurveCreator( const MbWireFrame &wf, const bool sameWire, + const RPArray & shellCreators, bool sameCreators, + const MbVector3D * dir, bool exact, bool truncate, + const MbSNameMaker & snMaker ); +public: + virtual ~MbProjCurveCreator(); + + // \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 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 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 + 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 size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. + virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. + 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 ); + + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbProjCurveCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbProjCurveCreator ) +}; + +IMPL_PERSISTENT_OPS( MbProjCurveCreator ) + +#endif // __CR_PROJECTION_CURVE_H diff --git a/C3d/Include/cr_revolution_solid.h b/C3d/Include/cr_revolution_solid.h index 665e662..0ead11a 100644 --- a/C3d/Include/cr_revolution_solid.h +++ b/C3d/Include/cr_revolution_solid.h @@ -66,12 +66,12 @@ public : \{ */ 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 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 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 GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. @@ -87,13 +87,13 @@ public : \{ */ virtual MbFaceShell * InitShell( bool in ); virtual void InitBasis( RPArray & items ); - virtual bool GetPlacement( MbPlacement3D & p ) const; + virtual bool GetPlacement( MbPlacement3D & ) const; /** \} */ /** \ru \name Функции строителя оболочки тела вращения. \en \name Functions of the revolution solid's shell creator. \{ */ - const MbSurface * GetSurface() const { return sweptData.GetSurface(); } ///< \ru Поверхность двумерных контуров. \en Surface of two-dimensional contours. - const MbAxis3D & GetAxis() const { return axis; } ///< \ru Ось вращения. \en Rotation axis. + const MbSurface * GetSurface() const { return sweptData.GetSurface(); } ///< \ru Поверхность двумерных контуров. \en Surface of two-dimensional contours. + const MbAxis3D & GetAxis() const { return axis; } ///< \ru Ось вращения. \en Rotation axis. /// \ru Дать параметры. \en Get the parameters. void GetParameters( RevolutionValues & p ) const { p = parameters; } @@ -110,6 +110,7 @@ private : IMPL_PERSISTENT_OPS( MbCurveRevolutionSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Создать оболочку тела вращения. \en Create a shell of the revolution solid. \~ diff --git a/C3d/Include/cr_ruled_shell.h b/C3d/Include/cr_ruled_shell.h index d170850..5d8b130 100644 --- a/C3d/Include/cr_ruled_shell.h +++ b/C3d/Include/cr_ruled_shell.h @@ -1,109 +1,109 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построить линейчатую оболочку. - \en Construct a ruled shell. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_RULED_SHELL_H -#define __CR_RULED_SHELL_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbFaceShell; -class MATH_CLASS MbCurveEdge; -class MATH_CLASS MbOrientedEdge; -class MATH_CLASS MbLoop; -struct MATH_CLASS RuledSurfaceValues; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель линейчатой оболочки. - \en Constructor of a ruled shell. \~ - \details \ru Строитель линейчатой оболочки по двум кривым. \n - \en Constructor of a ruled shell from two curves. \n \~ - \ingroup Model_Creators -*/ -//--- -class MATH_CLASS MbRuledShell : public MbCreator { - -private : - RuledSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. -private: - MbRuledShell( const MbRuledShell & obj, MbRegDuplicate * ireg ); -public: - /// \ru Конструктор по параметрам операции и именователю. \en Constructor by operation parameters and name-maker. - MbRuledShell( const RuledSurfaceValues & pars, const MbSNameMaker & n ); - virtual ~MbRuledShell(); - -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 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 GetProperties( MbProperties & properties ); ///< \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties & properties ); ///< \ru Записать свойства объекта \en Write properties of the object - virtual MbePrompt GetPropertyName(); ///< \ru Выдать заголовок свойства объекта \en Get name of object property - 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. - -public: - /// \ru Построение оболочки \en Creation of a shell - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - // \ru Дать параметры. \en Get the parameters. - void GetParameters( RuledSurfaceValues & params ) const; - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const RuledSurfaceValues & params ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledShell ) -OBVIOUS_PRIVATE_COPY( MbRuledShell ) -}; // MbRuledShell - -IMPL_PERSISTENT_OPS( MbRuledShell ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить линейчатую оболочку. - \en Construct a ruled shell. \~ - \details \ru Построить линейчатую оболочку по двум кривым. - Кривые могут быть составными. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a ruled shell from two curves - Curves can be composite. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] parameters - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь. - \en An object for naming the new objects. \~ - \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. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateRuledShell( RuledSurfaceValues & parameters, - const MbSNameMaker & operNames, - bool isPhantom, - MbResultType & res, - MbFaceShell *& shell ); - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построить линейчатую оболочку. + \en Construct a ruled shell. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_RULED_SHELL_H +#define __CR_RULED_SHELL_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbFaceShell; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbOrientedEdge; +class MATH_CLASS MbLoop; +struct MATH_CLASS RuledSurfaceValues; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель линейчатой оболочки. + \en Constructor of a ruled shell. \~ + \details \ru Строитель линейчатой оболочки по двум кривым. \n + \en Constructor of a ruled shell from two curves. \n \~ + \ingroup Model_Creators +*/ +//--- +class MATH_CLASS MbRuledShell : public MbCreator { + +private : + RuledSurfaceValues parameters; ///< \ru Параметры построения. \en Construction parameters. +private: + MbRuledShell( const MbRuledShell & obj, MbRegDuplicate * ireg ); +public: + /// \ru Конструктор по параметрам операции и именователю. \en Constructor by operation parameters and name-maker. + MbRuledShell( const RuledSurfaceValues & pars, const MbSNameMaker & n ); + virtual ~MbRuledShell(); + +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 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 GetProperties( MbProperties & properties ); ///< \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & properties ); ///< \ru Записать свойства объекта \en Write properties of the object + virtual MbePrompt GetPropertyName(); ///< \ru Выдать заголовок свойства объекта \en Get name of object property + 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. + +public: + /// \ru Построение оболочки \en Creation of a shell + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + // \ru Дать параметры. \en Get the parameters. + void GetParameters( RuledSurfaceValues & params ) const; + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const RuledSurfaceValues & params ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRuledShell ) +OBVIOUS_PRIVATE_COPY( MbRuledShell ) +}; // MbRuledShell + +IMPL_PERSISTENT_OPS( MbRuledShell ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить линейчатую оболочку. + \en Construct a ruled shell. \~ + \details \ru Построить линейчатую оболочку по двум кривым. + Кривые могут быть составными. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a ruled shell from two curves + Curves can be composite. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] parameters - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь. + \en An object for naming the new objects. \~ + \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. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateRuledShell( RuledSurfaceValues & parameters, + const MbSNameMaker & operNames, + bool isPhantom, + MbResultType & res, + MbFaceShell *& shell ); + + #endif // __CR_RULED_SHELL_H \ No newline at end of file diff --git a/C3d/Include/cr_section_shell.h b/C3d/Include/cr_section_shell.h new file mode 100644 index 0000000..a2fafd4 --- /dev/null +++ b/C3d/Include/cr_section_shell.h @@ -0,0 +1,137 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель оболочки на поверхности переменного сечения. + \en Constructor of shell of evolution solid. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SECTION_SHELL_H +#define __CR_SECTION_SHELL_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbFaceShell; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки на поверхности переменного сечения. + \en Constructor of the shell on swept mutable section surface. \~ + \details \ru Грань оболочки строится путём движения переменного сечения по опорной кривой. \n + \en Constructor of face by moving generating curve along a reference spine curve. \n \~ + \ingroup Model_Creators +*/ +// --- +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. + + /** \brief \ru Конструктор. + \en Constructor. \~ + \param[in] data - \ru Данные о поверхности переменного сечения. + \en Data about swept mutable section surface. \~ + \param[in] names - \ru Именователь грани оболочки. + \en Generating face names. \~ + */ + MbSectionShell( const MbSectionData & data, + const MbSectionCode & code, + const MbSNameMaker & names ); +private : + MbSectionShell( const MbSectionShell & init, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbSectionShell( const MbSectionShell & ); +public : + virtual ~MbSectionShell(); + + /** \ru \name Общие функции математического объекта. + \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 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 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 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 + /** \} */ + + /** \ru \name Общие функции твердого тела (формообразующей операции). + \en \name Common functions of the rigid solid (forming operations). + \{ */ + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + + virtual void SetYourVersion( VERSION version ); + /** \} */ + + /** \ru \name Функции строителя оболочки на поверхности переменного сечения. + \en \name Functions of creator of evolution solid shell. + \{ */ + /// \ru Дать параметры. \en Get the parameters. + const MbSectionData & GetSectionData() { return sectionData; } + /// \ru Установить параметры. \en Set the parameters. + void SetSectionData( const MbSectionData & data ) { sectionData = data; } + /// \ru Дать параметры. \en Get the parameters. + const MbSectionCode & GetSectionCode() { return sectionCode; } + /// \ru Установить параметры. \en Set the parameters. + void SetSectionCode( const MbSectionCode & code ) { sectionCode = code; } + /** \} */ + + /** \brief \ru Создать оболочку на поверхности переменного сечения. + \en Create a shell on swept mutable section surface. \~ + \details \ru Построить оболочку путём движения образующей кривой по направляющей кривой + и выполнить булеву операцию с оболочкой, если последняя задана. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Create a shell by moving the generating curve along the spine curve + and perform the Boolean operation with the shell if it is specified. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] solid - \ru Набор граней, к которым дополняется построение. + \en Face set the construction is complemented with respect to. \~ + \param[in] sameShell - \ru Способ копирования граней. + \en The method of copying faces. \~ + \param[in] data - \ru Данные о поверхности переменного сечения. + \en Data about swept mutable section surface. \~ + \param[in] names - \ru Именователь грани оболочки. + \en Generating face names. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Код ошибки порстроения. + \en Result code of building. \~ + \result \ru Возвращает строитель. + \en Returns the constructor of operation. \~ + */ + static MbSectionShell * Create( MbFaceShell * solid, + MbeCopyMode sameShell, + const MbSectionData & data, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + +private : + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbSectionShell & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSectionShell ) + +}; // MbSectionShell + +IMPL_PERSISTENT_OPS( MbSectionShell ) + + +#endif // __CR_SECTION_SHELL_H diff --git a/C3d/Include/cr_sheet_bend_any_solid.h b/C3d/Include/cr_sheet_bend_any_solid.h index 799360a..e1e4136 100644 --- a/C3d/Include/cr_sheet_bend_any_solid.h +++ b/C3d/Include/cr_sheet_bend_any_solid.h @@ -1,122 +1,122 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение оболочки тела с выполнеными сгибами. - \en Construction of a shell from any solid with bends. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SHEET_BEND_ANY_SOLID_H -#define __CR_SHEET_BEND_ANY_SOLID_H - - -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала с выполненым сгибом/разгибом. - \en Constructor of a shell from sheet material with bend/unbend. \~ - \details \ru Строитель оболочки из листового материала с выполненым сгибом/разгибом. - Построение сгиба/разгиба на касательную плоскость к указанной грани в указанной - точке с индивидуальными для каждого сгиба параметрами. \n - \en Constructor of a shell from sheet material with bend/unbend. - Construction of a bend/unbend to the tangent plane to the specified face at - the given point with parameters individual for each bend. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbBendAnySolid : public MbCreator { - MbPlane cutPlane; - SArray bends; - -public : - MbBendAnySolid( const MbPlane & cutPlane, - const SArray & bends, - const MbSNameMaker & names ); -private: - MbBendAnySolid( const MbBendAnySolid &, MbRegDuplicate * iReg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbBendAnySolid( const MbBendAnySolid & ); - -public: - virtual ~MbBendAnySolid(); - - // \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 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 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 solid - - virtual bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbBendAnySolid & operator = ( const MbBendAnySolid & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendAnySolid ) -}; - -IMPL_PERSISTENT_OPS( MbBendAnySolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку с выполнеными сгибами. - \en Construct a shell with bends. \~ - \details \ru Построить оболочку любого тела с выполнеными сгибами. - Построение сгиба/разгиба на касательную плоскость к указанной грани в указанной - точке с индивидуальными для каждого сгиба параметрами. \n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a shell from sheet material with bend/unbend. - Construction of a bend/unbend to the tangent plane to the specified face at - the given point with parameters individual for each bend. \n - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] initialShell - \ru Исходная оболочка. - \en The initial shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the initial shell. \~ - \param[in] bends - \ru Сгибы оболочки. - \en Bends of a shell. \~ - \param[in] fixedFace - \ru Неподвижная грань. - \en Fixed face. \~ - \param[in] fixedPoint - \ru Неподвижная точка. - \en Fixed point. \~ - \param[in] names - \ru Именователь граней. - \en An object for naming faces. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateAnyBend( MbFaceShell & initialShell, - const MbeCopyMode sameShell, - const MbPlane & cutPlane, - const SArray & bends, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - - -#endif // __CR_SHEET_BEND_ANY_SOLID_H - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение оболочки тела с выполнеными сгибами. + \en Construction of a shell from any solid with bends. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SHEET_BEND_ANY_SOLID_H +#define __CR_SHEET_BEND_ANY_SOLID_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала с выполненым сгибом/разгибом. + \en Constructor of a shell from sheet material with bend/unbend. \~ + \details \ru Строитель оболочки из листового материала с выполненым сгибом/разгибом. + Построение сгиба/разгиба на касательную плоскость к указанной грани в указанной + точке с индивидуальными для каждого сгиба параметрами. \n + \en Constructor of a shell from sheet material with bend/unbend. + Construction of a bend/unbend to the tangent plane to the specified face at + the given point with parameters individual for each bend. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbBendAnySolid : public MbCreator { + MbPlane cutPlane; + SArray bends; + +public : + MbBendAnySolid( const MbPlane & cutPlane, + const SArray & bends, + const MbSNameMaker & names ); +private: + MbBendAnySolid( const MbBendAnySolid &, MbRegDuplicate * iReg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbBendAnySolid( const MbBendAnySolid & ); + +public: + virtual ~MbBendAnySolid(); + + // \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 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 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 solid + + virtual bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbBendAnySolid & operator = ( const MbBendAnySolid & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBendAnySolid ) +}; + +IMPL_PERSISTENT_OPS( MbBendAnySolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку с выполнеными сгибами. + \en Construct a shell with bends. \~ + \details \ru Построить оболочку любого тела с выполнеными сгибами. + Построение сгиба/разгиба на касательную плоскость к указанной грани в указанной + точке с индивидуальными для каждого сгиба параметрами. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a shell from sheet material with bend/unbend. + Construction of a bend/unbend to the tangent plane to the specified face at + the given point with parameters individual for each bend. \n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] initialShell - \ru Исходная оболочка. + \en The initial shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the initial shell. \~ + \param[in] bends - \ru Сгибы оболочки. + \en Bends of a shell. \~ + \param[in] fixedFace - \ru Неподвижная грань. + \en Fixed face. \~ + \param[in] fixedPoint - \ru Неподвижная точка. + \en Fixed point. \~ + \param[in] names - \ru Именователь граней. + \en An object for naming faces. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateAnyBend( MbFaceShell & initialShell, + const MbeCopyMode sameShell, + const MbPlane & cutPlane, + const SArray & bends, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + + +#endif // __CR_SHEET_BEND_ANY_SOLID_H + diff --git a/C3d/Include/cr_sheet_bend_by_edge_solid.h b/C3d/Include/cr_sheet_bend_by_edge_solid.h index 8d4972b..37108f2 100644 --- a/C3d/Include/cr_sheet_bend_by_edge_solid.h +++ b/C3d/Include/cr_sheet_bend_by_edge_solid.h @@ -132,7 +132,7 @@ IMPL_PERSISTENT_OPS( MbBendsByEdgesSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateBendsByEdges( MbFaceShell & initialShell, +MATH_FUNC (MbCreator *) CreateBendsByEdges( SPtr & initialShell, const MbeCopyMode sameShell, const RPArray & edges, const bool unbended, diff --git a/C3d/Include/cr_sheet_bend_over_seg_solid.h b/C3d/Include/cr_sheet_bend_over_seg_solid.h index 2afdebd..2c14523 100644 --- a/C3d/Include/cr_sheet_bend_over_seg_solid.h +++ b/C3d/Include/cr_sheet_bend_over_seg_solid.h @@ -117,7 +117,7 @@ IMPL_PERSISTENT_OPS( MbBendOverSegSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateBendOverSegment( MbFaceShell & initialShell, +MATH_FUNC (MbCreator *) CreateBendOverSegment( SPtr & initialShell, MbeCopyMode sameShell, const RPArray & bendingFaces, MbCurve3D & curve, diff --git a/C3d/Include/cr_sheet_bend_unbend_solid.h b/C3d/Include/cr_sheet_bend_unbend_solid.h index d5f6164..d1d31e9 100644 --- a/C3d/Include/cr_sheet_bend_unbend_solid.h +++ b/C3d/Include/cr_sheet_bend_unbend_solid.h @@ -113,7 +113,7 @@ IMPL_PERSISTENT_OPS( MbBendUnbendSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateBendUnbend( MbFaceShell & initialShell, +MATH_FUNC (MbCreator *) CreateBendUnbend( SPtr & initialShell, MbeCopyMode sameShell, const RPArray & bends, const MbFace & fixedFace, diff --git a/C3d/Include/cr_sheet_builder_solid.h b/C3d/Include/cr_sheet_builder_solid.h new file mode 100644 index 0000000..1cbb454 --- /dev/null +++ b/C3d/Include/cr_sheet_builder_solid.h @@ -0,0 +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, // признак совпадения придания толщины с нормалью базовой грани, + const MbSolidToSheetMetalValues & params, // параметры построения листового тела, + 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 f5f60cd..2618b11 100644 --- a/C3d/Include/cr_sheet_closed_corner_solid.h +++ b/C3d/Include/cr_sheet_closed_corner_solid.h @@ -118,7 +118,7 @@ IMPL_PERSISTENT_OPS( MbClosedCornerSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateClosedCorner( MbFaceShell & initialShell, +MATH_FUNC (MbCreator *) CreateClosedCorner( SPtr & initialShell, MbeCopyMode sameShell, MbCurveEdge * curveEdgePlus, MbCurveEdge * curveEdgeMinus, diff --git a/C3d/Include/cr_sheet_joint_bend_solid.h b/C3d/Include/cr_sheet_joint_bend_solid.h index 82ac1ce..925e7ed 100644 --- a/C3d/Include/cr_sheet_joint_bend_solid.h +++ b/C3d/Include/cr_sheet_joint_bend_solid.h @@ -130,7 +130,7 @@ IMPL_PERSISTENT_OPS( MbJointBendSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateJointBend( MbFaceShell & initialShell, +MATH_FUNC (MbCreator *) CreateJointBend( c3d::ShellSPtr & initialShell, const MbeCopyMode sameShell, const MbPlacement3D & placement, const MbContour & contour, diff --git a/C3d/Include/cr_sheet_metal_solid.h b/C3d/Include/cr_sheet_metal_solid.h index 369958d..8e9dadb 100644 --- a/C3d/Include/cr_sheet_metal_solid.h +++ b/C3d/Include/cr_sheet_metal_solid.h @@ -167,7 +167,7 @@ IMPL_PERSISTENT_OPS( MbSheetMetalSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateSheetMetal( MbFaceShell * solid, +MATH_FUNC (MbCreator *) CreateSheetMetal( SPtr & solid, MbeCopyMode sameShell, const MbPlacement3D & placement, RPArray & contours, diff --git a/C3d/Include/cr_sheet_simplified_flat_solid.h b/C3d/Include/cr_sheet_simplified_flat_solid.h index 4e4b5b6..d3d9c96 100644 --- a/C3d/Include/cr_sheet_simplified_flat_solid.h +++ b/C3d/Include/cr_sheet_simplified_flat_solid.h @@ -1,103 +1,103 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение упрощённой развёртки листового тела. - \en Construction of the simplified flat pattern. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H -#define __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель упрощения развёртки тела из листового материала. - \en Constructor of the simplified flat pattern. \~ - \details \ru Строитель упрощения развёртки тела из листового материала. - Возможно два вида упрощения: обработка углов и слияние подобных граней. \n - \en Constructor of the simplified flat pattern. - There are two types of simplification. The first one is the corners treatment. The second one is the similar faces unification. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbSimplifyFlatSolid : public MbCreator { - MbSimplifyFlatPatternValues parameters; - -public : - MbSimplifyFlatSolid( const MbSimplifyFlatPatternValues & params, - const MbSNameMaker & names ); -private: - MbSimplifyFlatSolid( const MbSimplifyFlatSolid &, MbRegDuplicate * iReg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbSimplifyFlatSolid( const MbSimplifyFlatSolid & ); - -public: - virtual ~MbSimplifyFlatSolid(); - - // \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 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 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 solid - - virtual bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSimplifyFlatSolid & operator = ( const MbSimplifyFlatSolid & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimplifyFlatSolid ) -}; - -IMPL_PERSISTENT_OPS( MbSimplifyFlatSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Упростить развёртку листового тела. - \en Simplify flattened sheet solid. \~ - \details \ru Упростить развёртку листового тела. \n - \en Simplify flattened sheet solid. \n \~ - \param[in] solid - \ru Исходное тело. - \en The source solid. \~ - \param[in] sameShell - \ru Флаг удаления оболочки исходного тела. - \en Whether to delete the shell of the source solid. \~ - \param[in] params - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] nameMaker - \ru Именователь. - \en An object for naming the new objects. \~ - \param[out] result - \ru Результирующее тело. - \en The resultant solid. \~ - \result \ru - Код результата операции. - \en - The operation result code. \~ - \ingroup Sheet_Metal_Modeling -*/ -// --- -MATH_FUNC (MbCreator *) CreateSimplifiedFlatPattern( MbFaceShell & initialShell, - const MbeCopyMode sameShell, - const MbSimplifyFlatPatternValues & params, - const MbSNameMaker & nameMaker, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение упрощённой развёртки листового тела. + \en Construction of the simplified flat pattern. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H +#define __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель упрощения развёртки тела из листового материала. + \en Constructor of the simplified flat pattern. \~ + \details \ru Строитель упрощения развёртки тела из листового материала. + Возможно два вида упрощения: обработка углов и слияние подобных граней. \n + \en Constructor of the simplified flat pattern. + There are two types of simplification. The first one is the corners treatment. The second one is the similar faces unification. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbSimplifyFlatSolid : public MbCreator { + MbSimplifyFlatPatternValues parameters; + +public : + MbSimplifyFlatSolid( const MbSimplifyFlatPatternValues & params, + const MbSNameMaker & names ); +private: + MbSimplifyFlatSolid( const MbSimplifyFlatSolid &, MbRegDuplicate * iReg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbSimplifyFlatSolid( const MbSimplifyFlatSolid & ); + +public: + virtual ~MbSimplifyFlatSolid(); + + // \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 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 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 solid + + virtual bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSimplifyFlatSolid & operator = ( const MbSimplifyFlatSolid & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSimplifyFlatSolid ) +}; + +IMPL_PERSISTENT_OPS( MbSimplifyFlatSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Упростить развёртку листового тела. + \en Simplify flattened sheet solid. \~ + \details \ru Упростить развёртку листового тела. \n + \en Simplify flattened sheet solid. \n \~ + \param[in] solid - \ru Исходное тело. + \en The source solid. \~ + \param[in] sameShell - \ru Флаг удаления оболочки исходного тела. + \en Whether to delete the shell of the source solid. \~ + \param[in] params - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \param[out] result - \ru Результирующее тело. + \en The resultant solid. \~ + \result \ru - Код результата операции. + \en - The operation result code. \~ + \ingroup Sheet_Metal_Modeling +*/ +// --- +MATH_FUNC (MbCreator *) CreateSimplifiedFlatPattern( MbFaceShell & initialShell, + const MbeCopyMode sameShell, + const MbSimplifyFlatPatternValues & params, + const MbSNameMaker & nameMaker, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_SHEET_SIMPLIFIED_FLAT_SOLID_H + diff --git a/C3d/Include/cr_sheet_union_solid.h b/C3d/Include/cr_sheet_union_solid.h index 5029aaf..fb19969 100644 --- a/C3d/Include/cr_sheet_union_solid.h +++ b/C3d/Include/cr_sheet_union_solid.h @@ -1,112 +1,112 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель операции объединения листовых тел по торцу. - \en Constructor of operation of union of sheet solids by butt. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SHEET_UNION_SOLID_H -#define __CR_SHEET_UNION_SOLID_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель операции объединения листовых тел по торцу. - \en Constructor of operation of union of sheet solids by butt. \~ - \details \ru Строитель операции объединения листовых тел по торцу объединяет тела - только по указанному с помощью ориентированных рёбер торцу, - независимо от возможных пересечений тел в других местах.\n. - \en Constructor of operation of union of sheet solids by butt unites solids - only by the bound specified using oriented edges - independently of possible intersections of solids in other places.\n. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbSheetUnionSolid : public MbCreator { -protected : - RPArray creators; ///< \ru Журнал построения: 0<=i & solid2, const bool same2, const MbSNameMaker & n ); -private : - MbSheetUnionSolid( const MbSheetUnionSolid & init, MbRegDuplicate *ireg ); - -public : - virtual ~MbSheetUnionSolid(); - - // \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 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 & ); // \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 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 - - // \ru Общие функции твердого тела \en Common functions of solid - - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - - virtual void SetYourVersion( VERSION version, bool forAll ); - - /// \ru Количество строителей первого тела. \en Count of creators of the first solid. - size_t GetCountOne() const { return countOne; } - /// \ru Общее количество строителей. \en Total count of creators. - size_t GetCreatorsCount() const { return creators.Count(); } - /// \ru Добавить в журнал. \en Add to the history tree. - void AddCreator ( MbCreator & creator ); - /// \ru Дать строитель. \en Get the constructor. - MbCreator * GetCreator ( const size_t ind ) const; - void DeleteCreator( const size_t ind ); - -private : - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbSheetUnionSolid( const MbSheetUnionSolid & init ); - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSheetUnionSolid & operator = ( const MbSheetUnionSolid & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSheetUnionSolid ) -}; - -IMPL_PERSISTENT_OPS( MbSheetUnionSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создать оболочку объединённых по торцу листовых тел. - \en Create a shell of sheet solids united by a butt. \~ - \details \ru Для указанных оболочек построить оболочку как результат операции объединения над множествами граней двух тел. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en For the specified shells create a shell using operation of union of face sets of two solids. - The function simultaneously creates the shell and its constructor.\n \~ - \result \ru Возвращает строитель. - \en Returns the constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateSheetUnion( MbFaceShell & faceShell1, - const MbeCopyMode sameShell1, - const RPArray & creators2, - MbFaceShell & faceShell2, - const MbeCopyMode sameShell2, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_SHEET_UNION_SOLID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель операции объединения листовых тел по торцу. + \en Constructor of operation of union of sheet solids by butt. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SHEET_UNION_SOLID_H +#define __CR_SHEET_UNION_SOLID_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель операции объединения листовых тел по торцу. + \en Constructor of operation of union of sheet solids by butt. \~ + \details \ru Строитель операции объединения листовых тел по торцу объединяет тела + только по указанному с помощью ориентированных рёбер торцу, + независимо от возможных пересечений тел в других местах.\n. + \en Constructor of operation of union of sheet solids by butt unites solids + only by the bound specified using oriented edges + independently of possible intersections of solids in other places.\n. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbSheetUnionSolid : public MbCreator { +protected : + RPArray creators; ///< \ru Журнал построения: 0<=i & solid2, const bool same2, const MbSNameMaker & n ); +private : + MbSheetUnionSolid( const MbSheetUnionSolid & init, MbRegDuplicate *ireg ); + +public : + virtual ~MbSheetUnionSolid(); + + // \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 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 & ); // \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 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 + + // \ru Общие функции твердого тела \en Common functions of solid + + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + + virtual void SetYourVersion( VERSION version, bool forAll ); + + /// \ru Количество строителей первого тела. \en Count of creators of the first solid. + size_t GetCountOne() const { return countOne; } + /// \ru Общее количество строителей. \en Total count of creators. + size_t GetCreatorsCount() const { return creators.Count(); } + /// \ru Добавить в журнал. \en Add to the history tree. + void AddCreator ( MbCreator & creator ); + /// \ru Дать строитель. \en Get the constructor. + MbCreator * GetCreator ( const size_t ind ) const; + void DeleteCreator( const size_t ind ); + +private : + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbSheetUnionSolid( const MbSheetUnionSolid & init ); + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSheetUnionSolid & operator = ( const MbSheetUnionSolid & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSheetUnionSolid ) +}; + +IMPL_PERSISTENT_OPS( MbSheetUnionSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создать оболочку объединённых по торцу листовых тел. + \en Create a shell of sheet solids united by a butt. \~ + \details \ru Для указанных оболочек построить оболочку как результат операции объединения над множествами граней двух тел. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en For the specified shells create a shell using operation of union of face sets of two solids. + The function simultaneously creates the shell and its constructor.\n \~ + \result \ru Возвращает строитель. + \en Returns the constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateSheetUnion( MbFaceShell & faceShell1, + const MbeCopyMode sameShell1, + const RPArray & creators2, + MbFaceShell & faceShell2, + const MbeCopyMode sameShell2, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_SHEET_UNION_SOLID_H diff --git a/C3d/Include/cr_simple_creator.h b/C3d/Include/cr_simple_creator.h index 79d29d2..638eb1e 100644 --- a/C3d/Include/cr_simple_creator.h +++ b/C3d/Include/cr_simple_creator.h @@ -207,8 +207,8 @@ bool MbSimpleCreator::DeleteShellCopies( const CreatorsVector & creators ) //------------------------------------------------------------------------------ // \ru Есть ли в каком-то простом построителе (MbSimpleCreator) заданная оболочка. \en Is there a simple builder (MbSimpleCreator) that contains a given shell?. // --- -template -bool MbSimpleCreator::IsThisShell( const MbFaceShell & shell, const Creators & creators ) +template +bool MbSimpleCreator::IsThisShell( const MbFaceShell & shell, const CreatorsVector & creators ) { bool res = false; diff --git a/C3d/Include/cr_split_data.h b/C3d/Include/cr_split_data.h index 579ed47..ea8a9a5 100644 --- a/C3d/Include/cr_split_data.h +++ b/C3d/Include/cr_split_data.h @@ -1,523 +1,523 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Усекающие элементы оболочки. - \en Truncating elements of a shell. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SPLIT_DATA_H -#define __CR_SPLIT_DATA_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class reader; -class writer; -class MATH_CLASS MbProperties; -class MATH_CLASS MbCartPoint3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbSpaceItem; -class MATH_CLASS MbCurve; -class MATH_CLASS MbSurfaceIntersectionCurve; -class MATH_CLASS MbSNameMaker; -class MATH_CLASS MbSolid; -struct MATH_CLASS MbControlData3D; -class MbRegDuplicate; -class MbRegTransform; -enum MbeSenseValue; -enum MbeCopyMode; - - -//------------------------------------------------------------------------------ -/** \brief \ru Усекающие элементы. - \en Truncating elements. \~ - \details \ru Усекающие элементы используются для разделения граней на части и усечения оболочек. - Усечение может выполняться двумерными кривыми, расположенными в плоскости XY локальной системы координат, - трёхмерными кривыми, поверхностями и оболочками. - Усекающие элементы используются в строителе усеченной оболочки MbTruncatedShell и - строителе оболочки с разбиением граней MbSplitShell. \n - \en Truncating elements are used for splitting faces into parts and truncation of shells. - Truncating can be performed by two-dimensional curves located in the XY plane of the local coordinate system, - by three-dimensional curves, surfaces and shells. - Truncating elements are used in the creator of truncated shell MbTruncatedShell and - in the creator of shell with face splitting MbSplitShell. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS MbSplitData : public MbRefItem { - /// \ru Типы усекающих объектов. \en Truncating objects types. - enum MbeSplitItemsType { - sit_NoItems = 0, ///< \ru Нет объектов. \en No objects. - sit_Curves2d = 1, ///< \ru Двумерные кривые в локальной системе координат. \en Two-dimensional curves in the local coordinate system. - sit_Curves3d = 2, ///< \ru Трехмерные кривые. \en Three-dimensional curves. - sit_Surfaces = 3, ///< \ru Поверхности. \en Surfaces. - sit_Creators = 4, ///< \ru Строители тела. \en Solid creators. - }; - -private: - // Sketch contours - c3d::PlaneContoursSPtrVector sketchContours; ///< \ru Двумерные кривые. \en Two-dimensional curves. - MbPlacement3D place; ///< \ru Локальная система координат двумерных кривых. \en Local coordinate system of two-dimensional curves. - MbVector3D direction; ///< \ru Вектор выдавливания двумерных кривых. \en Extrusion direction vector of two-dimensional curves. - MbeSenseValue sense; ///< \ru Направление выдавливания двумерных кривых относительно вектора. \en Extrusion direction of two-dimensional curves relative to direction vector. - // Space Curves - c3d::SpaceCurvesSPtrVector spaceCurves; ///< \ru Пространственные кривые. \en Spatial curves. - // Surfaces - c3d::SurfacesSPtrVector surfaces; ///< \ru Поверхности. \en Surfaces. - // Shell - c3d::CreatorsSPtrVector creators; ///< \ru Строители оболочки. \en Shell creators. - c3d::ShellSPtr solidShell; ///< \ru Оболочка. \en A shell. - -public: - /// \ru Конструктор. \en Constructor. - MbSplitData() - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - } - /// \ru Конструктор по двумерному контуру в локальной системе координат. \en Constructor by two-dimensional contour in the local coordinate system. - MbSplitData( const MbPlacement3D & pl, MbeSenseValue dirSense, const MbContour & item, bool same ) - : place ( pl ) - , direction ( ) - , sense ( dirSense ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - SPtr sketchContour; - sketchContour = same ? const_cast(&item) : static_cast(&item.Duplicate()); - sketchContours.push_back( sketchContour ); - } - /// \ru Конструктор по двумерному контуру в локальной системе координат. \en Constructor by two-dimensional contour in the local coordinate system. - MbSplitData( const MbPlacement3D & pl, const MbVector3D & dir, const MbContour & item, bool same ) - : place ( pl ) - , direction ( dir ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); - - SPtr sketchContour; - sketchContour = same ? const_cast(&item) : static_cast(&item.Duplicate()); - sketchContours.push_back( sketchContour ); - } - /// \ru Конструктор по двумерным контурам в локальной системе координат. \en Constructor by two-dimensional contours in the local coordinate system. - template - MbSplitData( const MbPlacement3D & pl, MbeSenseValue dirSense, const PlaneContoursVector & items, bool same ) - : place ( pl ) - , direction ( ) - , sense ( dirSense ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - ::AddRefItems( items, same, sketchContours ); - } - /// \ru Конструктор по двумерным контурам в локальной системе координат. \en Constructor by two-dimensional contours in the local coordinate system. - template - MbSplitData( const MbPlacement3D & pl, const MbVector3D & dir, const PlaneContoursVector & items, bool same ) - : place ( pl ) - , direction ( dir ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); - - ::AddRefItems( items, same, sketchContours ); - } - /// \ru Конструктор по пространственным кривым. \en Constructor by spatial curves. - MbSplitData( const c3d::ConstSpaceCurvesSPtrVector & items, bool same ) - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - ::AddRefItems( items, same, spaceCurves ); - } - /// \ru Конструктор по пространственным кривым. \en Constructor by spatial curves. - MbSplitData( const c3d::ConstSpaceCurvesVector & items, bool same ) - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - ::AddRefItems( items, same, spaceCurves ); - } - /// \ru Конструктор по поверхности. \en Constructor by a surface. - MbSplitData( const MbSurface & item, bool same ) - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - SPtr surface; - surface = same ? const_cast(&item) : static_cast(&item.Duplicate()); - surfaces.push_back( surface ); - } - /// \ru Конструктор по поверхностям. \en Constructor by surfaces. - MbSplitData( const c3d::ConstSurfacesSPtrVector & items, bool same ) - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - ::AddRefItems( items, same, surfaces ); - } - /// \ru Конструктор по поверхностям. \en Constructor by surfaces. - MbSplitData( const c3d::ConstSurfacesVector & items, bool same ) - : place ( ) - , direction ( ) - , sense ( orient_BOTH ) - , sketchContours( ) - , spaceCurves ( ) - , surfaces ( ) - , creators ( ) - , solidShell ( NULL ) - { - ::AddRefItems( items, same, surfaces ); - } - /// \ru Конструктор по телу. \en Constructor by a solid. - MbSplitData( const MbSolid & solid, bool same, bool keepShell ); - /// \ru Конструктор копирования с регистратором копирования. \en Copy constructor with registrator of copying. - explicit MbSplitData( const MbSplitData &, bool same, MbRegDuplicate * iReg ); - /// \ru Деструктор. \en Destructor. - ~MbSplitData(); - -public: - /// \ru Инициализировать по двумерному контуру в локальной системе координат. \en Initialize by two-dimensional contour in the local coordinate system. - bool InitPlaneContour( const MbPlacement3D & pl, MbeSenseValue dirSense, const MbContour & item, bool same ) - { - DeleteItems(); - place.Init( pl ); - direction.SetZero(); - sense = dirSense; - - SPtr sketchContour; - sketchContour = same ? const_cast( &item ) : static_cast(&item.Duplicate()); - sketchContours.push_back( sketchContour ); - return true; - } - /// \ru Инициализировать по двумерному контуру в локальной системе координат. \en Initialize by two-dimensional contour in the local coordinate system. - bool InitPlaneContour( const MbPlacement3D & pl, const MbVector3D & dir, const MbContour & item, bool same ) - { - DeleteItems(); - place.Init( pl ); - direction.Init( dir ); - C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); - sense = orient_BOTH; - - SPtr sketchContour; - sketchContour = same ? const_cast( &item ) : static_cast(&item.Duplicate()); - sketchContours.push_back( sketchContour ); - return true; - } - /// \ru Инициализировать по двумерным контурам в локальной системе координат. \en Initialize by two-dimensional contours in the local coordinate system. - template - bool InitPlaneContours( const MbPlacement3D & pl, MbeSenseValue dirSense, const PlaneContoursVector & items, bool same ) - { - if ( items.size() > 0 ) { - DeleteItems(); - place.Init( pl ); - direction.SetZero(); - sense = dirSense; - - ::AddRefItems( items, same, sketchContours ); - return true; - } - return false; - } - /// \ru Инициализировать по двумерным контурам в локальной системе координат. \en Initialize by two-dimensional contours in the local coordinate system. - template - bool InitPlaneContours( const MbPlacement3D & pl, const MbVector3D & dir, const PlaneContoursVector & items, bool same ) - { - if ( items.size() > 0 ) { - DeleteItems(); - place.Init( pl ); - direction.Init( dir ); - C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); - sense = orient_BOTH; - - ::AddRefItems( items, same, sketchContours ); - return true; - } - return false; - } - /// \ru Инициализировать по пространственным кривым. \en Initialize by spatial curves. - template - bool InitSpaceCurves( const SpaceCurvesVector & items, bool same ) - { - if ( items.size() > 0 ) { - DeleteItems(); - - ::AddRefItems( items, same, spaceCurves ); - return true; - } - return false; - } - /// \ru Инициализировать по поверхностям. \en Initialize by surfaces. - template - bool InitSurfaces( const SurfacesVector & items, bool same ) - { - if ( items.size() > 0 ) { - DeleteItems(); - - ::AddRefItems( items, same, surfaces ); - return true; - } - return false; - } - /// \ru Инициализировать по телу. \en Initialize by a solid. - bool InitSolid( const MbSolid & solid, bool same, bool keepShell ); - /// \ru Инициализировать по построителям тела. \en Initialize by solid creators. - template - bool InitSolid( const CreatorsVector & solidCreators, bool sameCreators ) - { - DeleteItems(); - size_t creatorsCnt = solidCreators.size(); - if ( creatorsCnt > 0 ) { - MbRegDuplicate * iReg = NULL; - MbAutoRegDuplicate autoReg( iReg ); - SPtr creator; - creators.reserve( creatorsCnt ); - for ( size_t k = 0; k < creatorsCnt; ++k ) { - if ( solidCreators[k] != NULL ) { - creator = sameCreators ? &const_cast( *solidCreators[k] ) : static_cast( &solidCreators[k]->Duplicate( iReg ) ); - creators.push_back( creator ); - ::DetachItem( creator ); - } - } - if ( creators.size() > 0 ) - return true; - } - return false; - } - /// \ru Сделать равным. \en Make equal. - bool SetEqual ( const MbSplitData & ); - /// \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 ); - /// \ru Сдвинуть по вектору. \en Shift by a vector. - void Move ( const MbVector3D &, MbRegTransform * = NULL ); - /// \ru Повернуть вокруг оси. \en Rotate about an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); - /// \ru Отсутствуют ли объекты? \en Are the objects absent? - bool IsEmpty() const { - return ( sketchContours.empty() && - spaceCurves.empty() && - surfaces.empty() && - (creators.empty() && (solidShell == NULL)) ); } - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSplitData &, double accuracy ) const; - - /** \ru \name Доступ к эскизу. - \en \name Access to a sketch. - \{ */ - /// \ru Выдать количество двумерных кривых. \en Get number of two-dimensional curves. - size_t GetSketchCurvesCount() const { return sketchContours.size(); } - /// \ru Получить локальную систему координат двумерных кривых. \en Get the local coordinate system of two-dimensional curves. - const MbPlacement3D & GetSketchPlace() const { return place; } - /// \ru Получить локальную систему координат двумерных кривых. \en Get the local coordinate system of two-dimensional curves. - MbPlacement3D & SetSketchPlace() { return place; } - /// \ru Получить вектор направления выдавливания двумерных кривых. \en Get the extrusion direction vector of two-dimensional curves. - const MbVector3D & GetSketchDirection() const { return direction; } - /// \ru Получить вектор направления выдавливания двумерных кривых. \en Get the extrusion direction vector of two-dimensional curves. - MbVector3D & SetSketchDirection() { return direction; } - /// \ru Выдать направление выдавливания двумерных кривых. \en Get extrusion direction of two-dimensional curves. - const MbeSenseValue GetSketchSense() const { return sense; } - /// \ru Выдать направление выдавливания двумерных кривых. \en Get extrusion direction of two-dimensional curves. - MbeSenseValue & SetSketchSense() { return sense; } - /// \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 ); } - /// \ru Получить двумерную кривую по индексу. \en Get two-dimensional curve by index. - MbContour * SetSketchCurve( size_t k ) { return ((k < sketchContours.size()) ? sketchContours[k].get() : NULL ); } - /// \ru Получить все двумерные кривые. \en Get all two-dimensional curves. - template - void GetSketchCurves( PlaneContoursVector & curvs ) const - { - curvs.reserve( curvs.size() + sketchContours.size() ); - c3d::PlaneContourSPtr sketchContour; - for ( size_t k = 0, addCnt = sketchContours.size(); k < addCnt; ++k ) { - sketchContour = const_cast( sketchContours[k].get() ); - curvs.push_back( sketchContour ); - } - } - /// \ru Удалить двумерную кривую по индексу. \en Delete two-dimensional curve by index. - bool DeleteSketchCurve( size_t k ); - - /** \} */ - /** \ru \name Доступ к пространственным кривым. - \en \name Access to spatial curves. - \{ */ - /// \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 ); } - /// \ru Получить пространственную кривую по индексу. \en Get a spatial curve by index. - MbCurve3D * SetSpaceCurve( size_t k ) { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : NULL ); } - /// \ru Получить все пространственные кривые. \en Get all spatial curves. - template - void GetSpaceCurves( SpaceCurvesVector & curvs ) const - { - curvs.reserve( curvs.size() + spaceCurves.size() ); - c3d::SpaceCurveSPtr spaceCurve; - for ( size_t k = 0, addCnt = spaceCurves.size(); k < addCnt; ++k ) { - spaceCurve = const_cast( spaceCurves[k].get() ); - curvs.push_back( spaceCurve ); - } - } - /// \ru Установить пространственную кривую по индексу. \en Set spatial curve by index. - bool SetSpaceCurve( const MbCurve3D & curve, size_t k ); - - /** \} */ - /** \ru \name Доступ к поверхностям. - \en \name Access to surfaces. - \{ */ - /// \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); } - /// \ru Получить поверхность по индексу. \en Get a surface by index. - MbSurface * SetSurface( size_t k ) { return ((k < surfaces.size()) ? surfaces[k].get() : NULL); } - /// \ru Получить все поверхности. \en Get all surfaces. - template - void GetSurfaces( SurfacesVector & surfs ) const - { - surfs.reserve( surfs.size() + surfaces.size() ); - c3d::SurfaceSPtr surface; - for ( size_t k = 0, addCnt = surfaces.size(); k < addCnt; ++k ) { - surface = const_cast( surfaces[k].get() ); - surfs.push_back( surface ); - } - } - /// \ru Установить поверхность по индексу. \en Set a surface by index. - bool SetSurface( const MbSurface & surface, size_t k ); - - /** \} */ - /** \ru \name Доступ к строителям. - \en \name Access to creators. - \{ */ - /// \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 ); } - /// \ru Получить строитель по индексу. \en Get constructor by index. - MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? creators[k].get() : NULL ); } - /// \ru Получить все строители. \en Get all creators. - template - void GetCreators( CreatorsVector & crs ) const - { - crs.reserve( crs.size() + creators.size() ); - c3d::ConstCreatorSPtr creator; - for ( size_t k = 0, addCnt = creators.size(); k < addCnt; ++k ) { - creator = creators[k]; - crs.push_back( creator ); - ::DetachItem( creator ); - } - } - /// \ru Получить все строители. \en Get all creators. - template - void GetCreatorsCopies( CreatorsVector & crs ) const - { - MbRegDuplicate * iReg = 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 ) - creator = static_cast( &creators[k]->Duplicate( iReg ) ); - crs.push_back( creator ); - ::DetachItem( creator ); - creator = NULL; - } - } - /// \ru Получить все строители. \en Get all creators. - template - void SetCreators( CreatorsVector & crs ) - { - crs.reserve( crs.size() + creators.size() ); - c3d::CreatorSPtr creator; - for ( size_t k = 0, addCnt = creators.size(); k < addCnt; ++k ) { - creator = creators[k]; - crs.push_back( creator ); - ::DetachItem( creator ); - } - } - /// \ru Получить хранимую оболочку. \en Get stored shell. - const MbFaceShell * GetSolidShell() const { return solidShell; } - /// \ru Создать оболочку по строителям (solidShell остается нетронутой). \en Create a shell by creators (solidShell remains unchanged). - MbFaceShell * CreateShell( MbeCopyMode copyMode ); - /// \ru Создать оболочку по строителям. \en Create a shell by creators (solidShell remains unchanged). - bool UpdateShell( MbeCopyMode copyMode ); - /// \ru Удалить данные. \en Delete data. - void DeleteItems(); - /// \ru Прочитать данные. \en Read data. - void ReadItems ( reader & ); - /// \ru Записать данные. \en Write data. - void WriteItems( writer & ) const; - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & ); - /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties & ); - /// \ru Дать базовые объекты. \en Get the base objects. - void GetBasisItems ( RPArray & ); - /// \ru Выдать контрольные точки объекта. \en Get control points of object. - void GetBasisPoints( MbControlData3D & ) const; - /// \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void SetBasisPoints( const MbControlData3D & ); - /** \} */ -OBVIOUS_PRIVATE_COPY( MbSplitData ) -}; - - -#endif // __CR_SPLIT_DATA_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Усекающие элементы оболочки. + \en Truncating elements of a shell. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SPLIT_DATA_H +#define __CR_SPLIT_DATA_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class reader; +class writer; +class MATH_CLASS MbProperties; +class MATH_CLASS MbCartPoint3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbSpaceItem; +class MATH_CLASS MbCurve; +class MATH_CLASS MbSurfaceIntersectionCurve; +class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbSolid; +struct MATH_CLASS MbControlData3D; +class MbRegDuplicate; +class MbRegTransform; +enum MbeSenseValue; +enum MbeCopyMode; + + +//------------------------------------------------------------------------------ +/** \brief \ru Усекающие элементы. + \en Truncating elements. \~ + \details \ru Усекающие элементы используются для разделения граней на части и усечения оболочек. + Усечение может выполняться двумерными кривыми, расположенными в плоскости XY локальной системы координат, + трёхмерными кривыми, поверхностями и оболочками. + Усекающие элементы используются в строителе усеченной оболочки MbTruncatedShell и + строителе оболочки с разбиением граней MbSplitShell. \n + \en Truncating elements are used for splitting faces into parts and truncation of shells. + Truncating can be performed by two-dimensional curves located in the XY plane of the local coordinate system, + by three-dimensional curves, surfaces and shells. + Truncating elements are used in the creator of truncated shell MbTruncatedShell and + in the creator of shell with face splitting MbSplitShell. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbSplitData : public MbRefItem { + /// \ru Типы усекающих объектов. \en Truncating objects types. + enum MbeSplitItemsType { + sit_NoItems = 0, ///< \ru Нет объектов. \en No objects. + sit_Curves2d = 1, ///< \ru Двумерные кривые в локальной системе координат. \en Two-dimensional curves in the local coordinate system. + sit_Curves3d = 2, ///< \ru Трехмерные кривые. \en Three-dimensional curves. + sit_Surfaces = 3, ///< \ru Поверхности. \en Surfaces. + sit_Creators = 4, ///< \ru Строители тела. \en Solid creators. + }; + +private: + // Sketch contours + c3d::PlaneContoursSPtrVector sketchContours; ///< \ru Двумерные кривые. \en Two-dimensional curves. + MbPlacement3D place; ///< \ru Локальная система координат двумерных кривых. \en Local coordinate system of two-dimensional curves. + MbVector3D direction; ///< \ru Вектор выдавливания двумерных кривых. \en Extrusion direction vector of two-dimensional curves. + MbeSenseValue sense; ///< \ru Направление выдавливания двумерных кривых относительно вектора. \en Extrusion direction of two-dimensional curves relative to direction vector. + // Space Curves + c3d::SpaceCurvesSPtrVector spaceCurves; ///< \ru Пространственные кривые. \en Spatial curves. + // Surfaces + c3d::SurfacesSPtrVector surfaces; ///< \ru Поверхности. \en Surfaces. + // Shell + c3d::CreatorsSPtrVector creators; ///< \ru Строители оболочки. \en Shell creators. + c3d::ShellSPtr solidShell; ///< \ru Оболочка. \en A shell. + +public: + /// \ru Конструктор. \en Constructor. + MbSplitData() + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + } + /// \ru Конструктор по двумерному контуру в локальной системе координат. \en Constructor by two-dimensional contour in the local coordinate system. + MbSplitData( const MbPlacement3D & pl, MbeSenseValue dirSense, const MbContour & item, bool same ) + : place ( pl ) + , direction ( ) + , sense ( dirSense ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + SPtr sketchContour; + sketchContour = same ? const_cast(&item) : static_cast(&item.Duplicate()); + sketchContours.push_back( sketchContour ); + } + /// \ru Конструктор по двумерному контуру в локальной системе координат. \en Constructor by two-dimensional contour in the local coordinate system. + MbSplitData( const MbPlacement3D & pl, const MbVector3D & dir, const MbContour & item, bool same ) + : place ( pl ) + , direction ( dir ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); + + SPtr sketchContour; + sketchContour = same ? const_cast(&item) : static_cast(&item.Duplicate()); + sketchContours.push_back( sketchContour ); + } + /// \ru Конструктор по двумерным контурам в локальной системе координат. \en Constructor by two-dimensional contours in the local coordinate system. + template + MbSplitData( const MbPlacement3D & pl, MbeSenseValue dirSense, const PlaneContoursVector & items, bool same ) + : place ( pl ) + , direction ( ) + , sense ( dirSense ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + ::AddRefItems( items, same, sketchContours ); + } + /// \ru Конструктор по двумерным контурам в локальной системе координат. \en Constructor by two-dimensional contours in the local coordinate system. + template + MbSplitData( const MbPlacement3D & pl, const MbVector3D & dir, const PlaneContoursVector & items, bool same ) + : place ( pl ) + , direction ( dir ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); + + ::AddRefItems( items, same, sketchContours ); + } + /// \ru Конструктор по пространственным кривым. \en Constructor by spatial curves. + MbSplitData( const c3d::ConstSpaceCurvesSPtrVector & items, bool same ) + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + ::AddRefItems( items, same, spaceCurves ); + } + /// \ru Конструктор по пространственным кривым. \en Constructor by spatial curves. + MbSplitData( const c3d::ConstSpaceCurvesVector & items, bool same ) + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + ::AddRefItems( items, same, spaceCurves ); + } + /// \ru Конструктор по поверхности. \en Constructor by a surface. + MbSplitData( const MbSurface & item, bool same ) + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + SPtr surface; + surface = same ? const_cast(&item) : static_cast(&item.Duplicate()); + surfaces.push_back( surface ); + } + /// \ru Конструктор по поверхностям. \en Constructor by surfaces. + MbSplitData( const c3d::ConstSurfacesSPtrVector & items, bool same ) + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + ::AddRefItems( items, same, surfaces ); + } + /// \ru Конструктор по поверхностям. \en Constructor by surfaces. + MbSplitData( const c3d::ConstSurfacesVector & items, bool same ) + : place ( ) + , direction ( ) + , sense ( orient_BOTH ) + , sketchContours( ) + , spaceCurves ( ) + , surfaces ( ) + , creators ( ) + , solidShell ( NULL ) + { + ::AddRefItems( items, same, surfaces ); + } + /// \ru Конструктор по телу. \en Constructor by a solid. + MbSplitData( const MbSolid & solid, bool same, bool keepShell ); + /// \ru Конструктор копирования с регистратором копирования. \en Copy constructor with registrator of copying. + explicit MbSplitData( const MbSplitData &, bool same, MbRegDuplicate * iReg ); + /// \ru Деструктор. \en Destructor. + ~MbSplitData(); + +public: + /// \ru Инициализировать по двумерному контуру в локальной системе координат. \en Initialize by two-dimensional contour in the local coordinate system. + bool InitPlaneContour( const MbPlacement3D & pl, MbeSenseValue dirSense, const MbContour & item, bool same ) + { + DeleteItems(); + place.Init( pl ); + direction.SetZero(); + sense = dirSense; + + SPtr sketchContour; + sketchContour = same ? const_cast( &item ) : static_cast(&item.Duplicate()); + sketchContours.push_back( sketchContour ); + return true; + } + /// \ru Инициализировать по двумерному контуру в локальной системе координат. \en Initialize by two-dimensional contour in the local coordinate system. + bool InitPlaneContour( const MbPlacement3D & pl, const MbVector3D & dir, const MbContour & item, bool same ) + { + DeleteItems(); + place.Init( pl ); + direction.Init( dir ); + C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); + sense = orient_BOTH; + + SPtr sketchContour; + sketchContour = same ? const_cast( &item ) : static_cast(&item.Duplicate()); + sketchContours.push_back( sketchContour ); + return true; + } + /// \ru Инициализировать по двумерным контурам в локальной системе координат. \en Initialize by two-dimensional contours in the local coordinate system. + template + bool InitPlaneContours( const MbPlacement3D & pl, MbeSenseValue dirSense, const PlaneContoursVector & items, bool same ) + { + if ( items.size() > 0 ) { + DeleteItems(); + place.Init( pl ); + direction.SetZero(); + sense = dirSense; + + ::AddRefItems( items, same, sketchContours ); + return true; + } + return false; + } + /// \ru Инициализировать по двумерным контурам в локальной системе координат. \en Initialize by two-dimensional contours in the local coordinate system. + template + bool InitPlaneContours( const MbPlacement3D & pl, const MbVector3D & dir, const PlaneContoursVector & items, bool same ) + { + if ( items.size() > 0 ) { + DeleteItems(); + place.Init( pl ); + direction.Init( dir ); + C3D_ASSERT( (direction.MaxFactor() < LENGTH_EPSILON) || !direction.Orthogonal( place.GetAxisZ(), ANGLE_EPSILON ) ); + sense = orient_BOTH; + + ::AddRefItems( items, same, sketchContours ); + return true; + } + return false; + } + /// \ru Инициализировать по пространственным кривым. \en Initialize by spatial curves. + template + bool InitSpaceCurves( const SpaceCurvesVector & items, bool same ) + { + if ( items.size() > 0 ) { + DeleteItems(); + + ::AddRefItems( items, same, spaceCurves ); + return true; + } + return false; + } + /// \ru Инициализировать по поверхностям. \en Initialize by surfaces. + template + bool InitSurfaces( const SurfacesVector & items, bool same ) + { + if ( items.size() > 0 ) { + DeleteItems(); + + ::AddRefItems( items, same, surfaces ); + return true; + } + return false; + } + /// \ru Инициализировать по телу. \en Initialize by a solid. + bool InitSolid( const MbSolid & solid, bool same, bool keepShell ); + /// \ru Инициализировать по построителям тела. \en Initialize by solid creators. + template + bool InitSolid( const CreatorsVector & solidCreators, bool sameCreators ) + { + DeleteItems(); + size_t creatorsCnt = solidCreators.size(); + if ( creatorsCnt > 0 ) { + MbRegDuplicate * iReg = NULL; + MbAutoRegDuplicate autoReg( iReg ); + SPtr creator; + creators.reserve( creatorsCnt ); + for ( size_t k = 0; k < creatorsCnt; ++k ) { + if ( solidCreators[k] != NULL ) { + creator = sameCreators ? &const_cast( *solidCreators[k] ) : static_cast( &solidCreators[k]->Duplicate( iReg ) ); + creators.push_back( creator ); + ::DetachItem( creator ); + } + } + if ( creators.size() > 0 ) + return true; + } + return false; + } + /// \ru Сделать равным. \en Make equal. + bool SetEqual ( const MbSplitData & ); + /// \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 ); + /// \ru Сдвинуть по вектору. \en Shift by a vector. + void Move ( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Повернуть вокруг оси. \en Rotate about an axis. + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + /// \ru Отсутствуют ли объекты? \en Are the objects absent? + bool IsEmpty() const { + return ( sketchContours.empty() && + spaceCurves.empty() && + surfaces.empty() && + (creators.empty() && (solidShell == NULL)) ); } + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSplitData &, double accuracy ) const; + + /** \ru \name Доступ к эскизу. + \en \name Access to a sketch. + \{ */ + /// \ru Выдать количество двумерных кривых. \en Get number of two-dimensional curves. + size_t GetSketchCurvesCount() const { return sketchContours.size(); } + /// \ru Получить локальную систему координат двумерных кривых. \en Get the local coordinate system of two-dimensional curves. + const MbPlacement3D & GetSketchPlace() const { return place; } + /// \ru Получить локальную систему координат двумерных кривых. \en Get the local coordinate system of two-dimensional curves. + MbPlacement3D & SetSketchPlace() { return place; } + /// \ru Получить вектор направления выдавливания двумерных кривых. \en Get the extrusion direction vector of two-dimensional curves. + const MbVector3D & GetSketchDirection() const { return direction; } + /// \ru Получить вектор направления выдавливания двумерных кривых. \en Get the extrusion direction vector of two-dimensional curves. + MbVector3D & SetSketchDirection() { return direction; } + /// \ru Выдать направление выдавливания двумерных кривых. \en Get extrusion direction of two-dimensional curves. + const MbeSenseValue GetSketchSense() const { return sense; } + /// \ru Выдать направление выдавливания двумерных кривых. \en Get extrusion direction of two-dimensional curves. + MbeSenseValue & SetSketchSense() { return sense; } + /// \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 ); } + /// \ru Получить двумерную кривую по индексу. \en Get two-dimensional curve by index. + MbContour * SetSketchCurve( size_t k ) { return ((k < sketchContours.size()) ? sketchContours[k].get() : NULL ); } + /// \ru Получить все двумерные кривые. \en Get all two-dimensional curves. + template + void GetSketchCurves( PlaneContoursVector & curvs ) const + { + curvs.reserve( curvs.size() + sketchContours.size() ); + c3d::PlaneContourSPtr sketchContour; + for ( size_t k = 0, addCnt = sketchContours.size(); k < addCnt; ++k ) { + sketchContour = const_cast( sketchContours[k].get() ); + curvs.push_back( sketchContour ); + } + } + /// \ru Удалить двумерную кривую по индексу. \en Delete two-dimensional curve by index. + bool DeleteSketchCurve( size_t k ); + + /** \} */ + /** \ru \name Доступ к пространственным кривым. + \en \name Access to spatial curves. + \{ */ + /// \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 ); } + /// \ru Получить пространственную кривую по индексу. \en Get a spatial curve by index. + MbCurve3D * SetSpaceCurve( size_t k ) { return ((k < spaceCurves.size()) ? spaceCurves[k].get() : NULL ); } + /// \ru Получить все пространственные кривые. \en Get all spatial curves. + template + void GetSpaceCurves( SpaceCurvesVector & curvs ) const + { + curvs.reserve( curvs.size() + spaceCurves.size() ); + c3d::SpaceCurveSPtr spaceCurve; + for ( size_t k = 0, addCnt = spaceCurves.size(); k < addCnt; ++k ) { + spaceCurve = const_cast( spaceCurves[k].get() ); + curvs.push_back( spaceCurve ); + } + } + /// \ru Установить пространственную кривую по индексу. \en Set spatial curve by index. + bool SetSpaceCurve( const MbCurve3D & curve, size_t k ); + + /** \} */ + /** \ru \name Доступ к поверхностям. + \en \name Access to surfaces. + \{ */ + /// \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); } + /// \ru Получить поверхность по индексу. \en Get a surface by index. + MbSurface * SetSurface( size_t k ) { return ((k < surfaces.size()) ? surfaces[k].get() : NULL); } + /// \ru Получить все поверхности. \en Get all surfaces. + template + void GetSurfaces( SurfacesVector & surfs ) const + { + surfs.reserve( surfs.size() + surfaces.size() ); + c3d::SurfaceSPtr surface; + for ( size_t k = 0, addCnt = surfaces.size(); k < addCnt; ++k ) { + surface = const_cast( surfaces[k].get() ); + surfs.push_back( surface ); + } + } + /// \ru Установить поверхность по индексу. \en Set a surface by index. + bool SetSurface( const MbSurface & surface, size_t k ); + + /** \} */ + /** \ru \name Доступ к строителям. + \en \name Access to creators. + \{ */ + /// \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 ); } + /// \ru Получить строитель по индексу. \en Get constructor by index. + MbCreator * SetCreator( size_t k ) { return ((k < creators.size()) ? creators[k].get() : NULL ); } + /// \ru Получить все строители. \en Get all creators. + template + void GetCreators( CreatorsVector & crs ) const + { + crs.reserve( crs.size() + creators.size() ); + c3d::ConstCreatorSPtr creator; + for ( size_t k = 0, addCnt = creators.size(); k < addCnt; ++k ) { + creator = creators[k]; + crs.push_back( creator ); + ::DetachItem( creator ); + } + } + /// \ru Получить все строители. \en Get all creators. + template + void GetCreatorsCopies( CreatorsVector & crs ) const + { + MbRegDuplicate * iReg = 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 ) + creator = static_cast( &creators[k]->Duplicate( iReg ) ); + crs.push_back( creator ); + ::DetachItem( creator ); + creator = NULL; + } + } + /// \ru Получить все строители. \en Get all creators. + template + void SetCreators( CreatorsVector & crs ) + { + crs.reserve( crs.size() + creators.size() ); + c3d::CreatorSPtr creator; + for ( size_t k = 0, addCnt = creators.size(); k < addCnt; ++k ) { + creator = creators[k]; + crs.push_back( creator ); + ::DetachItem( creator ); + } + } + /// \ru Получить хранимую оболочку. \en Get stored shell. + const MbFaceShell * GetSolidShell() const { return solidShell; } + /// \ru Создать оболочку по строителям (solidShell остается нетронутой). \en Create a shell by creators (solidShell remains unchanged). + MbFaceShell * CreateShell( MbeCopyMode copyMode ); + /// \ru Создать оболочку по строителям. \en Create a shell by creators (solidShell remains unchanged). + bool UpdateShell( MbeCopyMode copyMode ); + /// \ru Удалить данные. \en Delete data. + void DeleteItems(); + /// \ru Прочитать данные. \en Read data. + void ReadItems ( reader & ); + /// \ru Записать данные. \en Write data. + void WriteItems( writer & ) const; + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties & ); + /// \ru Записать свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties & ); + /// \ru Дать базовые объекты. \en Get the base objects. + void GetBasisItems ( RPArray & ); + /// \ru Выдать контрольные точки объекта. \en Get control points of object. + void GetBasisPoints( MbControlData3D & ) const; + /// \ru Изменить объект по контрольным точкам. \en Change the object by control points. + void SetBasisPoints( const MbControlData3D & ); + /** \} */ +OBVIOUS_PRIVATE_COPY( MbSplitData ) +}; + + +#endif // __CR_SPLIT_DATA_H diff --git a/C3d/Include/cr_stamp_bead_solid.h b/C3d/Include/cr_stamp_bead_solid.h index 6f02c0f..beddeaa 100644 --- a/C3d/Include/cr_stamp_bead_solid.h +++ b/C3d/Include/cr_stamp_bead_solid.h @@ -143,7 +143,7 @@ IMPL_PERSISTENT_OPS( MbBeadSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateBead( MbFaceShell * initialShell, +MATH_FUNC (MbCreator *) CreateBead( SPtr & initialShell, const MbeCopyMode sameShell, const MbFace * face, const MbPlacement3D & placement, diff --git a/C3d/Include/cr_stamp_jalousie_solid.h b/C3d/Include/cr_stamp_jalousie_solid.h index b52a413..7f7bd83 100644 --- a/C3d/Include/cr_stamp_jalousie_solid.h +++ b/C3d/Include/cr_stamp_jalousie_solid.h @@ -134,7 +134,7 @@ IMPL_PERSISTENT_OPS( MbJalousieSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateJalousie( MbFaceShell * initialShell, +MATH_FUNC (MbCreator *) CreateJalousie( SPtr & initialShell, const MbeCopyMode sameShell, const MbFace * face, const MbPlacement3D & placement, diff --git a/C3d/Include/cr_stamp_jog_solid.h b/C3d/Include/cr_stamp_jog_solid.h index bf1189e..e9e6ada 100644 --- a/C3d/Include/cr_stamp_jog_solid.h +++ b/C3d/Include/cr_stamp_jog_solid.h @@ -138,18 +138,18 @@ IMPL_PERSISTENT_OPS( MbJogSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateSheetSolidJog( MbFaceShell & solid, - MbeCopyMode sameShell, - const RPArray & bendingFaces, - MbCurve3D & curve, - const bool unbended, - const MbJogValues & parameters, - const MbBendValues & secondBendParams, - MbSNameMaker & names, - RPArray & firstBendFaces, - RPArray & secondBendFaces, - MbResultType & res, - MbFaceShell *& shell ); +MATH_FUNC (MbCreator *) CreateSheetSolidJog( SPtr & solid, + MbeCopyMode sameShell, + const RPArray & bendingFaces, + MbCurve3D & curve, + const bool unbended, + const MbJogValues & parameters, + const MbBendValues & secondBendParams, + MbSNameMaker & names, + RPArray & firstBendFaces, + RPArray & secondBendFaces, + MbResultType & res, + MbFaceShell *& shell ); #endif // __CR_STAMP_JOG_SOLID_H diff --git a/C3d/Include/cr_stamp_remove_solid.h b/C3d/Include/cr_stamp_remove_solid.h index c5a431b..ee56931 100644 --- a/C3d/Include/cr_stamp_remove_solid.h +++ b/C3d/Include/cr_stamp_remove_solid.h @@ -1,110 +1,110 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение оболочки тела с без указанной операции. - \en Construction of a shell without the specified operation. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_STAMP_REMOVE_SOLID_H -#define __CR_STAMP_REMOVE_SOLID_H - - -#include -//#include -//#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала с удалёнными элементами указанной операции. - \en The constructor of a shell from sheet material without elements of the specified operation. \~ - \details \ru Строитель оболочки из листового материала с удалёнными элементами указанной операции. - Удаляет грани с указанным главным именем операции и затягивает образовавшуюся дыру расширением соседних граней. \n - \en The constructor of a shell from sheet material without elements of the specified operation. - It removes faces with specified main name and then mends the hole by stretching the neighbour faces. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbRemoveOperationSolid : public MbCreator { - SimpleName removeName; - -public : - MbRemoveOperationSolid( const SimpleName removeName, - const MbSNameMaker & names ); -private: - MbRemoveOperationSolid( const MbRemoveOperationSolid &, MbRegDuplicate * iReg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbRemoveOperationSolid( const MbRemoveOperationSolid & ); - -public: - virtual ~MbRemoveOperationSolid(); - - // \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 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 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 solid - - virtual bool CreateShell( MbFaceShell *& shell, - MbeCopyMode sameShell, - RPArray * items = NULL ); // \ru Построение \en Construction - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbRemoveOperationSolid & operator = ( const MbRemoveOperationSolid & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRemoveOperationSolid ) -}; - -IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку без указанной операции. - \en Constructs a shell without the specified operation. \~ - \details \ru Построить оболочку без указанной операции. - Удаляет грани с указанным главным именем операции и затягивает образовавшуюся дыру расширением соседних граней. \n - \en Constructs a shell without the specified operation. - It removes faces with specified main name and then mends the hole by stretching the neighbour faces. \n \~ - \param[in] initialShell - \ru Исходная оболочка. - \en The initial shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the initial shell. \~ - \param[in] removeName - \ru Главное имя операции которую надо удалить. - \en The main name of the operation to be removed. \~ - \param[in] names - \ru Именователь граней. - \en An object for naming faces. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateRemovedOperationResult( MbFaceShell & initialShell, - const MbeCopyMode sameShell, - const SimpleName removeName, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - - -#endif // __CR_STAMP_REMOVE_SOLID_H - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение оболочки тела с без указанной операции. + \en Construction of a shell without the specified operation. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_STAMP_REMOVE_SOLID_H +#define __CR_STAMP_REMOVE_SOLID_H + + +#include +//#include +//#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала с удалёнными элементами указанной операции. + \en The constructor of a shell from sheet material without elements of the specified operation. \~ + \details \ru Строитель оболочки из листового материала с удалёнными элементами указанной операции. + Удаляет грани с указанным главным именем операции и затягивает образовавшуюся дыру расширением соседних граней. \n + \en The constructor of a shell from sheet material without elements of the specified operation. + It removes faces with specified main name and then mends the hole by stretching the neighbour faces. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbRemoveOperationSolid : public MbCreator { + SimpleName removeName; + +public : + MbRemoveOperationSolid( const SimpleName removeName, + const MbSNameMaker & names ); +private: + MbRemoveOperationSolid( const MbRemoveOperationSolid &, MbRegDuplicate * iReg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbRemoveOperationSolid( const MbRemoveOperationSolid & ); + +public: + virtual ~MbRemoveOperationSolid(); + + // \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 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 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 solid + + virtual bool CreateShell( MbFaceShell *& shell, + MbeCopyMode sameShell, + RPArray * items = NULL ); // \ru Построение \en Construction + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbRemoveOperationSolid & operator = ( const MbRemoveOperationSolid & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbRemoveOperationSolid ) +}; + +IMPL_PERSISTENT_OPS( MbRemoveOperationSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку без указанной операции. + \en Constructs a shell without the specified operation. \~ + \details \ru Построить оболочку без указанной операции. + Удаляет грани с указанным главным именем операции и затягивает образовавшуюся дыру расширением соседних граней. \n + \en Constructs a shell without the specified operation. + It removes faces with specified main name and then mends the hole by stretching the neighbour faces. \n \~ + \param[in] initialShell - \ru Исходная оболочка. + \en The initial shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the initial shell. \~ + \param[in] removeName - \ru Главное имя операции которую надо удалить. + \en The main name of the operation to be removed. \~ + \param[in] names - \ru Именователь граней. + \en An object for naming faces. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateRemovedOperationResult( MbFaceShell & initialShell, + const MbeCopyMode sameShell, + const SimpleName removeName, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + + +#endif // __CR_STAMP_REMOVE_SOLID_H + + diff --git a/C3d/Include/cr_stamp_rib_solid.h b/C3d/Include/cr_stamp_rib_solid.h index b89ed07..1f945cb 100644 --- a/C3d/Include/cr_stamp_rib_solid.h +++ b/C3d/Include/cr_stamp_rib_solid.h @@ -1,135 +1,135 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель листового тела с ребром жёсткости. - \en Constructor of a sheet solid with a rib. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_STAMP_RIB_SOLID_H -#define __CR_STAMP_RIB_SOLID_H - - -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель тела с ребром жёсткости. - \en Constructor of a sheet solid with a rib. \~ - \details \ru Строитель тела с ребром жёсткости, форма которого задана плоским контуром. - \en Constructor of a solid with a rib whose shape is specified by a planar contour. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbStampRibSolid : public MbCreator { -protected : - MbPlacement3D place; ///< \ru Подложка для формообразующей кривой, точки и вектора уклона. \en Placement of the forming curve, point and inclination vector. - MbContour * spine; ///< \ru Формообразующая кривая (хребет ребра жёсткости). \en Forming curve (rib's spine). - size_t index; ///< \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. \en The segment index in the contour from which the inclination direction will be set. - SheetRibValues parameters; ///< \ru Параметры формообразования. \en Forming parameters. - -public : - MbStampRibSolid( const MbPlacement3D & place, - const MbContour & contour, - size_t index, - const SheetRibValues & param, - const MbSNameMaker & names ); -private : - MbStampRibSolid( const MbStampRibSolid & bres, MbRegDuplicate * ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbStampRibSolid( const MbStampRibSolid & bres ); -public : - virtual ~MbStampRibSolid(); - - // \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 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 - - 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 - - // \ru Общие функции твердого тела \en Common functions of solid - - virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( SheetRibValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const SheetRibValues & params ) { parameters = params; } - -private : - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbStampRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStampRibSolid ) -}; // MbRibSolid - -IMPL_PERSISTENT_OPS( MbStampRibSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создать оболочку с ребром жёсткости. - \en Create a shell with a rib. \~ - \details \ru Для указанной листовой оболочки построить оболочку с ребром жёсткости, форма которого задана плоским контуром.\n - Одновременно с построением оболочки функция создаёт её строитель. \n - \en For a specified sheet shell create a shell with a rib which shape is given by the planar contour.\n - The function simultaneously constructs the shell and creates its constructor. \n \~ - \param[in] solid - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Способ копирования граней исходной оболочки. - \en Method of copying the source shell faces. \~ - \param[in] place - \ru Локальная система координат, в плоскости XY которай расположен двумерный контур. - \en A local coordinate system the two-dimensional contour is located in XY plane of. \~ - \param[in] contour - \ru Двумерный контур ребра жесткости расположен в плоскости XY локальной системы координат. - \en Two-dimensional contour of a rib located in XY plane of the local coordinate system. \~ - \param[in] index - \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. - \en Index of a segment in the contour at which the inclination direction will be set. \~ - \param[in] parameters - \ru Параметры операции. - \en The operation parameters. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] shell - \ru Построенный набор граней. - \en Constructed set of faces. \~ - \result \ru Возвращает строитель, если операция была выполнена успешно. - \en Returns the constructor if the operation has been successfully performed. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateSheetRib( MbFaceShell * solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbContour & contour, - size_t index, - SheetRibValues & parameters, - const MbSNameMaker & operNames, - MbResultType & res, - MbFaceShell *& shell ); - - -//------------------------------------------------------------------------------ -// Построение элементов ребра жёсткости. -// --- -MATH_FUNC (MbResultType) CreateSheetRibParts( MbFaceShell * solid, - MbeCopyMode sameShell, - const MbPlacement3D & place, - const MbContour & contour, - const size_t index, - const SheetRibValues & pars, - const MbSNameMaker & names, - MbFaceShell *& shellToAdd, - MbFaceShell *& shellToSubtract ); - -#endif // __CR_STAMP_RIB_SOLID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель листового тела с ребром жёсткости. + \en Constructor of a sheet solid with a rib. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_STAMP_RIB_SOLID_H +#define __CR_STAMP_RIB_SOLID_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель тела с ребром жёсткости. + \en Constructor of a sheet solid with a rib. \~ + \details \ru Строитель тела с ребром жёсткости, форма которого задана плоским контуром. + \en Constructor of a solid with a rib whose shape is specified by a planar contour. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbStampRibSolid : public MbCreator { +protected : + MbPlacement3D place; ///< \ru Подложка для формообразующей кривой, точки и вектора уклона. \en Placement of the forming curve, point and inclination vector. + MbContour * spine; ///< \ru Формообразующая кривая (хребет ребра жёсткости). \en Forming curve (rib's spine). + size_t index; ///< \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. \en The segment index in the contour from which the inclination direction will be set. + SheetRibValues parameters; ///< \ru Параметры формообразования. \en Forming parameters. + +public : + MbStampRibSolid( const MbPlacement3D & place, + const MbContour & contour, + size_t index, + const SheetRibValues & param, + const MbSNameMaker & names ); +private : + MbStampRibSolid( const MbStampRibSolid & bres, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbStampRibSolid( const MbStampRibSolid & bres ); +public : + virtual ~MbStampRibSolid(); + + // \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 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 + + 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 + + // \ru Общие функции твердого тела \en Common functions of solid + + virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, + RPArray *items = NULL ); // \ru Построение \en Construction + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( SheetRibValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const SheetRibValues & params ) { parameters = params; } + +private : + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbStampRibSolid & ); // \ru НЕЛЬЗЯ!!! \en NOT ALLOWED!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbStampRibSolid ) +}; // MbRibSolid + +IMPL_PERSISTENT_OPS( MbStampRibSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создать оболочку с ребром жёсткости. + \en Create a shell with a rib. \~ + \details \ru Для указанной листовой оболочки построить оболочку с ребром жёсткости, форма которого задана плоским контуром.\n + Одновременно с построением оболочки функция создаёт её строитель. \n + \en For a specified sheet shell create a shell with a rib which shape is given by the planar contour.\n + The function simultaneously constructs the shell and creates its constructor. \n \~ + \param[in] solid - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Способ копирования граней исходной оболочки. + \en Method of copying the source shell faces. \~ + \param[in] place - \ru Локальная система координат, в плоскости XY которай расположен двумерный контур. + \en A local coordinate system the two-dimensional contour is located in XY plane of. \~ + \param[in] contour - \ru Двумерный контур ребра жесткости расположен в плоскости XY локальной системы координат. + \en Two-dimensional contour of a rib located in XY plane of the local coordinate system. \~ + \param[in] index - \ru Индекс сегмента в контуре, от которого будет установлено направление уклона. + \en Index of a segment in the contour at which the inclination direction will be set. \~ + \param[in] parameters - \ru Параметры операции. + \en The operation parameters. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] shell - \ru Построенный набор граней. + \en Constructed set of faces. \~ + \result \ru Возвращает строитель, если операция была выполнена успешно. + \en Returns the constructor if the operation has been successfully performed. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateSheetRib( MbFaceShell * solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbContour & contour, + size_t index, + SheetRibValues & parameters, + const MbSNameMaker & operNames, + MbResultType & res, + MbFaceShell *& shell ); + + +//------------------------------------------------------------------------------ +// Построение элементов ребра жёсткости. +// --- +MATH_FUNC (MbResultType) CreateSheetRibParts( MbFaceShell * solid, + MbeCopyMode sameShell, + const MbPlacement3D & place, + const MbContour & contour, + const size_t index, + const SheetRibValues & pars, + const MbSNameMaker & names, + MbFaceShell *& shellToAdd, + MbFaceShell *& shellToSubtract ); + +#endif // __CR_STAMP_RIB_SOLID_H diff --git a/C3d/Include/cr_stamp_solid.h b/C3d/Include/cr_stamp_solid.h index 5884f77..a025e29 100644 --- a/C3d/Include/cr_stamp_solid.h +++ b/C3d/Include/cr_stamp_solid.h @@ -131,7 +131,7 @@ IMPL_PERSISTENT_OPS( MbStampSolid ) \ingroup Model_Creators */ // --- -MATH_FUNC (MbCreator *) CreateStamp( MbFaceShell * initialShell, // исходная оболочка +MATH_FUNC (MbCreator *) CreateStamp( SPtr & initialShell, // исходная оболочка const MbeCopyMode sameShell, // флаг способа использования исходной оболочки const MbFace * face, // грань штамповки const MbPlacement3D & placement, // локальная система координат контура diff --git a/C3d/Include/cr_stamp_spherical_solid.h b/C3d/Include/cr_stamp_spherical_solid.h index 773d3ef..af6bb97 100644 --- a/C3d/Include/cr_stamp_spherical_solid.h +++ b/C3d/Include/cr_stamp_spherical_solid.h @@ -1,147 +1,147 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель оболочки из листового материала сферической штамповкой. - \en Constructor of a shell from the sheet material with spherical stamping. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_STAMP_SPHERICAL_SOLID_H -#define __CR_STAMP_SPHERICAL_SOLID_H - - -#include -#include -#include - - -class MATH_CLASS MbCurveBoundedSurface; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала сферической штамповкой. - \en Constructor of a shell from the sheet material with spherical stamping. \~ - \details \ru Строитель оболочки из листового материала сферической штамповкой. \n - Строится только закрытая штамповка. \n - \en Constructor of a shell from the sheet material by spherical stamping. \n - Stamping of closed type only are constructed. \n - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbSphericalStampSolid : public MbCreator { -private: - MbItemIndex faceIndex; ///< \ru Индекс грани, на которой строится штамповка. \en Index of the face the stamping is constructed on. - MbItemIndex pairFaceIndex; ///< \ru Индекс парной грани. \en Index of the pair face. - MbCurveBoundedSurface * boundSurface; ///< \ru Поверхность, границами которой надо подрезать штамповку. \en Surface, by which bounds the stamp is cutted. - MbPlacement3D placement; ///< \ru Локальная система координат контура штамповки. \en The local coordinate system of contour of stamping. - MbStampingValues parameters; ///< \ru Параметры штамповки. \en Stamping parameters. - double thickness; ///< \ru Толщина листа. \en Thickness of the plate. - bool add; ///< \ru Создавать добавляемую или вычитаемую часть штамповки. \en Create additional or subtructional part of a stamp. - MbCartPoint center; ///< \ru Центр донышка штамповки. \en Center of the bottom of the stamping. - -public : - MbSphericalStampSolid( const MbItemIndex & faceIndex, - const MbItemIndex & pairFaceIndex, - const MbCurveBoundedSurface * boundSurface, - const MbPlacement3D & placement, - const MbStampingValues & params, - const double thickness, - const bool add, - const MbCartPoint & center, - const MbSNameMaker & names ); -private: - MbSphericalStampSolid( const MbSphericalStampSolid &, MbRegDuplicate * iReg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbSphericalStampSolid( const MbSphericalStampSolid & ); - -public: - virtual ~MbSphericalStampSolid(); - - // \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 - 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 Общие функции твердого тела \en Common functions of solid - - virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение \en Construction - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( MbStampingValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbStampingValues & params ) { parameters = params; } - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - MbSphericalStampSolid & operator = ( const MbSphericalStampSolid & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSphericalStampSolid ) -}; - -IMPL_PERSISTENT_OPS( MbSphericalStampSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку из листового материала со сферической штамповкой. - \en Construct a shell form sheet material by spherical stamping. \~ - \details \ru На базе исходной оболочки из листового материала построить оболочку методом сферической штамповки или части сферической штамповки без исходного листового тела. \n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en A shell is to be constructed on the basis of the source shell by the method of spherical stamping or parts of spherical stamp without the basis sheet solid. \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] face - \ru Грань штамповки. - \en The face for stamping. \~ - \param[in] placement - \ru Локальная система координат, в плоскости XY которй расположен контур штамповки. - \en The local coordinate system in the XY plane of which the stamping contour is located. \~ - \param[in] parameters - \ru Параметры штамповки. - \en The parameters of stamping. \~ - \param[in] thickness - \ru Толщина листа. - \en The thickness of the sheet solid. - \param[in] add - \ru Какую часть сферической штамповки создавать. - \en Which part of the spherical stamp to create. - \param[in] center - \ru Центр штамповки. - \en The center of the stamping. \~ - \param[in] operNames - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] res - \ru Код результата операции выдавливания. - \en The extrusion operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateSphericalStamp( MbFaceShell * solid, - const MbeCopyMode sameShell, - const MbFace * face, - const MbPlacement3D & placement, - const MbStampingValues & parameters, - const double thickness, - const bool add, - const MbCartPoint & center, - MbSNameMaker & operNames, - MbResultType & res, - SPtr & shell ); - - -#endif // __CR_STAMP_SPHERICAL_SOLID_H - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель оболочки из листового материала сферической штамповкой. + \en Constructor of a shell from the sheet material with spherical stamping. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_STAMP_SPHERICAL_SOLID_H +#define __CR_STAMP_SPHERICAL_SOLID_H + + +#include +#include +#include + + +class MATH_CLASS MbCurveBoundedSurface; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала сферической штамповкой. + \en Constructor of a shell from the sheet material with spherical stamping. \~ + \details \ru Строитель оболочки из листового материала сферической штамповкой. \n + Строится только закрытая штамповка. \n + \en Constructor of a shell from the sheet material by spherical stamping. \n + Stamping of closed type only are constructed. \n + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbSphericalStampSolid : public MbCreator { +private: + MbItemIndex faceIndex; ///< \ru Индекс грани, на которой строится штамповка. \en Index of the face the stamping is constructed on. + MbItemIndex pairFaceIndex; ///< \ru Индекс парной грани. \en Index of the pair face. + MbCurveBoundedSurface * boundSurface; ///< \ru Поверхность, границами которой надо подрезать штамповку. \en Surface, by which bounds the stamp is cutted. + MbPlacement3D placement; ///< \ru Локальная система координат контура штамповки. \en The local coordinate system of contour of stamping. + MbStampingValues parameters; ///< \ru Параметры штамповки. \en Stamping parameters. + double thickness; ///< \ru Толщина листа. \en Thickness of the plate. + bool add; ///< \ru Создавать добавляемую или вычитаемую часть штамповки. \en Create additional or subtructional part of a stamp. + MbCartPoint center; ///< \ru Центр донышка штамповки. \en Center of the bottom of the stamping. + +public : + MbSphericalStampSolid( const MbItemIndex & faceIndex, + const MbItemIndex & pairFaceIndex, + const MbCurveBoundedSurface * boundSurface, + const MbPlacement3D & placement, + const MbStampingValues & params, + const double thickness, + const bool add, + const MbCartPoint & center, + const MbSNameMaker & names ); +private: + MbSphericalStampSolid( const MbSphericalStampSolid &, MbRegDuplicate * iReg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbSphericalStampSolid( const MbSphericalStampSolid & ); + +public: + virtual ~MbSphericalStampSolid(); + + // \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 + 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 Общие функции твердого тела \en Common functions of solid + + virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, + RPArray *items = NULL ); // \ru Построение \en Construction + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( MbStampingValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbStampingValues & params ) { parameters = params; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + MbSphericalStampSolid & operator = ( const MbSphericalStampSolid & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSphericalStampSolid ) +}; + +IMPL_PERSISTENT_OPS( MbSphericalStampSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку из листового материала со сферической штамповкой. + \en Construct a shell form sheet material by spherical stamping. \~ + \details \ru На базе исходной оболочки из листового материала построить оболочку методом сферической штамповки или части сферической штамповки без исходного листового тела. \n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en A shell is to be constructed on the basis of the source shell by the method of spherical stamping or parts of spherical stamp without the basis sheet solid. \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] face - \ru Грань штамповки. + \en The face for stamping. \~ + \param[in] placement - \ru Локальная система координат, в плоскости XY которй расположен контур штамповки. + \en The local coordinate system in the XY plane of which the stamping contour is located. \~ + \param[in] parameters - \ru Параметры штамповки. + \en The parameters of stamping. \~ + \param[in] thickness - \ru Толщина листа. + \en The thickness of the sheet solid. + \param[in] add - \ru Какую часть сферической штамповки создавать. + \en Which part of the spherical stamp to create. + \param[in] center - \ru Центр штамповки. + \en The center of the stamping. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] res - \ru Код результата операции выдавливания. + \en The extrusion operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateSphericalStamp( SPtr & solid, + const MbeCopyMode sameShell, + const MbFace * face, + const MbPlacement3D & placement, + const MbStampingValues & parameters, + const double thickness, + const bool add, + const MbCartPoint & center, + MbSNameMaker & operNames, + MbResultType & res, + SPtr & shell ); + + +#endif // __CR_STAMP_SPHERICAL_SOLID_H + diff --git a/C3d/Include/cr_stamp_user_solid.h b/C3d/Include/cr_stamp_user_solid.h index a675b6d..4e1f13f 100644 --- a/C3d/Include/cr_stamp_user_solid.h +++ b/C3d/Include/cr_stamp_user_solid.h @@ -1,110 +1,110 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель оболочки из листового материала штамповкой телом-инструментом. - \en Constructor of a shell from the sheet material with stamping by a tool solid. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_USERSTAMP_SOLID_H -#define __CR_USERSTAMP_SOLID_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель оболочки из листового материала штамповкой телом-инструментом. - \en Constructor of a shell from the sheet material with stamping by tool solid. \~ - \details \ru Строитель оболочки из листового материала закрытой или открытой штамповкой телом-инструментом. - Тело-инструмент может являться пуансоном или матрицей.\n - Строятся штамповки двух типов: \n - закрытая - не указаны вскрываемые грани тела-инструмента, \n - открытая - когда лист пробит штамповкой насквозь, указаны вскрываемые грани. \n - \en Constructor of a shell from the sheet material by open or closed stamping by tool solid. - The tool solid may be a punch or a die. \n - Stamping of two types are constructed: \n - closed - pierce faces of tool solid are not specified, \n - open - when a sheet is punched through by stamping, pierce faces of tool solid are specified. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbUserStampSolid : public MbCreator { -private: - MbItemIndex faceIndex; ///< \ru Индекс грани, на которой строится штамповка. \en Index of the face the stamping is constructed on. - MbItemIndex pairFaceIndex; ///< \ru Индекс грани парной к грани штамповки. \en Index of the face which is pair to the stamp face. - SArray pierceIndices; ///< \ru Индексы граней для вырубки. \en Face indicies for opening. - RPArray creators; ///< \ru Журнал построения оболочки тела-инструмента. \en History tree of the shell of the tool solid. - size_t countOne; ///< \ru Разделитель строителей тел-операндов. \en Separator of operand solids creators. - MbUserStampingValues parameters; ///< \ru Параметры штамповки. \en Stamping parameters. - double thickness; ///< \ru Толщина листа. \en The thickness of the sheet metal. - bool punch; ///< \ru Является тело-инструмент пуансоном или матрицей? \en Is tool body a punch or a die. - -public : - MbUserStampSolid( const RPArray & creatorsTool, - const bool sameTool, - const MbItemIndex & faceIndex, - const MbItemIndex & pairFaceIndex, - SArray & pierceIndices, - const MbUserStampingValues & params, - const double thickness, - const bool isPunch, - const MbSNameMaker & names ); -private: - MbUserStampSolid( const MbUserStampSolid &, MbRegDuplicate * iReg ); - -public: - virtual ~MbUserStampSolid(); - - // \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. - - virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, - RPArray *items = NULL ); // \ru Построение оболочки штамповки. \en Construction of a stamping shell. - - // \ru Получить параметры. \en Get the parameters. - void GetParameters( MbUserStampingValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const MbUserStampingValues & params ) { parameters = params; } - -private: - OBVIOUS_PRIVATE_COPY( MbUserStampSolid ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserStampSolid ) -}; - -IMPL_PERSISTENT_OPS( MbUserStampSolid ) - - -//------------------------------------------------------------------------------ -/** \brief \ru Построить оболочку из листового материала штамповкой телом-инструментом. - \en Construct a shell form sheet material by tool body stamping. \~ - \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] solid - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the source shell. \~ - \param[in] face - \ru Грань штамповки. - \en The face for stamping. \~ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель оболочки из листового материала штамповкой телом-инструментом. + \en Constructor of a shell from the sheet material with stamping by a tool solid. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_USERSTAMP_SOLID_H +#define __CR_USERSTAMP_SOLID_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель оболочки из листового материала штамповкой телом-инструментом. + \en Constructor of a shell from the sheet material with stamping by tool solid. \~ + \details \ru Строитель оболочки из листового материала закрытой или открытой штамповкой телом-инструментом. + Тело-инструмент может являться пуансоном или матрицей.\n + Строятся штамповки двух типов: \n + закрытая - не указаны вскрываемые грани тела-инструмента, \n + открытая - когда лист пробит штамповкой насквозь, указаны вскрываемые грани. \n + \en Constructor of a shell from the sheet material by open or closed stamping by tool solid. + The tool solid may be a punch or a die. \n + Stamping of two types are constructed: \n + closed - pierce faces of tool solid are not specified, \n + open - when a sheet is punched through by stamping, pierce faces of tool solid are specified. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbUserStampSolid : public MbCreator { +private: + MbItemIndex faceIndex; ///< \ru Индекс грани, на которой строится штамповка. \en Index of the face the stamping is constructed on. + MbItemIndex pairFaceIndex; ///< \ru Индекс грани парной к грани штамповки. \en Index of the face which is pair to the stamp face. + SArray pierceIndices; ///< \ru Индексы граней для вырубки. \en Face indicies for opening. + RPArray creators; ///< \ru Журнал построения оболочки тела-инструмента. \en History tree of the shell of the tool solid. + size_t countOne; ///< \ru Разделитель строителей тел-операндов. \en Separator of operand solids creators. + MbToolStampingValues parameters; ///< \ru Параметры штамповки. \en Stamping parameters. + double thickness; ///< \ru Толщина листа. \en The thickness of the sheet metal. + bool punch; ///< \ru Является тело-инструмент пуансоном или матрицей? \en Is tool body a punch or a die. + +public : + MbUserStampSolid( const RPArray & creatorsTool, + const bool sameTool, + const MbItemIndex & faceIndex, + const MbItemIndex & pairFaceIndex, + SArray & pierceIndices, + const MbToolStampingValues & params, + const double thickness, + const bool isPunch, + const MbSNameMaker & names ); +private: + MbUserStampSolid( const MbUserStampSolid &, MbRegDuplicate * iReg ); + +public: + virtual ~MbUserStampSolid(); + + // \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. + + virtual bool CreateShell( MbFaceShell *&shell, MbeCopyMode sameShell, + RPArray *items = NULL ); // \ru Построение оболочки штамповки. \en Construction of a stamping shell. + + // \ru Получить параметры. \en Get the parameters. + void GetParameters( MbToolStampingValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const MbToolStampingValues & params ) { parameters = params; } + +private: + OBVIOUS_PRIVATE_COPY( MbUserStampSolid ) + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserStampSolid ) +}; + +IMPL_PERSISTENT_OPS( MbUserStampSolid ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Построить оболочку из листового материала штамповкой телом-инструментом. + \en Construct a shell form sheet material by tool body stamping. \~ + \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] solid - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] face - \ru Грань штамповки. + \en The face for stamping. \~ \param[in] toolSolid - \ru Оболочка тела-инструмента. \en A shell of tool solid. \~ \param[in] sameShellTool - \ru Режим копирования оболочки тела-инструмента. @@ -118,24 +118,24 @@ IMPL_PERSISTENT_OPS( MbUserStampSolid ) \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 *) CreateUserStamp( MbFaceShell & initialShell, // Исходная оболочка, - const MbeCopyMode sameShell, // флаг способа использования исходной оболочки, - const MbFace & targetFace, // грань штамповки, - const RPArray & creatorsTool, // журнал построения инструмента, - MbFaceShell & toolShell, // оболочка тела-инструмента, - const MbeCopyMode sameShellTool, // флаг способа использования оболочки инструмента, - bool isPunch, // является инструмент пуансоном или матрицей, - const RPArray & pierceFaces, // вскрываемые для вырубки грани инструмента, - const MbUserStampingValues & params, // параметры штамповки, - const MbSNameMaker & nameMaker, // именователь, - MbResultType & res, // флаг успешности операции, - SPtr & resultShell ); // результирующая оболочка. - - -#endif // __CR_USERSTAMP_SOLID_H + \en The resultant solid. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \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 ); // результирующая оболочка. + + +#endif // __CR_USERSTAMP_SOLID_H diff --git a/C3d/Include/cr_stitch_solid.h b/C3d/Include/cr_stitch_solid.h index cbd268a..94f6894 100644 --- a/C3d/Include/cr_stitch_solid.h +++ b/C3d/Include/cr_stitch_solid.h @@ -56,17 +56,20 @@ private: PArray< RPArray > creatorsArray; ///< \ru Множества строителей для каждой сшиваемой оболочки. \en Set of creators for each shell being stitched. bool formSolidBody; ///< \ru Флаг необходимости формирования замкнутой оболочки. \en Whether to construct a closed shell. double stitchPrecision; ///< \ru Максимально допустимое расстояние между сшиваемыми рёбрами. \en Maximal acceptable distance between edges being stitched. + bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). public : template MbStitchedSolid( const PArray & creatorsData, bool tryClosed, double precision, - const MbSNameMaker & names ) - : MbCreator( names ) - , creatorsArray( creatorsData.size(), 1, true ) - , formSolidBody( tryClosed ) - , stitchPrecision( precision ) + const MbSNameMaker & names, + bool edgesMerging ) + : MbCreator ( names ) + , creatorsArray ( creatorsData.size(), 1, true ) + , formSolidBody ( tryClosed ) + , stitchPrecision( precision ) + , mergeEdges ( edgesMerging ) { size_t i, setsCnt = creatorsData.size(); @@ -87,7 +90,7 @@ public : simpleCreators.reserve( estSimpleCnt ); } - SPtr creator; + c3d::CreatorSPtr creator; for ( i = 0; i < setsCnt; ++i ) { Creators * creatorsSet = creatorsData[i]; if ( creatorsSet != NULL ) { @@ -129,8 +132,8 @@ public: 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 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 & ); // \ru Дать базовые объекты \en Get the base objects virtual void GetBasisPoints( MbControlData3D & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. @@ -158,6 +161,7 @@ private: IMPL_PERSISTENT_OPS( MbStitchedSolid ) + //------------------------------------------------------------------------------ /** \brief \ru Построение оболочки сшивки. \en Construction of a shell of stitching. \~ @@ -171,6 +175,8 @@ IMPL_PERSISTENT_OPS( MbStitchedSolid ) \en Maximal acceptable distance between edges being stitched. \~ \param[in] operNames - \ru Именователь операции. \en An object defining names generation in the operation. \~ + \param[in] mergeEdges - \ru Сливать подобные ребра (true). + \en Whether to merge similar edges (true). \~ \param[out] res - \ru Код результата операции выдавливания. \en The extrusion operation result code. \~ \result \ru Возвращает построенную оболочку, если операция была выполнена успешно. @@ -182,9 +188,40 @@ MATH_FUNC (MbFaceShell *) CreateStitchShell( const RPArray & initia bool formSolidBody, double stitchPrecision, const MbSNameMaker & operNames, + bool mergeEdges, MbeStitchResType & res ); +//------------------------------------------------------------------------------ +/** \brief \ru Построение оболочки сшивки. + \en Construction of a shell of stitching. \~ + \details \ru Построение оболочки сшивки. \n + \en Construction of a shell of stitching. \n \~ + \param[in] initialShells - \ru Множество оболочек для сшивки. + \en A set of shells for stitching. \~ + \param[in] formSolidBody - \ru Создавать тело? + \en Whether to create a solid. \~ + \param[in] stitchPrecision - \ru Максимально допустимое расстояние между сшиваемыми рёбрами. + \en Maximal acceptable distance between edges being stitched. \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] mergeEdges - \ru Сливать подобные ребра (true). + \en Whether to merge similar edges (true). \~ + \param[out] res - \ru Код результата операции выдавливания. + \en The extrusion operation result code. \~ + \result \ru Возвращает построенную оболочку, если операция была выполнена успешно. + \en Returns the constructed shell if the operation has been successfully performed. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbFaceShell *) CreateStitchShell( const c3d::ShellsSPtrVector & initialShells, + bool formSolidBody, + double stitchPrecision, + const MbSNameMaker & operNames, + bool mergeEdges, + MbeStitchResType & res ); + + //------------------------------------------------------------------------------ /** \brief \ru Построить оболочку путём сшивки граней. \en Create a shell by faces stitching. \~ @@ -204,6 +241,8 @@ MATH_FUNC (MbFaceShell *) CreateStitchShell( const RPArray & initia \en Maximal acceptable distance between edges being stitched. \~ \param[in] operNames - \ru Именователь операции. \en An object defining names generation in the operation. \~ + \param[in] mergeEdges - \ru Сливать подобные ребра (true). + \en Whether to merge similar edges (true). \~ \param[out] res - \ru Код результата операции выдавливания. \en The extrusion operation result code. \~ \param[out] resultShell - \ru Построенная оболочка. @@ -218,6 +257,7 @@ MATH_FUNC (MbCreator *) CreateStitchedSolid( const PArray< RPArray > bool formSolidBody, double stitchPrecision, const MbSNameMaker & operNames, + bool mergeEdges, MbeStitchResType & res, MbFaceShell *& resultShell ); diff --git a/C3d/Include/cr_surface_spline.h b/C3d/Include/cr_surface_spline.h index 8b95545..ccbe886 100644 --- a/C3d/Include/cr_surface_spline.h +++ b/C3d/Include/cr_surface_spline.h @@ -1,141 +1,141 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель сплайна на поверхности по точками. - \en Constructor of spline on a surface by points. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_SURFACE_SPLINE_H -#define __CR_SURFACE_SPLINE_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCartPoint; -class MATH_CLASS MbSurface; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель пространственного сплайна. - \en Spatial spline constructor. \~ - \details \ru Строитель пространственного сплайна.\n - \en Spatial spline constructor.\n \~ - \ingroup Model_Creators -*/ -// --- -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 - -protected: - MbSurfaceSplineCreator( const MbSurfaceSplineCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor - MbSurfaceSplineCreator( const MbSurfaceSplineCreator & ); // \ru Не реализовано \en Not implemented - 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 ); -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 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 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 - 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 Построить кривую по журналу построения \en Create a curve from the history tree - virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); - - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbSurfaceSplineCreator & ); // \ru Не реализовано!!! \en Not implemented!!! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSurfaceSplineCreator ) -}; - -IMPL_PERSISTENT_OPS( MbSurfaceSplineCreator ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создать кривую на поверхности. - \en Create a curve on a surface. \~ - \details \ru Создать кривую на поверхности. \n - Примечания: \n - 1. Если есть сопряжения, то количество сопряжений д.б. равно количеству точек. \n - Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n - 2. Если сплайн строится через точки, то сопряжения могуть быть заданы произвольно. \n - 2. Если сплайн строится по полюсам и он незамкнут, то сопряжения могут быть только на концах. \n - 3. Если сплайн строится по полюсам и он замкнут, то сопряжения должны отсутствовать. \n - 4. Множество весов д.б. пуст или синхронизирован с массивом точек по количеству (с опцией throughPoints веса игнорируются). \n - \en Create a curve on a surface. \n - Notes: \n - 1. If the tangents are specified, then the number of tangents should be equal to the number of points. \n - Missing tangents should be represented by null pointers in the array \n - 2. If the spline is created from points, arbitrary tangents can be defined. \n - 2. If the spline is created from poles and it is open, only the end tangents can be specified. \n - 3. If the spline is constructed from poles and it is closed, the tangents cannot be specified. \n - 4. The weight array should be empty or synchronized with the point array by size (with option throughPoints the weights are ignored). \n \~ - \param[in] surface - \ru Поверхность. - \en The surface. \~ - \param[in] throughPoints - \ru Провести сплайн через точки. - \en Create a spline through points. \~ - \param[in] paramPnts - \ru Множество параметрических точкек. - \en Parametric point array. \~ - \param[in] paramWts - \ru Множество весов параметрических точек. - \en An array of parametric point weights. \~ - \param[in] paramClosed - \ru Строить замкнутый параметрический сплайн. - \en Create a closed parametric spline. \~ - \param[in] spaceTransitions - \ru Сопряжения в точках. - \en Tangents at the points. \~ - \param[in] snMaker - \ru Именователь кривых каркаса. - \en An object defining the frame curves names. \~ - \param[out] resType - \ru Код результата операции - \en Operation result code \~ - \param[out] resCurves - \ru Множество эквидистантных кривых. - \en Offset curve array. \~ - \return \ru Возвращает строитель. - \en Returns the constructor. \~ - \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 ); - - -#endif // __CR_SURFACE_SPLINE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель сплайна на поверхности по точками. + \en Constructor of spline on a surface by points. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_SURFACE_SPLINE_H +#define __CR_SURFACE_SPLINE_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCartPoint; +class MATH_CLASS MbSurface; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель пространственного сплайна. + \en Spatial spline constructor. \~ + \details \ru Строитель пространственного сплайна.\n + \en Spatial spline constructor.\n \~ + \ingroup Model_Creators +*/ +// --- +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 + +protected: + MbSurfaceSplineCreator( const MbSurfaceSplineCreator &, MbRegDuplicate * iReg ); // \ru Конструктор копирования \en Copy-constructor + MbSurfaceSplineCreator( const MbSurfaceSplineCreator & ); // \ru Не реализовано \en Not implemented + 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 ); +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 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 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 + 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 Построить кривую по журналу построения \en Create a curve from the history tree + virtual bool CreateWireFrame( MbWireFrame *&, MbeCopyMode, RPArray * items = NULL ); + + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbSurfaceSplineCreator & ); // \ru Не реализовано!!! \en Not implemented!!! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSurfaceSplineCreator ) +}; + +IMPL_PERSISTENT_OPS( MbSurfaceSplineCreator ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создать кривую на поверхности. + \en Create a curve on a surface. \~ + \details \ru Создать кривую на поверхности. \n + Примечания: \n + 1. Если есть сопряжения, то количество сопряжений д.б. равно количеству точек. \n + Отсутствующие сопряжения должны быть представлены нулевыми указателями в массиве \n + 2. Если сплайн строится через точки, то сопряжения могуть быть заданы произвольно. \n + 2. Если сплайн строится по полюсам и он незамкнут, то сопряжения могут быть только на концах. \n + 3. Если сплайн строится по полюсам и он замкнут, то сопряжения должны отсутствовать. \n + 4. Множество весов д.б. пуст или синхронизирован с массивом точек по количеству (с опцией throughPoints веса игнорируются). \n + \en Create a curve on a surface. \n + Notes: \n + 1. If the tangents are specified, then the number of tangents should be equal to the number of points. \n + Missing tangents should be represented by null pointers in the array \n + 2. If the spline is created from points, arbitrary tangents can be defined. \n + 2. If the spline is created from poles and it is open, only the end tangents can be specified. \n + 3. If the spline is constructed from poles and it is closed, the tangents cannot be specified. \n + 4. The weight array should be empty or synchronized with the point array by size (with option throughPoints the weights are ignored). \n \~ + \param[in] surface - \ru Поверхность. + \en The surface. \~ + \param[in] throughPoints - \ru Провести сплайн через точки. + \en Create a spline through points. \~ + \param[in] paramPnts - \ru Множество параметрических точкек. + \en Parametric point array. \~ + \param[in] paramWts - \ru Множество весов параметрических точек. + \en An array of parametric point weights. \~ + \param[in] paramClosed - \ru Строить замкнутый параметрический сплайн. + \en Create a closed parametric spline. \~ + \param[in] spaceTransitions - \ru Сопряжения в точках. + \en Tangents at the points. \~ + \param[in] snMaker - \ru Именователь кривых каркаса. + \en An object defining the frame curves names. \~ + \param[out] resType - \ru Код результата операции + \en Operation result code \~ + \param[out] resCurves - \ru Множество эквидистантных кривых. + \en Offset curve array. \~ + \return \ru Возвращает строитель. + \en Returns the constructor. \~ + \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 ); + + +#endif // __CR_SURFACE_SPLINE_H diff --git a/C3d/Include/cr_transformed_solid.h b/C3d/Include/cr_transformed_solid.h index 7863eb7..d7b1c5f 100644 --- a/C3d/Include/cr_transformed_solid.h +++ b/C3d/Include/cr_transformed_solid.h @@ -1,114 +1,114 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Строитель трансформируемой оболочки. - \en Constructor of a transformed shell. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CR_TRANSFORMED_SOLID_H -#define __CR_TRANSFORMED_SOLID_H - - -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель трансформируемой оболочки. - \en Constructor of a transformed shell. \~ - \details \ru Строитель трансформируемой оболочки, матрица преобразования которой - получена по изменению положения контрольных точек габаритного куба. \n - \en Constructor of a transformed shell the transformation matrix of which - is obtained due to the change of bounding box control points positions. \n \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbTransformedSolid : public MbCreator { -protected: - TransformValues parameters; ///< \ru Параметры преобразования оболочки. \en Parameters of a shell transformation. - MbCube cube; ///< \ru Габаритный куб. \en Bounding box. - SArray cubePoints; ///< \ru Контрольные точки куба. \en Control points of the bounding box. - -public: // \ru Конструктор по параметрам \en Constructor by parameters - MbTransformedSolid( const TransformValues &, const MbCube &, const MbSNameMaker & ); -private: // \ru Конструктор дублирующий \en Duplication constructor - MbTransformedSolid( const MbTransformedSolid &, MbRegDuplicate * ireg ); - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbTransformedSolid( const MbTransformedSolid & ); - -public: // \ru Деструктор \en Destructor - ~MbTransformedSolid(); - -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 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 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 - 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 Построение оболочки \en Creation of a shell - virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, - RPArray * items = 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 & ); - - // \ru Дать параметры. \en Get the parameters. - void GetParameters( TransformValues & params ) const { params = parameters; } - // \ru Установить параметры. \en Set the parameters. - void SetParameters( const TransformValues & params ) { parameters = params; } - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbTransformedSolid & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformedSolid ) -}; - -IMPL_PERSISTENT_OPS( MbTransformedSolid ) - -//------------------------------------------------------------------------------ -/** \brief \ru Создание строителя масштабированной оболочки. - \en Creation of constructor of a scaled shell. \~ - \details \ru Построить оболочку путём трансформации исходной оболочки по матрице преобразования, - полученной по изменению положения контрольных точек габаритного куба.\n - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Create a shell by transformation of the source shell according to the transformation matrix - obtained due to the change of the bounding box control points positions.\n - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] outer - \ru Исходная оболочка. - \en The source shell. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the source shell. \~ - \param[in] parameters - \ru Параметры модификации. - \en Parameters of the modification. \~ - \param[in] names - \ru Именователь операции. - \en An object defining names generation in the operation. \~ - \param[out] res - \ru Код результата операции выдавливания. - \en The extrusion operation result code. \~ - \param[out] shell - \ru Построенная оболочка. - \en The resultant shell. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \ingroup Model_Creators -*/ -// --- -MATH_FUNC (MbCreator *) CreateTransformedSolid( MbFaceShell * outer, - MbeCopyMode sameShell, - const TransformValues & parameters, - const MbSNameMaker & names, - MbResultType & res, - MbFaceShell *& shell ); - - -#endif // __CR_TRANSFORMED_SOLID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Строитель трансформируемой оболочки. + \en Constructor of a transformed shell. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CR_TRANSFORMED_SOLID_H +#define __CR_TRANSFORMED_SOLID_H + + +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель трансформируемой оболочки. + \en Constructor of a transformed shell. \~ + \details \ru Строитель трансформируемой оболочки, матрица преобразования которой + получена по изменению положения контрольных точек габаритного куба. \n + \en Constructor of a transformed shell the transformation matrix of which + is obtained due to the change of bounding box control points positions. \n \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbTransformedSolid : public MbCreator { +protected: + TransformValues parameters; ///< \ru Параметры преобразования оболочки. \en Parameters of a shell transformation. + MbCube cube; ///< \ru Габаритный куб. \en Bounding box. + SArray cubePoints; ///< \ru Контрольные точки куба. \en Control points of the bounding box. + +public: // \ru Конструктор по параметрам \en Constructor by parameters + MbTransformedSolid( const TransformValues &, const MbCube &, const MbSNameMaker & ); +private: // \ru Конструктор дублирующий \en Duplication constructor + MbTransformedSolid( const MbTransformedSolid &, MbRegDuplicate * ireg ); + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbTransformedSolid( const MbTransformedSolid & ); + +public: // \ru Деструктор \en Destructor + ~MbTransformedSolid(); + +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 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 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 + 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 Построение оболочки \en Creation of a shell + virtual bool CreateShell( MbFaceShell *&, MbeCopyMode sameShell, + RPArray * items = 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 & ); + + // \ru Дать параметры. \en Get the parameters. + void GetParameters( TransformValues & params ) const { params = parameters; } + // \ru Установить параметры. \en Set the parameters. + void SetParameters( const TransformValues & params ) { parameters = params; } + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbTransformedSolid & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTransformedSolid ) +}; + +IMPL_PERSISTENT_OPS( MbTransformedSolid ) + +//------------------------------------------------------------------------------ +/** \brief \ru Создание строителя масштабированной оболочки. + \en Creation of constructor of a scaled shell. \~ + \details \ru Построить оболочку путём трансформации исходной оболочки по матрице преобразования, + полученной по изменению положения контрольных точек габаритного куба.\n + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Create a shell by transformation of the source shell according to the transformation matrix + obtained due to the change of the bounding box control points positions.\n + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] outer - \ru Исходная оболочка. + \en The source shell. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the source shell. \~ + \param[in] parameters - \ru Параметры модификации. + \en Parameters of the modification. \~ + \param[in] names - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[out] res - \ru Код результата операции выдавливания. + \en The extrusion operation result code. \~ + \param[out] shell - \ru Построенная оболочка. + \en The resultant shell. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \ingroup Model_Creators +*/ +// --- +MATH_FUNC (MbCreator *) CreateTransformedSolid( MbFaceShell * outer, + MbeCopyMode sameShell, + const TransformValues & parameters, + const MbSNameMaker & names, + MbResultType & res, + MbFaceShell *& shell ); + + +#endif // __CR_TRANSFORMED_SOLID_H diff --git a/C3d/Include/cr_truncated_shell.h b/C3d/Include/cr_truncated_shell.h index c40689e..8f4da09 100644 --- a/C3d/Include/cr_truncated_shell.h +++ b/C3d/Include/cr_truncated_shell.h @@ -1,156 +1,156 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Построение усеченной оболочки. - \en Construction of a truncated shell. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TRUNCATED_SHELL_H -#define __TRUNCATED_SHELL_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbSpaceItem; -class MATH_CLASS MbPlacement3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbFace; -class MATH_CLASS MbSolid; -class MATH_CLASS MbSNameMaker; -struct MATH_CLASS MbMergingFlags; - - -//------------------------------------------------------------------------------ -/** \brief \ru Строитель усеченной оболочки. - \en Constructor of a truncated shell. \~ - \details \ru Строитель усеченной оболочки режет исходную оболочку на части указанными элементами, - которыми могут служить двумерные кривые в локальной системе координат, трёхмерные кривые, поверхности и оболочки. \n - \en Constructor of a truncated shell cuts the initial shell into parts by the specified elements - which can be two-dimensional curves in the local coordinate system, three-dimensional curves, surfaces and shells. \n \~ - \ingroup Model_Creators -*/ -// --- -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. - 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 & ); - /// \ru Конструктор по трехмерным кривым. \en Constructor by three-dimensional curves. - MbTruncatedShell( const RPArray &, bool same, - const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); - /// \ru Конструктор по поверхностям. \en Constructor by surfaces. - MbTruncatedShell( const RPArray &, bool same, - const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); - /// \ru Конструктор по строителям тела. \en Constructor by solid creators. - MbTruncatedShell( const MbSolid &, bool same, bool keepShell, - bool orient, const MbMergingFlags &, const MbSNameMaker & ); - - virtual ~MbTruncatedShell(); - -private: - MbTruncatedShell( const MbTruncatedShell &, MbRegDuplicate * ); - -public: - 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 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 - 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. - virtual size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. - virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. - virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ); // \ru Получить внутренние построители по типу. \en Get internal creators by type. - - 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 - - // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data - virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, - RPArray * items = NULL ); - - // \ru Установить номера выбраных граней усекаемого тела \en Set indices of selected faces of the solid being truncated. - void SetSelIndices( const std::vector & selInds ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTruncatedShell ) -OBVIOUS_PRIVATE_COPY( MbTruncatedShell ) -}; - -IMPL_PERSISTENT_OPS( MbTruncatedShell ) - -//------------------------------------------------------------------------------ -/** \brief \ru Построить усечённую оболочку. - \en Build a truncated shell. \~ - \details \ru Построить усечённую оболочку резкой исходного тела на части указанными элементами, - которыми могут служить двумерные кривые в локальной системе координат, трёхмерные кривые, поверхности и оболочки. - Одновременно с построением оболочки функция создаёт её строитель.\n - \en Construct a truncated shell by cutting the initial solid into parts by the specified elements - which can be two-dimensional curves in the local coordinate system, three-dimensional curves, surfaces and shells. - The function simultaneously creates the shell and its constructor.\n \~ - \param[in] initSolid - \ru Исходное тело. - \en The initial solid. \~ - \param[in] selIndices - \ru Идентификаторы выбранныых граней, приотсутствии - всё тело. - \en Identifiers of selected faces, if not specified - the whole solid. \~ - \param[in] sameShell - \ru Режим копирования исходной оболочки. - \en Mode of copying the initial shell. \~ - \param[in] operNames - \ru Именователь граней. - \en An object for naming faces. \~ - \param[in] items - \ru Усекающие объекты. - \en Truncating objects. \~ - \param[in] orients - \ru Ориентация усекающих объектов. - \en The truncating objects orientation. \~ - \param[in] curvesSplitMode - \ru Кривые используются как линии разъема. - \en The curves are used as parting lines. \~ - \param[in] solidsCopyMode - \ru Режим копирования усекающих объектов. - \en Mode of copying the truncating objects. \~ - \param[in] mergeFlags - \ru Флаги слияния элементов оболочки. - \en Control flags of shell items merging. \~ - \param[out] res - \ru Код результата операции. - \en Operation result code. \~ - \param[out] resShell - \ru Построенная усеченная оболочка. - \en Constructed truncated shell. \~ - \param[out] resDir - \ru Направление фантома усечения. - \en Direction of truncation phantom. \~ - \result \ru Возвращает строитель оболочки. - \en Returns the shell constructor. \~ - \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 ); - - -#endif // __TRUNCATED_SHELL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Построение усеченной оболочки. + \en Construction of a truncated shell. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TRUNCATED_SHELL_H +#define __TRUNCATED_SHELL_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbSpaceItem; +class MATH_CLASS MbPlacement3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbFace; +class MATH_CLASS MbSolid; +class MATH_CLASS MbSNameMaker; +struct MATH_CLASS MbMergingFlags; + + +//------------------------------------------------------------------------------ +/** \brief \ru Строитель усеченной оболочки. + \en Constructor of a truncated shell. \~ + \details \ru Строитель усеченной оболочки режет исходную оболочку на части указанными элементами, + которыми могут служить двумерные кривые в локальной системе координат, трёхмерные кривые, поверхности и оболочки. \n + \en Constructor of a truncated shell cuts the initial shell into parts by the specified elements + which can be two-dimensional curves in the local coordinate system, three-dimensional curves, surfaces and shells. \n \~ + \ingroup Model_Creators +*/ +// --- +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. + 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 & ); + /// \ru Конструктор по трехмерным кривым. \en Constructor by three-dimensional curves. + MbTruncatedShell( const RPArray &, bool same, + const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); + /// \ru Конструктор по поверхностям. \en Constructor by surfaces. + MbTruncatedShell( const RPArray &, bool same, + const SArray & orients, const MbMergingFlags &, const MbSNameMaker & ); + /// \ru Конструктор по строителям тела. \en Constructor by solid creators. + MbTruncatedShell( const MbSolid &, bool same, bool keepShell, + bool orient, const MbMergingFlags &, const MbSNameMaker & ); + + virtual ~MbTruncatedShell(); + +private: + MbTruncatedShell( const MbTruncatedShell &, MbRegDuplicate * ); + +public: + 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 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 + 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. + virtual size_t GetCreatorsCount( MbeCreatorType ct ) const; // \ru Посчитать внутренние построители по типу. \en Count internal creators by type. + virtual bool GetInternalCreators( MbeCreatorType, c3d::ConstCreatorsSPtrVector & ) const; // \ru Получить внутренние построители по типу. \en Get internal creators by type. + virtual bool SetInternalCreators( MbeCreatorType, c3d::CreatorsSPtrVector & ); // \ru Получить внутренние построители по типу. \en Get internal creators by type. + + 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 + + // \ru Построение оболочки по исходным данным \en Construction of a shell from the given data + virtual bool CreateShell( MbFaceShell *& shell, MbeCopyMode sameShell, + RPArray * items = NULL ); + + // \ru Установить номера выбраных граней усекаемого тела \en Set indices of selected faces of the solid being truncated. + void SetSelIndices( const std::vector & selInds ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTruncatedShell ) +OBVIOUS_PRIVATE_COPY( MbTruncatedShell ) +}; + +IMPL_PERSISTENT_OPS( MbTruncatedShell ) + +//------------------------------------------------------------------------------ +/** \brief \ru Построить усечённую оболочку. + \en Build a truncated shell. \~ + \details \ru Построить усечённую оболочку резкой исходного тела на части указанными элементами, + которыми могут служить двумерные кривые в локальной системе координат, трёхмерные кривые, поверхности и оболочки. + Одновременно с построением оболочки функция создаёт её строитель.\n + \en Construct a truncated shell by cutting the initial solid into parts by the specified elements + which can be two-dimensional curves in the local coordinate system, three-dimensional curves, surfaces and shells. + The function simultaneously creates the shell and its constructor.\n \~ + \param[in] initSolid - \ru Исходное тело. + \en The initial solid. \~ + \param[in] selIndices - \ru Идентификаторы выбранныых граней, приотсутствии - всё тело. + \en Identifiers of selected faces, if not specified - the whole solid. \~ + \param[in] sameShell - \ru Режим копирования исходной оболочки. + \en Mode of copying the initial shell. \~ + \param[in] operNames - \ru Именователь граней. + \en An object for naming faces. \~ + \param[in] items - \ru Усекающие объекты. + \en Truncating objects. \~ + \param[in] orients - \ru Ориентация усекающих объектов. + \en The truncating objects orientation. \~ + \param[in] curvesSplitMode - \ru Кривые используются как линии разъема. + \en The curves are used as parting lines. \~ + \param[in] solidsCopyMode - \ru Режим копирования усекающих объектов. + \en Mode of copying the truncating objects. \~ + \param[in] mergeFlags - \ru Флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[out] res - \ru Код результата операции. + \en Operation result code. \~ + \param[out] resShell - \ru Построенная усеченная оболочка. + \en Constructed truncated shell. \~ + \param[out] resDir - \ru Направление фантома усечения. + \en Direction of truncation phantom. \~ + \result \ru Возвращает строитель оболочки. + \en Returns the shell constructor. \~ + \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 ); + + +#endif // __TRUNCATED_SHELL_H diff --git a/C3d/Include/cr_union_solid.h b/C3d/Include/cr_union_solid.h index e25208b..b0851e5 100644 --- a/C3d/Include/cr_union_solid.h +++ b/C3d/Include/cr_union_solid.h @@ -11,6 +11,7 @@ #include #include +#include #include @@ -27,15 +28,38 @@ class MATH_CLASS MbUnionSolid : public MbCreator { protected : c3d::CreatorsSPtrVector creators; ///< \ru Набор данных для построения исходных оболочек. \en Data set for construction of the source shells. - c3d::IndicesVector countNumbers; ///< \ru Индекс начального строителя для следующей оболочки. \en Index of the source creator for the next shell. + c3d::IndicesVector countNumbers; ///< \ru Индексы начального строителя для следующей оболочки. \en Indices of the source creator for the next shell. c3d::IndicesVector sharedLinks; ///< \ru Номера общих наборов строителей для оболочек. \en Numbers of common creators sets for shells. - size_t sharedCount; ///< \ru Количество общих набор строителей. \en The number of common creators sets. + size_t sharedCount; ///< \ru Количество общих наборов строителей. \en The number of common creators sets. OperationType operation; ///< \ru Тип булевой операции над оболочками. \en Type of Boolean operation on shells. bool checkIntersection; ///< \ru Проверять ли на пересечение тела. \en Whether to check the solids for intersection. - bool mergeFaces; ///< \ru Объединять подобные грани (true). \en Whether to union similar faces (true). + MbMergingFlags mergeFlags; ///< \ru Управляющие флаги слияния элементов оболочки. \en Control flags of shell items merging double buildSag; ///< \ru Угловое отклонение при движении по кривым и поверхностям. \en Angular deviation while moving along curves and surfaces. public : + /** \brief \ru Конструктор по параметрам. + \en Constructor by operation parameters. \~ + \details \ru Конструктор по параметрам. \n + \en Constructor by operation parameters. \n \~ + \param[in] creators - \ru Построители оболочек. + \en Shells creators. \~ + \param[in] sameCreators - \ru Использовать оригиналы построителей. + \en Use creators originals (true). \~ + \param[in] countNumbers - \ru Индексы начального строителя для следующей оболочки. + \en Indices of the source creator for the next shell. \~ + \param[in] sharedCnt - \ru Количество общих наборов строителей. + \en The number of common creators sets. \~ + \param[in] sharedLinks - \ru Номера общих наборов строителей для оболочек. + \en Numbers of common creators sets for shells. \~ + \param[in] operType - \ru Тип булевой операции над оболочками. + \en Type of Boolean operation on shells. \~ + \param[in] checkIntersection - \ru Проверять ли на пересечение тела. + \en Whether to check the solids for intersection. \~ + \param[in] mergeFlags - \ru Управляющие флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ + \param[in] nameMaker - \ru Именователь. + \en Names maker. \~ + */ MbUnionSolid( const c3d::CreatorsSPtrVector & creators, bool sameCreators, const c3d::IndicesVector & countNumbers, @@ -43,7 +67,7 @@ public : const c3d::IndicesVector & sharedLinks, OperationType operType, bool checkIntersection, - bool mergeFaces, + const MbMergingFlags & mergeFlags, const MbSNameMaker & nameMaker ); private : MbUnionSolid( const MbUnionSolid &, MbRegDuplicate * ); @@ -132,8 +156,8 @@ IMPL_PERSISTENT_OPS( MbUnionSolid ) \en A Boolean operation type. \~ \param[in] checkIntersect - \ru Проверять ли пересечение оболочек. \en Whether to check shells intersection. \~ - \param[in] mergeFaces - \ru Сливать подобные грани. - \en Whether to merge similar faces. \~ + \param[in] mergeFlags - \ru Управляющие флаги слияния элементов оболочки. + \en Control flags of shell items merging. \~ \param[in] operNames - \ru Именователь операции. \en An object defining names generation in the operation. \~ \param[in] isArray - \ru Являются ли оболочки размноженными по прямоугольной сетке копиями? @@ -157,7 +181,7 @@ MATH_FUNC (MbCreator *) CreateUnion( MbFaceShell * solid, MbeCopyMode sameShells, OperationType oType, bool checkIntersect, - bool mergeFaces, + const MbMergingFlags & mergeFlags, const MbSNameMaker & operNames, bool isArray, // \ru Флаг массива \en Flag of array MbResultType & res, diff --git a/C3d/Include/creator.h b/C3d/Include/creator.h index 78c2f0d..5eaeba2 100644 --- a/C3d/Include/creator.h +++ b/C3d/Include/creator.h @@ -136,6 +136,7 @@ enum MbeCreatorType { ct_SimplifyFlatSolid = 618, ///< \ru Строитель упрощения развёртки листового тела. \en Constructor of the sheet solid flat pattern simplification. ct_UserStampSolid = 619, ///< \ru Строитель оболочки с штамповкой телом. \en Constructor of a shell with stamping by solid. ct_RemoveOperationSolid = 620, ///< \ru Строитель удаления операции листового тела. \en Constructor of removing of the sheet solid. + ct_BuildSheetMetalSolid = 621, ///< \ru Строитель листового тела по произвольному телу. \en Constructor of building sheet metal solid based on an arbitary solid. // \ru Строители оболочек. \en Creators of shells. ct_JoinShell = 701, ///< \ru Строитель оболочки соединения. \en Constructor of a joint shell. @@ -147,6 +148,7 @@ enum MbeCreatorType { ct_PatchSetCreator = 707, ///< \ru Строитель заплатки по кривым на оболочке. \en Constructor of a patch by curves on the shell. ct_FilletShell = 708, ///< \ru Строитель оболочки грани соединения. \en Constructor of a shell of a fillet face. ct_MedianShell = 709, ///< \ru Строитель срединной оболочки тела. \en Constructor of a median shell of solid. \n + ct_SectionShell = 710, ///< \ru Строитель оболочки на поверхности переменного сечения. \en Constructor of the shell on swept mutable section surface. \n // \ru Строители других объектов (вставлять новые типы перед этим типом). \en Creators of the other objects (insert new types before this type). ct_AttributeProvider = 801, ///< \ru Поставщик атрибутов для примитивов оболочки. \en Attribute provider for the shell primitives. @@ -463,12 +465,14 @@ public : virtual void SetYourVersion( VERSION version, bool forAll ); /// \ru Выдать версию объекта. \en Get the object version. VERSION GetYourVersion() const { return names.GetMathVersion(); } + /// \ru Выдать именователь объекта. \en Get the name-maker. - const MbSNameMaker & GetYourName() const { return names; } + const MbSNameMaker & GetYourNameMaker() const { return names; } /// \ru Выдать именователь объекта для редактирования. \en Get the object's name-maker for editing. - MbSNameMaker & SetYourName() { return names; } + MbSNameMaker & SetYourNameMaker() { return names; } /// \ru Установить именователь объекта. \en Set the object's name-maker. - void SetName( const MbSNameMaker & n ) { names.SetName( n ); } + void SetNameMaker( const MbSNameMaker & n ) { names.SetNameMaker( n ); } + /// \ru Выдать главное имя объекта. \en Get the main name of the object. SimpleName GetMainName() const { return names.GetMainName(); } /// \ru Установить главное имя объекта. \en Set the main name of the object. @@ -489,7 +493,7 @@ public : The function sets a flag that allow to write the object once and to use the references to the recorded instance in the other records. Reading is performed once too, in other cases of reading the address of the already read object is used. \~ */ - void PrepareWrite() { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } /** \} */ private: diff --git a/C3d/Include/creator_transaction.h b/C3d/Include/creator_transaction.h index 6c5368f..430c7ac 100644 --- a/C3d/Include/creator_transaction.h +++ b/C3d/Include/creator_transaction.h @@ -1,159 +1,159 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Журнал построения объекта. - \en The history tree of object. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CREATOR_TRANSACTION_H -#define __CREATOR_TRANSACTION_H - - -#include -#include -#include -#include - - -class MATH_CLASS reader; -class MATH_CLASS writer; -class MATH_CLASS IProgressIndicator; -class MATH_CLASS MbCartPoint3D; -class MATH_CLASS MbVector3D; -class MATH_CLASS MbAxis3D; -class MATH_CLASS MbMatrix3D; -class MATH_CLASS MbSpaceItem; -class MATH_CLASS MbFaceShell; -class MATH_CLASS MbWireFrame; -class MATH_CLASS MbPointFrame; -class MATH_CLASS MbProperties; -struct MATH_CLASS MbControlData3D; -class MbRegDuplicate; -class MbRegTransform; -enum MbeCopyMode; - - -//------------------------------------------------------------------------------ -/** \brief \ru Журнал построения объекта. - \en The history tree of object. \~ - \details \ru Журнал построения содержит упорядоченное множество строителей, - последовательная работа которых строит объект. \n - Неактивные строители (с состоянием mps_Skip) не принимают участия в построении объекта. - \en The history tree contains an ordered set of creators - whose successive work creates the objects. \n - Inactive creators (with state mps_Skip) are not used in the object construction. \~ - \ingroup Model_Creators -*/ -// --- -class MATH_CLASS MbTransactions -{ -private: - c3d::CreatorsVector transactions; ///< \ru Упорядоченное множество строителей. \en An ordered set of creators. - -protected: - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with registrator. - MbTransactions( const MbTransactions &, MbRegDuplicate * iReg ); -public: - /// \ru Конструктор без параметров. \en Constructor without parameters. - MbTransactions(); - /// \ru Конструктор по строителям. \en Constructor by creators. - template - MbTransactions( const Creators & creators ) - : transactions() - { - size_t iCount = creators.size(); - if ( iCount > 0 ) { - transactions.reserve( iCount ); - for ( size_t i = 0; i < iCount; i++ ) { - MbCreator * creator = const_cast( creators[i] ); - if ( creator != NULL ) { - creator->AddRef(); - transactions.push_back( creator ); - } - } - } - } - - /// \ru Деструктор. \en Destructor. - virtual ~MbTransactions(); -public: - - /// \ru Перестроить объект по протоколу построения. \en Reconstruct object according to the history tree. - 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; - /// \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; - /// \ru Преобразовать согласно матрице строители. \en Transform the creators according to the matrix. - void CreatorsTransform( const MbMatrix3D &, MbRegTransform * = NULL ); - /// \ru Сдвинуть вдоль вектора строители. \en Move creators along the vector. - void CreatorsMove ( const MbVector3D &, MbRegTransform * = NULL ); - /// \ru Повернуть вокруг оси строители на заданный угол. \en Rotate the creators about the axis by the given angle. - void CreatorsRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); - /// \ru Выдать количество строителей. \en Get the creators count. - size_t GetCreatorsCount() const { return transactions.size(); } - /// \ru Зарезервировать место для строителей. \en Reserve space for creators. - void Reserve( size_t count ) { transactions.reserve( transactions.size() + count ); } - /// \ru Выдать строитель по его индексу. \en Get constructor by its index. - const MbCreator * GetCreator( size_t ind ) const; - /// \ru Выдать строитель по его индексу с возможностью редактирования. \en Get constructor by its index with possibility of editing. - MbCreator * SetCreator( size_t ind ); - /// \ru Добавить свои строители в присланный массив. \en Add your own creators to the given array. - virtual bool GetCreators( RPArray & ) const; - /// \ru Добавить свои строители в присланный массив. \en Add your own creators to the given array. - virtual bool GetCreators( c3d::CreatorsSPtrVector & ) const; - /// \ru Добавить копии своих строителей в присланный массив. \en Add copies of your own creators to the given array. - bool GetCreatorsCopies( RPArray & ) const; - /// \ru Добавить копии своих строителей в присланный массив. \en Add copies of your own creators to the given array. - bool GetCreatorsCopies( c3d::CreatorsSPtrVector & ) const; - /// \ru Найти номер строителя в журнале или вернуть SYS_MAX_T в случае отсутствия. \en Find the number of creators in the history tree or return SYS_MAX_T if it is absent. - size_t FindCreator( const MbCreator * creator ); - /// \ru Добавить строитель (addSame = false) или его копию (addSame = true) в журнал. \en Add the constructor (addSame = false) or its copy (addSame = true) to the history tree. - bool AddCreator ( const MbCreator &, bool addSame = false ); - /// \ru Добавить строитель (addSame = false) или его копию (addSame = true) в журнал. \en Add the constructor (addSame = false) or its copy (addSame = true) to the history tree. - bool AddCreator ( const MbCreator *, bool addSame = false ); - /// \ru Добавить строители в журнал. \en Add creators to the history tree. - void AddCreators( const RPArray & ); - /// \ru Вытереть строитель с указанным номером из журнала и отдать его. \en Remove the constructor with the specified index from the history tree and return it. - MbCreator * DetachCreator ( size_t ind ); - /// \ru Удалить строитель с указанным номером и вытереть его из журнала. \en Delete the constructor with the specified index and remove it from the history tree. - bool DeleteCreator ( size_t ind ); - /// \ru Удалить все строители и очистить журнал. \en Delete all the creators and clear the history tree. - void DeleteCreators(); - /// \ru Дать статус строителя с указанным номером. \en Get the status of creator with the specified index. - int GetCreatorStatus( size_t ind ) const; - /// \ru Установить строителю с указанным номером статус. \en Set status to creator with the specified index. - bool SetCreatorStatus( size_t ind, MbeProcessState ); - /// \ru Дать количество активных строителей. \en Get the active creators count. - size_t GetActiveCreatorsCount() const; - /// \ru Установить количество активных строителей от начала до заданного номера. \en Set the count of active creators from the beginning to the given index. - bool SetActiveCreatorsCount( size_t activeCount ); - /// \ru Выдать создаваемый заданным числом строителей объект и базовые объекты остальных строителей. \en Get the object created by the specified number of creators and the basis items of the other creators. - void BreakCreatorsToBasisItem( size_t c, RPArray & ); - /// \ru Выдать базовые объекты строителей. \en Get the basis items of the creators. - void GetCreatorsBasisItems ( RPArray & ); - /// \ru Выдать базовые точки строителей. \en Get the basis points of the creators. - void GetCreatorsBasisPoints( MbControlData3D & ) const; - /// \ru Изменить объект по контрольным точкам. \en Change the object by control points. - void SetCreatorsBasisPoints( const MbControlData3D & ); - /// \ru Выдать свойства строителей (на копиях или на оригиналах строителей). \en Get properties of the creators (using original creators or their copies). - void GetProperties( MbProperties &, bool sameCreators = false ); - /// \ru Установить свойства строителей. \en Set properties of the creators. - void SetProperties( const MbProperties & ); - /// \ru Прочитать строители из потока. \en Read creators from the stream. - void CreatorsRead ( reader & in ); - /// \ru Записать строители в поток. \en Write creators to the stream. - void CreatorsWrite( writer & out ) const; - -OBVIOUS_PRIVATE_COPY( MbTransactions ) -}; - - -#endif // __CREATOR_TRANSACTION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Журнал построения объекта. + \en The history tree of object. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CREATOR_TRANSACTION_H +#define __CREATOR_TRANSACTION_H + + +#include +#include +#include +#include + + +class MATH_CLASS reader; +class MATH_CLASS writer; +class MATH_CLASS IProgressIndicator; +class MATH_CLASS MbCartPoint3D; +class MATH_CLASS MbVector3D; +class MATH_CLASS MbAxis3D; +class MATH_CLASS MbMatrix3D; +class MATH_CLASS MbSpaceItem; +class MATH_CLASS MbFaceShell; +class MATH_CLASS MbWireFrame; +class MATH_CLASS MbPointFrame; +class MATH_CLASS MbProperties; +struct MATH_CLASS MbControlData3D; +class MbRegDuplicate; +class MbRegTransform; +enum MbeCopyMode; + + +//------------------------------------------------------------------------------ +/** \brief \ru Журнал построения объекта. + \en The history tree of object. \~ + \details \ru Журнал построения содержит упорядоченное множество строителей, + последовательная работа которых строит объект. \n + Неактивные строители (с состоянием mps_Skip) не принимают участия в построении объекта. + \en The history tree contains an ordered set of creators + whose successive work creates the objects. \n + Inactive creators (with state mps_Skip) are not used in the object construction. \~ + \ingroup Model_Creators +*/ +// --- +class MATH_CLASS MbTransactions +{ +private: + c3d::CreatorsVector transactions; ///< \ru Упорядоченное множество строителей. \en An ordered set of creators. + +protected: + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with registrator. + MbTransactions( const MbTransactions &, MbRegDuplicate * iReg ); +public: + /// \ru Конструктор без параметров. \en Constructor without parameters. + MbTransactions(); + /// \ru Конструктор по строителям. \en Constructor by creators. + template + MbTransactions( const Creators & creators ) + : transactions() + { + size_t iCount = creators.size(); + if ( iCount > 0 ) { + transactions.reserve( iCount ); + for ( size_t i = 0; i < iCount; i++ ) { + MbCreator * creator = const_cast( creators[i] ); + if ( creator != NULL ) { + creator->AddRef(); + transactions.push_back( creator ); + } + } + } + } + + /// \ru Деструктор. \en Destructor. + virtual ~MbTransactions(); +public: + + /// \ru Перестроить объект по протоколу построения. \en Reconstruct object according to the history tree. + 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; + /// \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; + /// \ru Преобразовать согласно матрице строители. \en Transform the creators according to the matrix. + void CreatorsTransform( const MbMatrix3D &, MbRegTransform * = NULL ); + /// \ru Сдвинуть вдоль вектора строители. \en Move creators along the vector. + void CreatorsMove ( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Повернуть вокруг оси строители на заданный угол. \en Rotate the creators about the axis by the given angle. + void CreatorsRotate ( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + /// \ru Выдать количество строителей. \en Get the creators count. + size_t GetCreatorsCount() const { return transactions.size(); } + /// \ru Зарезервировать место для строителей. \en Reserve space for creators. + void Reserve( size_t count ) { transactions.reserve( transactions.size() + count ); } + /// \ru Выдать строитель по его индексу. \en Get constructor by its index. + const MbCreator * GetCreator( size_t ind ) const; + /// \ru Выдать строитель по его индексу с возможностью редактирования. \en Get constructor by its index with possibility of editing. + MbCreator * SetCreator( size_t ind ); + /// \ru Добавить свои строители в присланный массив. \en Add your own creators to the given array. + virtual bool GetCreators( RPArray & ) const; + /// \ru Добавить свои строители в присланный массив. \en Add your own creators to the given array. + virtual bool GetCreators( c3d::CreatorsSPtrVector & ) const; + /// \ru Добавить копии своих строителей в присланный массив. \en Add copies of your own creators to the given array. + bool GetCreatorsCopies( RPArray & ) const; + /// \ru Добавить копии своих строителей в присланный массив. \en Add copies of your own creators to the given array. + bool GetCreatorsCopies( c3d::CreatorsSPtrVector & ) const; + /// \ru Найти номер строителя в журнале или вернуть SYS_MAX_T в случае отсутствия. \en Find the number of creators in the history tree or return SYS_MAX_T if it is absent. + size_t FindCreator( const MbCreator * creator ); + /// \ru Добавить строитель (addSame = false) или его копию (addSame = true) в журнал. \en Add the constructor (addSame = false) or its copy (addSame = true) to the history tree. + bool AddCreator ( const MbCreator &, bool addSame = false ); + /// \ru Добавить строитель (addSame = false) или его копию (addSame = true) в журнал. \en Add the constructor (addSame = false) or its copy (addSame = true) to the history tree. + bool AddCreator ( const MbCreator *, bool addSame = false ); + /// \ru Добавить строители в журнал. \en Add creators to the history tree. + void AddCreators( const RPArray & ); + /// \ru Вытереть строитель с указанным номером из журнала и отдать его. \en Remove the constructor with the specified index from the history tree and return it. + MbCreator * DetachCreator ( size_t ind ); + /// \ru Удалить строитель с указанным номером и вытереть его из журнала. \en Delete the constructor with the specified index and remove it from the history tree. + bool DeleteCreator ( size_t ind ); + /// \ru Удалить все строители и очистить журнал. \en Delete all the creators and clear the history tree. + void DeleteCreators(); + /// \ru Дать статус строителя с указанным номером. \en Get the status of creator with the specified index. + int GetCreatorStatus( size_t ind ) const; + /// \ru Установить строителю с указанным номером статус. \en Set status to creator with the specified index. + bool SetCreatorStatus( size_t ind, MbeProcessState ); + /// \ru Дать количество активных строителей. \en Get the active creators count. + size_t GetActiveCreatorsCount() const; + /// \ru Установить количество активных строителей от начала до заданного номера. \en Set the count of active creators from the beginning to the given index. + bool SetActiveCreatorsCount( size_t activeCount ); + /// \ru Выдать создаваемый заданным числом строителей объект и базовые объекты остальных строителей. \en Get the object created by the specified number of creators and the basis items of the other creators. + void BreakCreatorsToBasisItem( size_t c, RPArray & ); + /// \ru Выдать базовые объекты строителей. \en Get the basis items of the creators. + void GetCreatorsBasisItems ( RPArray & ); + /// \ru Выдать базовые точки строителей. \en Get the basis points of the creators. + void GetCreatorsBasisPoints( MbControlData3D & ) const; + /// \ru Изменить объект по контрольным точкам. \en Change the object by control points. + void SetCreatorsBasisPoints( const MbControlData3D & ); + /// \ru Выдать свойства строителей (на копиях или на оригиналах строителей). \en Get properties of the creators (using original creators or their copies). + void GetProperties( MbProperties &, bool sameCreators = false ); + /// \ru Установить свойства строителей. \en Set properties of the creators. + void SetProperties( const MbProperties & ); + /// \ru Прочитать строители из потока. \en Read creators from the stream. + void CreatorsRead ( reader & in ); + /// \ru Записать строители в поток. \en Write creators to the stream. + void CreatorsWrite( writer & out ) const; + +OBVIOUS_PRIVATE_COPY( MbTransactions ) +}; + + +#endif // __CREATOR_TRANSACTION_H diff --git a/C3d/Include/cur_arc.h b/C3d/Include/cur_arc.h index db401d9..b622cb6 100644 --- a/C3d/Include/cur_arc.h +++ b/C3d/Include/cur_arc.h @@ -57,7 +57,7 @@ class DiskreteLengthData; \ingroup Curves_2D */ // --- -class MATH_CLASS MbArc : public MbCurve, public MbSyncItem { +class MATH_CLASS MbArc : public MbCurve { protected : MbPlacement position; ///< \ru Локальная система координат. \en Local coordinate system. double a; ///< \ru Радиус полуоси вдоль X. \en Radius of semiaxis along X. @@ -948,9 +948,6 @@ public : */ void Init( const MbCartPoint & pc, const MbCartPoint & p1, const MbCartPoint & p2, int initSense ); - // \ru NES 9.12.2011 не нашла реализации этой функции. \en NES 9.12.2011 didn't find the implementation of this function. - // void Init( double t1, double t2, 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 Или вторую точку (зависит от correctFirstPnt) \en Or the second point (depends on correctFirstPnt) diff --git a/C3d/Include/cur_arc3d.h b/C3d/Include/cur_arc3d.h index 1ceceeb..e40e931 100644 --- a/C3d/Include/cur_arc3d.h +++ b/C3d/Include/cur_arc3d.h @@ -15,8 +15,8 @@ #include -#define CONIC_COUNT 32 -#define LINES_COUNT 10 +const_expr size_t CONIC_COUNT = 32; +const_expr size_t LINES_COUNT = 10; class MATH_CLASS MbArc; diff --git a/C3d/Include/cur_b_spline.h b/C3d/Include/cur_b_spline.h index b4f1622..199e50e 100644 --- a/C3d/Include/cur_b_spline.h +++ b/C3d/Include/cur_b_spline.h @@ -1,108 +1,108 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Набор В-сплайнов NURBS кривой. - \en B-spline set of NURBS-curve. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_B_SPLINE_H -#define __CUR_B_SPLINE_H - - -#include -#include - - -class MATH_CLASS MbNurbs3D; -class MATH_CLASS MbNurbs; - - -//------------------------------------------------------------------------------ -/** \brief \ru Набор В-сплайнов NURBS кривой. - \en B-spline set of NURBS-curve. \~ - \details \ru Объект со свойствами кривой служит для визуализации набора В-сплайнов некоторой NURBS кривой. \n - В-сплайны NURBS кривой располагаются в плоскости XY локальной системы координат position. - Длина рисунка всех В-сплайнов равна параметру a, высота рисунка всех В-сплайнов равна параметру h. - \en Object with curve properties is used to visualize B-spline set of some NURBS-curve. \n - B-splines of NURBS-curve are located in the XY plane of the local coordinate system. - Picture length of all B-splines is equal to the parameter a, the height of all B-splines is the parameter h. \~ - \ingroup Curves_3D -*/ -// --- -class MATH_CLASS MbBSpline : public MbCurve3D { -private: - ptrdiff_t degree; ///< \ru Степень В-сплайнов. \en Degree of B-splines. - SArray knots; ///< \ru Узловой вектор. \en Knot vector. - ptrdiff_t pCount; ///< \ru Число точек. \en Number of points. - bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. - MbPlacement3D position; ///< \ru Плоскость для отрисовки. \en A plane for drawing. - double a; ///< \ru Горизонтальный размер (длина рисунка). \en Horizontal size (picture length). - double h; ///< \ru Вертикальный размер (высота рисунка). \en Vertical size (picture height). - -public: - MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbNurbs & nurbs ); - MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbNurbs3D & nurbs ); - MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const SArray & t ); -private: - MbBSpline( const MbBSpline & init ); -public: - virtual ~MbBSpline(); - -public: - VISITING_CLASS( MbBSpline ); - - // \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 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 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 - 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. - - // \ru Общие функции кривой \en 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 - // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ - virtual void PointOn ( double &t, MbCartPoint3D &pnt ) const; // \ru Точка на кривой \en The point on the curve - virtual void FirstDer ( double &t, MbVector3D &fd ) const; // \ru Первая производная \en First derivative - virtual void SecondDer( double &t, MbVector3D &sd ) const; // \ru Вторая производная \en Second derivative - virtual void ThirdDer ( double &t, MbVector3D &td ) const; // \ru Третья производная по t \en Third derivative with respect to 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 double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculate step of approximation - - virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; - - virtual void Inverse( MbRegTransform * iReg = 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 - ptrdiff_t CalculateFunctions( double x, double * m, - double * mm0, double * mm1, double * mm2, double * mm3 ) const; - ptrdiff_t CalculateParam( double & t, double & x ) const; // \ru Расчет параметра и номера сплайна \en Calculation of the parameter and spline number - void GetWeightFunctions( double t, double * m, - double * mm0, double * mm1, double * mm2, double * mm3 ) const; // \ru Определение В-сплайнов \en Definition of B-splines - -private: - void operator = ( const MbBSpline & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBSpline ) -}; // MbBSpline - -IMPL_PERSISTENT_OPS( MbBSpline ) - -#endif // __CUR_B_SPLINE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Набор В-сплайнов NURBS кривой. + \en B-spline set of NURBS-curve. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_B_SPLINE_H +#define __CUR_B_SPLINE_H + + +#include +#include + + +class MATH_CLASS MbNurbs3D; +class MATH_CLASS MbNurbs; + + +//------------------------------------------------------------------------------ +/** \brief \ru Набор В-сплайнов NURBS кривой. + \en B-spline set of NURBS-curve. \~ + \details \ru Объект со свойствами кривой служит для визуализации набора В-сплайнов некоторой NURBS кривой. \n + В-сплайны NURBS кривой располагаются в плоскости XY локальной системы координат position. + Длина рисунка всех В-сплайнов равна параметру a, высота рисунка всех В-сплайнов равна параметру h. + \en Object with curve properties is used to visualize B-spline set of some NURBS-curve. \n + B-splines of NURBS-curve are located in the XY plane of the local coordinate system. + Picture length of all B-splines is equal to the parameter a, the height of all B-splines is the parameter h. \~ + \ingroup Curves_3D +*/ +// --- +class MATH_CLASS MbBSpline : public MbCurve3D { +private: + ptrdiff_t degree; ///< \ru Степень В-сплайнов. \en Degree of B-splines. + SArray knots; ///< \ru Узловой вектор. \en Knot vector. + ptrdiff_t pCount; ///< \ru Число точек. \en Number of points. + bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. + MbPlacement3D position; ///< \ru Плоскость для отрисовки. \en A plane for drawing. + double a; ///< \ru Горизонтальный размер (длина рисунка). \en Horizontal size (picture length). + double h; ///< \ru Вертикальный размер (высота рисунка). \en Vertical size (picture height). + +public: + MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbNurbs & nurbs ); + MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbNurbs3D & nurbs ); + MbBSpline( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, const SArray & t ); +private: + MbBSpline( const MbBSpline & init ); +public: + virtual ~MbBSpline(); + +public: + VISITING_CLASS( MbBSpline ); + + // \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 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 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 + 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. + + // \ru Общие функции кривой \en 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 + // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ + virtual void PointOn ( double &t, MbCartPoint3D &pnt ) const; // \ru Точка на кривой \en The point on the curve + virtual void FirstDer ( double &t, MbVector3D &fd ) const; // \ru Первая производная \en First derivative + virtual void SecondDer( double &t, MbVector3D &sd ) const; // \ru Вторая производная \en Second derivative + virtual void ThirdDer ( double &t, MbVector3D &td ) const; // \ru Третья производная по t \en Third derivative with respect to 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 double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculate step of approximation + + virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; + + virtual void Inverse( MbRegTransform * iReg = 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 + ptrdiff_t CalculateFunctions( double x, double * m, + double * mm0, double * mm1, double * mm2, double * mm3 ) const; + ptrdiff_t CalculateParam( double & t, double & x ) const; // \ru Расчет параметра и номера сплайна \en Calculation of the parameter and spline number + void GetWeightFunctions( double t, double * m, + double * mm0, double * mm1, double * mm2, double * mm3 ) const; // \ru Определение В-сплайнов \en Definition of B-splines + +private: + void operator = ( const MbBSpline & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbBSpline ) +}; // MbBSpline + +IMPL_PERSISTENT_OPS( MbBSpline ) + +#endif // __CUR_B_SPLINE_H diff --git a/C3d/Include/cur_bezier.h b/C3d/Include/cur_bezier.h index 9dda0c1..f75bccf 100644 --- a/C3d/Include/cur_bezier.h +++ b/C3d/Include/cur_bezier.h @@ -128,6 +128,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( const MbBezier & other ); /** \brief \ru Создать сплайн по четырем точкам. @@ -142,6 +144,8 @@ public : When number of points is more then four classical cubic bezier is created for each sequential four points. The smoothness of result curve can be broken. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( const SArray & initList ); /** \brief \ru Создать сплайн по массиву всех точек. @@ -160,6 +164,8 @@ public : It must be obtained from point array of three-dimensional curve MbBezier3D which is planar, by projecting them onto the plane of the curve. The number of points must be multiple of three. The minimal number of points is six. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( bool closed, const SArray & points ); /** \brief \ru Создать сплайн по сегменту Bezier-кривой. @@ -170,6 +176,8 @@ public : \en A given curve. \~ \param[in] iseg - \ru Номер сегмента кривой. \en A number of curve segment. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( const MbBezier & pCurve, ptrdiff_t iseg ); /** \brief \ru Создать сплайн по полюсам. @@ -183,11 +191,13 @@ public : \param[in] cls - \ru Замкнутость кривой. \en A curve closedness. \~ \param[in] initForm - \ru Форма сплайна. Возможные значения:\n - 0 - Стандартная форма. - 1 - Более выпуклая форма кривой. + 0 - Стандартная форма. \n + 1 - Более выпуклая форма кривой. \en The shape of spline. Possible values:\n - 0 - The standard form. - 1 - More convex form of curve. \~ + 0 - The standard form. \n + 1 - More convex form of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( const SArray & initList, bool cls, int initForm = 0 ); /** \brief \ru Создать сплайн по дуге окружности. @@ -196,6 +206,8 @@ public : \en There was constructed a Bezier curve which approximates a given arc of a circle. \~ \param[in] arc - \ru Дуга окружности. \en Circle arc. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier * Create( const MbArc & arc ); // \ru Инициализация по дуге окружности \en Initialization by a circle arc @@ -285,7 +297,7 @@ public : /** \ru \name Функции движения по кривой \en \name Functions of the motion along the curve \{ */ - virtual double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of the approximation step with consideration of the curvature radius + virtual double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of the approximation step with consideration of the curvature radius virtual double DeviationStep( double t, double angle ) const; // \ru Вычисление шага аппроксимации по угловой толерантности \en Calculation of the approximation step by angular tolerance /** \} */ @@ -296,7 +308,7 @@ public : virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; - virtual MbContour * NurbsContour() const; + virtual MbContour * NurbsContour() const; virtual void Inverse( MbRegTransform * iReg = NULL ); // \ru Изменение направления кривой на противоположное \en Change to the opposite direction of a curve @@ -314,7 +326,7 @@ public : virtual size_t GetPointsCount() const; ///< \ru Вернуть количество несовпадающих контрольных точек. \en Return the number of non-coincedent control points. virtual void GetPoint( ptrdiff_t index, MbCartPoint & pnt ) const; // \ru Выдать точку \en Get point - virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get the point index which is nearest to the given. + virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get the point index which is nearest to the given. virtual void GetRuleInterval( ptrdiff_t index, double & t1, double & t2 ) const; // \ru Выдать интервал влияния точки \en Get the interval of point influence @@ -461,7 +473,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /** \} */ @@ -469,11 +482,11 @@ protected: virtual bool CanChangeClosed() const; // \ru Можно ли поменять признак замкнутости \en Whether it is possible to change the attribute of closedness private : void CheckData( double & t ) const; - void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" - void EvaluateSlope0 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form - void EvaluateSlope1 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form + void EvaluateSlope ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index \en Calculate derivatives at the pole "index" + void EvaluateSlope0 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 0-ой формы \en Calculate derivatives at the pole "index" for 0-th form + void EvaluateSlope1 ( ptrdiff_t index ); // \ru Рассчитать производные в полюсе index для 1-ой формы \en Calculate derivatives at the pole "index" for 1-th form void SetDerives(); // \ru Рассчитать все производные \en Calculate all derivatives - void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index. \en Calculate derivatives at poles when changing the pole "index". + void SetDerives ( ptrdiff_t index ); // \ru Рассчитать производные в полюсах при изменении полюса index. \en Calculate derivatives at poles when changing the pole "index". void operator = ( const MbBezier & ); // \ru Не реализовано. \en Not implemented. diff --git a/C3d/Include/cur_bezier3d.h b/C3d/Include/cur_bezier3d.h index 4fd36d0..45215cf 100644 --- a/C3d/Include/cur_bezier3d.h +++ b/C3d/Include/cur_bezier3d.h @@ -58,6 +58,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier3D * Create( const MbBezier3D & other ); /** \brief \ru Создать сплайн. @@ -70,6 +72,8 @@ public : \en A closedness attribute. \~ \param[in] initForm - \ru Форма кривой. \en Form of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier3D * Create( const SArray & initList, bool cls, int initForm = 0 ); /** \brief \ru Создать сплайн. @@ -80,6 +84,8 @@ public : \en The two-dimensional spline. \~ \param[in] place - \ru Локальная система координат сплайна. \en Local coordinate system of spline. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier3D * Create( const MbBezier & bezier, const MbPlacement3D & place ); /** \brief \ru Создать сплайн. @@ -90,6 +96,8 @@ public : \en Start point of curve. \~ \param[in] p2 - \ru Конечная точка кривой. \en End point of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbBezier3D * Create( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); @@ -184,7 +192,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); private : void CheckBezierClosed(); // \ru Проверка признака замкнутости. \en Check closed. diff --git a/C3d/Include/cur_bridge3d.h b/C3d/Include/cur_bridge3d.h index 358d30b..fecd521 100644 --- a/C3d/Include/cur_bridge3d.h +++ b/C3d/Include/cur_bridge3d.h @@ -27,7 +27,8 @@ \ingroup Curves_3D */ // --- -class MATH_CLASS MbBridgeCurve3D : public MbCurve3D { +class MATH_CLASS MbBridgeCurve3D : public MbCurve3D +{ protected: MbCurve3D * curve1; ///< \ru Первая соединяемая кривая. \en The first curve to connect. MbCurve3D * curve2; ///< \ru Вторая соединяемая кривая. \en The second curve to connect. @@ -103,7 +104,7 @@ public: virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve3D * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - const MbCube &GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } // \ru Выдать габарит кривой \en Get the bounding box of a curve + const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get the bounding box of a curve private: inline void CheckParam ( double & t ) const; // \ru Проверка параметра \en Check parameter diff --git a/C3d/Include/cur_character_curve.h b/C3d/Include/cur_character_curve.h index eb22602..ce9dccb 100644 --- a/C3d/Include/cur_character_curve.h +++ b/C3d/Include/cur_character_curve.h @@ -1,151 +1,152 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Двумерная кривая, координатные функции которой заданы в символьном виде. - \en Functionally defined two-dimensional curve. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_CHARACTER_CURVE_H -#define __CUR_CHARACTER_CURVE_H - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbFunction; - - -//------------------------------------------------------------------------------ -/** \brief \ru Двумерная кривая, координатные функции которой заданы в символьном виде. - \en Functionally defined two-dimensional curve. \~ - \details \ru Координатные функции кривой заданы в виде пользовательских функций общего параметра t. - Каждая координата кривой описана своей функцией в виде строкового выражения. - Параметр кривой, он же параметр координатных функций, изменяется на отрезке [tmin tmax]. \n - Все пользовательские функции заданы в локальной системе координат position. - Система координат может быть декартовой или полярной. - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n - r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)). - \en Functions of coordinates of curve are given as custom functions of common parameter t. - Each coordinate of the curve is described by its own function in form of string expression. - Parameter of the curve, which is also the parameter of functions of coordinates, varies in range [tmin tmax]. \n - All the custom functions are given in the local coordinate system position. - The coordinate system can be Cartesian or polar. - The radius-vector of the curve in method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n - r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)). \~ - \ingroup Curves_2D -*/ -// --- -class MATH_CLASS MbCharacterCurve : public MbCurve { -private: - MbFunction * xFunction; ///< \ru Функция координаты x. \en Function of x-coordinate. - MbFunction * yFunction; ///< \ru Функция координаты y. \en Function of y-coordinate. - MbPlacement position; ///< \ru Локальная система координат, в которой заданы координатные функции. \en The local coordinate system the functions of coordinates are specified in. - MbMatrix transform; ///< \ru Матрица трансформации кривой. \en Transformation matrix of the curve. - double tmin; ///< \ru Минимальное значение параметра кривой. \en The minimal value of a curve parameter. - double tmax; ///< \ru Максимальное значение параметра кривой. \en The maximal value of the curve parameter. - bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. - MbeLocalSystemType coordinateType; ///< \ru Тип системы координат, в которой заданы координатные функции \en Type of coordinate system the functions of coordinates are specified in - c3d::DoubleVector specialParams; ///< \ru Перечень параметров особых точек кривой \en List of parameters of curve's singular points - // \ru Буферные данные для ускорения вычислений. \en Buffer data to speed up computations. - mutable double metricLength; - mutable MbRect rect; - -public: - MbCharacterCurve( MbFunction & x, MbFunction & y, - MbeLocalSystemType cs, - const MbPlacement & place, - double tmin_, double tmax_ ); -protected: - MbCharacterCurve( const MbCharacterCurve & ); -public: - virtual ~MbCharacterCurve(); - -public: - VISITING_CLASS( MbCharacterCurve ); - - // \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 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 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. - - // \ru Общие функции кривой. \en Common functions of the 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 - // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ - virtual void PointOn ( double & t, MbCartPoint & ) const; // \ru Точка на кривой \en Point on the curve - virtual void FirstDer( double & t, MbVector & ) const; // \ru Первая производная \en The first derivative - virtual void SecondDer( double & t, MbVector & ) const; // \ru Вторая производная \en The second derivative - virtual void ThirdDer( double & t, MbVector & ) const; // \ru Третья производная по t \en The third derivative with respect to t - // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ - virtual void Explore( double & t, bool ext, - MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const; - - 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 bool HasLength ( double & length ) const; // \ru Метрическая длина кривой \en Metric length of a curve - - virtual double GetMetricLength () const; // \ru Метрическая длина кривой \en Metric length of a curve - virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой \en Metric length evaluation of a curve - - virtual void Inverse ( MbRegTransform * iReg = 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; - - virtual MbCurve * Trimmed ( double t1, double t2, int sense ) const; - virtual MbeState DeletePart ( double t1, double t2, MbCurve *& part2 ); // \ru Удалить часть кривой между параметрами t1 и t2 \en Remove a piece of curve between t1 and t2 parameters - virtual MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ); // \ru Оставить часть кривой между параметрами t1 и t2 \en Keep a piece of curve between t1 and t2 parameters - - 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 void GetProperties ( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties ( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object - - void CheckParam ( double & t ) const; - void CalculateParam( double t, MbCartPoint & point, - MbVector & firstDer, MbVector & secondDer, MbVector & thirdDer ) const; - - const MbFunction * GetX() const { return xFunction; } - const MbFunction * GetY() const { return yFunction; } - const MbMatrix & GetMatrix() const { return transform; } - const MbPlacement & GetPlacement() const { return position; } - MbeLocalSystemType GetCoordinateType() const { return coordinateType; } - void GetSpecialParams( std::vector & params ) const; - -protected: - double ApproximationStep( double t, bool isAngle, double sag ) const; - void ConvertParamsInd( size_t componentIndex, - const std::vector & tComponent, - std::vector & tCrv ) const; - void ConvertParams( const double tCrv, - double (&tComponents) [2], - double (&proportionFactors)[2]) const; - -private: - // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. - void CheckClosed(); - -private: - void operator = ( const MbCharacterCurve & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve ) -}; - -IMPL_PERSISTENT_OPS( MbCharacterCurve ) - -#endif // __CUR_CHARACTER_CURVE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Двумерная кривая, координатные функции которой заданы в символьном виде. + \en Functionally defined two-dimensional curve. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_CHARACTER_CURVE_H +#define __CUR_CHARACTER_CURVE_H + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbFunction; + + +//------------------------------------------------------------------------------ +/** \brief \ru Двумерная кривая, координатные функции которой заданы в символьном виде. + \en Functionally defined two-dimensional curve. \~ + \details \ru Координатные функции кривой заданы в виде пользовательских функций общего параметра t. + Каждая координата кривой описана своей функцией в виде строкового выражения. + Параметр кривой, он же параметр координатных функций, изменяется на отрезке [tmin tmax]. \n + Все пользовательские функции заданы в локальной системе координат position. + Система координат может быть декартовой или полярной. + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n + r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)). + \en Functions of coordinates of curve are given as custom functions of common parameter t. + Each coordinate of the curve is described by its own function in form of string expression. + Parameter of the curve, which is also the parameter of functions of coordinates, varies in range [tmin tmax]. \n + All the custom functions are given in the local coordinate system position. + The coordinate system can be Cartesian or polar. + The radius-vector of the curve in method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n + r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)). \~ + \ingroup Curves_2D +*/ +// --- +class MATH_CLASS MbCharacterCurve : public MbCurve { +private: + MbFunction * xFunction; ///< \ru Функция координаты x. \en Function of x-coordinate. + MbFunction * yFunction; ///< \ru Функция координаты y. \en Function of y-coordinate. + MbPlacement position; ///< \ru Локальная система координат, в которой заданы координатные функции. \en The local coordinate system the functions of coordinates are specified in. + MbMatrix transform; ///< \ru Матрица трансформации кривой. \en Transformation matrix of the curve. + double tmin; ///< \ru Минимальное значение параметра кривой. \en The minimal value of a curve parameter. + double tmax; ///< \ru Максимальное значение параметра кривой. \en The maximal value of the curve parameter. + bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. + MbeLocalSystemType coordinateType; ///< \ru Тип системы координат, в которой заданы координатные функции \en Type of coordinate system the functions of coordinates are specified in + c3d::DoubleVector specialParams; ///< \ru Перечень параметров особых точек кривой \en List of parameters of curve's singular points + // \ru Буферные данные для ускорения вычислений. \en Buffer data to speed up computations. + mutable double metricLength; + mutable MbRect rect; + +public: + MbCharacterCurve( MbFunction & x, MbFunction & y, + MbeLocalSystemType cs, + const MbPlacement & place, + double tmin_, double tmax_ ); +protected: + MbCharacterCurve( const MbCharacterCurve & ); +public: + virtual ~MbCharacterCurve(); + +public: + VISITING_CLASS( MbCharacterCurve ); + + // \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 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 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. + + // \ru Общие функции кривой. \en Common functions of the 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 + // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ + virtual void PointOn ( double & t, MbCartPoint & ) const; // \ru Точка на кривой \en Point on the curve + virtual void FirstDer( double & t, MbVector & ) const; // \ru Первая производная \en The first derivative + virtual void SecondDer( double & t, MbVector & ) const; // \ru Вторая производная \en The second derivative + virtual void ThirdDer( double & t, MbVector & ) const; // \ru Третья производная по t \en The third derivative with respect to t + // \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ + virtual void Explore( double & t, bool ext, + MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const; + + 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 bool HasLength ( double & length ) const; // \ru Метрическая длина кривой \en Metric length of a curve + + virtual double GetMetricLength () const; // \ru Метрическая длина кривой \en Metric length of a curve + 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 size_t GetCount () const; // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. + virtual MbNurbs * NurbsCurve ( const MbCurveIntoNurbsInfo & ) const; + + virtual MbCurve * Trimmed ( double t1, double t2, int sense ) const; + virtual MbeState DeletePart ( double t1, double t2, MbCurve *& part2 ); // \ru Удалить часть кривой между параметрами t1 и t2 \en Remove a piece of curve between t1 and t2 parameters + virtual MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ); // \ru Оставить часть кривой между параметрами t1 и t2 \en Keep a piece of curve between t1 and t2 parameters + + 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 void GetProperties ( MbProperties & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties ( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + + void CheckParam ( double & t ) const; + void CalculateParam( double t, MbCartPoint & point, + MbVector & firstDer, MbVector & secondDer, MbVector & thirdDer ) const; + + const MbFunction * GetX() const { return xFunction; } + const MbFunction * GetY() const { return yFunction; } + const MbMatrix & GetMatrix() const { return transform; } + const MbPlacement & GetPlacement() const { return position; } + MbeLocalSystemType GetCoordinateType() const { return coordinateType; } + void GetSpecialParams( std::vector & params ) const; + +protected: + double ApproximationStep( double t, bool isAngle, double sag ) const; + void ConvertParamsInd( size_t componentIndex, + const std::vector & tComponent, + std::vector & tCrv ) const; + void ConvertParams( const double tCrv, + double (&tComponents) [2], + double (&proportionFactors)[2]) const; + +private: + // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. + void CheckClosed(); + +private: + void operator = ( const MbCharacterCurve & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve ) +}; + +IMPL_PERSISTENT_OPS( MbCharacterCurve ) + +#endif // __CUR_CHARACTER_CURVE_H diff --git a/C3d/Include/cur_character_curve3d.h b/C3d/Include/cur_character_curve3d.h index 213d8b6..84382ba 100644 --- a/C3d/Include/cur_character_curve3d.h +++ b/C3d/Include/cur_character_curve3d.h @@ -1,153 +1,160 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Кривая, координатные функции которой заданы в символьном виде. - \en Functionally defined curve. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_CHARCTER_CURVE3D_H -#define __CUR_CHARCTER_CURVE3D_H - - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbFunction; -class MATH_CLASS MbCharacterCurve; - - -//------------------------------------------------------------------------------ -/** \brief \ru Кривая, координатные функции которой заданы в символьном виде. - \en Functionally defined curve. \~ - \details \ru Координатные функции кривой заданы в виде пользовательских функций общего параметра t. - Каждая координата кривой описана своей функцией в виде строкового выражения. - Параметр кривой, он же параметр координатных функций, изменяется на отрезке [tmin tmax]. \n - Все пользовательские функции заданы в локальной системе координат position. - Система координат может быть декартовой, цилиндрической или сферической. - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n - r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)) + (position.axisZ zFunction(t)). - \en Functions of coordinates of the curve are given as custom functions of common parameter t. - Each coordinate of the curve is described by its own function in form of string expression. - Parameter of the curve, which is also the parameter of functions of coordinates, varies in range [tmin tmax]. \n - All the custom functions are given in the local coordinate system position. - The coordinate system can be Cartesian, cylindrical or spherical. - The radius-vector of the curve in method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n - r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)) + (position.axisZ zFunction(t)). \~ - \ingroup Curves_3D -*/ -// --- -class MATH_CLASS MbCharacterCurve3D : public MbCurve3D { -private: - MbFunction * xFunction; ///< \ru Функция координаты x. \en Function of x-coordinate. - MbFunction * yFunction; ///< \ru Функция координаты y. \en Function of y-coordinate. - MbFunction * zFunction; ///< \ru Функция координаты z. \en Function of z-coordinate - MbPlacement3D position; ///< \ru Локальная система координат, в которой заданы координатные функции. \en The local coordinate system the functions of coordinates are specified in. - MbMatrix3D transform; ///< \ru Матрица трансформации кривой. \en Transformation matrix of the curve. - double tmin; ///< \ru Минимальное значение параметра кривой. \en The minimal value of a curve parameter. - double tmax; ///< \ru Максимальное значение параметра кривой. \en The maximal value of the curve parameter. - bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. - MbeLocalSystemType3D coordinateType; ///< \ru Тип системы координат, в которой заданы координатные функции. \en Type of coordinate system the functions of coordinates are specified in. - c3d::DoubleVector specialParams; ///< \ru Множество параметров особых точек кривой. \en Set of parameters of curve's singular points. - // \ru Буферные данные для ускорения вычислений. \en Buffer data to speed up computations. - mutable double metricLength; - mutable MbCube cube; - -public: - MbCharacterCurve3D( MbFunction & x, MbFunction & y, MbFunction & z, - MbeLocalSystemType3D cs, const MbPlacement3D & place, - double tmin_, double tmax_ ); - MbCharacterCurve3D( const MbCharacterCurve & init, const MbPlacement3D & place ); // \ru Конструктор по двумерной кривой \en Constructor by two-dimensional curve -protected: - MbCharacterCurve3D( const MbCharacterCurve3D & ); -public: - virtual ~MbCharacterCurve3D(); - -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 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 AddYourGabaritTo( MbCube & ) const; - virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an 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 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 Общие функции кривой. \en Common functions of the 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 - // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ - virtual void PointOn ( double & t, MbCartPoint3D & ) const; // \ru Точка на кривой \en Point on the curve - virtual void FirstDer( double & t, MbVector3D & ) const; // \ru Первая производная \en The first derivative - virtual void SecondDer( double & t, MbVector3D & ) const; // \ru Вторая производная \en The second derivative - virtual void ThirdDer( double & t, MbVector3D & ) const; // \ru Третья производная по t \en The third derivative with respect to 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 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 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 - // \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 - // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. - virtual size_t GetCount() const; - virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; - - void CheckParam ( double & t ) const; - void CalculateParam( double t, MbCartPoint3D & point, - MbVector3D & firstDer, MbVector3D & secondDer, MbVector3D & thirdDer ) const; - - const MbFunction * GetX() const { return xFunction; } - const MbFunction * GetY() const { return yFunction; } - const MbFunction * GetZ() const { return zFunction; } - const MbMatrix3D & GetMatrix() const { return transform; } - const MbPlacement3D & GetPlacement() const { return position; } - MbeLocalSystemType3D GetCoordinateType() const { return coordinateType; } - -protected: -// void GetSpecialParams( std::vector & params ) const; - double ApproximationStep( double t, bool isAngle, double constraint ) const; - void ConvertParamsInd( size_t componentIndex, - const std::vector & tComponent, - std::vector & tCrv ) const; - void ConvertParams( const double tCrv, - double (&tComponents)[3], - double (&proportionFactors)[3]) const; - -private: - // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. - void CheckClosed(); - -private: - void operator = ( const MbCharacterCurve3D & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve3D ) -}; - -IMPL_PERSISTENT_OPS( MbCharacterCurve3D ) - -#endif // __CUR_CHARCTER_CURVE3D_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Кривая, координатные функции которой заданы в символьном виде. + \en Functionally defined curve. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_CHARCTER_CURVE3D_H +#define __CUR_CHARCTER_CURVE3D_H + + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbFunction; +class MATH_CLASS MbCharacterCurve; + + +//------------------------------------------------------------------------------ +/** \brief \ru Кривая, координатные функции которой заданы в символьном виде. + \en Functionally defined curve. \~ + \details \ru Координатные функции кривой заданы в виде пользовательских функций общего параметра t. + Каждая координата кривой описана своей функцией в виде строкового выражения. + Параметр кривой, он же параметр координатных функций, изменяется на отрезке [tmin tmax]. \n + Все пользовательские функции заданы в локальной системе координат position. + Система координат может быть декартовой, цилиндрической или сферической. + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n + r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)) + (position.axisZ zFunction(t)). + \en Functions of coordinates of the curve are given as custom functions of common parameter t. + Each coordinate of the curve is described by its own function in form of string expression. + Parameter of the curve, which is also the parameter of functions of coordinates, varies in range [tmin tmax]. \n + All the custom functions are given in the local coordinate system position. + The coordinate system can be Cartesian, cylindrical or spherical. + The radius-vector of the curve in method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n + r(t) = position.origin + (position.axisX xFunction(t)) + (position.axisY yFunction(t)) + (position.axisZ zFunction(t)). \~ + \ingroup Curves_3D +*/ +// --- +class MATH_CLASS MbCharacterCurve3D : public MbCurve3D { +private: + MbFunction * xFunction; ///< \ru Функция координаты x. \en Function of x-coordinate. + MbFunction * yFunction; ///< \ru Функция координаты y. \en Function of y-coordinate. + MbFunction * zFunction; ///< \ru Функция координаты z. \en Function of z-coordinate + MbPlacement3D position; ///< \ru Локальная система координат, в которой заданы координатные функции. \en The local coordinate system the functions of coordinates are specified in. + MbMatrix3D transform; ///< \ru Матрица трансформации кривой. \en Transformation matrix of the curve. + double tmin; ///< \ru Минимальное значение параметра кривой. \en The minimal value of a curve parameter. + double tmax; ///< \ru Максимальное значение параметра кривой. \en The maximal value of the curve parameter. + bool closed; ///< \ru Признак замкнутости кривой. \en An attribute of curve closedness. + MbeLocalSystemType3D coordinateType; ///< \ru Тип системы координат, в которой заданы координатные функции. \en Type of coordinate system the functions of coordinates are specified in. + c3d::DoubleVector specialParams; ///< \ru Множество параметров особых точек кривой. \en Set of parameters of curve's singular points. + + // \ru Буферные данные для ускорения вычислений. \en Buffer data to speed up computations. + mutable double metricLength; + mutable MbCube cube; + +public: + /// \ru Конструктор (использует оригиналы функций). \en Constructor (uses functions originals). + MbCharacterCurve3D( MbFunction & x, + MbFunction & y, + MbFunction & z, + MbeLocalSystemType3D cs, + const MbPlacement3D & place, + double tmin, + double tmax ); + /// \ru Конструктор по двумерной кривой \en Constructor by two-dimensional curve + MbCharacterCurve3D( const MbCharacterCurve &, const MbPlacement3D & ); +protected: + MbCharacterCurve3D( const MbCharacterCurve3D & ); +public: + virtual ~MbCharacterCurve3D(); + +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 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 AddYourGabaritTo( MbCube & ) const; + virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an 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 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 Общие функции кривой. \en Common functions of the 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 + // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ + virtual void PointOn ( double & t, MbCartPoint3D & ) const; // \ru Точка на кривой \en Point on the curve + virtual void FirstDer ( double & t, MbVector3D & ) const; // \ru Первая производная \en The first derivative + virtual void SecondDer( double & t, MbVector3D & ) const; // \ru Вторая производная \en The second derivative + virtual void ThirdDer ( double & t, MbVector3D & ) const; // \ru Третья производная по t \en The third derivative with respect to 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 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 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 + // \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 + // \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. + virtual size_t GetCount() const; + virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; + + void CheckParam ( double & t ) const; + void CalculateParam( double t, MbCartPoint3D & point, + MbVector3D & firstDer, MbVector3D & secondDer, MbVector3D & thirdDer ) const; + + const MbFunction * GetX() const { return xFunction; } + const MbFunction * GetY() const { return yFunction; } + const MbFunction * GetZ() const { return zFunction; } + const MbMatrix3D & GetMatrix() const { return transform; } + const MbPlacement3D & GetPlacement() const { return position; } + MbeLocalSystemType3D GetCoordinateType() const { return coordinateType; } + +protected: +// void GetSpecialParams( std::vector & params ) const; + double ApproximationStep( double t, bool isAngle, double constraint ) const; + void ConvertParamsInd( size_t componentIndex, + const std::vector & tComponent, + std::vector & tCrv ) const; + void ConvertParams( const double tCrv, + double (&tComponents)[3], + double (&proportionFactors)[3]) const; + +private: + // \ru Проверить и установить признак замкнутости. \en Check and set the flag of closedness. + void CheckClosed(); + +private: + void operator = ( const MbCharacterCurve3D & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCharacterCurve3D ) +}; + +IMPL_PERSISTENT_OPS( MbCharacterCurve3D ) + +#endif // __CUR_CHARCTER_CURVE3D_H diff --git a/C3d/Include/cur_cone_spiral.h b/C3d/Include/cur_cone_spiral.h index cc48305..dc5b0c2 100644 --- a/C3d/Include/cur_cone_spiral.h +++ b/C3d/Include/cur_cone_spiral.h @@ -20,7 +20,7 @@ \details \ru Плоская, коническая или цилиндрическая спираль. Ось спирали направлена вдоль оси Z локальной системы координат. \n Параметр кривой отсчитывается от оси position.axisX локальной системы координат. - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n для плоской спирали: \n r(t) = position.origin + (position.axisX rad cos(t)) + (position.axisY rad sin(t)), где rad = radius + (stepd2pi t), если tgAlpha = pi/2 или rad = radius - (stepd2pi t), если tgAlpha = -pi/2; @@ -32,7 +32,7 @@ \en Planar, Conical or cylindrical spiral. A spiral axis is directed along the Z-axis of the local coordinate system. \n The curve parameter is measured from the axis "position.axisX" of the local coordinate system. - The radius-vector of curve in the method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n + The radius-vector of curve in the method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n for planar spiral: \n r(t) = position.origin + (position.axisX rad cos(t)) + (position.axisY rad sin(t)), where rad = radius + (stepd2pi t), if tgAlpha = pi/2 or rad = radius - (stepd2pi t), if tgAlpha = -pi/2; @@ -44,7 +44,7 @@ \ingroup Curves_3D */ // --- -class MATH_CLASS MbConeSpiral: public MbSpiral +class MATH_CLASS MbConeSpiral : public MbSpiral { public: enum ConeSpiralType { @@ -59,43 +59,146 @@ protected: double tgAlpha; ///< \ru Тангенс угла полуконуса. \en Tangent of the semicone angle. double stepd2pi; ///< \ru Шаг спирали, деленный на 2*pi. \en Spiral step divided by 2*pi. -public: - /// \ru Цилиндрическая спираль по трем точкам и шагу. \en Cylindrical spiral by three points and step. +protected: + /// \ru Цилиндрическая спираль по трем разным точкам и ненулевому шагу. \en Cylindrical spiral by three different points and non-zero step. MbConeSpiral( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, double st, bool left = false ); - /// \ru Коническая спираль по основанию, радиусам двух оснований, и высоте с шагом. \en Conical spiral by the base, radii of the two bases and height with step. + /// \ru Коническая спираль по основанию, радиусам двух оснований и высоте с шагом. \en Conical spiral by the base, radii of the two bases and height with step. MbConeSpiral( const MbPlacement3D & pl, double radius1, double radius2, double height, double st ); - /// \ru Коническая спираль , радиусу, углу уклона, высоте с шагом, и основанию. \en Conical spiral by radius, inclination angle, height with step and base. + /// \ru Коническая спираль по радиусу, углу уклона, высоте с шагом, и основанию. \en Conical spiral by radius, inclination angle, height with step and base. MbConeSpiral( double radius, double angle, double height, double st, const MbPlacement3D & pl ); /// \ru Цилиндрическая спираль по радиусу основания, шагу, основанию, и двум параметрам. \en Cylindrical spiral by bottom radius, step, base and two parameters. MbConeSpiral( double radius, double st, const MbPlacement3D & pl, double t1, double t2 ); - /// \ru Коническая спираль по радиусу основания, высоте, тангенсу угла наклона, основанию, и параметрам. \en Conical spiral by bottom radius, height, tangent of inclination angle, base and parameters. + /// \ru Коническая спираль по радиусу основания, ненулевой высоте, тангенсу угла наклона, основанию, и параметрам. \en Conical spiral by bottom radius, non-zero height, tangent of inclination angle, base and parameters. MbConeSpiral( double r0, double h, double tgAH, const MbPlacement3D & pl, double u1, double v1, double u2, double v2 ); protected: /// \ru Конструктор копирования. \en Copy-constructor. - MbConeSpiral( const MbConeSpiral & init ); - + MbConeSpiral( const MbConeSpiral & ); public: /// \ru Деструктор. \en Destructor. virtual ~MbConeSpiral(); +public: + /** \brief \ru Создать цилиндрическую спираль по трем разным точкам и ненулевому шагу. + \en Create cylindrical spiral by three different points and non-zero step. \~ + \details \ru Создать цилиндрическую спираль по трем разным точкам и ненулевому шагу. \n + \en Create cylindrical spiral by three different points and non-zero step. \n \~ + \param[in] p0 - \ru Начало локальной системы координат. + \en Origin point of the local coordinate system. \~ + \param[in] p1 - \ru Точка в направлении оси Z, определяющая высоту спирали. + \en Point in the direction of the Z axis determining the height of the spiral. \~ + \param[in] p2 - \ru Точка в направлении оси X. + \en Point in the direction of the X axis. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] left - \ru Признак левой системы координат. + \en Flag of the left coordinate system. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbConeSpiral * Create( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, double st, bool left = false ); + /** \brief \ru Создать коническую спираль по основанию, радиусам двух оснований и высоте с шагом. + \en Create conical spiral by the base, radii of the two bases and height with step. \~ + \details \ru Создать коническую спираль по основанию, радиусам двух оснований и высоте с ненулевым шагом. \n + \en Create conical spiral by the base, radii of the two bases and height with non-zero step. \n \~ + \param[in] pl - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] radius1 - \ru Начальный радиус основания спирали. + \en Starting radius of spiral. \~ + \param[in] radius2 - \ru Конечный радиус основания спирали. + \en Ending radius of spiral. \~ + \param[in] height - \ru Высота спирали. + \en Height of spiral. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbConeSpiral * Create( const MbPlacement3D & pl, double radius1, double radius2, double height, double st ); + + /** \brief \ru Создать коническую спираль по радиусу, углу уклона, высоте с шагом, и основанию. + \en Create conical spiral by radius, inclination angle, height, step and base. \~ + \details \ru Создать коническую спираль по радиусу, углу уклона, высоте, шагу между витками и основанию (локальной системе координат). \n + \en Create conical spiral by radius, inclination angle, height, step between coils of spiral and base (locale coordinate system). \n \~ + \param[in] radius - \ru Радиус основания спирали. + \en Radius of spiral. \~ + \param[in] angle - \ru Угол уклона. + \en Inclination angle. \~ + \param[in] height - \ru Высота спирали. + \en Height of spiral. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] pl - \ru Локальная система координат. + \en A local coordinate system. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbConeSpiral * Create( double radius, double angle, double height, double st, const MbPlacement3D & pl ); + /** \brief \ru Создать цилиндрическую спираль по радиусу основания, шагу, основанию, и двум параметрам. + \en Create cylindrical spiral by bottom radius, step, base and two parameters. \~ + \details \ru Создать цилиндрическую спираль по радиусу основания, шагу, основанию, и двум параметрам. \n + \en Create cylindrical spiral by bottom radius, step, base and starting and ending parameters. \n \~ + \param[in] radius - \ru Радиус основания спирали. + \en Radius of spiral. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] pl - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] t1 - \ru Начальный параметр. + \en Starting parameter. \~ + \param[in] t2 - \ru Конечный параметр. + \en Ending parameter. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbConeSpiral * Create( double radius, double st, const MbPlacement3D & pl, double t1, double t2 ); + + /** \brief \ru Создать коническую спираль по радиусу основания, ненулевой высоте, тангенсу угла наклона, основанию, и параметрам. + \en Create conical spiral by bottom radius, non-zero height, tangent of inclination angle, base and parameters. \~ + \details \ru Создать коническую спираль по отрезку на конусе : радиусу основания, ненулевой высоте, тангенсу угла наклона, основанию, и параметрам. + Конструктор предназначен для создания конической спирали по отрезку на конической поверхности. \n + \en Create conical spiral by bottom radius, non-zero height, tangent of inclination angle, base and parameters. + The constructor is used internally to create a conical spiral representing a segment on a conical surface. \n \~ + \param[in] r0 - \ru Радиус основания конуса. + \en Radius of spiral. \~ + \param[in] h - \ru Высота спирали. + \en Height of spiral. \~ + \param[in] tgAH - \ru Вспомогательная величина h*tan(angle) где angle - угол между осью Z и боковой образующей. + \en Auxiliary value h*tan(angle) where angle is angle between Z-axis and lateral generatrix. \~ + \param[in] pl - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] u1 - \ru Начальный параметр по U. + \en Starting parameter by U. \~ + \param[in] v1 - \ru Начальный параметр по V. + \en Starting parameter by V. \~ + \param[in] u2 - \ru Конечный параметр по U. + \en Ending parameter by U. \~ + \param[in] v2 - \ru Конечный параметр по V. + \en Ending parameter by V. \~ + \warning \ru Для внутреннего использования. + \en For internal use only. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbConeSpiral * Create( double r0, double h, double tgAH, const MbPlacement3D & pl, double u1, double v1, double u2, double v2 ); + public: VISITING_CLASS( MbConeSpiral ); /// \ru Инициализация конической спирали по конической спирали. \en Initialization of conical spiral by conical spiral. - void Init( const MbConeSpiral & init ); + void Init( const MbConeSpiral & ); /// \ru Инициализация цилиндрической спирали по основанию. \en Initialization of cylindrical spiral by base. - void Init( const MbPlacement3D & place ); + bool Init( const MbPlacement3D &, bool resetToCylindrical ); /// \ru Инициализация конической спирали по радиусам оснований, высоте и шагу. \en Initialization of conical spiral by bottom radii, height and step. - void Init( double radius1, double radius2, double height, double st ); + bool Init( double radius1, double radius2, double height, double st ); /// \ru Инициализация конической спирали по основанию, радиусам оснований, и высоте с шагом. \en Initialization of conical spiral by the base, radii of bases and height with step. - void Init( const MbPlacement3D & place, double radius1, double radius2, double height, double st ); + bool Init( const MbPlacement3D & place, double radius1, double radius2, double height, double st ); 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 bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; + virtual bool IsSame( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -125,7 +228,7 @@ 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 the direction. + virtual void Inverse( MbRegTransform * = NULL ); // \ru Изменить направление. \en Change the direction. virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual double CalculateLength( double t1, double t2 ) const; @@ -134,7 +237,7 @@ public: virtual bool NearPointProjection( const MbCartPoint3D & p, double & t, bool ext, MbRect1D * tRange = NULL ) const; // \ru Частные функции спирали. \en Special functions for spiral. - virtual void SetStep( double s ); // \ru Изменить шаг. \en Change the step. + virtual bool SetStep( double s ); // \ru Изменить шаг. \en Change the step. virtual double GetSpiralRadius( double t ) const; // \ru Выдать радиус физический спирали. \en Get a radius of the physical spiral. 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. @@ -153,28 +256,34 @@ public: /// \ru Узнать тип конической спирали \en Learn the type of conical spiral. ConeSpiralType GetType() const { return type; } private: + /// \ru Явяется ли спираль конической (в том числе плоской). \en Whether the spiral is conic (including flat). bool IsConeType() const { return ::fabs( tgAlpha ) > LENGTH_EPSILON; } - void CalConeTMax(); // \ru Усеченное значение tmax для случая закручивающихся в точку плоской или конической спиралей. \en Trimmed value tmax for the case of planar or conical spirals trailing to the point. - double GetR( double t ) const; // \ru Текущий радиус. \en The current radius. - double GetRDerive( double t ) const; // \ru Производная текущего радиуса. \en The derivative of the current radius. - // \ru Ближайшая проекция точки на плоскую спираль. \en The nearest point projection on the planar spiral. + /// \ru Усеченное значение tmax для случая закручивающихся в точку плоской или конической спиралей. \en Trimmed value tmax for the case of planar or conical spirals trailing to the point. + void CalConeTMax(); + /// \ru Текущий радиус. \en The current radius. + double GetR( double t ) const; + /// \ru Производная текущего радиуса. \en The derivative of the current radius. + double GetRDerive( double t ) const; + /// \ru Ближайшая проекция точки на плоскую спираль. \en The nearest point projection on the planar spiral. bool PlaneProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; - // \ru Ближайшая проекция точки на цилиндрическую спираль. \en The nearest point projection on the cylindrical spiral. + /// \ru Ближайшая проекция точки на цилиндрическую спираль. \en The nearest point projection on the cylindrical spiral. bool CylindricalProjection( const MbCartPoint3D & pSpace, double & tProj, bool ext, MbRect1D * tRange ) const; private: // \ru Объявление (перегрузка) оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en Declaration (overload) of the assignment operator without its implementation, to prevent the default assignment. MbConeSpiral & operator = ( const MbConeSpiral & ); - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConeSpiral ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbConeSpiral ) }; IMPL_PERSISTENT_OPS( MbConeSpiral ) + //------------------------------------------------------------------------------ // \ru Дать направление движения по спирали \en Give the direction of motion on a spiral // --- -inline void MbConeSpiral::GetSpiralDir( MbVector3D & dir ) const +inline +void MbConeSpiral::GetSpiralDir( MbVector3D & dir ) const { dir.Init( position.GetAxisZ() ); @@ -193,7 +302,8 @@ inline void MbConeSpiral::GetSpiralDir( MbVector3D & dir ) const //------------------------------------------------------------------------------ // \ru Внутренний радиус \en Inner radius // --- -inline double MbConeSpiral::GetR( double t ) const +inline +double MbConeSpiral::GetR( double t ) const { //C3D_ASSERT( position.IsIsotropic() || ::fabs(tgAlpha) < LENGTH_EPSILON ); // \ru Проверить корректность работы \en Check the correctness of working switch ( type ) { // t = [0; 2*pi] @@ -207,7 +317,8 @@ inline double MbConeSpiral::GetR( double t ) const //------------------------------------------------------------------------------ // \ru Производная внутреннего радиуса \en Derivative of inner radius // --- -inline double MbConeSpiral::GetRDerive( double /*t */) const +inline +double MbConeSpiral::GetRDerive( double /*t */) const { switch ( type ) { // t = [0; 2*pi] case cst_Plane : return tgAlpha > 0.0 ? stepd2pi : -stepd2pi; diff --git a/C3d/Include/cur_contour.h b/C3d/Include/cur_contour.h index 41b5a99..dfd947a 100644 --- a/C3d/Include/cur_contour.h +++ b/C3d/Include/cur_contour.h @@ -69,7 +69,7 @@ typedef std::vector ConstPlaneContoursSPtrVector; \ingroup Curves_2D */ // --- -class MATH_CLASS MbContour : public MbCurve, public MbNestSyncItem { +class MATH_CLASS MbContour : public MbCurve { protected : RPArray segments; ///< \ru Множество сегментов контура. \en An array of contour segments. bool closed; ///< \ru Признак замкнутости кривой. \en An Attribute of curve closedness. @@ -84,7 +84,7 @@ public : MbContour(); /// \ru Конструктор по набору кривых. \en Constructor by curves vector. template - MbContour( const Curves &, bool same ); + MbContour( const Curves &, bool sameCurves ); protected : explicit MbContour( const MbContour *, MbRegDuplicate * ); ///< \ru Конструктор копирования. \en Copy constructor. public : @@ -102,7 +102,7 @@ public: virtual MbPlaneItem & Duplicate( MbRegDuplicate * = 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 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. @@ -136,8 +136,12 @@ public: const MbRect & GetGabarit() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } const MbRect & GetCube() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } + + /// \ru Сбросить рассчитанный габарит контура. \en Reset the calculated contour bounding box. void SetDirtyGabarit() const { rect.SetEmpty(); } + /// \ru Копировать габарит контура в контур (использовать только для передачи габарита в копию контура). \en Copy contour bounding box to contour copy (use only to transfer into contour copy). void CopyGabarit( const MbContour & c ) { rect = c.rect; } + /// \ru Пуст ли габарит контура? \en Is the contour bounding box empty? bool IsGabaritEmpty() const { return rect.IsEmpty(); } virtual double DistanceToPoint( const MbCartPoint & ) const; // \ru Расстояние до точки \en Distance to a point. @@ -219,6 +223,7 @@ public: double GetParamLength() const { return paramLength; } double CalculateParamLength(); // \ru Посчитать параметрическую длину \en Calculate the parametric length + /// \ru Вычисление площади контура, если контур замкнут. \en Calculation of contour area if contour is closed. double GetArea( double sag = Math::deviateSag ) const { sag = ::fabs(sag); @@ -228,10 +233,10 @@ public: } virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; - virtual MbContour * NurbsContour() const; + virtual MbContour * NurbsContour() const; - void SetClosed(); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - void CheckClosed( double eps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + void SetClosed(); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + void CheckClosed( double closedEps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. void InitClosed( bool c ) { closed = c; } ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. /** \brief \ru Проверить замкнутость и непрерывность точек контура. @@ -249,7 +254,7 @@ public: */ bool IsClosedContinuousC0( double eps = 5.0 * PARAM_NEAR ) const; - void CloseByLineSeg( bool calcData ); ///< \ru Замкнуть контур отрезком. \en Close the contour by segment. + void CloseByLineSeg( bool calcInternalData ); ///< \ru Замкнуть контур отрезком. \en Close the contour by segment. // \ru Посчитать метрическую длину разомкнутой кривой с заданной точностью \en Calculate the metric length of unclosed curve within the given tolerance virtual double CalculateLength( double t1, double t2 ) const; @@ -265,8 +270,20 @@ public: rect.SetEmpty(); areaSign.first = -1.0; } - ptrdiff_t FindSegment( double & t, double & tSeg ) const; ///< \ru Нахождение сегмента контура. \en Finding of a contour segment. - size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. + /** \brief \ru Найти сегмент контура. + \en Find a contour segment. \~ + \details \ru Найти сегмент контура по параметру контура. \n + \en Find a contour segment by parameter on contour. \n \~ + \param[in,out] t - \ru Параметр контура. + \en Contour parameter. \~ + \param[out] tSeg - \ru Параметр сегмента контура. + \en Contour segment parameter. \~ + \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. + \en Returns the segment number in case of successful execution or -1. \~ + */ + ptrdiff_t FindSegment( double & t, double & tSeg ) const; + + size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. const MbCurve * GetSegment( size_t ind ) const { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. MbCurve * SetSegment( size_t ind ) { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. @@ -281,7 +298,19 @@ 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 DistanceToBorder( const MbCartPoint & ) const; ///< \ru Параметрическое расстояние до ближайшей границы \en Parametric distance to the nearest boundary + + /** \brief \ru Параметрическое расстояние до ближайшей границы. + \en Parametric distance to the nearest boundary. + \details \ru Параметрическое расстояние до ближайшей границы. \n + \en Parametric distance to the nearest boundary. \n \~ + \param[in] pnt - \ru Тестируемая точка. + \en A testing point. \~ + \param[in] eps - \ru Точность. + \en Accuracy. \~ + \return \ru Расстояние до ближайшей границы. + \en Distance to the nearest boundary. \~ + */ + double DistanceToBorder( const MbCartPoint & pnt, double eps = Math::paramRegion ) const; void Trimm( double t1, double t2 ); ///< \ru Выделить часть контура. \en Trim a part of the contour. @@ -383,12 +412,15 @@ public: /// \ru Установить направление обхода контура. \en Set the traverse direction of the contour. void SetSense( int sense ); - // \ru Изменить направление обхода контура \en Change the traverse direction of the contour + // \ru Изменить направление обхода контура \en Change the traverse direction of the contour virtual void Inverse( MbRegTransform * = 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 // \ru Выдать характерную точку ограниченной кривой если она ближе чем dmax \en Get characteristic point of bounded curve if it is closer than dmax virtual bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const; // \ru Расстояние до точки, если оно меньше d \en Distance to the point if it is less than d virtual bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const; + /// \ru Выдать среднюю точку сегмента контура. \en Get a mid-point of the contour segment. bool GetSegmentMiddlePoint( const MbCartPoint & from, MbCartPoint & midPoint ) const; /// \ru Выдать линейный сегмент контура. \en Get the linear segment of contour. @@ -401,9 +433,9 @@ public: virtual bool GetWeightCentre( MbCartPoint & ) const; // \ru Выдать центр тяжести контура \en Get gravity center of contour virtual bool GetCentre ( MbCartPoint & ) const; // \ru Выдать центр кривой \en Get the center of curve - /// \ru Найти ближайший к точке узел контура \en Find the nearest node of contour to point + /// \ru Найти ближайший к точке узел контура. \en Find the nearest node of contour to point. ptrdiff_t FindNearestNode( const MbCartPoint & to ) const; - /// \ru Найти ближайший к точке сегмент контура \en Find the nearest segment of contour to point + /// \ru Найти ближайший к точке сегмент контура. \en Find the nearest segment of contour to point. ptrdiff_t FindNearestSegment( const MbCartPoint & to ) const; // \ru Определение особых точек офсетной кривой \en Determination of singular points of the offset curve @@ -419,9 +451,9 @@ public: virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. /** \brief \ru Непрерывна ли первая производная кривой по длине и направлению? - \en Have the first derivative of the curve the continuous length and direction? + \en Have the first derivative of the curve the continuous length and direction? \details \ru Отсутствуют ли разрывы производной по длине и направлению в стыках сегментов контура? \n - \en Are absent any discontinuities of the derivative at length or at direction in the junction of path segments? \n \~ + \en Are absent any discontinuities of the derivative at length or at direction in the junction of path segments? \n \~ \param[out] contLength - \ru Непрерывность длины (да/нет). \en The length is continuous (true/false). \~ \param[out] contDirect - \ru Непрерывность направления (да/нет). @@ -432,13 +464,15 @@ public: virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы производных по длине в стыках сегментов. - \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. + \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. \details \ru Устранить разрывы производных по длине в стыках сегментов. \n - \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. \n \~ + \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. \n \~ \param[in] epsilon - \ru Погрешность вычисления. - \en The accuracy of the calculation. \~ + \en The accuracy of the calculation. \~ + \param[in] version - \ru Версия математики. + \en Math version. \~ */ - virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /// \ru Получить границы участков кривой, на которых сохраняется непрерывность кривизны. /// \en Get the boundaries of the sections of the curve on which the continuity of curvature is preserved. \~ @@ -449,21 +483,73 @@ public: \en \name Function for working with segments of contour \{ */ - bool Init( List & curves ); ///< \ru Инициализация по списку кривых. \en Initialization by list of curves. - void Init( const MbContour & other ); ///< \ru Инициализация по контуру. \en Initialization by a contour. + bool Init( List & ); ///< \ru Инициализация по списку кривых. \en Initialization by list of curves. + void Init( const MbContour & ); ///< \ru Инициализация по контуру. \en Initialization by a contour. + + /** \brief \ru Инициализация по массиву кривых. + \en Initialization by array of curves. \~ + \details \ru Инициализация по массиву кривых. \n + \en Initialization by array of curves. \n \~ + \param[in] curves - \ru Кривые. + \en Curves. \~ + \param[in] sameCurves - \ru Использовать оригиналы кривых (true) или их копии (false). + \en Use original curves (true) or copies thereof (false). \~ + \return \ru Возвращает true, если кривые были добавлена. + \en Returns true if curves were added. \~ + */ template - bool Init( Curves & curves, bool same ); ///< \ru Инициализация по массиву кривых. \en Initialization by array of curves. + bool Init( Curves & curves, bool sameCurves ); + /// \ru Инициализация по массиву точек (замкнутый контур). \en Initialization by array of points (closed contour). template - bool InitByPoints( const Points & ); ///< \ru Инициализация по массиву точек (замкнутый контур). \en Initialization by array of points (closed contour). + bool InitByPoints( const Points & ); + bool InitAsRectangle( const MbCartPoint * ); ///< \ru Инициализация как прямоугольника ( приходит 4 точки ) \en Initialization as rectangle (4 points are given). - bool InitByRectangle( const MbRect & ); ///< \ru Инициализация по прямоугольнику габарита. \en Initialization by rectangle of bounding box. + bool InitByRectangle( const MbRect & ); ///< \ru Инициализация по прямоугольнику габарита. \en Initialization by rectangle of bounding box. bool AddSegment ( MbCurve * ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. bool AddSegmentOrDeleteCurve( MbCurve * ); ///< \ru Добавить кривую как сегмент или удалить ее. \en Add a curve as segment or remove its. + + /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. + \en Add a (truncated) segment copy to the end of the contour. \~ + \details \ru Добавить (усеченную) копию сегмента в конец контура. \n + \en Add a (truncated) segment copy to the end of the contour. \n \~ + \param[in] pBasis- \ru Исходная кривая. + \en Initial curve. \~ + \param[in] t1 - \ru Начальный параметр усечения. + \en Truncation starting parameter. \~ + \param[in] t2 - \ru Конечный параметр усечения. + \en Truncation ending parameter. \~ + \param[in] sense - \ru Направление усеченной кривой относительно исходной. \n + sense = 1 - направление кривой сохраняется. + sense = -1 - направление кривой меняется на обратное. + \en Direction of a trimmed curve in relation to an initial curve. + sense = 1 - direction does not change. + sense = -1 - direction changes to the opposite value. \~ + \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. + \en Returns, if successful, a non-zero pointer to the added curve. \~ + */ MbCurve * AddSegment( const MbCurve * pBasis, double t1, double t2, int sense = 1 ); + bool AddAtSegment ( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент перед сегментом контура с индексом index. \en Insert a segment before the contour segment with the index "index". bool AddAfterSegment( MbCurve * newSegment, size_t index ); ///< \ru Вставить сегмент после сегмента контура с индексом index. \en Insert a segment after the contour segment with the index "index". - /// \ru Функция добавления новой кривой с управляемой проверкой. \en Function for addition of a new curve with checking. + + /** \brief \ru Добавить новый элемент в начало или конец контура. + \en Add the new element to the beginning or end of contour. \~ + \details \ru Добавить новый элемент в начало или конец контура. \n + \en Add the new element to the beginning or end of contour. \n \~ + \param[in] curve - \ru Добавляемая кривая. + \en Added curve. \~ + \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). + \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ + \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. + \en Add the curve only at the end of the contour. \~ + \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. + \en Check a presence of the same curve in the contour. \~ + \param[in] version - \ru Версия. + \en Version. \~ + \return \ru Возвращает true, если кривая была добавлена. + \en Returns true if the curve was added. \~ + */ bool AddCurveWithRuledCheck( MbCurve & newCur, double absEps, bool toEndOnly = false, bool checkSame = true, VERSION version = Math::DefaultMathVersion() ); @@ -495,7 +581,7 @@ public: void GetPolygon( double sag, SArray & poly, double eps ) const; ///< \ru Дать точки полигона. \en Get points of polygon. bool IsAnyCurvilinear() const; ///< \ru Есть ли в контуре криволинейный сегмент. \en Whether the contour has a curved segment. - bool IsSameSegments( const MbContour & cntr ) const; ///< \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. + bool IsSameSegments( const MbContour &, double accuracy = PARAM_PRECISION ) const; ///< \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. bool GetBegSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать начальную точку i-го сегмента. \en Get the start point of i-th segment. bool GetEndSegmentPoint( size_t i, MbCartPoint & ) const; ///< \ru Дать конечную точку i-го сегмента. \en Get the end point of i-th segment. diff --git a/C3d/Include/cur_contour3d.h b/C3d/Include/cur_contour3d.h index a271260..49d9bfa 100644 --- a/C3d/Include/cur_contour3d.h +++ b/C3d/Include/cur_contour3d.h @@ -171,7 +171,10 @@ public: // \ru Преобразование в NURBS кривую \en Transform to NURBS-curve virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; 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 + // \ru Изменить направление \en Change direction + virtual void Inverse( MbRegTransform * iReg = 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. virtual bool IsSimilarToCurve( const MbCurve3D & other, double precision = METRIC_PRECISION ) const; @@ -231,11 +234,13 @@ public: \en Eliminate the discontinuities of the derivatives of the length of the joints of the segments. \n \~ \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ + \param[in] version - \ru Версия математики. + \en Math version. \~ */ - virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /// \ru Найти все особые точки функции кривизны кривой. \en Find all the special points of the curvature function of the curve. - virtual void GetCurvatureSpecialPoints( std::vector & points ) const; + virtual void GetCurvatureSpecialPoints( std::vector & points ) const; /** \} */ /** \ru \name Функции работы с сегментами контура @@ -245,25 +250,62 @@ public: /// \ru Инициализация по набору кривых (sameCurves - кривые или их копии). \en Initialize by curves (sameCurves - curves or their copies). template bool Init( const CurvesVector & initSegments, bool sameCurves, bool cls ); - /// \ru Инициализация по набору кривых (замкнутый контур). \en Initialize by curves (closed contour). + /// \ru Инициализация по набору точек (замкнутый контур). \en Initialize by points (closed contour). template bool Init( const PointsVector & points ); - ptrdiff_t FindSegment( double & t, double & tSeg ) const; ///< \ru Нахождение сегмента контура. \en Finding of a contour segment. + /** \brief \ru Найти сегмент контура. + \en Find a contour segment. \~ + \details \ru Найти сегмент контура по параметру контура. \n + \en Find a contour segment by parameter on contour. \n \~ + \param[in,out] t - \ru Параметр контура. + \en Contour parameter. \~ + \param[out] tSeg - \ru Параметр сегмента контура. + \en Contour segment parameter. \~ + \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. + \en Returns the segment number in case of successful execution or -1. \~ + */ + ptrdiff_t FindSegment( double & t, double & tSeg ) const; + size_t GetSegmentsCount() const { return segments.size(); } ///< \ru Выдать количество сегментов контура. \en Get the number of contour segments. template void GetSegments( CurvesVector & curves ) const; ///< \ru Получить кривые контура. \en Get contour segments. + void DetachSegments(); ///< \ru Отцепить все сегменты контура. \en Detach all segments of contour. void DeleteSegments(); ///< \ru Отсоединить используемые сегменты и удалить остальные. \en Delete used segments and remove other segments. + void DeleteSegment( size_t ind ); ///< \ru Удалить сегмент контура. \en Delete the segment of contour. MbCurve3D * DetachSegment( size_t ind ); ///< \ru Отцепить сегмент контура. \en Detach the segment of contour. + const MbCurve3D * GetSegment( size_t ind ) const { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. MbCurve3D * SetSegment( size_t ind ) { return segments[ind]; } ///< \ru Выдать сегмент контура по индексу. \en Get contour segment by the index. + void SetSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Заменить сегмент в контуре. \en Replace a segment in the contour. void AddSegment ( MbCurve3D & newSegment, bool same ); ///< \ru Добавить сегмент в контур. \en Add a segment to the contour. void AddAtSegment ( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур перед сегментом с индексом ind. \en Add a segment to the contour before the segment with index ind. void AddAfterSegment( MbCurve3D & newSegment, size_t ind, bool same ); ///< \ru Добавить сегмент в контур после сегмента с индексом ind. \en Add a segment to the contour after the segment with index ind. + + /** \brief \ru Добавить (усеченную) копию сегмента в конец контура. + \en Add a (truncated) segment copy to the end of the contour. \~ + \details \ru Добавить (усеченную) копию сегмента в конец контура. \n + \en Add a (truncated) segment copy to the end of the contour. \n \~ + \param[in] pBasis- \ru Исходная кривая. + \en Initial curve. \~ + \param[in] t1 - \ru Начальный параметр усечения. + \en Truncation starting parameter. \~ + \param[in] t2 - \ru Конечный параметр усечения. + \en Truncation ending parameter. \~ + \param[in] sense - \ru Направление усеченной кривой относительно исходной. \n + sense = 1 - направление кривой сохраняется. + sense = -1 - направление кривой меняется на обратное. + \en Direction of a trimmed curve in relation to an initial curve. + sense = 1 - direction does not change. + sense = -1 - direction changes to the opposite value. \~ + \return \ru Возвращает в случае успешного выполнения ненулевой указатель на добавленную кривую. + \en Returns, if successful, a non-zero pointer to the added curve. \~ + */ MbCurve3D * AddSegment( MbCurve3D & pBasis, double t1, double t2, int sense ); + void SegmentsAdd( MbCurve3D & newSegment, bool calculateParamLength = true ); ///< \ru Добавить сегмент в контур без проверки. \en Add a segment to the contour without checking. bool GetCornerAngle( size_t index, MbCartPoint3D & origin, MbVector3D & axis, MbVector3D & tau, double & angle, double angleEps ) const; @@ -275,15 +317,34 @@ public: /// \ru Управление распределением памяти в массиве segments. \en Control of memory allocation in the array "segments". void SegmentsReserve( size_t additionalSpace ) { segments.Reserve( additionalSpace ); } ///< \ru Зарезервировать место. \en Reserve space. void SegmentsAdjust () { segments.Adjust(); } ///< \ru Удалить лишнюю память. \en Free the unnecessary memory. - /// \ru Добавить новый элемент в начало или конец контура. \en Add the new element to the beginning or end of contour. - bool AddCurveWithRuledCheck( MbCurve3D &, double absEps, bool toEndOnly = false, bool checkSame = true, + + /** \brief \ru Добавить новый элемент в начало или конец контура. + \en Add the new element to the beginning or end of contour. \~ + \details \ru Добавить новый элемент в начало или конец контура. \n + \en Add the new element to the beginning or end of contour. \n \~ + \param[in] curve - \ru Добавляемая кривая. + \en Added curve. \~ + \param[in] absEps - \ru Точность проверки совпадения концов кривых (1e-8 - 1e-4). + \en Accuracy of verification of curve end coincidence (1e-8 - 1e-4). \~ + \param[in] toEndOnly - \ru Добавлять кривую только в конец контура. + \en Add the curve only at the end of the contour. \~ + \param[in] checkSame - \ru Проверять наличие такой же (добавляемой) кривой в контуре. + \en Check a presence of the same curve in the contour. \~ + \param[in] checkSame - \ru Версия. + \en Version. \~ + \return \ru Возвращает true, если кривая была добавлена. + \en Returns true if the curve was added. \~ + */ + bool AddCurveWithRuledCheck( MbCurve3D & curve, double absEps, bool toEndOnly = false, bool checkSame = true, VERSION version = Math::DefaultMathVersion() ); + /// \ru Проверка непрерывности контура. \en Check for contour continuity. bool CheckConnection( double eps = METRIC_PRECISION ) const; void CalculateParamLength(); ///< \ru Рассчитать параметрическую длину. \en Calculate parametric length. - void CheckClosed( double eps ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. - /// \ru Содержат ли контура идентичные сегменты \en Whether contours contains identical segments. - bool IsSameSegments( const MbContour3D & ) const; + void CheckClosed( double /*closedEps*/ ); ///< \ru Установить признак замкнутости контура. \en Set the closedness attribute of contour. + /// \ru Содержат ли контура идентичные сегменты. \en Whether contours contains identical segments. + bool IsSameSegments( const MbContour3D &, double accuracy = METRIC_PRECISION ) const; + /// \ru Нахождение точки сегмента контура по индексу сегмента. \en Finding the point of a contour segment by segment index. void FindCorner( size_t index, MbCartPoint3D & ) const; /** \} */ diff --git a/C3d/Include/cur_contour_on_plane.h b/C3d/Include/cur_contour_on_plane.h index 2a6ef58..fbda561 100644 --- a/C3d/Include/cur_contour_on_plane.h +++ b/C3d/Include/cur_contour_on_plane.h @@ -12,9 +12,9 @@ #include +#include -class MATH_CLASS MbPlane; class MATH_CLASS MbAxis3D; @@ -65,7 +65,7 @@ public : 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 MbContourOnSurface & CurvesDuplicate() const; // \ru Сделать копию со старой подложкой. \en Make a copy with old substrate. - 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 IsSame( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Определить, является ли копией данного объекта? \en Determine whether the object is copy of a given object. virtual void GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. @@ -96,7 +96,7 @@ public : virtual double GetLengthEvaluation() const; // \ru Оценить метрическую длину кривой. \en Evaluate the metric length of curve. virtual double CalculateMetricLength() const; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of curve. - virtual bool ChangeSurface( MbSurface & newsurf ); // \ru Заменить поверхность контура. \en Replace the surface of contour. + 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? // \ru Дать плоскую кривую и плейсмент, если пространственная кривая плоская (после использования вызывать DeleteItem на двумерную кривую). \en Get planar curve and placement if the space curve is planar (after the using call DeleteItem for two-dimensional curves) @@ -106,11 +106,11 @@ 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 curve axis. - virtual void GetCentre( MbCartPoint3D & wc ) const; // \ru Дать центр тяжести. \en Get the center of gravity. - virtual void GetWeightCentre( MbCartPoint3D & wc ) const; // \ru Дать центр тяжести. \en Get the center of gravity. + virtual void GetCentre( MbCartPoint3D & ) const; // \ru Дать центр тяжести. \en Get the center of gravity. + virtual void GetWeightCentre( MbCartPoint3D & ) const; // \ru Дать центр тяжести. \en Get the center of gravity. virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой. \en Calculate the bounding box of curve. - virtual bool IsStraight() const; // \ru Определить, является ли линия прямолинейной? \en Wetermine whether the line is straight. + virtual bool IsStraight() 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. @@ -120,7 +120,7 @@ public : /// \ru Получить локальную систему координат плоскости. \en Get the local coordinate system of a plane. const MbPlacement3D & GetPlacement() const; /// \ru Получить плоскость. \en Get the plane. - const MbPlane & GetPlane() const { return (const MbPlane &)GetSurface(); } + const MbPlane & GetPlane() const { return static_cast(GetSurface()); } /// \ru Сделать правой локальную систему координат плоскости. \en Make the local coordinate system of plane right. void SetRightPlacement(); @@ -129,12 +129,12 @@ 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 * ireg = NULL ); + void InvertNormal( MbRegTransform * = NULL ); private: void operator = ( const MbContourOnPlane & ); // \ru Не реализовано !!! \en Not implemented !!! - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContourOnPlane ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContourOnPlane ) }; IMPL_PERSISTENT_OPS( MbContourOnPlane ) diff --git a/C3d/Include/cur_contour_on_surface.h b/C3d/Include/cur_contour_on_surface.h index 639e7e1..b3adb1e 100644 --- a/C3d/Include/cur_contour_on_surface.h +++ b/C3d/Include/cur_contour_on_surface.h @@ -41,7 +41,7 @@ class MbSegmentsSearchTree; \ingroup Curves_3D */ // --- -class MATH_CLASS MbContourOnSurface : public MbCurve3D, public MbSyncItem { +class MATH_CLASS MbContourOnSurface : public MbCurve3D { protected : MbSurface * surface; ///< \ru Указатель на базовую поверхность (всегда не NULL). \en The pointer to the base surface (this value is never NULL). @@ -155,16 +155,16 @@ public : virtual void CalculateGabarit( MbCube & ) const; // \ru Вычислить габарит кривой. \en Calculate the bounding box of curve. /// \ru Сбросить рассчитанный габарит. \en Reset the calculated bounding box. - void SetDirtyGabarit() const { cube.SetEmpty(); } + void SetDirtyGabarit() const; /// \ru Выдать габарит кривой. \en Get the bounding box of curve. - const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } + const MbCube & GetGabarit() const; /// \ru Вычислить параметрический габарит контура. \en Calculate the parametric bounding box of the contour. virtual void CalculateUVLimits( MbRect & uvRect ); 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 carrier elements. /// \ru Заменить поверхность контура. \en Replace the surface of contour. - virtual bool ChangeSurface( MbSurface & ); + 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. @@ -186,7 +186,8 @@ public : /// \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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); // \ru Доступ к полям класса. \en Access to the fields of a class. @@ -210,7 +211,17 @@ public : /// \ru Вычислить нормали к поверхности по параметру кривой. \en Calculate normals to the surface in the curve parameter. void SurfaceNormal( double t, MbVector3D & n ) const; - /// \ru Найти сегмент контура по параметру на контуре. \en Find a segment of contour in the contour parameter. + /** \brief \ru Найти сегмент контура. + \en Find a contour segment. \~ + \details \ru Найти сегмент контура по параметру контура. \n + \en Find a contour segment by parameter on contour. \n \~ + \param[in,out] t - \ru Параметр контура. + \en Contour parameter. \~ + \param[out] tSeg - \ru Параметр сегмента контура. + \en Contour segment parameter. \~ + \return \ru Возвращает номер сегмента в случае успешного выполнения или -1. + \en Returns the segment number in case of successful execution or -1. \~ + */ ptrdiff_t FindSegment ( double & t, double & tSeg ) const; /// \ru Найти точку сегмента контура по индексу. \en Find a point of the contour segment by the index. void FindCorner ( ptrdiff_t index, MbCartPoint & ) const; diff --git a/C3d/Include/cur_contour_with_breaks.h b/C3d/Include/cur_contour_with_breaks.h index 094d086..456155e 100644 --- a/C3d/Include/cur_contour_with_breaks.h +++ b/C3d/Include/cur_contour_with_breaks.h @@ -1,982 +1,982 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контур с разрывами. - \en Contour with breaks. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_CONTOUR_WITH_BREAKS_H -#define __CUR_CONTOUR_WITH_BREAKS_H - - -#include -#include -#include - - -class MATH_CLASS MbBreaksPart; -class MATH_CLASS MbBreak; - - -//------------------------------------------------------------------------------ -/** \brief \ru Контур c разрывами. - \en Contour with breaks. \~ - \details \ru Контур c разрывами.\n - Для использования в мультилинии MbMultiline.\n - Содержит разрывы MbBreak, видимые части - контуры MbContour.\n - При использовании в мультилинии каждуй раз при перестроении контура в нем обновляется - список номеров по количеству сегментов контура. - Каждый номер показывает номер сегмента базовой кривой мультилинии, - которому соответствует этот сегмент контура.\n - Если сегмент контура является эквидистантой сегмента базовой кривой, - то ему соответствует номер этого сегмента.\n - Если контур является сегментом обхода вершины мультилинии, - то ему соответствует номер, соответствующий предыдущему сегменту контура.\n - Разрывы в контуре не могут накладываться друг на друга. - Если в результате перестроения один разрыв наложился на другой, то они объединяются. - \en Contour with breaks.\n - For using in the multiline MbMultiline.\n - Contains breaks MbBreak, visible parts - contours MbContour.\n - When using in a multiline every time when contour is rebuilding in it are updated - list of numbers by the number of contour segments - Each number indicates the segment number of base curve of multiline. - which corresponds to this segment of contour.\n - If segment of contour is equidistant of base curve segment, - then it corresponds to the number of this segment.\n - If contour is segment of multiline vertices traverse. - then it corresponds to the number corresponding the previous segment of the contour.\n - Breaks in the contour can not be overlapped each other. - If in the result of rebuilding a break overlapped on the other break then they are combined. \~ - \ingroup Curves_2D -*/ // --- -class MATH_CLASS MbContourWithBreaks : public MbContour -{ -private: - RPArray breaks; // \ru Разрывы. \en Breaks. - RPArray visibleContours; // \ru Видимые контуры \en Visible contours. - SArray baseSegNumbers; // \ru Номера сегментов базового контура \en Numbers of segments of base contour - // \ru для задания неподвижных точек разрыва \en to define the fixed points of break - // \ru заполняется при использовании контура в мультилинии. \en filled when using the contour in the multiline. -public: - - /** \brief \ru Создание пустого контура. - \en Creation of empty contour. \~ - \details \ru Создание пустого контура без сегментов.\n - \en Creation of empty contour without segments. \n \~ - */ - MbContourWithBreaks(); - - MbContourWithBreaks( const MbContour & cnt ); ///< \ru Копирующий конструктор. \en Copy-constructor. - -private: - MbContourWithBreaks( const MbContourWithBreaks & ); // \ru не реализовано \en not implemented -protected : - MbContourWithBreaks( const MbContourWithBreaks &, MbRegDuplicate * ); -public: - virtual ~MbContourWithBreaks(); - -public : - VISITING_CLASS( MbContourWithBreaks ); - - /**\ru \name Общие функции геометрического объекта. - \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. - /** \} */ - /**\ru \name Функции доступа к данным: разрывы. - \en \name Functions for access to data: breaks. - \{ */ - size_t GetBreaksCount () const { return breaks.Count(); } ///< \ru Число разрывов. \en The number of breaks. - - /** \brief \ru Разрыв по номеру. - \en A break by the number. \~ - \details \ru Разрыв по номеру.\n - Номер не проверяется на корректность. - \en A break by the number. \n - A number isn't checked for correctness. \~ - \param[in] i - \ru Номер разрыва, должен быть меньше количества разрывов. - \en The number of break must be less than the number of breaks. \~ - \return \ru Указатель на разрыв. - \en Pointer to break. \~ - */ - MbBreak * GetBreak ( size_t i ) const { return breaks[i]; } - - /** \brief \ru Разрыв по номеру в параметрах контура. - \en A break by the number in contour parameters. \~ - \details \ru Разрыв по номеру в параметрах контура.\n - Номер проверяется на корректность. - В случае, если номер больше числа сегментов результат - вывернутая область. - \en A break by the number in contour parameters. \n - A number Is checked for correctness. - If number is more than numbers of segments then result is everted region. \~ - \param[in] i - \ru Номер разрыва, должен быть меньше количества разрывов. - \en The break number must be less than the number of all breaks. \~ - \return \ru Интервал разрыва в параметрах контура. - \en Break interval in contour parameters. \~ - */ - MbRect1D GetBreaksRange ( size_t i ) const; - - /** \} */ - /**\ru \name Функции доступа к данным: видимые участки. - \en \name Functions for access to data: visible regions. - \{ */ - - /** \brief \ru Количество видимых частей. - \en The number of visible parts. \~ - \details \ru Количество видимых частей.\n - Если в контуре нет разрывов, то возвращает 0. - \en The number of visible parts. \n - If contour does not contain breaks, then returns 0. \~ - \return \ru Число видимых частей. - \en The number of visible parts. \~ - */ - size_t GetVisibleCount () const { return visibleContours.Count(); } - - /** \brief \ru Видимая часть по номеру. - \en A visible part by the number. \~ - \details \ru Видимая часть по номеру.\n - Номер не проверяется на корректность. - \en A visible part by the number. \n - A number isn't checked for correctness. \~ - \param[in] i - \ru Номер видимой части, должен быть меньше количества видимых частей. - \en The number of visible part must be less than the number of visible parts. \~ - \return \ru Указатель не контур - видимую часть. - \en A pointer to visible part of the contour. \~ - */ - const MbContour * GetVisibleContour ( size_t i ) const { return visibleContours[i]; } - - /** \} */ - /**\ru \name Функции доступа к данным: невидимые участки. - \en \name Functions for access to data: Invisible regions. - \{ */ - - /** \brief \ru Невидимая часть по номеру разрыва. - \en Invisible part by the number of break. \~ - \details \ru Невидимая часть по номеру разрыва.\n - Номер проверяется на корректность. - В случае, если номер не меньше числа разрывов, функция вернет 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 - 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. \~ - \return \ru Указатель не контур - видимую часть. - \en A pointer to visible part of the contour. \~ - */ - MbContour * GetInvisibleContour ( size_t i ) const; - - /** \} */ - /**\ru \name Работа с разрывами: добавление. - \en \name Working with breaks: addition. - \{ */ - - /** \brief \ru Добавить разрыв между точками. - \en Add a break between points. \~ - \details \ru Добавить разрыв между точками.\n - \en Add a break between points. \n \~ - \param[in] point1 - \ru Первая граница разрыва. - \en The first boundary of break. \~ - \param[in] point2 - \ru Вторая граница разрыва. - \en The second boundary of break. \~ - \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n - в случае разомкнутого контура она игнорируется. - \en A point which indicates a removable part of the closed contour, \n - in the case of open contour it is ignored. \~ - \param[in] invertBreak - \ru Признак добавления разрыва на противоположную часть контура. - \en addition attribute of break on the opposite part of contour. \~ - \return \ru true, если разрыв был добавлен. - \en true if break has been added. \~ - */ - bool AddBreak ( const MbCartPoint & point1, const MbCartPoint & point2, - const MbCartPoint & point3, bool invertBreak = false ); - - /** \brief \ru Добавить разрыв между параметрами контура. - \en Add a break between contour parameters. \~ - \details \ru Добавить разрыв между параметрами контура.\n - \en Add a break between contour parameters. \n \~ - \param[in] t1 - \ru Первая граница разрыва. - \en The first boundary of break. \~ - \param[in] t2 - \ru Вторая граница разрыва. - \en The second boundary of break. \~ - \param[in] t3 - \ru Параметр, который показывает удаляемую часть замкнутого контура,\n - в случае разомкнутого контура он игнорируется. - \en A parameter which indicates a removable part of the closed contour, \n - in the case if contour is open it is ignored. \~ - \param[in] invertBreak - \ru Признак добавления разрыва на противоположную часть контура. - \en addition attribute of break on the opposite part of contour. \~ - \return \ru true, если разрыв был добавлен. - \en true if break has been added. \~ - */ - bool AddBreak ( double t1, double t2, double t3, bool invertBreak = false ); - - /** \brief \ru Добавить разрыв по интервалу параметров контура. - \en Add a break by interval of contour parameters. \~ - \details \ru Добавить разрыв по интервалу параметров контура.\n - \en Add a break by interval of contour parameters. \n \~ - \param[in] range - \ru Интервал параметров контура,\n - если range.zmin больше range.zmax, то результат работы функции - будет корректным только в случае замкнутого контура - - добавится разрыв, проходящий через начало контура. - \en An interval of contour parameters. \n - if range.zmin is greater than range.zmax then the function result - is correct only in the case of closed contour - - added a break passing through the origin of the contour. \~ - \return \ru true, если разрыв был добавлен. - \en true if break has been added. \~ - */ - bool AddBreak ( const MbRect1D & range ); - - /** \} */ - /**\ru \name Работа с разрывами: удаление. - \en \name Working with breaks: removing. - \{ */ - - /** \brief \ru Удалить разрывы. - \en Remove breaks. \~ - \details \ru Удалить все разрывы.\n - \en Remove all breaks. \n \~ - \return \ru true, если хотя бы один разрыв был удален. - \en true, if at least one break has been removed. \~ - */ - bool DeleteBreaks (); ///< \ru Удалить разрывы. \en Remove breaks. - - /** \brief \ru Удалить разрыв по номеру разрыва. - \en Remove a break by the number. \~ - \details \ru Удалить разрыв по номеру разрыва.\n - \en Remove a break by the number. \n \~ - \param[in] breakIndex - \ru Номер разрыва,\n - проверяется на корректность.\n - \en The number of break. \n - checked for correctness. \n \~ - \param[in] rebuild - \ru Нужно ли перестроить контур после удаления разрыва.\n - Если контур не перестраивать, видимые части контура не будут соответствовать разрывам.\n - Перестроить контур можно отдельно вызовом RebuildBreaks. - \en Is the contour to be rebuilt after removing break. \n - If don't rebuild contour then the visible parts of contour do not match breaks. \n - Rebuild contour you can be separately by call RebuildBreaks. \~ - \return \ru true, если разрыв был удален. - \en true if break has been removed. \~ - */ - bool DeleteBreakAtNumber ( size_t breakIndex, bool rebuild = false); - - /** \brief \ru Удалить разрыв по параметру на контуре. - \en Remove a break by parameter on the contour. \~ - \details \ru Удалить разрыв по параметру на контуре.\n - \en Remove a break by parameter on the contour. \n \~ - \return \ru true, если разрыв был удален - \en true if break has been removed \~ - */ - bool DeleteBreakAtParam ( double t ); - - /** \brief \ru Удалить разрывы на сегментах с соответствующим базовым номером. - \en Remove breaks on the segments with the corresponding base number. \~ - \details \ru Удалить разрывы на сегментах с соответствующим базовым номером.\n - Разрывы удаляться, если в контуре заполнены базовые номера сегментов. - Номера заполняются при перестроении мультилинии, содержащей контур.\n - Если сегменту контура соответствует одна из частей разрыва, то весь разрыв будет удален. - \en Remove breaks on the segments with the corresponding base number. \n - Break are removed if base numbers of segments are filled in contour. - The number are filled when multiline is rebuilt which contrains contour. \n - If segment of contour corresponds to one of break parts then entire break is removed. \~ - \param[in] baseNumber - \ru Номер сегмента базовой кривой. - \en A segment number of base curve. \~ - \param[in] delTracingBreaks - \ru Нужно ли удалять разрывы с сегментоа, соответствующих обходу вершины мультилинии. - \en Is it necessary for breaks to be removed from segments which correspond to multiline vertices traverse. \~ - \param[in] delEquidBreaks - \ru Нужно ли удалять разрывы с сегментов, соответствующих эквидистантам. - \en breaks to be removed from segments which correspond to equidistants. \~ - \param[in] delInLineSeg - \ru Удалять ли разрывы с прямолинейных сегментов. - \en Is it necessary to remode breaks from straight segments. \~ - */ - void DeleteBreaksAtBaseNumber ( size_t baseNumber, bool delTracingBreaks, - bool delEquidBreaks, bool delInLineSeg = true ); - /** \} */ - /**\ru \name Удаление разрывов и видимых частей малой метрической длины. - \en \name Removing of breaks and visible parts of the small metric length. - \{ */ - - /** \brief \ru Удалить разрывы малой метрической длины. - \en Remove breaks of the small metric length. \~ - \details \ru Удалить разрывы малой метрической длины.\n - В случае успеха видимые контуры перестраиваются соответственно разрывам. - \en Remove breaks of the small metric length. \n - In case of success the visible contours are rebuilt by breaks. \~ - \param[in] length - \ru Минимальная длина невидимой части. - \en Minimal length of invisible part. \~ - \return \ru true, если хотя бы один разрыв был удален. - \en true, if at least one break has been removed. \~ - */ - bool DeleteSmallBreaks ( double length ); - - /** \brief \ru Удалить видимые части малой метрической длины. - \en Remove visible parts of the small metric length. \~ - \details \ru Удалить видимые части малой метрической длины.\n - Соответствует объединению близких разрывов в один. - В случае успеха видимые контуры перестраиваются соответственно разрывам. - \en Remove visible parts of the small metric length. \n - Corresponds to union of close discontinuities into one. - In case of success the visible contours are rebuilt by breaks. \~ - \param[in] length - \ru Минимальная длина видимой части. - \en Minimal length of visible part. \~ - \return \ru true, если разрывы были изменены. - \en true if breaks have been changed. \~ - */ - bool DeleteSmallVisContours ( double length ); - - /** \} */ - /**\ru \name Работа с разрывами - \en \name Working with breaks - \{ */ - - /** \brief \ru Номер разрыва, край которого попал в окрестность точки. - \en The number of break the edge of which is into point neighbourhood. \~ - \details \ru Номер разрыва, край которого попал в окрестность точки.\n - \en The number of break the edge of which is into point neighbourhood. \n \~ - \param[in] p - \ru Точка. - \en Point. \~ - \param[in] rad - \ru Радиус окрестности точки для поиска разрыва. - \en Radius of point neighborhood to search the break. \~ - \param[out] index - \ru Номер разрыва. - \en The number of break. \~ - \return \ru true, если разрыв найден. - \en true if the break is found. \~ - */ - bool GetBreakAtPoint ( const MbCartPoint & p, double rad, - size_t & index ) const; - - /** \brief \ru Номера разрывов, которые хотя бы одним краем попадают в область. - \en Numbers of breaks which at least one edge fall into the region. \~ - \details \ru Номера разрывов, которые хотя бы одним краем попадают в область.\n - \en Numbers of breaks which at least one edge fall into the region. \n \~ - \param[in] rect - \ru Область поиска. - \en Region of search. \~ - \param[out] breaksNumbers - \ru Номера разрывов. - \en Numbers of breaks. \~ - \return \ru true, если хотя бы один разрыв найден. - \en true, if at least one break has been found. \~ - */ - bool GetBreaksInRect ( const MbRect & rect, - SArray & breaksNumbers ) const; - - /** \brief \ru Номера разрывов, которые хотя бы одним краем попадают в область. - \en Numbers of breaks which at least one edge fall into the region. \~ - \details \ru Номера разрывов, которые хотя бы одним краем попадают в область, заданную контуром.\n - \en Numbers of breaks which at least one edge fall into the region given contour. \n \~ - \param[in] contour - \ru Контур должен быть замкнутым и иметь правильное направление. - \en Contour must be closed and have the right direction. \~ - \param[out] breaksNumbers - \ru Номера разрывов. - \en Numbers of breaks. \~ - \return \ru true, если хотя бы один разрыв найден. - \en true, if at least one break has been found. \~ - */ - bool GetBreaksInRect ( const MbContour & contour, - SArray & breaksNumbers ) const; - - /** \brief \ru Определить попадает ли точка в любой из разрывов. - \en Determine whether a point it inside a break. \~ - \details \ru Определить попадает ли точка в любой из разрывов.\n - \en Determine whether a point it inside a break. \n \~ - \param[in] p - \ru Точка для проверки. - \en A point for the check. \~ - \return \ru true, если точка попадает в любой из разрывов. - \en true, if point falls into any break. \~ - */ - bool HitToBreaks ( const MbCartPoint & p ) const; - - /** \brief \ru Находится ли интервал параметров на разрыве. - \en Whether the interval of parameters is on break. \~ - \details \ru Находится ли интервал параметров на разрыве.\n - \en Whether the interval of parameters is on break. \n \~ - \param[in] rect - \ru Интервал для проверки. - \en Interval to check. \~ - \return \ru true, если интервал полностью находится на разрыве или совпадает с ним. - \en true if interval entirely is on the break or coincides with it. \~ - */ - bool IsRectInBreak ( const MbRect1D & rect ); - - /** \brief \ru Обновить невидимые и видимые контуры. - \en Update visible and invisible contours. \~ - \details \ru Обновить невидимые и видимые контуры соответственно базовой кривой мультилинии.\n - После перестроения разрывы должны соответствовать сегментам базовой кривой мультилинии. - \en Update visible and invisible contours by base curve of multiline respectively. \n - After rebuilding the breaks must correspond to segments of base multiline curve. \~ - \param[in] oldBaseNumbers - \ru Старые номера базовых сегментов,\n - должны быть запомнены до изменения мультилинии. - \en Old numbers of base segments, \n - must be saved before multiline is changed. \~ - */ - void RebuildBreaks ( SArray & oldBaseNumbers ); - - /** \brief \ru Обновить невидимые и видимые контуры. - \en Update visible and invisible contours. \~ - \details \ru Обновить невидимые и видимые контуры соответственно разрывам. - \en Update visible and invisible contours according to breaks. \~ - */ - void RebuildBreaks ( ); - - /** \brief \ru Преобразование в соответствии с матрицей. - \en Transform according to matrix. \~ - \details \ru Преобразование в соответствии с матрицей.\n - Используется для преобразования мультилинии. - Преобразует длину и расстояние от фиксированной точки прямолинейного разрыва, - а так же фиксированную точку. - \en Transform according to matrix.\n - Used to transform multiline. - Transforms length and distance from fixed point of straight break, - and fixed point. \~ - \param[in] matr - \ru Матрица преобразования. - \en A transformation matrix. \~ - */ - void TransformMultlinesBreaks ( const MbMatrix & matr ); - - /** \brief \ru Параметр привязки части разрыва. - \en A binding parameter of a break part. \~ - \details \ru Посчитать параметр привязки части разрыва в зависимости от типа сегмента контура.\n - \en Calculate binding parameter of a break part according to the type of contour segment. \n \~ - \param[in] brPart - \ru Часть разрыва этого контура. - \en A break part of this contour. \~ - \param[out] segNumber - \ru Номер сегмента контура. - \en A number of the contour segment. \~ - \return \ru Параметр центра разрыва на сегменте контура. - \en A parameter of the break center on the contour segment. \~ - */ - double GetLocalBreaksParam ( const MbBreaksPart & brPart, - size_t & segNumber ) const; - - /** \} */ - /**\ru \name Работа с разрывами: изменение разрыва. - \en \name Working with breaks: changing a break. - \{ */ - - /** \brief \ru Фиксировать точку. - \en Fix the point. \~ - \details \ru Поставить фиксированную точку части разрыва.\n - \en Set the fixed point of a break part. \n \~ - \param[in] newPoint - \ru Новая фиксированная точка. - \en A new fixed point. \~ - \param[out] part - \ru Часть разрыва контура для изменения. - \en A part of contour break to change. \~ - */ - void SetBreakFixedPoint ( const MbCartPoint & newPoint, - MbBreaksPart & part ); - - /** \brief \ru Фиксировать переменную. - \en Fix the variable. \~ - \details \ru Поставить фиксированную переменную части разрыва.\n - \en Set the fixed variable of a break part. \n \~ - \param[in] newFixedVar - \ru Новая фиксированная переменная. - \en New fixed variable. \~ - \param[out] part - \ru Часть разрыва контура для изменения. - \en A part of contour break to change. \~ - */ - void SetBreakFixedVar ( double newFixedVar, MbBreaksPart & part); - - /** \} */ - /**\ru \name Работа с разрывами: отслеживание разрыва - \en \name Working with breaks: tracking a break - \{ */ - /// \ru Количество номеров сегментов базового контура \en Count of segments numbers of the base contour - // \ru (должно соответствовать количеству сегментов контура) \en (must be equal to count of contour segments) - size_t GetBaseNumbersCount () const { return baseSegNumbers.Count(); } - - /// \ru Номера сегментов базового контура. \en Numbers of segments of base contour. - void GetBaseNumbers ( SArray & baseNumbers ) const; - - /** \brief \ru Номер сегмента базового контура. - \en Segment number of the base contour. \~ - \details \ru Номер сегмента базового контура.\n - Номер сегмента будет найден, если массив номеров не пуст и - корректно насчитан, то есть число номеров совпадает с числом сегментов контура - \en Segment number of the base contour. \n - Segment number will be found if the array of numbers is not empty and - it was numbered correctly, ie count of numbers is equal to count of contour segments \~ - \param[in] i - \ru Индекс номера. - \en Index of number. \~ - \return \ru Номер сегмента из массива номеров. - \en Number of segment from the array of numbers. \~ - */ - size_t GetBaseNumber ( size_t i ) const; - - /** \brief \ru Добавить номер базового сегмента. - \en Add number of the base segment. \~ - \details \ru Добавить номер сегмента базового контура в конец массива.\n - \en Add segment number of base contour to the end of array. \n \~ - \param[in] number - \ru Номер для добавления. - \en Number to add. \~ - */ - void AddBaseSegNumber ( size_t number ); - - /** \brief \ru Добавить номер базового сегмента. - \en Add number of the base segment. \~ - \details \ru Добавить номер сегмента базового контура в начало массива.\n - \en Add segment number of base contour to the beginning of array. \n \~ - \param[in] number - \ru Номер для добавления. - \en Number to add. \~ - */ - void AddBaseSegNumberAtBegin ( size_t number ); - - /** \brief \ru Вставить номер после lastInd. - \en Insert number after the lastInd. \~ - \details \ru Вставить после элемента номер lastInd номер, соответствующий lastInd.\n - \en Insert number corresponding lastInd after element lastInd. \n \~ - \param[in] lastInd - \ru Индекс номера. - \en Index of number. \~ - */ - void InsertLastSegNumber ( size_t lastInd ); - - /** \brief \ru Удалить элемент по индексу. - \en Delete element by an index. \~ - \details \ru Удалить номер базового сегмента по индексу.\n - \en Remove number of the base segment by an index. \n \~ - \param[in] ind - \ru Индекс номера. - \en Index of number. \~ - */ - void DeleteBaseSegNumber ( size_t ind ); - - /// \ru Очистить массив с номерами базовых сегментов. \en Clear the array with numbers of base segments. - void ClearBaseSegNumbers () { baseSegNumbers.HardFlush(); } - - /** \brief \ru Изменить номера сегментов в разрывах. - \en Change numbers of segments in the breaks. \~ - \details \ru Изменить номера сегментов в разрывах.\n - Заданному номеру базового сегмента соответствует сегмент - эквидистанта на контуре. - Для всех разрывов: - если хотя бы часть разрыва находится на этом сегменте, - у всех его частей номер сегмента будет изменен. - \en Change numbers of segments in the breaks. \n - A given number of the base segments corresponds to the segment - equidistant on the contour. - For all breaks: - if at least one part of break is in this segment, - the segment number of all of its parts will be changed. \~ - \param[in] begBaseNumber - \ru Номер базового сегмента. - \en An index of the base segment. \~ - \param[in] deltaN - \ru Величина изменение номера сегмента частей разрывов. - \en The change value of segment number of breaks parts. \~ - */ - void ChangeBreaksSegNumbers ( size_t begBaseNumber, ptrdiff_t deltaN ); - - /** \brief \ru Изменить разрывы соотвестсвенно замкнутости. - \en Change breaks of closedness respectively. \~ - \details \ru Изменить разрывы соотвестсвенно замкнутости.\n - При изменении признака замкнутости контура нужно изменить разрывы - соответственно новому значению замкнутости.\n - Если контур стал разомкнутым - разрыв, находящийся на первом и последнем - сегменте одновременно, делится на 2 части.\n - Если контур стал замкнутым - разрывы, первый из который примыкает к левому краю - первого сегмента контура, а второй из которых примыкает к правому краю последнего - сегмента контура, объединяется в один. - \en Change breaks of closedness respectively. \n - When changing attribute of contour closedness breaks need to change - respectively to the new value of closedness. \n - If contour has become open - the break located on the first and last - segment is divided into 2 parts at the same time. \n - If contour has become closed - breaks, the first of which is adjacent to the left boundary - of the first contour segment and the second of which is adjacent to the right boundary of the last - contour segment are united into one. \~ - \param[in] newClosed - \ru Новый признак замкнутости контура. - \en The new closedness attribute of contour. \~ - */ - void ChangeBreaksAtClosed ( bool newClosed ); - - /** \brief \ru Изменить номера сегментов частей разрывов. - \en Change segments numbers of breaks parts. \~ - \details \ru Изменить номера сегментов частей разрывов.\n - \en Change segments numbers of breaks parts. \n \~ - \param[in] deltaN - \ru Величина изменения. - \en A change value. \~ - */ - void MoveBreaksSegNumbers ( ptrdiff_t deltaN ); - - /** \brief \ru Находится ли часть разрыва этого контура на сегменте обхода вершин. - \en Is the break part of this contour located on the segment of vertices traverse. \~ - \details \ru Находится ли часть разрыва этого контура на сегменте обхода вершин.\n - \en Is the break part of this contour located on the segment of vertices traverse. \n \~ - \param[in] part - \ru Часть разрыва этого контура. - \en A break part of this contour. \~ - \param[out] vertNumber - \ru В случае успеха вернет номер вершины. - \en In the case of success returns the vertex number. \~ - \return \ru true, если часть разрыва находится на сегменте обхода вершины. - \en true, if the break part is located on the segment of vertices traverse. \~ - */ - bool IsTrasingBreaksPart ( const MbBreaksPart & part, - size_t & vertNumber ) const; - - /** \brief \ru Поменяться разрывами. - \en Swap breaks. \~ - \details \ru Поменяться разрывами.\n - \en Swap breaks. \n \~ - \param[in] other - \ru Контур с разрывами для обмена. - \en A contour with breaks to swap. \~ - */ - void SwapBreaksAndBaseNumbers ( MbContourWithBreaks & other ); - - /** \brief \ru Добавить разрывы контура. - \en Add contour breaks. \~ - \details \ru Добавить разрывы контура.\n - \en Add contour breaks. \n \~ - \param[in] other - \ru Контур с разрывами для добавления разрывов. - \en A contour with breaks for adding breaks. \~ - */ - void AddContoursBreaks ( const MbContourWithBreaks & other ); - - /** \brief \ru Заменить номера базовых сегментов. - \en Replace the numbers of base segments. \~ - \details \ru Заменить номера базовых сегментов.\n - \en Replace the numbers of base segments. \n \~ - \param[in] other - \ru Контур с новыми номерами. - \en A contour with new numbers. \~ - */ - void ChangeBaseNumbers ( const MbContourWithBreaks & other ); - /** \} */ - -private: - void DeleteBreaks ( size_t segmentIndex, - bool delInLineSeg = true ); // \ru удалить разрывы на сегменте с номером index \en remove breaks from segment with number "index" - void DeleteBreaksPartAtSegNum ( size_t segNumber, size_t oldSegCount ); // \ru часть разрыва по номеру сегмента \en part of break by the segment number - bool DeleteBreaksPartOrBreak ( size_t breakIndex, size_t partIndex, - size_t oldSegCount ); // \ru часть разрыва или разрыв \en part of break or break -private: - void CalculateVisibleContours ( ); // \ru посчитать видимые части \en calculate visible parts - void CalculateInvisibleContours( RPArray & invisibleContours ); // \ru посчитать невидимые части \en calculate invisible parts - void CalculateContours ( const CSSArray & ranges, // \ru посчитать контуры по интервалам \en calculate contours by intervals - RPArray & contours, - bool visible ) const; // \ru для видимых частей вызывать AddRef() \en call AddRef() for visible parts - void CalculateInVisibleRanges ( CSSArray & breaksRanges ); // \ru посчитать невидимые интервалы \en calculate invisible intervals - void CalculateVisibleRanges ( CSSArray & breaksRanges, - CSSArray & visibleRanges ) const; // \ru посчитать видимые интервалы \en Calculate visible intervals - void CalculateRanges ( const CSSArray & startingInt, // \ru посчитать противоположные интервалы \en Calculate opposite intervals - CSSArray & resultInt ) const; // \ru второй массив по первому \en the second array by the first - void CalculateBreaksPart ( const MbRect1D & segParams, - size_t segNumber, MbBreak & brRange ) const; // \ru посчитать часть разрыва \en Calculate a part of the break - void CalculateBreak ( const MbRect1D & range, - MbBreak & brRange ) const; // \ru посчитать разрыв по интервалу \en Calculate the break by interval - MbRect1D GetLocalBreaksRange ( const MbBreaksPart & part, - double brParam, size_t segNumber ) const; // \ru интервал по параметру привязки \en interval by the binding parameter - void AddCalcBreak ( const MbRect1D & range ); - void ChangeBreaksSegNumbers ( const SArray & oldBaseNumbers, - SArray & oldEqCounts, - SArray & newEqCounts ); // \ru изменить номера сегментов у разрывов \en change segments numbers of breaks - void RedefineBreaksParts (); // \ru доопределить неопределенные части разрыва \en complete the definition of indefinite parts of the break - - // \ru для преобразования контуров \en for transformation of contours - void TransformBreaks ( const MbMatrix & matr ); // \ru преобразование в соответствии с матрицей \en transform according to the matrix - - size_t GetLocalBreaksRange ( const MbBreaksPart & part, - MbRect1D & localRect ) const; // \ru разрыв по номеру в параметрах сегмента \en a break by the number in segment parameters - - - void operator = ( const MbContourWithBreaks & ); // \ru не реализован \en not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContourWithBreaks ) - -}; // MbContourWithBreaks - -IMPL_PERSISTENT_OPS( MbContourWithBreaks ) - -//------------------------------------------------------------------------------ -/** \brief \ru Часть разрыва. - \en Part of break. \~ - \details \ru Часть разрыва контура мультилинии. Относится к одному сегменту контура.\n - Для использования в разрыве MbBreak. - \en Part of multiline contour break. Applicable to one segment of the contour.\n - For using in the break MbBreak. \~ - \ingroup Algorithms_2D -*/ // --- -class MATH_CLASS MbBreaksPart { - -private : - size_t segNumber; // \ru Номер сегмента \en Number of the segment. - double fixedVar; // \ru Фиксированная переменная \en Fixed variable - // \ru ( tMax - tCentre ) / ( tCentre - tMin ), tCentre - параметр центра разрыва \en ( tMax - tCentre ) / ( tCentre - tMin ), tCentre - center of the break - // \ru для отрезка - расстояние до проекции неподвижной точки \en for segment - distance to projection of the fixed point - double length; // \ru Длина части разрыва (для отрезка) \en Length of the break part (for segment) - // \ru для дуг и по умолчанию сохраняем параметрическую длину \en For arcs and save parametric length by default. - // \ru (для дуги - угол) \en (for arc - angle) - MbCartPoint fixedPoint; // \ru неподвижная точка ( корректное значение для отрезка ) \en fixed point (correct value for segment) - -public: - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по номеру сегмента, фиксированной переменной, длине, неподвижной точке. - \en Constructor by a number of segment, fixed variable, length, fixed point. \~ - \param[in] sNumber - \ru Номер сегмента контура, на котором находится часть разрыва. - \en Number of contour segment where a part of break is located. \~ - \param[in] fixVar - \ru Фиксированная переменная:\n - для отрезка - расстояние до проекции неподвижной точки,\n - в общем случае - величина, равная ( tMax - tCentre ) / ( tCentre - tMin ), где\n - tMin - минимальный параметр сегмента,\n - tMax - максимальный параметр сегмента,\n - tCentre - параметр центра части разрыва. - \en Fixed variable:\n - for segment - distance to projection of the fixed point,\n - In general case - a value which is equal to ( tMax - tCentre ) / ( tCentre - tMin ), where \n - tMin - minimal parameter of the segment,\n - tMax - maximal parameter of the segment,\n - tCentre - parameter of the break part center. \~ - \param[in] len - \ru Длина части разрыва:\n - для отрезка - метрическая длина,\n - в общем случае - параметрическая длина. - \en Length of the break part:\n - for segment - metric length, \n - In the general case - parametric length. \~ - \param[in] p - \ru Неподвижная точка:\n - для отрезка - используется для привязки части разрыва,\n - в общем случае - не имеет смысла. - \en Fixed point:\n - for segment - used to bind part of the break,\n - in general case - it is useless. \~ - */ - MbBreaksPart( size_t sNumber, double fixVar, double len, const MbCartPoint & p ) - : segNumber ( sNumber ), - fixedVar ( fixVar ), - length ( len ), - fixedPoint( p ) - { - } - - /// \ru Копирующий конструктор. \en Copy-constructor. - MbBreaksPart( const MbBreaksPart & other ) - : segNumber ( other.GetSegmentNumber() ), - fixedVar ( other.GetFixedVar() ), - length ( other.GetLength() ), - fixedPoint( other.GetFixedPoint() ) - { - } - - ~MbBreaksPart(){}; - - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - size_t GetSegmentNumber() const { return segNumber; } ///< \ru Номер сегмента контура. \en A number of the contour segment. - double GetFixedVar() const { return fixedVar; } ///< \ru Фиксированная переменная. \en fixed variable - double GetLength() const { return length; } ///< \ru Длина части разрыва. \en Length of the break part. - const MbCartPoint & GetFixedPoint() const { return fixedPoint; } ///< \ru Фиксированная точка. \en Fixed point. - - /** \} */ - /**\ru \name Функции изменения данных. - \en \name Functions for changing data. - \{ */ - - /// \ru Изменить номер сегмента контура. \en Change a number of the contour segment. - void SetSegmentNumber( size_t newNumber ) { segNumber = newNumber; } - /// \ru Изменить фиксированную переменную. \en Change a fixed variable. - void SetFixedFar ( double newFixedVar ) { fixedVar = newFixedVar; } - /// \ru Изменить длину части разрыва. \en Change the length of the break part. - void SetLength ( double newLength ) { length = newLength; } - /// \ru Изменить фиксированную точку. \en Change a fixed point. - void SetFixedPoint ( const MbCartPoint & point ) { fixedPoint.Init( point ); } - - /** \brief \ru Переместить. - \en Move. \~ - \details \ru Переместить на вектор.\n - \en Move by vector.\n \~ - \param[in] to - \ru Вектор перемещения. - \en Movement vector. \~ - */ - void Move ( const MbVector & to ) { fixedPoint.Move( to ); } - - /** \brief \ru Повернуть. - \en Rotate. \~ - \details \ru Повернуть на угол вокруг точки.\n - \en Rotate at angle around a point.\n \~ - \param[in] pnt - \ru Точка - центр поворота. - \en A point is a rotation center. \~ - \param[in] angle - \ru Двумерный нормализованный вектор, задающий угол вращения. - \en A two-dimensional normalized vector which defines a rotation angle. \~ - */ - void Rotate ( const MbCartPoint & pnt, const MbDirection & angle ) { fixedPoint.Rotate( pnt, angle ); } - - /** \brief \ru Преобразование. - \en Transformation. \~ - \details \ru Преобразование в соответствии с матрицей.\n - \en Transform according to matrix.\n \~ - \param[in] matr - \ru Матрица трансформации. - \en Transformation matrix. \~ - */ - void Transform ( const MbMatrix & matr ) { fixedPoint.Transform( matr ); } - - /** \brief \ru Изменить номер сегмента. - \en Change a number of the segment. \~ - \details \ru Изменить номер сегмента на заданную величину.\n - Номер сегмента не изменится, если величина изменения будет отрицательной и большей по модулю, чем номер. - \en Change a number of the segment by a given value. \n - The number of the segment does not change if the amount of change is negative and greater in absolute value than the number. \~ - \param[in] deltaN - \ru Величина увеличения номера сегмента. - \en Increase value of the segment number. \~ - */ - void ChangeSegNumber ( ptrdiff_t deltaN ) { if( deltaN >= 0 || (ptrdiff_t)segNumber >= -deltaN ) segNumber += deltaN; } - /** \} */ -private: - void operator = ( const MbBreaksPart & ); // \ru не реализован \en not implemented -}; // MbBreaksPart - - -//------------------------------------------------------------------------------ -/** \brief \ru Разрыв. - \en Break. \~ - \details \ru Разрыв контура.\n - Для использования в контуре с разрывом MbContourWithBreaks.\n - Разрыв состоит из частей MbBreaksPart, каждая из которых находится на одном сегменте контура.\n - В разрыве может быть 1 или 2 части. - Если разрыв должен располагаться более чем на трех сегментах, то он имеет 2 части, - соответствующие первому и последнему сегментам. - \en Contour break.\n - For using in the contour with break MbContourWithBreaks.\n - The break consists of parts MbBreaksPart all of which are on the same segment of the contour. \n - The break can have 1 or 2 parts. - If the break must be located more than three segments it has two parts, - corresponding to the first and the last segments. \~ - \ingroup Algorithms_2D -*/ // --- -class MATH_CLASS MbBreak { - -private: - SArray parts; // \ru части разрыва: \en part of break: - // \ru одна, если разрыв на одном сегменте, \en one if the break is on the one segment, - // \ru две, если на нескольких сегментах - первая и последняя \en two if break is on the several segments - the first and the last - -public: - - /** \brief \ru Конструктор пустого разрыва. - \en Constructor of an empty break. \~ - \details \ru Конструктор пустого разрыва.\n - Такой разрыв не может находиться в контуре с разрывом MbContourWithBreaks. - Он будет удален при перестроении. - \en Constructor of an empty break. \n - Such break can not be in the contour with break MbContourWithBreaks. - It will be removed when rebuilding. \~ - */ - MbBreak(): parts () { } - - /// \ru Копирующий конструктор. \en Copy-constructor. - MbBreak( const MbBreak & other ): parts ( other.parts ) {} - - ~MbBreak() {} - -public: - - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - ///< \ru Количество частей. \en The number of parts. - size_t PartsCount () const { return parts.Count(); } - - /** \brief \ru Часть по номеру. - \en A part by the number. \~ - \details \ru Часть по номеру части разрыва.\n - Номер не проверяется на корректность. - \en A part by the number of the break part. \n - A number isn't checked for correctness. \~ - \param[in] number - \ru Номер части разрыва, должен быть меньше количества частей. - \en The number of break part must be less than the number of parts. \~ - \return \ru Ссылку на часть разрыва. - \en Reference to part of break. \~ - */ - MbBreaksPart & GetPart ( size_t number ) const { return parts[number]; } - - /** \} */ - /**\ru \name Функции изменения данных. - \en \name Functions for changing data. - \{ */ - - /// \ru Добавить часть разрыва. \en Add a part of break. - void AddPart ( MbBreaksPart part ) { parts.Add( part ); } - /// \ru Удалить все части разрыва. \en Remove all parts of break. - void DeleteParts () { parts.HardFlush(); } - - /** \brief \ru Удалить часть. - \en Remove a part. \~ - \details \ru Удалить часть разрыва по номеру.\n - Номер проверяется на корректность. - Если номер не меньше количества частей, то разрыв не изменится. - \en Remove a part of break by the number. \n - A number Is checked for correctness. - If the number isn't less than the number of parts the break doesn't change. \~ - \param[in] number - \ru Номер части разрыва, должен быть меньше количества частей. - \en The number of break part must be less than the number of parts. \~ - */ - void DeletePart ( size_t number ) { if( number < PartsCount() ) parts.RemoveInd( number ); } - - /** \brief \ru Переместить. - \en Move. \~ - \details \ru Переместить на вектор.\n - \en Move by vector.\n \~ - \param[in] to - \ru Вектор перемещения. - \en Movement vector. \~ - */ - void Move( const MbVector & to ) - { - for( size_t i = 0, count = parts.Count(); i < count; ++i ) - parts[i].Move( to ); - } - - /** \brief \ru Повернуть. - \en Rotate. \~ - \details \ru Повернуть на угол вокруг точки.\n - \en Rotate at angle around a point.\n \~ - \param[in] pnt - \ru Точка - центр поворота. - \en A point is a rotation center. \~ - \param[in] angle - \ru Двумерный нормализованный вектор, задающий угол вращения. - \en A two-dimensional normalized vector which defines a rotation angle. \~ - */ - void Rotate( const MbCartPoint & pnt, const MbDirection & angle ) - { - for( size_t i = 0, count = parts.Count(); i < count; ++i ) - parts[i].Rotate( pnt, angle ); - } - - /** \brief \ru Преобразовать. - \en Transform. \~ - \details \ru Преобразовать в соответствии с матрицей.\n - \en Transform according to matrix.\n \~ - \param[in] matr - \ru Матрица трансформации. - \en Transformation matrix. \~ - */ - void Transform( const MbMatrix & matr ) - { - for( size_t i = 0, count = parts.Count(); i < count; ++i ) - parts[i].Transform( matr ); - } - /** \} */ -private: - void operator =( const MbBreak & ); // \ru не реализован \en not implemented - -}; // MbBreak - - -//------------------------------------------------------------------------------ -/** \brief \ru Ближайшие проекции на контур. - \en Nearest projections on the contour. \~ - \details \ru Ближайшие проекции точки на контур.\n - \en Nearest projections of point on the contour. \n \~ - \param[in] contour - \ru Контур. - \en A contour. \~ - \param[in] pnt - \ru Проецируемая точка. - \en Projecting point. \~ - \param[out] tProjs - \ru Параметры ближайших проекций. - \en Parameters of nearest projections. \~ - \param[in] isNear - \ru Выбрать только проекции, - находящиеся от проецируемой точки не дальше заданной точности. - \en Select only the projections - which are located from projecting point within a given tolerance. \~ - \param[in] mEps - \ru Точность выбора ближайших точек. - \en A tolerance of nearest points selection. \~ - \ingroup Algorithms_2D -*/ -// --- -MATH_FUNC (void) NearPointProjections( const MbContour & contour, const MbCartPoint & pnt, - SArray & tProjs, bool isNear, double mEps = METRIC_REGION ); - - - -#endif // __CUR_CONTOUR_WITH_BREAKS_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контур с разрывами. + \en Contour with breaks. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_CONTOUR_WITH_BREAKS_H +#define __CUR_CONTOUR_WITH_BREAKS_H + + +#include +#include +#include + + +class MATH_CLASS MbBreaksPart; +class MATH_CLASS MbBreak; + + +//------------------------------------------------------------------------------ +/** \brief \ru Контур c разрывами. + \en Contour with breaks. \~ + \details \ru Контур c разрывами.\n + Для использования в мультилинии MbMultiline.\n + Содержит разрывы MbBreak, видимые части - контуры MbContour.\n + При использовании в мультилинии каждуй раз при перестроении контура в нем обновляется + список номеров по количеству сегментов контура. + Каждый номер показывает номер сегмента базовой кривой мультилинии, + которому соответствует этот сегмент контура.\n + Если сегмент контура является эквидистантой сегмента базовой кривой, + то ему соответствует номер этого сегмента.\n + Если контур является сегментом обхода вершины мультилинии, + то ему соответствует номер, соответствующий предыдущему сегменту контура.\n + Разрывы в контуре не могут накладываться друг на друга. + Если в результате перестроения один разрыв наложился на другой, то они объединяются. + \en Contour with breaks.\n + For using in the multiline MbMultiline.\n + Contains breaks MbBreak, visible parts - contours MbContour.\n + When using in a multiline every time when contour is rebuilding in it are updated + list of numbers by the number of contour segments + Each number indicates the segment number of base curve of multiline. + which corresponds to this segment of contour.\n + If segment of contour is equidistant of base curve segment, + then it corresponds to the number of this segment.\n + If contour is segment of multiline vertices traverse. + then it corresponds to the number corresponding the previous segment of the contour.\n + Breaks in the contour can not be overlapped each other. + If in the result of rebuilding a break overlapped on the other break then they are combined. \~ + \ingroup Curves_2D +*/ // --- +class MATH_CLASS MbContourWithBreaks : public MbContour +{ +private: + RPArray breaks; // \ru Разрывы. \en Breaks. + RPArray visibleContours; // \ru Видимые контуры \en Visible contours. + SArray baseSegNumbers; // \ru Номера сегментов базового контура \en Numbers of segments of base contour + // \ru для задания неподвижных точек разрыва \en to define the fixed points of break + // \ru заполняется при использовании контура в мультилинии. \en filled when using the contour in the multiline. +public: + + /** \brief \ru Создание пустого контура. + \en Creation of empty contour. \~ + \details \ru Создание пустого контура без сегментов.\n + \en Creation of empty contour without segments. \n \~ + */ + MbContourWithBreaks(); + + MbContourWithBreaks( const MbContour & cnt ); ///< \ru Копирующий конструктор. \en Copy-constructor. + +private: + MbContourWithBreaks( const MbContourWithBreaks & ); // \ru не реализовано \en not implemented +protected : + MbContourWithBreaks( const MbContourWithBreaks &, MbRegDuplicate * ); +public: + virtual ~MbContourWithBreaks(); + +public : + VISITING_CLASS( MbContourWithBreaks ); + + /**\ru \name Общие функции геометрического объекта. + \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. + /** \} */ + /**\ru \name Функции доступа к данным: разрывы. + \en \name Functions for access to data: breaks. + \{ */ + size_t GetBreaksCount () const { return breaks.Count(); } ///< \ru Число разрывов. \en The number of breaks. + + /** \brief \ru Разрыв по номеру. + \en A break by the number. \~ + \details \ru Разрыв по номеру.\n + Номер не проверяется на корректность. + \en A break by the number. \n + A number isn't checked for correctness. \~ + \param[in] i - \ru Номер разрыва, должен быть меньше количества разрывов. + \en The number of break must be less than the number of breaks. \~ + \return \ru Указатель на разрыв. + \en Pointer to break. \~ + */ + MbBreak * GetBreak ( size_t i ) const { return breaks[i]; } + + /** \brief \ru Разрыв по номеру в параметрах контура. + \en A break by the number in contour parameters. \~ + \details \ru Разрыв по номеру в параметрах контура.\n + Номер проверяется на корректность. + В случае, если номер больше числа сегментов результат - вывернутая область. + \en A break by the number in contour parameters. \n + A number Is checked for correctness. + If number is more than numbers of segments then result is everted region. \~ + \param[in] i - \ru Номер разрыва, должен быть меньше количества разрывов. + \en The break number must be less than the number of all breaks. \~ + \return \ru Интервал разрыва в параметрах контура. + \en Break interval in contour parameters. \~ + */ + MbRect1D GetBreaksRange ( size_t i ) const; + + /** \} */ + /**\ru \name Функции доступа к данным: видимые участки. + \en \name Functions for access to data: visible regions. + \{ */ + + /** \brief \ru Количество видимых частей. + \en The number of visible parts. \~ + \details \ru Количество видимых частей.\n + Если в контуре нет разрывов, то возвращает 0. + \en The number of visible parts. \n + If contour does not contain breaks, then returns 0. \~ + \return \ru Число видимых частей. + \en The number of visible parts. \~ + */ + size_t GetVisibleCount () const { return visibleContours.Count(); } + + /** \brief \ru Видимая часть по номеру. + \en A visible part by the number. \~ + \details \ru Видимая часть по номеру.\n + Номер не проверяется на корректность. + \en A visible part by the number. \n + A number isn't checked for correctness. \~ + \param[in] i - \ru Номер видимой части, должен быть меньше количества видимых частей. + \en The number of visible part must be less than the number of visible parts. \~ + \return \ru Указатель не контур - видимую часть. + \en A pointer to visible part of the contour. \~ + */ + const MbContour * GetVisibleContour ( size_t i ) const { return visibleContours[i]; } + + /** \} */ + /**\ru \name Функции доступа к данным: невидимые участки. + \en \name Functions for access to data: Invisible regions. + \{ */ + + /** \brief \ru Невидимая часть по номеру разрыва. + \en Invisible part by the number of break. \~ + \details \ru Невидимая часть по номеру разрыва.\n + Номер проверяется на корректность. + В случае, если номер не меньше числа разрывов, функция вернет 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 + 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. \~ + \return \ru Указатель не контур - видимую часть. + \en A pointer to visible part of the contour. \~ + */ + MbContour * GetInvisibleContour ( size_t i ) const; + + /** \} */ + /**\ru \name Работа с разрывами: добавление. + \en \name Working with breaks: addition. + \{ */ + + /** \brief \ru Добавить разрыв между точками. + \en Add a break between points. \~ + \details \ru Добавить разрыв между точками.\n + \en Add a break between points. \n \~ + \param[in] point1 - \ru Первая граница разрыва. + \en The first boundary of break. \~ + \param[in] point2 - \ru Вторая граница разрыва. + \en The second boundary of break. \~ + \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n + в случае разомкнутого контура она игнорируется. + \en A point which indicates a removable part of the closed contour, \n + in the case of open contour it is ignored. \~ + \param[in] invertBreak - \ru Признак добавления разрыва на противоположную часть контура. + \en addition attribute of break on the opposite part of contour. \~ + \return \ru true, если разрыв был добавлен. + \en true if break has been added. \~ + */ + bool AddBreak ( const MbCartPoint & point1, const MbCartPoint & point2, + const MbCartPoint & point3, bool invertBreak = false ); + + /** \brief \ru Добавить разрыв между параметрами контура. + \en Add a break between contour parameters. \~ + \details \ru Добавить разрыв между параметрами контура.\n + \en Add a break between contour parameters. \n \~ + \param[in] t1 - \ru Первая граница разрыва. + \en The first boundary of break. \~ + \param[in] t2 - \ru Вторая граница разрыва. + \en The second boundary of break. \~ + \param[in] t3 - \ru Параметр, который показывает удаляемую часть замкнутого контура,\n + в случае разомкнутого контура он игнорируется. + \en A parameter which indicates a removable part of the closed contour, \n + in the case if contour is open it is ignored. \~ + \param[in] invertBreak - \ru Признак добавления разрыва на противоположную часть контура. + \en addition attribute of break on the opposite part of contour. \~ + \return \ru true, если разрыв был добавлен. + \en true if break has been added. \~ + */ + bool AddBreak ( double t1, double t2, double t3, bool invertBreak = false ); + + /** \brief \ru Добавить разрыв по интервалу параметров контура. + \en Add a break by interval of contour parameters. \~ + \details \ru Добавить разрыв по интервалу параметров контура.\n + \en Add a break by interval of contour parameters. \n \~ + \param[in] range - \ru Интервал параметров контура,\n + если range.zmin больше range.zmax, то результат работы функции + будет корректным только в случае замкнутого контура - + добавится разрыв, проходящий через начало контура. + \en An interval of contour parameters. \n + if range.zmin is greater than range.zmax then the function result + is correct only in the case of closed contour - + added a break passing through the origin of the contour. \~ + \return \ru true, если разрыв был добавлен. + \en true if break has been added. \~ + */ + bool AddBreak ( const MbRect1D & range ); + + /** \} */ + /**\ru \name Работа с разрывами: удаление. + \en \name Working with breaks: removing. + \{ */ + + /** \brief \ru Удалить разрывы. + \en Remove breaks. \~ + \details \ru Удалить все разрывы.\n + \en Remove all breaks. \n \~ + \return \ru true, если хотя бы один разрыв был удален. + \en true, if at least one break has been removed. \~ + */ + bool DeleteBreaks (); ///< \ru Удалить разрывы. \en Remove breaks. + + /** \brief \ru Удалить разрыв по номеру разрыва. + \en Remove a break by the number. \~ + \details \ru Удалить разрыв по номеру разрыва.\n + \en Remove a break by the number. \n \~ + \param[in] breakIndex - \ru Номер разрыва,\n + проверяется на корректность.\n + \en The number of break. \n + checked for correctness. \n \~ + \param[in] rebuild - \ru Нужно ли перестроить контур после удаления разрыва.\n + Если контур не перестраивать, видимые части контура не будут соответствовать разрывам.\n + Перестроить контур можно отдельно вызовом RebuildBreaks. + \en Is the contour to be rebuilt after removing break. \n + If don't rebuild contour then the visible parts of contour do not match breaks. \n + Rebuild contour you can be separately by call RebuildBreaks. \~ + \return \ru true, если разрыв был удален. + \en true if break has been removed. \~ + */ + bool DeleteBreakAtNumber ( size_t breakIndex, bool rebuild = false); + + /** \brief \ru Удалить разрыв по параметру на контуре. + \en Remove a break by parameter on the contour. \~ + \details \ru Удалить разрыв по параметру на контуре.\n + \en Remove a break by parameter on the contour. \n \~ + \return \ru true, если разрыв был удален + \en true if break has been removed \~ + */ + bool DeleteBreakAtParam ( double t ); + + /** \brief \ru Удалить разрывы на сегментах с соответствующим базовым номером. + \en Remove breaks on the segments with the corresponding base number. \~ + \details \ru Удалить разрывы на сегментах с соответствующим базовым номером.\n + Разрывы удаляться, если в контуре заполнены базовые номера сегментов. + Номера заполняются при перестроении мультилинии, содержащей контур.\n + Если сегменту контура соответствует одна из частей разрыва, то весь разрыв будет удален. + \en Remove breaks on the segments with the corresponding base number. \n + Break are removed if base numbers of segments are filled in contour. + The number are filled when multiline is rebuilt which contrains contour. \n + If segment of contour corresponds to one of break parts then entire break is removed. \~ + \param[in] baseNumber - \ru Номер сегмента базовой кривой. + \en A segment number of base curve. \~ + \param[in] delTracingBreaks - \ru Нужно ли удалять разрывы с сегментоа, соответствующих обходу вершины мультилинии. + \en Is it necessary for breaks to be removed from segments which correspond to multiline vertices traverse. \~ + \param[in] delEquidBreaks - \ru Нужно ли удалять разрывы с сегментов, соответствующих эквидистантам. + \en breaks to be removed from segments which correspond to equidistants. \~ + \param[in] delInLineSeg - \ru Удалять ли разрывы с прямолинейных сегментов. + \en Is it necessary to remode breaks from straight segments. \~ + */ + void DeleteBreaksAtBaseNumber ( size_t baseNumber, bool delTracingBreaks, + bool delEquidBreaks, bool delInLineSeg = true ); + /** \} */ + /**\ru \name Удаление разрывов и видимых частей малой метрической длины. + \en \name Removing of breaks and visible parts of the small metric length. + \{ */ + + /** \brief \ru Удалить разрывы малой метрической длины. + \en Remove breaks of the small metric length. \~ + \details \ru Удалить разрывы малой метрической длины.\n + В случае успеха видимые контуры перестраиваются соответственно разрывам. + \en Remove breaks of the small metric length. \n + In case of success the visible contours are rebuilt by breaks. \~ + \param[in] length - \ru Минимальная длина невидимой части. + \en Minimal length of invisible part. \~ + \return \ru true, если хотя бы один разрыв был удален. + \en true, if at least one break has been removed. \~ + */ + bool DeleteSmallBreaks ( double length ); + + /** \brief \ru Удалить видимые части малой метрической длины. + \en Remove visible parts of the small metric length. \~ + \details \ru Удалить видимые части малой метрической длины.\n + Соответствует объединению близких разрывов в один. + В случае успеха видимые контуры перестраиваются соответственно разрывам. + \en Remove visible parts of the small metric length. \n + Corresponds to union of close discontinuities into one. + In case of success the visible contours are rebuilt by breaks. \~ + \param[in] length - \ru Минимальная длина видимой части. + \en Minimal length of visible part. \~ + \return \ru true, если разрывы были изменены. + \en true if breaks have been changed. \~ + */ + bool DeleteSmallVisContours ( double length ); + + /** \} */ + /**\ru \name Работа с разрывами + \en \name Working with breaks + \{ */ + + /** \brief \ru Номер разрыва, край которого попал в окрестность точки. + \en The number of break the edge of which is into point neighbourhood. \~ + \details \ru Номер разрыва, край которого попал в окрестность точки.\n + \en The number of break the edge of which is into point neighbourhood. \n \~ + \param[in] p - \ru Точка. + \en Point. \~ + \param[in] rad - \ru Радиус окрестности точки для поиска разрыва. + \en Radius of point neighborhood to search the break. \~ + \param[out] index - \ru Номер разрыва. + \en The number of break. \~ + \return \ru true, если разрыв найден. + \en true if the break is found. \~ + */ + bool GetBreakAtPoint ( const MbCartPoint & p, double rad, + size_t & index ) const; + + /** \brief \ru Номера разрывов, которые хотя бы одним краем попадают в область. + \en Numbers of breaks which at least one edge fall into the region. \~ + \details \ru Номера разрывов, которые хотя бы одним краем попадают в область.\n + \en Numbers of breaks which at least one edge fall into the region. \n \~ + \param[in] rect - \ru Область поиска. + \en Region of search. \~ + \param[out] breaksNumbers - \ru Номера разрывов. + \en Numbers of breaks. \~ + \return \ru true, если хотя бы один разрыв найден. + \en true, if at least one break has been found. \~ + */ + bool GetBreaksInRect ( const MbRect & rect, + SArray & breaksNumbers ) const; + + /** \brief \ru Номера разрывов, которые хотя бы одним краем попадают в область. + \en Numbers of breaks which at least one edge fall into the region. \~ + \details \ru Номера разрывов, которые хотя бы одним краем попадают в область, заданную контуром.\n + \en Numbers of breaks which at least one edge fall into the region given contour. \n \~ + \param[in] contour - \ru Контур должен быть замкнутым и иметь правильное направление. + \en Contour must be closed and have the right direction. \~ + \param[out] breaksNumbers - \ru Номера разрывов. + \en Numbers of breaks. \~ + \return \ru true, если хотя бы один разрыв найден. + \en true, if at least one break has been found. \~ + */ + bool GetBreaksInRect ( const MbContour & contour, + SArray & breaksNumbers ) const; + + /** \brief \ru Определить попадает ли точка в любой из разрывов. + \en Determine whether a point it inside a break. \~ + \details \ru Определить попадает ли точка в любой из разрывов.\n + \en Determine whether a point it inside a break. \n \~ + \param[in] p - \ru Точка для проверки. + \en A point for the check. \~ + \return \ru true, если точка попадает в любой из разрывов. + \en true, if point falls into any break. \~ + */ + bool HitToBreaks ( const MbCartPoint & p ) const; + + /** \brief \ru Находится ли интервал параметров на разрыве. + \en Whether the interval of parameters is on break. \~ + \details \ru Находится ли интервал параметров на разрыве.\n + \en Whether the interval of parameters is on break. \n \~ + \param[in] rect - \ru Интервал для проверки. + \en Interval to check. \~ + \return \ru true, если интервал полностью находится на разрыве или совпадает с ним. + \en true if interval entirely is on the break or coincides with it. \~ + */ + bool IsRectInBreak ( const MbRect1D & rect ); + + /** \brief \ru Обновить невидимые и видимые контуры. + \en Update visible and invisible contours. \~ + \details \ru Обновить невидимые и видимые контуры соответственно базовой кривой мультилинии.\n + После перестроения разрывы должны соответствовать сегментам базовой кривой мультилинии. + \en Update visible and invisible contours by base curve of multiline respectively. \n + After rebuilding the breaks must correspond to segments of base multiline curve. \~ + \param[in] oldBaseNumbers - \ru Старые номера базовых сегментов,\n + должны быть запомнены до изменения мультилинии. + \en Old numbers of base segments, \n + must be saved before multiline is changed. \~ + */ + void RebuildBreaks ( SArray & oldBaseNumbers ); + + /** \brief \ru Обновить невидимые и видимые контуры. + \en Update visible and invisible contours. \~ + \details \ru Обновить невидимые и видимые контуры соответственно разрывам. + \en Update visible and invisible contours according to breaks. \~ + */ + void RebuildBreaks ( ); + + /** \brief \ru Преобразование в соответствии с матрицей. + \en Transform according to matrix. \~ + \details \ru Преобразование в соответствии с матрицей.\n + Используется для преобразования мультилинии. + Преобразует длину и расстояние от фиксированной точки прямолинейного разрыва, + а так же фиксированную точку. + \en Transform according to matrix.\n + Used to transform multiline. + Transforms length and distance from fixed point of straight break, + and fixed point. \~ + \param[in] matr - \ru Матрица преобразования. + \en A transformation matrix. \~ + */ + void TransformMultlinesBreaks ( const MbMatrix & matr ); + + /** \brief \ru Параметр привязки части разрыва. + \en A binding parameter of a break part. \~ + \details \ru Посчитать параметр привязки части разрыва в зависимости от типа сегмента контура.\n + \en Calculate binding parameter of a break part according to the type of contour segment. \n \~ + \param[in] brPart - \ru Часть разрыва этого контура. + \en A break part of this contour. \~ + \param[out] segNumber - \ru Номер сегмента контура. + \en A number of the contour segment. \~ + \return \ru Параметр центра разрыва на сегменте контура. + \en A parameter of the break center on the contour segment. \~ + */ + double GetLocalBreaksParam ( const MbBreaksPart & brPart, + size_t & segNumber ) const; + + /** \} */ + /**\ru \name Работа с разрывами: изменение разрыва. + \en \name Working with breaks: changing a break. + \{ */ + + /** \brief \ru Фиксировать точку. + \en Fix the point. \~ + \details \ru Поставить фиксированную точку части разрыва.\n + \en Set the fixed point of a break part. \n \~ + \param[in] newPoint - \ru Новая фиксированная точка. + \en A new fixed point. \~ + \param[out] part - \ru Часть разрыва контура для изменения. + \en A part of contour break to change. \~ + */ + void SetBreakFixedPoint ( const MbCartPoint & newPoint, + MbBreaksPart & part ); + + /** \brief \ru Фиксировать переменную. + \en Fix the variable. \~ + \details \ru Поставить фиксированную переменную части разрыва.\n + \en Set the fixed variable of a break part. \n \~ + \param[in] newFixedVar - \ru Новая фиксированная переменная. + \en New fixed variable. \~ + \param[out] part - \ru Часть разрыва контура для изменения. + \en A part of contour break to change. \~ + */ + void SetBreakFixedVar ( double newFixedVar, MbBreaksPart & part); + + /** \} */ + /**\ru \name Работа с разрывами: отслеживание разрыва + \en \name Working with breaks: tracking a break + \{ */ + /// \ru Количество номеров сегментов базового контура \en Count of segments numbers of the base contour + // \ru (должно соответствовать количеству сегментов контура) \en (must be equal to count of contour segments) + size_t GetBaseNumbersCount () const { return baseSegNumbers.Count(); } + + /// \ru Номера сегментов базового контура. \en Numbers of segments of base contour. + void GetBaseNumbers ( SArray & baseNumbers ) const; + + /** \brief \ru Номер сегмента базового контура. + \en Segment number of the base contour. \~ + \details \ru Номер сегмента базового контура.\n + Номер сегмента будет найден, если массив номеров не пуст и + корректно насчитан, то есть число номеров совпадает с числом сегментов контура + \en Segment number of the base contour. \n + Segment number will be found if the array of numbers is not empty and + it was numbered correctly, ie count of numbers is equal to count of contour segments \~ + \param[in] i - \ru Индекс номера. + \en Index of number. \~ + \return \ru Номер сегмента из массива номеров. + \en Number of segment from the array of numbers. \~ + */ + size_t GetBaseNumber ( size_t i ) const; + + /** \brief \ru Добавить номер базового сегмента. + \en Add number of the base segment. \~ + \details \ru Добавить номер сегмента базового контура в конец массива.\n + \en Add segment number of base contour to the end of array. \n \~ + \param[in] number - \ru Номер для добавления. + \en Number to add. \~ + */ + void AddBaseSegNumber ( size_t number ); + + /** \brief \ru Добавить номер базового сегмента. + \en Add number of the base segment. \~ + \details \ru Добавить номер сегмента базового контура в начало массива.\n + \en Add segment number of base contour to the beginning of array. \n \~ + \param[in] number - \ru Номер для добавления. + \en Number to add. \~ + */ + void AddBaseSegNumberAtBegin ( size_t number ); + + /** \brief \ru Вставить номер после lastInd. + \en Insert number after the lastInd. \~ + \details \ru Вставить после элемента номер lastInd номер, соответствующий lastInd.\n + \en Insert number corresponding lastInd after element lastInd. \n \~ + \param[in] lastInd - \ru Индекс номера. + \en Index of number. \~ + */ + void InsertLastSegNumber ( size_t lastInd ); + + /** \brief \ru Удалить элемент по индексу. + \en Delete element by an index. \~ + \details \ru Удалить номер базового сегмента по индексу.\n + \en Remove number of the base segment by an index. \n \~ + \param[in] ind - \ru Индекс номера. + \en Index of number. \~ + */ + void DeleteBaseSegNumber ( size_t ind ); + + /// \ru Очистить массив с номерами базовых сегментов. \en Clear the array with numbers of base segments. + void ClearBaseSegNumbers () { baseSegNumbers.HardFlush(); } + + /** \brief \ru Изменить номера сегментов в разрывах. + \en Change numbers of segments in the breaks. \~ + \details \ru Изменить номера сегментов в разрывах.\n + Заданному номеру базового сегмента соответствует сегмент - эквидистанта на контуре. + Для всех разрывов: + если хотя бы часть разрыва находится на этом сегменте, + у всех его частей номер сегмента будет изменен. + \en Change numbers of segments in the breaks. \n + A given number of the base segments corresponds to the segment - equidistant on the contour. + For all breaks: + if at least one part of break is in this segment, + the segment number of all of its parts will be changed. \~ + \param[in] begBaseNumber - \ru Номер базового сегмента. + \en An index of the base segment. \~ + \param[in] deltaN - \ru Величина изменение номера сегмента частей разрывов. + \en The change value of segment number of breaks parts. \~ + */ + void ChangeBreaksSegNumbers ( size_t begBaseNumber, ptrdiff_t deltaN ); + + /** \brief \ru Изменить разрывы соотвестсвенно замкнутости. + \en Change breaks of closedness respectively. \~ + \details \ru Изменить разрывы соотвестсвенно замкнутости.\n + При изменении признака замкнутости контура нужно изменить разрывы + соответственно новому значению замкнутости.\n + Если контур стал разомкнутым - разрыв, находящийся на первом и последнем + сегменте одновременно, делится на 2 части.\n + Если контур стал замкнутым - разрывы, первый из который примыкает к левому краю + первого сегмента контура, а второй из которых примыкает к правому краю последнего + сегмента контура, объединяется в один. + \en Change breaks of closedness respectively. \n + When changing attribute of contour closedness breaks need to change + respectively to the new value of closedness. \n + If contour has become open - the break located on the first and last + segment is divided into 2 parts at the same time. \n + If contour has become closed - breaks, the first of which is adjacent to the left boundary + of the first contour segment and the second of which is adjacent to the right boundary of the last + contour segment are united into one. \~ + \param[in] newClosed - \ru Новый признак замкнутости контура. + \en The new closedness attribute of contour. \~ + */ + void ChangeBreaksAtClosed ( bool newClosed ); + + /** \brief \ru Изменить номера сегментов частей разрывов. + \en Change segments numbers of breaks parts. \~ + \details \ru Изменить номера сегментов частей разрывов.\n + \en Change segments numbers of breaks parts. \n \~ + \param[in] deltaN - \ru Величина изменения. + \en A change value. \~ + */ + void MoveBreaksSegNumbers ( ptrdiff_t deltaN ); + + /** \brief \ru Находится ли часть разрыва этого контура на сегменте обхода вершин. + \en Is the break part of this contour located on the segment of vertices traverse. \~ + \details \ru Находится ли часть разрыва этого контура на сегменте обхода вершин.\n + \en Is the break part of this contour located on the segment of vertices traverse. \n \~ + \param[in] part - \ru Часть разрыва этого контура. + \en A break part of this contour. \~ + \param[out] vertNumber - \ru В случае успеха вернет номер вершины. + \en In the case of success returns the vertex number. \~ + \return \ru true, если часть разрыва находится на сегменте обхода вершины. + \en true, if the break part is located on the segment of vertices traverse. \~ + */ + bool IsTrasingBreaksPart ( const MbBreaksPart & part, + size_t & vertNumber ) const; + + /** \brief \ru Поменяться разрывами. + \en Swap breaks. \~ + \details \ru Поменяться разрывами.\n + \en Swap breaks. \n \~ + \param[in] other - \ru Контур с разрывами для обмена. + \en A contour with breaks to swap. \~ + */ + void SwapBreaksAndBaseNumbers ( MbContourWithBreaks & other ); + + /** \brief \ru Добавить разрывы контура. + \en Add contour breaks. \~ + \details \ru Добавить разрывы контура.\n + \en Add contour breaks. \n \~ + \param[in] other - \ru Контур с разрывами для добавления разрывов. + \en A contour with breaks for adding breaks. \~ + */ + void AddContoursBreaks ( const MbContourWithBreaks & other ); + + /** \brief \ru Заменить номера базовых сегментов. + \en Replace the numbers of base segments. \~ + \details \ru Заменить номера базовых сегментов.\n + \en Replace the numbers of base segments. \n \~ + \param[in] other - \ru Контур с новыми номерами. + \en A contour with new numbers. \~ + */ + void ChangeBaseNumbers ( const MbContourWithBreaks & other ); + /** \} */ + +private: + void DeleteBreaks ( size_t segmentIndex, + bool delInLineSeg = true ); // \ru удалить разрывы на сегменте с номером index \en remove breaks from segment with number "index" + void DeleteBreaksPartAtSegNum ( size_t segNumber, size_t oldSegCount ); // \ru часть разрыва по номеру сегмента \en part of break by the segment number + bool DeleteBreaksPartOrBreak ( size_t breakIndex, size_t partIndex, + size_t oldSegCount ); // \ru часть разрыва или разрыв \en part of break or break +private: + void CalculateVisibleContours ( ); // \ru посчитать видимые части \en calculate visible parts + void CalculateInvisibleContours( RPArray & invisibleContours ); // \ru посчитать невидимые части \en calculate invisible parts + void CalculateContours ( const CSSArray & ranges, // \ru посчитать контуры по интервалам \en calculate contours by intervals + RPArray & contours, + bool visible ) const; // \ru для видимых частей вызывать AddRef() \en call AddRef() for visible parts + void CalculateInVisibleRanges ( CSSArray & breaksRanges ); // \ru посчитать невидимые интервалы \en calculate invisible intervals + void CalculateVisibleRanges ( CSSArray & breaksRanges, + CSSArray & visibleRanges ) const; // \ru посчитать видимые интервалы \en Calculate visible intervals + void CalculateRanges ( const CSSArray & startingInt, // \ru посчитать противоположные интервалы \en Calculate opposite intervals + CSSArray & resultInt ) const; // \ru второй массив по первому \en the second array by the first + void CalculateBreaksPart ( const MbRect1D & segParams, + size_t segNumber, MbBreak & brRange ) const; // \ru посчитать часть разрыва \en Calculate a part of the break + void CalculateBreak ( const MbRect1D & range, + MbBreak & brRange ) const; // \ru посчитать разрыв по интервалу \en Calculate the break by interval + MbRect1D GetLocalBreaksRange ( const MbBreaksPart & part, + double brParam, size_t segNumber ) const; // \ru интервал по параметру привязки \en interval by the binding parameter + void AddCalcBreak ( const MbRect1D & range ); + void ChangeBreaksSegNumbers ( const SArray & oldBaseNumbers, + SArray & oldEqCounts, + SArray & newEqCounts ); // \ru изменить номера сегментов у разрывов \en change segments numbers of breaks + void RedefineBreaksParts (); // \ru доопределить неопределенные части разрыва \en complete the definition of indefinite parts of the break + + // \ru для преобразования контуров \en for transformation of contours + void TransformBreaks ( const MbMatrix & matr ); // \ru преобразование в соответствии с матрицей \en transform according to the matrix + + size_t GetLocalBreaksRange ( const MbBreaksPart & part, + MbRect1D & localRect ) const; // \ru разрыв по номеру в параметрах сегмента \en a break by the number in segment parameters + + + void operator = ( const MbContourWithBreaks & ); // \ru не реализован \en not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbContourWithBreaks ) + +}; // MbContourWithBreaks + +IMPL_PERSISTENT_OPS( MbContourWithBreaks ) + +//------------------------------------------------------------------------------ +/** \brief \ru Часть разрыва. + \en Part of break. \~ + \details \ru Часть разрыва контура мультилинии. Относится к одному сегменту контура.\n + Для использования в разрыве MbBreak. + \en Part of multiline contour break. Applicable to one segment of the contour.\n + For using in the break MbBreak. \~ + \ingroup Algorithms_2D +*/ // --- +class MATH_CLASS MbBreaksPart { + +private : + size_t segNumber; // \ru Номер сегмента \en Number of the segment. + double fixedVar; // \ru Фиксированная переменная \en Fixed variable + // \ru ( tMax - tCentre ) / ( tCentre - tMin ), tCentre - параметр центра разрыва \en ( tMax - tCentre ) / ( tCentre - tMin ), tCentre - center of the break + // \ru для отрезка - расстояние до проекции неподвижной точки \en for segment - distance to projection of the fixed point + double length; // \ru Длина части разрыва (для отрезка) \en Length of the break part (for segment) + // \ru для дуг и по умолчанию сохраняем параметрическую длину \en For arcs and save parametric length by default. + // \ru (для дуги - угол) \en (for arc - angle) + MbCartPoint fixedPoint; // \ru неподвижная точка ( корректное значение для отрезка ) \en fixed point (correct value for segment) + +public: + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по номеру сегмента, фиксированной переменной, длине, неподвижной точке. + \en Constructor by a number of segment, fixed variable, length, fixed point. \~ + \param[in] sNumber - \ru Номер сегмента контура, на котором находится часть разрыва. + \en Number of contour segment where a part of break is located. \~ + \param[in] fixVar - \ru Фиксированная переменная:\n + для отрезка - расстояние до проекции неподвижной точки,\n + в общем случае - величина, равная ( tMax - tCentre ) / ( tCentre - tMin ), где\n + tMin - минимальный параметр сегмента,\n + tMax - максимальный параметр сегмента,\n + tCentre - параметр центра части разрыва. + \en Fixed variable:\n + for segment - distance to projection of the fixed point,\n + In general case - a value which is equal to ( tMax - tCentre ) / ( tCentre - tMin ), where \n + tMin - minimal parameter of the segment,\n + tMax - maximal parameter of the segment,\n + tCentre - parameter of the break part center. \~ + \param[in] len - \ru Длина части разрыва:\n + для отрезка - метрическая длина,\n + в общем случае - параметрическая длина. + \en Length of the break part:\n + for segment - metric length, \n + In the general case - parametric length. \~ + \param[in] p - \ru Неподвижная точка:\n + для отрезка - используется для привязки части разрыва,\n + в общем случае - не имеет смысла. + \en Fixed point:\n + for segment - used to bind part of the break,\n + in general case - it is useless. \~ + */ + MbBreaksPart( size_t sNumber, double fixVar, double len, const MbCartPoint & p ) + : segNumber ( sNumber ), + fixedVar ( fixVar ), + length ( len ), + fixedPoint( p ) + { + } + + /// \ru Копирующий конструктор. \en Copy-constructor. + MbBreaksPart( const MbBreaksPart & other ) + : segNumber ( other.GetSegmentNumber() ), + fixedVar ( other.GetFixedVar() ), + length ( other.GetLength() ), + fixedPoint( other.GetFixedPoint() ) + { + } + + ~MbBreaksPart(){}; + + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + size_t GetSegmentNumber() const { return segNumber; } ///< \ru Номер сегмента контура. \en A number of the contour segment. + double GetFixedVar() const { return fixedVar; } ///< \ru Фиксированная переменная. \en fixed variable + double GetLength() const { return length; } ///< \ru Длина части разрыва. \en Length of the break part. + const MbCartPoint & GetFixedPoint() const { return fixedPoint; } ///< \ru Фиксированная точка. \en Fixed point. + + /** \} */ + /**\ru \name Функции изменения данных. + \en \name Functions for changing data. + \{ */ + + /// \ru Изменить номер сегмента контура. \en Change a number of the contour segment. + void SetSegmentNumber( size_t newNumber ) { segNumber = newNumber; } + /// \ru Изменить фиксированную переменную. \en Change a fixed variable. + void SetFixedFar ( double newFixedVar ) { fixedVar = newFixedVar; } + /// \ru Изменить длину части разрыва. \en Change the length of the break part. + void SetLength ( double newLength ) { length = newLength; } + /// \ru Изменить фиксированную точку. \en Change a fixed point. + void SetFixedPoint ( const MbCartPoint & point ) { fixedPoint.Init( point ); } + + /** \brief \ru Переместить. + \en Move. \~ + \details \ru Переместить на вектор.\n + \en Move by vector.\n \~ + \param[in] to - \ru Вектор перемещения. + \en Movement vector. \~ + */ + void Move ( const MbVector & to ) { fixedPoint.Move( to ); } + + /** \brief \ru Повернуть. + \en Rotate. \~ + \details \ru Повернуть на угол вокруг точки.\n + \en Rotate at angle around a point.\n \~ + \param[in] pnt - \ru Точка - центр поворота. + \en A point is a rotation center. \~ + \param[in] angle - \ru Двумерный нормализованный вектор, задающий угол вращения. + \en A two-dimensional normalized vector which defines a rotation angle. \~ + */ + void Rotate ( const MbCartPoint & pnt, const MbDirection & angle ) { fixedPoint.Rotate( pnt, angle ); } + + /** \brief \ru Преобразование. + \en Transformation. \~ + \details \ru Преобразование в соответствии с матрицей.\n + \en Transform according to matrix.\n \~ + \param[in] matr - \ru Матрица трансформации. + \en Transformation matrix. \~ + */ + void Transform ( const MbMatrix & matr ) { fixedPoint.Transform( matr ); } + + /** \brief \ru Изменить номер сегмента. + \en Change a number of the segment. \~ + \details \ru Изменить номер сегмента на заданную величину.\n + Номер сегмента не изменится, если величина изменения будет отрицательной и большей по модулю, чем номер. + \en Change a number of the segment by a given value. \n + The number of the segment does not change if the amount of change is negative and greater in absolute value than the number. \~ + \param[in] deltaN - \ru Величина увеличения номера сегмента. + \en Increase value of the segment number. \~ + */ + void ChangeSegNumber ( ptrdiff_t deltaN ) { if( deltaN >= 0 || (ptrdiff_t)segNumber >= -deltaN ) segNumber += deltaN; } + /** \} */ +private: + void operator = ( const MbBreaksPart & ); // \ru не реализован \en not implemented +}; // MbBreaksPart + + +//------------------------------------------------------------------------------ +/** \brief \ru Разрыв. + \en Break. \~ + \details \ru Разрыв контура.\n + Для использования в контуре с разрывом MbContourWithBreaks.\n + Разрыв состоит из частей MbBreaksPart, каждая из которых находится на одном сегменте контура.\n + В разрыве может быть 1 или 2 части. + Если разрыв должен располагаться более чем на трех сегментах, то он имеет 2 части, + соответствующие первому и последнему сегментам. + \en Contour break.\n + For using in the contour with break MbContourWithBreaks.\n + The break consists of parts MbBreaksPart all of which are on the same segment of the contour. \n + The break can have 1 or 2 parts. + If the break must be located more than three segments it has two parts, + corresponding to the first and the last segments. \~ + \ingroup Algorithms_2D +*/ // --- +class MATH_CLASS MbBreak { + +private: + SArray parts; // \ru части разрыва: \en part of break: + // \ru одна, если разрыв на одном сегменте, \en one if the break is on the one segment, + // \ru две, если на нескольких сегментах - первая и последняя \en two if break is on the several segments - the first and the last + +public: + + /** \brief \ru Конструктор пустого разрыва. + \en Constructor of an empty break. \~ + \details \ru Конструктор пустого разрыва.\n + Такой разрыв не может находиться в контуре с разрывом MbContourWithBreaks. + Он будет удален при перестроении. + \en Constructor of an empty break. \n + Such break can not be in the contour with break MbContourWithBreaks. + It will be removed when rebuilding. \~ + */ + MbBreak(): parts () { } + + /// \ru Копирующий конструктор. \en Copy-constructor. + MbBreak( const MbBreak & other ): parts ( other.parts ) {} + + ~MbBreak() {} + +public: + + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + ///< \ru Количество частей. \en The number of parts. + size_t PartsCount () const { return parts.Count(); } + + /** \brief \ru Часть по номеру. + \en A part by the number. \~ + \details \ru Часть по номеру части разрыва.\n + Номер не проверяется на корректность. + \en A part by the number of the break part. \n + A number isn't checked for correctness. \~ + \param[in] number - \ru Номер части разрыва, должен быть меньше количества частей. + \en The number of break part must be less than the number of parts. \~ + \return \ru Ссылку на часть разрыва. + \en Reference to part of break. \~ + */ + MbBreaksPart & GetPart ( size_t number ) const { return parts[number]; } + + /** \} */ + /**\ru \name Функции изменения данных. + \en \name Functions for changing data. + \{ */ + + /// \ru Добавить часть разрыва. \en Add a part of break. + void AddPart ( MbBreaksPart part ) { parts.Add( part ); } + /// \ru Удалить все части разрыва. \en Remove all parts of break. + void DeleteParts () { parts.HardFlush(); } + + /** \brief \ru Удалить часть. + \en Remove a part. \~ + \details \ru Удалить часть разрыва по номеру.\n + Номер проверяется на корректность. + Если номер не меньше количества частей, то разрыв не изменится. + \en Remove a part of break by the number. \n + A number Is checked for correctness. + If the number isn't less than the number of parts the break doesn't change. \~ + \param[in] number - \ru Номер части разрыва, должен быть меньше количества частей. + \en The number of break part must be less than the number of parts. \~ + */ + void DeletePart ( size_t number ) { if( number < PartsCount() ) parts.RemoveInd( number ); } + + /** \brief \ru Переместить. + \en Move. \~ + \details \ru Переместить на вектор.\n + \en Move by vector.\n \~ + \param[in] to - \ru Вектор перемещения. + \en Movement vector. \~ + */ + void Move( const MbVector & to ) + { + for( size_t i = 0, count = parts.Count(); i < count; ++i ) + parts[i].Move( to ); + } + + /** \brief \ru Повернуть. + \en Rotate. \~ + \details \ru Повернуть на угол вокруг точки.\n + \en Rotate at angle around a point.\n \~ + \param[in] pnt - \ru Точка - центр поворота. + \en A point is a rotation center. \~ + \param[in] angle - \ru Двумерный нормализованный вектор, задающий угол вращения. + \en A two-dimensional normalized vector which defines a rotation angle. \~ + */ + void Rotate( const MbCartPoint & pnt, const MbDirection & angle ) + { + for( size_t i = 0, count = parts.Count(); i < count; ++i ) + parts[i].Rotate( pnt, angle ); + } + + /** \brief \ru Преобразовать. + \en Transform. \~ + \details \ru Преобразовать в соответствии с матрицей.\n + \en Transform according to matrix.\n \~ + \param[in] matr - \ru Матрица трансформации. + \en Transformation matrix. \~ + */ + void Transform( const MbMatrix & matr ) + { + for( size_t i = 0, count = parts.Count(); i < count; ++i ) + parts[i].Transform( matr ); + } + /** \} */ +private: + void operator =( const MbBreak & ); // \ru не реализован \en not implemented + +}; // MbBreak + + +//------------------------------------------------------------------------------ +/** \brief \ru Ближайшие проекции на контур. + \en Nearest projections on the contour. \~ + \details \ru Ближайшие проекции точки на контур.\n + \en Nearest projections of point on the contour. \n \~ + \param[in] contour - \ru Контур. + \en A contour. \~ + \param[in] pnt - \ru Проецируемая точка. + \en Projecting point. \~ + \param[out] tProjs - \ru Параметры ближайших проекций. + \en Parameters of nearest projections. \~ + \param[in] isNear - \ru Выбрать только проекции, + находящиеся от проецируемой точки не дальше заданной точности. + \en Select only the projections + which are located from projecting point within a given tolerance. \~ + \param[in] mEps - \ru Точность выбора ближайших точек. + \en A tolerance of nearest points selection. \~ + \ingroup Algorithms_2D +*/ +// --- +MATH_FUNC (void) NearPointProjections( const MbContour & contour, const MbCartPoint & pnt, + SArray & tProjs, bool isNear, double mEps = METRIC_REGION ); + + + +#endif // __CUR_CONTOUR_WITH_BREAKS_H diff --git a/C3d/Include/cur_cosinusoid.h b/C3d/Include/cur_cosinusoid.h index e331252..b9fb77b 100644 --- a/C3d/Include/cur_cosinusoid.h +++ b/C3d/Include/cur_cosinusoid.h @@ -26,7 +26,7 @@ class MbRegTransform; /** \brief \ru Косинусоида в двумерном пространстве. \en Cosinusoid in two-dimensional space. \~ \details \ru Косинусоида расположена вдоль оси X локальной системы координат. \n - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией\n + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией\n r(t) = position.origin + (position.axisX ((tmin + t) - phase) / frequency) + (amplitude cos(tmin + t) position.axisY).\n Косинусоида приведена на рисунке ниже. t = 0 @@ -39,7 +39,7 @@ class MbRegTransform; / | \/ y = amplitude cos(frequency x + phase) \en Cosinusoid located along the X-axis of the local coordinate system. \n - Radius-vector of the curve in the method PointOn(double&t,MbCartPoint3D&r) is described by the vector function\n + Radius-vector of the curve in the method PointOn(double&t,MbCartPoint3D&r) is described by the vector function\n r(t) = position.origin + (position.axisX ((tmin + t) - phase) / frequency) + (amplitude cos(tmin + t) position.axisY).\n Cosinusoid is shown in the figure below. t = 0 @@ -54,7 +54,7 @@ class MbRegTransform; \ingroup Curves_2D */ // --- -class MATH_CLASS MbCosinusoid: public MbCurve, public MbNestSyncItem { +class MATH_CLASS MbCosinusoid: public MbCurve { private : MbPlacement position; ///< \ru Локальная система координат. \en Local coordinate system. double frequency; ///< \ru Циклическая частота (angular frequency). \en Angular frequency. @@ -93,7 +93,7 @@ public: 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 bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; + 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 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. diff --git a/C3d/Include/cur_crooked_spiral.h b/C3d/Include/cur_crooked_spiral.h index 8ed8ae9..a01898f 100644 --- a/C3d/Include/cur_crooked_spiral.h +++ b/C3d/Include/cur_crooked_spiral.h @@ -1,149 +1,151 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Спираль постоянного радиуса и осью, заданной произвольной кривой на плоскости XZ position. - \en Spiral with constant radius and axis defined by an arbitrary curve on the XZ plane "position". \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_CROOKET_SPIRAL_H -#define __CUR_CROOKET_SPIRAL_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Спираль с криволинейной осью. - \en Spiral with a curvilinear axis. \~ - \details \ru Спираль постоянного радиуса и осью, заданной произвольной плоской кривой. - Ось спирали определяется кривой curve, располагающейся в плоскости ZX локальной системы координат спирали. - При этом ось Z локальной системы координат спирали служит осью X системы координат двумерной кривой curve, - а ось X локальной системы координат спирали служит осью Y системы координат двумерной кривой curve, - что приведено на рис. 1 ниже. \n - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n - r(t) = position.origin + - (position.axisX (point.y + (radius cos(t) normal.ay)) + - (position.axisY radius sin(t)) + - (position.axisZ (point.x + (radius cos(t) normal.ax)), - где point - точка кривой curve, normal - нормаль кривой curve. - Рис. 1. - ^ Ось X локальной системы координат спирали является осью Y системы координат curve. - | - | curve(w) - | - +----> Ось Z локальной системы координат спирали является осью X системы координат curve. - \en Spiral with a constant radius and axis defined by an arbitrary plane curve. - Spiral axis is determined by the curve "curve" based in the ZX plane of the local coordinate system of spiral. - The Z-axis of the local coordinate system is the X-axis of coordinate system of two-dimensional uv-curve "curve", - and the X-axis of the local coordinate system is the Y-axis of the coordinate system of two-dimensional uv-curve "curve", - that is shown in fig. 1 below. \n - The radius-vector of curve in the method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n - r(t) = position.origin + - (position.axisX (point.y + (radius cos(t) normal.ay)) + - (position.axisY radius sin(t)) + - (position.axisZ (point.x + (radius cos(t) normal.ax)), - where "point" is point of the curve "curve", "normal" is normal of the curve "curve". - Fig. 1 1. - ^ X-axis of the local coordinate system of the spiral is Y-axis of the coordinate system of the curve "curve". - | - | curve(w) - | - +----> Z-axis of the local coordinate system of the spiral is X-axis of the coordinate system of the curve "curve". \~ - \ingroup Curves_3D -*/ -// --- -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). - 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". - double t0; ///< \ru Начальный угол спирали. \en The initial angle of the spiral. - bool curveSense; ///< \ru Совпадение направления оси спирали с направлением кривой curve. \en The coincidence of the direction of the spiral axis with the direction of the curve "curve". - CurveParams curveParams; ///< \ru Параметры спирали (параметрические сдвиги от начала кривой) и параметры двумерной кривой. \en Parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". - -protected: - MbCrookedSpiral( const MbCrookedSpiral & init ); // \ru Не реализовано \en Not implemented - MbCrookedSpiral( const MbCrookedSpiral & init, MbRegDuplicate * iReg ); -public : - MbCrookedSpiral( const MbPlacement3D & pos, MbCurve & axisCurve, double radius, double step, bool same ); // \ru Спираль с кривой осью \en Spiral with a curvilinear axis - virtual ~MbCrookedSpiral(); - -public : - VISITING_CLASS( MbCrookedSpiral ); - - void Init( const MbCrookedSpiral & init ); - void Init( const MbPlacement3D & place ); - - // \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 bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; - virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal - - 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 Common functions of curve - - virtual bool IsClosed() const; // \ru Проверка замкнутости кривой \en Check for curve closedness - // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ - virtual void PointOn ( double & t, MbCartPoint3D & pnt ) const; // \ru Точка на кривой \en Point on the curve - virtual void FirstDer ( double & t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative - virtual void SecondDer( double & t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative - virtual void ThirdDer ( double & t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to t - // \ru Функции для работы внутри и вне области определения кривой. \en Functions for working inside and outside of the curve domain. \~ - virtual void _PointOn ( double t, MbCartPoint3D & pnt ) const; // \ru Точка на кривой \en Point on the curve - virtual void _FirstDer ( double t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative - virtual void _SecondDer( double t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative - virtual void _ThirdDer ( double t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to 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 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; - virtual void GetBasisItems( RPArray & ); - - // \ru Функции спирали \en Functions of spiral - - virtual void SetStep( double s ); // \ru Изменить шаг \en Change step - virtual double GetSpiralRadius( double t ) const; // \ru Выдать физический радиус спирали \en Get physical radius of spiral - const MbCurve & GetAxisCurve() const { return *curve; }; // \ru Выдать осевую кривую \en Get axial curve - double GetSpiralRadius() const { return radius; }; // \ru Выдать радиус \en Get radius - void SetSpiralRadius( double r ) { radius = r; }; // \ru Изменить радиус \en Change radius - bool GetCurveSense () const { return curveSense;};// \ru Выдать признак совпадения направления на спирали и оси (кривой) \en Get attribute of coincidence of the direction on the spiral and axis (curve) - -private: - void GetFirstDerNormW ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNormW ) const; // \ru Выдать первую производную нормали по параметру кривой оси \en Get the first derivative of normal vector with respect to parameter of axis curve - void GetSecondDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNormW ) const; // \ru Выдать вторую производную нормали по параметру кривой оси \en Get the second derivative of normal vector with respect to parameter of axis curve - void GetThirdDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNormW ) const; // \ru Выдать третью производную нормали по параметру кривой оси \en Get the third derivative of normal vector with respect to parameter of axis curve - void GetFirstDerNormT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNorm ) const; // \ru Выдать первую производную нормали по параметру спирали \en Get the first derivative of normal vector with respect to parameter of the spiral - void GetSecondDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNorm ) const; // \ru Выдать вторую производную нормали по параметру спирали \en Get the second derivative of normal vector with respect to parameter of the spiral - void GetThirdDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNorm ) const; // \ru Выдать третью производную нормали по параметру спирали \en Get the third derivative of normal vector with respect to parameter of the spiral - void GetFirstDerT ( const MbVector & fDerW, MbVector & fd ) const; // \ru Выдать первую производную кривой оси по параметру спирали \en Get the first derivative of axis curve with respect to parameter of the spiral - void GetSecondDerT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & sd ) const; // \ru Выдать вторую производную кривой оси по параметру спирали \en Get the second derivative of axis curve with respect to parameter of the spiral - void GetThirdDerT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & td ) const; // \ru Выдать третью производную кривой оси по параметру спирали \en Get the third derivative of axis curve with respect to parameter of the spiral - double GetFirstDerParamT ( const MbVector & fDerW ) const; // \ru Выдать первую производную параметра кривой оси по параметру спирали \en Get the first derivative of axis curve parameter with respect to parameter of the spiral - double GetSecondDerParamT( const MbVector & fDerW, const MbVector & sDerW ) const; // \ru Выдать вторую производную параметра кривой оси по параметру спирали \en Get the second derivative of axis curve parameter with respect to parameter of the spiral - double GetThirdDerParamT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW ) const; // \ru Выдать третью производную параметра кривой оси по параметру спирали \en Get the third derivative of axis curve parameter with respect to parameter of the spiral - void GetCurveParams ( double tSense, MbCartPoint & point, MbDirection & normal, - MbVector & fDerW, MbVector & sDerW, MbVector & tDerW ) const; // \ru Параметры кривой оси, соответствующие параметру спирали t \en Parameters of axis curve corresponding to the parameter t of the spiral - void CalculateParams (); // \ru Посчитать параметры спирали (параметрические сдвиги от начала кривой) и параметры кривой. \en Calculate parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". - bool NearestLeftParams ( double tSense, c3d::DoublePair & paramPair ) const; // \ru Ближайшая слева пара параметров спирали и кривой. \en Nearest left parameters pair of spiral and "curve". - -private: - void operator = ( const MbCrookedSpiral & ); // \ru Не реализовано \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCrookedSpiral ) -}; // MbCrookedSpiral - -IMPL_PERSISTENT_OPS( MbCrookedSpiral ) - -#endif // __CUR_CROOKET_SPIRAL_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Спираль постоянного радиуса и осью, заданной произвольной кривой на плоскости XZ position. + \en Spiral with constant radius and axis defined by an arbitrary curve on the XZ plane "position". \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_CROOKET_SPIRAL_H +#define __CUR_CROOKET_SPIRAL_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Спираль с криволинейной осью. + \en Spiral with a curvilinear axis. \~ + \details \ru Спираль постоянного радиуса и осью, заданной произвольной плоской кривой. + Ось спирали определяется кривой curve, располагающейся в плоскости ZX локальной системы координат спирали. + При этом ось Z локальной системы координат спирали служит осью X системы координат двумерной кривой curve, + а ось X локальной системы координат спирали служит осью Y системы координат двумерной кривой curve, + что приведено на рис. 1 ниже. \n + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией: \n + r(t) = position.origin + + (position.axisX (point.y + (radius cos(t) normal.ay)) + + (position.axisY radius sin(t)) + + (position.axisZ (point.x + (radius cos(t) normal.ax)), + где point - точка кривой curve, normal - нормаль кривой curve. + Рис. 1. + ^ Ось X локальной системы координат спирали является осью Y системы координат curve. + | + | curve(w) + | + +----> Ось Z локальной системы координат спирали является осью X системы координат curve. + \en Spiral with a constant radius and axis defined by an arbitrary plane curve. + Spiral axis is determined by the curve "curve" based in the ZX plane of the local coordinate system of spiral. + The Z-axis of the local coordinate system is the X-axis of coordinate system of two-dimensional uv-curve "curve", + and the X-axis of the local coordinate system is the Y-axis of the coordinate system of two-dimensional uv-curve "curve", + that is shown in fig. 1 below. \n + The radius-vector of curve in the method PointOn(double&t,MbCartPoint3D&r) is described by a vector function: \n + r(t) = position.origin + + (position.axisX (point.y + (radius cos(t) normal.ay)) + + (position.axisY radius sin(t)) + + (position.axisZ (point.x + (radius cos(t) normal.ax)), + where "point" is point of the curve "curve", "normal" is normal of the curve "curve". + Fig. 1 1. + ^ X-axis of the local coordinate system of the spiral is Y-axis of the coordinate system of the curve "curve". + | + | curve(w) + | + +----> Z-axis of the local coordinate system of the spiral is X-axis of the coordinate system of the curve "curve". \~ + \ingroup Curves_3D +*/ +// --- +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). + 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". + double t0; ///< \ru Начальный угол спирали. \en The initial angle of the spiral. + bool curveSense; ///< \ru Совпадение направления оси спирали с направлением кривой curve. \en The coincidence of the direction of the spiral axis with the direction of the curve "curve". + CurveParams curveParams; ///< \ru Параметры спирали (параметрические сдвиги от начала кривой) и параметры двумерной кривой. \en Parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". + +protected: + MbCrookedSpiral( const MbCrookedSpiral &, MbRegDuplicate * ); +public : + /// \ru Конструктор спирали с криволинейной осью. \en Spiral with a curvilinear axis. + MbCrookedSpiral( const MbPlacement3D & pos, MbCurve & axisCurve, double radius, double step, bool same ); +public: + virtual ~MbCrookedSpiral(); + +public : + VISITING_CLASS( MbCrookedSpiral ); + + /// \ru Инициализация спирали по спирали. \en Spiral initialization by spiral. + void Init( const MbCrookedSpiral & ); + /// \ru Инициализация спирали по основанию (локальной системе координат). \en Spiral initialization by base (local coordinate system). + void Init( const MbPlacement3D & ); + + // \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 bool IsSame( const MbSpaceItem & other, double accuracy = LENGTH_EPSILON ) const; + virtual bool SetEqual( const MbSpaceItem & init ); // \ru Сделать равным \en Make equal + + 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 Common functions of curve + + virtual bool IsClosed() const; // \ru Проверка замкнутости кривой \en Check for curve closedness + // \ru Функции для работы внутри области определения кривой. \en Functions for working inside of the curve domain. \~ + virtual void PointOn ( double & t, MbCartPoint3D & pnt ) const; // \ru Точка на кривой \en Point on the curve + virtual void FirstDer ( double & t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative + virtual void SecondDer( double & t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative + virtual void ThirdDer ( double & t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to t + // \ru Функции для работы внутри и вне области определения кривой. \en Functions for working inside and outside of the curve domain. \~ + virtual void _PointOn ( double t, MbCartPoint3D & pnt ) const; // \ru Точка на кривой \en Point on the curve + virtual void _FirstDer ( double t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative + virtual void _SecondDer( double t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative + virtual void _ThirdDer ( double t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to 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 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; + virtual void GetBasisItems( RPArray & ); + + // \ru Функции спирали \en Functions of spiral + + virtual bool SetStep( double s ); // \ru Изменить шаг \en Change step + virtual double GetSpiralRadius( double t ) const; // \ru Выдать физический радиус спирали \en Get physical radius of spiral + + const MbCurve & GetAxisCurve() const { return *curve; } ///< \ru Выдать осевую кривую. \en Get axial curve. + double GetSpiralRadius() const { return radius; } ///< \ru Выдать радиус. \en Get radius. + void SetSpiralRadius( double r ) { radius = r; }; ///< \ru Изменить радиус. \en Change radius. + bool GetCurveSense () const { return curveSense; } ///< \ru Выдать признак совпадения направления на спирали и оси (кривой). \en Get attribute of coincidence of the direction on the spiral and axis (curve). + +private: + void GetFirstDerNormW ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNormW ) const; // \ru Выдать первую производную нормали по параметру кривой оси \en Get the first derivative of normal vector with respect to parameter of axis curve + void GetSecondDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNormW ) const; // \ru Выдать вторую производную нормали по параметру кривой оси \en Get the second derivative of normal vector with respect to parameter of axis curve + void GetThirdDerNormW ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNormW ) const; // \ru Выдать третью производную нормали по параметру кривой оси \en Get the third derivative of normal vector with respect to parameter of axis curve + void GetFirstDerNormT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & fdNorm ) const; // \ru Выдать первую производную нормали по параметру спирали \en Get the first derivative of normal vector with respect to parameter of the spiral + void GetSecondDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & sdNorm ) const; // \ru Выдать вторую производную нормали по параметру спирали \en Get the second derivative of normal vector with respect to parameter of the spiral + void GetThirdDerNormT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & tdNorm ) const; // \ru Выдать третью производную нормали по параметру спирали \en Get the third derivative of normal vector with respect to parameter of the spiral + void GetFirstDerT ( const MbVector & fDerW, MbVector & fd ) const; // \ru Выдать первую производную кривой оси по параметру спирали \en Get the first derivative of axis curve with respect to parameter of the spiral + void GetSecondDerT ( const MbVector & fDerW, const MbVector & sDerW, MbVector & sd ) const; // \ru Выдать вторую производную кривой оси по параметру спирали \en Get the second derivative of axis curve with respect to parameter of the spiral + void GetThirdDerT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW, MbVector & td ) const; // \ru Выдать третью производную кривой оси по параметру спирали \en Get the third derivative of axis curve with respect to parameter of the spiral + double GetFirstDerParamT ( const MbVector & fDerW ) const; // \ru Выдать первую производную параметра кривой оси по параметру спирали \en Get the first derivative of axis curve parameter with respect to parameter of the spiral + double GetSecondDerParamT( const MbVector & fDerW, const MbVector & sDerW ) const; // \ru Выдать вторую производную параметра кривой оси по параметру спирали \en Get the second derivative of axis curve parameter with respect to parameter of the spiral + double GetThirdDerParamT ( const MbVector & fDerW, const MbVector & sDerW, const MbVector & tDerW ) const; // \ru Выдать третью производную параметра кривой оси по параметру спирали \en Get the third derivative of axis curve parameter with respect to parameter of the spiral + void GetCurveParams ( double tSense, MbCartPoint & point, MbDirection & normal, + MbVector & fDerW, MbVector & sDerW, MbVector & tDerW ) const; // \ru Параметры кривой оси, соответствующие параметру спирали t \en Parameters of axis curve corresponding to the parameter t of the spiral + void CalculateParams (); // \ru Посчитать параметры спирали (параметрические сдвиги от начала кривой) и параметры кривой. \en Calculate parameters of spiral (parametric shifts from the beginning of the curve) and parameters of "curve". + bool NearestLeftParams ( double tSense, c3d::DoublePair & paramPair ) const; // \ru Ближайшая слева пара параметров спирали и кривой. \en Nearest left parameters pair of spiral and "curve". + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCrookedSpiral ) +OBVIOUS_PRIVATE_COPY( MbCrookedSpiral ) +}; // MbCrookedSpiral + +IMPL_PERSISTENT_OPS( MbCrookedSpiral ) + +#endif // __CUR_CROOKET_SPIRAL_H diff --git a/C3d/Include/cur_cubic_spline.h b/C3d/Include/cur_cubic_spline.h index 36054e6..b8da59a 100644 --- a/C3d/Include/cur_cubic_spline.h +++ b/C3d/Include/cur_cubic_spline.h @@ -53,7 +53,7 @@ protected : MbCubicSpline(); ///< \ru Конструктор по умолчанию. \en Constructor by default. MbCubicSpline( const MbCubicSpline & other ); ///< \ru Дублирующий конструктор. \en Duplicating constructor. /// \ru Конструктор по заданной кривой. \en Constructor by a given curve. - MbCubicSpline( const MbCurve & ); + MbCubicSpline( const MbCurve &, VERSION ); /** \brief \ru Конструктор. \en Constructor. \~ @@ -90,6 +90,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline * Create( const MbCubicSpline & other ); /** \brief \ru Создать сплайн gj rhb. @@ -98,8 +100,10 @@ public : \en Create spline by a given curve and set parameters of spline.\n \~ \param[in] curve - \ru Заданная кривая. \en Given curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbCubicSpline * Create( const MbCurve & curve ); + static MbCubicSpline * Create( const MbCurve & curve, VERSION version ); /** \brief \ru Создать сплайн. \en Create spline. \~ \details \ru Создать сплайн и установить параметры сплайна.\n @@ -108,6 +112,8 @@ public : \en Set of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline * Create( const SArray & points, bool cls ); /** \brief \ru Создать сплайн. @@ -120,6 +126,8 @@ public : \en Set of second derivatives at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline * Create( const SArray & points, const SArray & seconds, bool cls ); @@ -133,6 +141,8 @@ public : \en Set of parameters at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline * Create( const SArray & points, const SArray & params, bool cls ); @@ -148,6 +158,8 @@ public : \en Set of parameters at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline * Create( const SArray & points, const SArray & seconds, @@ -160,19 +172,19 @@ public : \en \name Spline initialization functions. \{ */ /// \ru Инициализатор по заданной кривой. \en Initializer by a given curve. - bool Init( const MbCurve & ); + bool Init( const MbCurve &, VERSION version ); /// \ru Инициализатор по точкам и признаку замкнутости. \en Initializer by points and an attribute of closedness. - bool Init( const SArray &, bool ); + bool Init( const SArray &, bool ); /// \ru Инициализатор по точкам, вторым производным и признаку замкнутости. \en Initializer by points, second derivatives and closedness attribute. - bool Init( const SArray &, - const SArray &, bool ); + bool Init( const SArray &, + const SArray &, bool ); /// \ru Инициализатор по точкам, параметрам и признаку замкнутости. \en Initializer by points, parameters and closedness attribute. - bool Init( const SArray &, - const SArray &, bool ); + bool Init( const SArray &, + const SArray &, bool ); /// \ru Инициализатор по точкам, вторым производным, параметрам и признаку замкнутости. \en Initializer by points, second derivatives, parameters and closedness attribute. - bool Init( const SArray &, - const SArray &, - const SArray &, bool ); + bool Init( const SArray &, + const SArray &, + const SArray &, bool ); /// \ru Дублирующий инициализатор. \en Duplicating initializer. void InitC( const MbCubicSpline & ); /** \} */ @@ -182,7 +194,7 @@ 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 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 @@ -218,9 +230,8 @@ public : virtual void Explore( double & t, bool ext, MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const; - // \ru четвертая производная \en Fourth derivative - void FourDer ( double &, MbVector & ) const; ///< \ru Вычислить четвертую производную. \en Calculate the fourth derivative. - void PointOnLine ( double &, MbCartPoint & ); ///< \ru Вычислить точку на кривой при линейной аппроксимации. \en Calculate a point on the curve with a linear approximation. + void FourDer ( double &, MbVector & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. + void PointOnLine( double &, MbCartPoint & ) const; ///< \ru Вычислить точку на кривой при линейной аппроксимации. \en Calculate a point on the curve with a linear approximation. /** \} */ /** \ru \name Функции движения по кривой diff --git a/C3d/Include/cur_cubic_spline3d.h b/C3d/Include/cur_cubic_spline3d.h index ab23832..dc387a8 100644 --- a/C3d/Include/cur_cubic_spline3d.h +++ b/C3d/Include/cur_cubic_spline3d.h @@ -67,7 +67,7 @@ protected: const MbVector3D & vectE, bool sInit, bool eInit ); - MbCubicSpline3D( const MbCurve3D & curve ); // \ru Конструктор по другой кривой \en Constructor by another curve + MbCubicSpline3D( const MbCurve3D & curve, VERSION version ); // \ru Конструктор по другой кривой \en Constructor by another curve // \ru Конструктор по двумерному сплайну на плоскости \en Constructor by a two-dimensional spline on the plane MbCubicSpline3D( const MbCubicSpline & initFlat, const MbPlacement3D & plane ); public: @@ -77,6 +77,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const MbCubicSpline3D & other ); /** \brief \ru Создать сплайн. @@ -85,8 +87,12 @@ public : \en Create spline by a given curve and set parameters of spline.\n \~ \param[in] curve - \ru Заданная кривая. \en Given curve. \~ + \param[in] version - \ru Версия. + \en Version. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbCubicSpline3D * Create( const MbCurve3D & curve ); + static MbCubicSpline3D * Create( const MbCurve3D & curve, VERSION version ); /** \brief \ru Создать сплайн. \en Create spline. \~ \details \ru Создать сплайн и установить параметры сплайна.\n @@ -96,7 +102,9 @@ public : \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ \param[in] version - \ru Версия. - \en Version. \~ + \en Version. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const SArray & points, bool cls, @@ -113,6 +121,8 @@ public : \en A closedness attribute. \~ \param[in] version - \ru Версия. \en Version. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const SArray & points, const SArray & seconds, @@ -128,6 +138,8 @@ public : \en Set of parameters at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const SArray & points, const SArray & params, @@ -144,6 +156,8 @@ public : \en Set of parameters at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const SArray & points, const SArray & seconds, @@ -157,6 +171,8 @@ public : \en Plane spline. \~ \param[in] plane - \ru Плоскость кривой. \en Plane of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbCubicSpline3D * Create( const MbCubicSpline & initFlat, const MbPlacement3D & plane ); /** \brief \ru Создать сплайн. @@ -173,6 +189,8 @@ public : \en Use or not first derivative at the begin. \~ \param[in] eInit - \ru Учитывать ли производную в конце. \en Use or not first derivative at the end. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ // \ru Конструктор по точкам, первым производным на краях (если их надо учитывать) \en Constructor by points, first derivatives at the edges (if they should be considered) static MbCubicSpline3D * Create( const SArray & points, @@ -180,6 +198,32 @@ public : const MbVector3D & vectE, bool sInit, bool eInit ); + /** \brief \ru Создать сплайн. + \en Create spline. \~ + \details \ru Создать сплайн и установить параметры сплайна.\n + \en Create spline and set parameters of spline.\n \~ + \param[in] points - \ru Набор контрольных точек. + \en Set of control points. \~ + \param[in] params - \ru Набор параметров в контрольных точках. + \en Set of parameters at the control points. \~ + \param[in] vectS - \ru Первая производная в начале. + \en First derivative at the begin. \~ + \param[in] vectE - \ru Первая производная в конце. + \en First derivative at the end. \~ + \param[in] sInit - \ru Учитывать ли производную в начале. + \en Use or not first derivative at the begin. \~ + \param[in] eInit - \ru Учитывать ли производную в конце. + \en Use or not first derivative at the end. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + // \ru Конструктор по точкам, первым производным на краях (если их надо учитывать) \en Constructor by points, first derivatives at the edges (if they should be considered) + static MbCubicSpline3D * Create( const SArray & points, + const SArray & params, + const MbVector3D & vectS, + const MbVector3D & vectE, + bool sInit, + bool eInit ); public: VISITING_CLASS( MbCubicSpline3D ); @@ -197,7 +241,7 @@ public: // \ru Инициализация по точкам, параметрам и краевым производным \en Initialization by points, parameters and boundary derivatives bool Init( const SArray &, const SArray &, const MbVector3D &, const MbVector3D &, bool, bool ); - bool Init( const MbCurve3D & ); // \ru Инициализатор по другой кривой \en Initializer by another curve + bool Init( const MbCurve3D &, VERSION version ); // \ru Инициализатор по другой кривой \en Initializer by another curve void InitC( const MbCubicSpline3D & ); // \ru Дублирующий инициализатор \en Duplicating initializer // \ru Инициализатор по двумерному сплайну на плоскости \en Initializer by a two-dimensional spline on the plane void Init( const MbCubicSpline &, const MbPlacement3D & ); @@ -227,7 +271,7 @@ public: virtual void Explore( double & t, bool ext, MbCartPoint3D & pnt, MbVector3D & fir, MbVector3D * sec, MbVector3D * thir ) const; - void FourDer ( double &, MbVector3D & ) const; // \ru четвертая производная \en Fourth derivative + void FourDer( double &, MbVector3D & ) const; ///< \ru Оценить четвертую производную. \en Estimate the fourth derivative. // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve virtual MbNurbs3D * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; diff --git a/C3d/Include/cur_curve_spiral.h b/C3d/Include/cur_curve_spiral.h index ee06016..31e391a 100644 --- a/C3d/Include/cur_curve_spiral.h +++ b/C3d/Include/cur_curve_spiral.h @@ -42,20 +42,48 @@ protected: bool curveSense; ///< \ru Совпадение направления оси спирали с направлением кривой curve. \en The coincidence of the direction of the spiral axis with the direction of the curve "curve". public: - MbCurveSpiral( const MbPlacement3D & pl, double rad, double s, double t1, double t2 ); // \ru Цилиндрическая спираль \en Cylindrical spiral - MbCurveSpiral( const MbPlacement3D & pos, MbCurve & lawCurve, double s, bool same ); // \ru Спираль с образующей кривой \en Spiral with a generating curve - + /** \brief \ru Создать цилиндрическую спираль по радиусу основания, шагу, основанию, и двум параметрам. + \en Create cylindrical spiral by bottom radius, step, base and two parameters. \~ + \details \ru Создать цилиндрическую спираль по радиусу основания, шагу, основанию, и двум параметрам. \n + \en Create cylindrical spiral by bottom radius, step, base and starting and ending parameters. \n \~ + \param[in] place - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] radius - \ru Радиус основания спирали. + \en Radius of spiral. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] t1 - \ru Начальный параметр. + \en Starting parameter. \~ + \param[in] t2 - \ru Конечный параметр. + \en Ending parameter. \~ + */ + MbCurveSpiral( const MbPlacement3D & place, double radius, double st, double t1, double t2 ); + /** \brief \ru Конструктор спирали по её основанию, закону изменения радиуса и шагу. + \en The constructor of spiral by its base, the law of radius change and step. \~ + \details \ru Конструктор спирали по её основанию (локальной системе координат), закону изменения радиуса в виде образующей кривой и шагу между витками спирали. \n + \en The constructor of spiral by its base (local coordinate system), the law of radius change (in the form of the 2D-curve) and step between coils of spiral. \n \~ + \param[in] place - \ru Локальная система координат. + \en A local coordinate system. \~ + \param[in] lawCurve - \ru Закон изменения радиуса. + \en The law of radius change. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] sameLawCurve - \ru Флаг использования оригинала кривой. + \en Flag of original curve use. \~ + */ + MbCurveSpiral( const MbPlacement3D & place, MbCurve & lawCurve, double st, bool sameLawCurve ); protected: - MbCurveSpiral( const MbCurveSpiral & init ); - + MbCurveSpiral( const MbCurveSpiral & ); public : virtual ~MbCurveSpiral(); public: VISITING_CLASS( MbCurveSpiral ); - void Init( const MbCurveSpiral & init ); - void Init( const MbPlacement3D & place ); + /// \ru Инициализация спирали по спирали. \en Spiral initialization by spiral. + void Init( const MbCurveSpiral & ); + /// \ru Инициализация спирали по основанию (локальной системе координат). \en Spiral initialization by base (local coordinate system). + void Init( const MbPlacement3D & ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -90,7 +118,7 @@ public: // \ru Функции спирали \en Functions of spiral - virtual void SetStep( double s ); // \ru Изменить шаг \en Change step + virtual bool SetStep( double s ); // \ru Изменить шаг \en Change step virtual double GetSpiralRadius ( double t ) const; // \ru Выдать физический радиус спирали \en Get physical radius of spiral protected: diff --git a/C3d/Include/cur_hermit.h b/C3d/Include/cur_hermit.h index 1196811..bab0288 100644 --- a/C3d/Include/cur_hermit.h +++ b/C3d/Include/cur_hermit.h @@ -88,6 +88,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const MbHermit & ); /** \brief \ru Создать сплайн. @@ -98,6 +100,8 @@ public : \en Set of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const SArray & initList, bool cls ); /** \brief \ru Создать сплайн. @@ -110,6 +114,8 @@ public : \en Set of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const SArray & initParams, const SArray & initPoints, bool cls ); @@ -125,6 +131,8 @@ public : \en Set of derivatives at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const SArray & initParams, const SArray & initPoints, const SArray & initVectors, bool cls ); @@ -140,6 +148,8 @@ public : \en Array, containing indexes of points with same derivative. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const SArray & initParams, const SArray & initPoints, const SArray & vLabels, bool cls ); @@ -151,6 +161,8 @@ public : \en Start point of curve. \~ \param[in] p2 - \ru Конечная точка кривой. \en End point of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( const MbCartPoint & p1, const MbCartPoint & p2 ); /** \brief \ru Создать сплайн. @@ -169,6 +181,8 @@ public : \en End point of curve. \~ \param[in] v2 - \ru Касательный вектор к кривой в конечной точке. \en A tangent vector to the curve at the end point. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit * Create( double t1, const MbCartPoint & p1, const MbVector & v1, double t2, const MbCartPoint & p2, const MbVector & v2 ); @@ -217,7 +231,7 @@ public : // \ru Создать NURBS представление кривой \en Create a NURBS representation of the curve virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve - virtual MbContour * NurbsContour() const; + virtual MbContour * NurbsContour() const; virtual double GetTMin() const; // \ru Вернуть минимальное значение параметра \en Get the minimum value of parameter virtual double GetTMax() const; // \ru Вернуть максимальное значение параметра \en Get the maximum value of parameter @@ -254,7 +268,7 @@ public : virtual size_t GetCount() const; // \ru Выдать индекс точки, ближайшей к заданной \en Get index of the nearest point to the given one - virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; + virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; virtual void Rebuild(); // \ru Пересчитать кривую \en Rebuild the curve virtual void SetClosed( bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. @@ -286,7 +300,7 @@ public : void SetLimitVector( int n, const MbVector & v ); /// \ru Создать кривую путём сращивания части данной кривой с частью кривой init. \en Create a curve by joining a part of this curve with a part of "init" curve. MbHermit * CurvesCombine( double t0, double w0, bool add, - const MbHermit & init, double t1, double w1, double koef ) const; + 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; } @@ -302,6 +316,9 @@ public : // \ru Вставить точки и параметры в перед кривой в заданной последовательности. \en Parameters and points insetr to beg successively. bool InsertPoints( SArray & params, SArray & points ); + // \ru При линейном расположении нескольких точек согласовать производные на краях участка. \en Aligning the derivatives on the group if several points are located linearly. + bool DerivativesCorrection( double accuracy ); + /// \ru Определение максимального индекса массива параметров слева. \en Determination of the maximum index of parameter array on the left. ptrdiff_t GetIndex( double t ) const; @@ -328,6 +345,7 @@ private: IMPL_PERSISTENT_OPS( MbHermit ) + //------------------------------------------------------------------------------ /// \ru Определение местных координат области поверхности \en Definition of local coordinates in a surface region // --- diff --git a/C3d/Include/cur_hermit3d.h b/C3d/Include/cur_hermit3d.h index 6a48a28..6a58df8 100644 --- a/C3d/Include/cur_hermit3d.h +++ b/C3d/Include/cur_hermit3d.h @@ -73,6 +73,8 @@ public: \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const MbHermit3D & ); /** \brief \ru Создать сплайн. @@ -83,6 +85,8 @@ public: \en Set of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const SArray & initList, bool cls ); /** \brief \ru Создать сплайн. @@ -95,6 +99,8 @@ public: \en Set of control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const SArray & initParams, const SArray & initPoints, bool cls ); @@ -110,6 +116,8 @@ public: \en Set of derivatives at the control points. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const SArray & initParams, const SArray & initPoints, const SArray & initVectors, bool cls ); @@ -125,6 +133,8 @@ public: \en Array, containing indexes of points with same derivative. \~ \param[in] cls - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const SArray & initParams, const SArray & initPoints, const SArray & vLabels, bool cls ); @@ -136,6 +146,8 @@ public: \en The two-dimensional spline. \~ \param[in] place - \ru Локальная система координат сплайна. \en Local coordinate system of spline. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const MbHermit & init, const MbPlacement3D & plane ); /** \brief \ru Создать сплайн. @@ -146,6 +158,8 @@ public: \en Start point of curve. \~ \param[in] p2 - \ru Конечная точка кривой. \en End point of curve. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ); /** \brief \ru Создать сплайн. @@ -164,6 +178,8 @@ public: \en End point of curve. \~ \param[in] v2 - \ru Касательный вектор к кривой в конечной точке. \en A tangent vector to the curve at the end point. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbHermit3D * Create( double t1, const MbCartPoint3D & p1, const MbVector3D & v1, double t2, const MbCartPoint3D & p2, const MbVector3D & v2 ); @@ -171,18 +187,24 @@ public: public : VISITING_CLASS( MbHermit3D ); - // \ru Установить параметры сплайна \en Set parameters of spline + /// \ru Установить параметры сплайна по точкам и флагу замкнутости. \en Set parameters of spline by points and closeness flag. bool Init( const SArray & initPoints, bool cls ); + /// \ru Установить параметры сплайна по параметрам, точкам и флагу замкнутости. \en Set parameters of spline by parameters, points and closeness flag. bool Init( const SArray & initParams, const SArray & initPoints, bool cls ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. bool Init( const SArray & initParams, const SArray & initPoints, const SArray & initVectors, bool cls ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. bool Init( const SArray & initParams, const SArray & initPoints, const SArray & vLabels, bool cls ); + /// \ru Установить параметры сплайна по другому сплайну Эрмита. \en Set parameters of spline by another spline of Hermit. void Init( const MbHermit3D & ); + /// \ru Установить параметры сплайна по двумерному сплайну Эрмита. \en Set parameters of spline by two-dimensional spline of Hermit. void Init( const MbHermit &, const MbPlacement3D & ); + /// \ru Установить параметры сплайна. \en Set parameters of spline. void Init( double t1, const MbCartPoint3D & p1, const MbVector3D & v1, double t2, const MbCartPoint3D & p2, const MbVector3D & v2 ); @@ -271,14 +293,14 @@ public : void CalculateDerivatives(); void SetLimitVector( ptrdiff_t n, const MbVector3D & v ); - size_t GetVectorListCount() const { return vectorList.size(); } - void GetVectorList( SArray & vectors ) const { vectors = vectorList; } + size_t GetVectorListCount() const { return vectorList.size(); } + void GetVectorList( SArray & vectors ) const { vectors = vectorList; } const MbVector3D & _GetVectorList( size_t i ) const { return vectorList[i]; } MbVector3D & _SetVectorList( size_t i ) { MbPolyCurve3D::Refresh(); return vectorList[i]; } - size_t GetTListCount() const { return tList.size(); } - void GetTList( SArray & params ) const { params = tList; } - double _GetTList( size_t i ) const { return tList[i]; } + size_t GetTListCount() const { return tList.size(); } + void GetTList( SArray & params ) const { params = tList; } + double _GetTList( size_t i ) const { return tList[i]; } void LocalCoordinate( double & t, ptrdiff_t & index1, ptrdiff_t & index2, @@ -286,6 +308,10 @@ public : double & paramD, double & paramW, double & quota1, double & quota2 ) const; ptrdiff_t GetIndex( double t ) const; + + // \ru При линейном расположении нескольких точек согласовать производные на краях участка. \en Aligning the derivatives on the group if several points are located linearly. + bool DerivativesCorrection( double accuracy ); + private: bool Break( MbHermit3D & trimPart, double t1, double t2 ) const; // \ru Разбить на две части \en Split into two parts bool SetCorrection( size_t ind, double tDelta ); // \ru Скорректировать кривую по индексу. \en Curve correction by index. @@ -298,6 +324,7 @@ private: IMPL_PERSISTENT_OPS( MbHermit3D ) + //------------------------------------------------------------------------------ // \ru Определение местных координат области поверхности \en Definition of local coordinates in a surface region // --- diff --git a/C3d/Include/cur_line.h b/C3d/Include/cur_line.h index 0baa480..8008f95 100644 --- a/C3d/Include/cur_line.h +++ b/C3d/Include/cur_line.h @@ -61,7 +61,7 @@ public : void Init( const MbCartPoint & pnt, const MbDirection & dir ) { origin = pnt; direction = dir; } void Init( const MbCartPoint & pnt, const MbVector & dir ) { origin = pnt; direction = dir; } void Init( const MbCartPoint & p1, const MbCartPoint & p2 ) { origin = p1; direction.Calculate( p1, p2 ); } - void Init( double a, double b, double c ); // \ru Инициализация прямой по коэффициентам \en Initialization of a line by coefficients + void Init( double a, double b, double c ); // \ru Инициализация прямой по коэффициентам \en Initialization of a line by coefficients /** \} */ /** \ru \name Общие функции геометрического объекта. @@ -84,7 +84,8 @@ public : virtual bool IsVisibleInRect( const MbRect &, bool exact = false ) const; // \ru Виден ли объект в заданном прям-ке \en Whether the object is visible in the given rectangle using MbCurve::IsVisibleInRect; - virtual double DistanceToPoint( const MbCartPoint & ) const; // \ru Расстояние до точки \en Distance to a point + virtual double DistanceToPoint( const MbCartPoint & ) const; // \ru Расстояние до точки \en Distance to a point + virtual bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const; // \ru Вычислить расстояние до точки, если оно меньше d. \en Calculate the distance to the point if it is less than d. /** \} */ /** \ru \name Функции описания области определения кривой. @@ -134,7 +135,7 @@ public : /** \ru \name Общие функции кривой \en \name Common functions of curve \{ */ - virtual MbCurve * Offset( double rad ) const; // \ru Смещение прямой \en Shift of line + virtual MbCurve * Offset( double rad ) const; // \ru Смещение прямой \en Shift of line // \ru Удалить часть прямой между параметрами t1 и t2 \en Remove a part of the line between t1 and t2 parameters virtual MbeState DeletePart( double t1, double t2, MbCurve *& part2 ); @@ -289,7 +290,8 @@ inline void MbLine::Implicit( double & A, double & B, double & C ) const { //------------------------------------------------------------------------------ -// \ru Определение параметров t1, t2 точки пересечения прямых, заданных точкой и вектором направления \en Definition of parameters t1, t2 of the intersection point of lines given a point and a direction vector +// \ru Определение параметров t1, t2 точки пересечения прямых, заданных точкой и вектором направления. +// \en Definition of parameters t1, t2 of the intersection point of lines given a point and a direction vector. // --- inline bool LineLineCrossParams( const MbCartPoint & origin1, const MbVector & direction1, const MbCartPoint & origin2, const MbVector & direction2, @@ -297,7 +299,7 @@ inline bool LineLineCrossParams( const MbCartPoint & origin1, const MbVector & d { double d = direction1.y * direction2.x - direction1.x * direction2.y; - if ( ::fabs( d ) > EPSILON ) { + if ( ::fabs( d ) > EPSILON ) { // \ru Прямые не параллельны. \en Lines not parallel. double dx = origin2.x - origin1.x; double dy = origin2.y - origin1.y; @@ -306,6 +308,18 @@ inline bool LineLineCrossParams( const MbCartPoint & origin1, const MbVector & d 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 ); + t1 = ( (middle.x - origin1.x) * direction1.x + (middle.y - origin1.y) * direction1.y ); + t2 = ( (middle.x - origin2.x) * direction2.x + (middle.y - origin2.y) * direction2.y ); + d = ( direction1.x * direction1.x ) + ( direction1.y * direction1.y ); + if ( d > NULL_EPSILON ) + t1 /= d; + d = ( direction2.x * direction2.x ) + ( direction2.y * direction2.y ); + if ( d > NULL_EPSILON ) + t2 /= d; + return false; // \ru Прямые совпадают или параллельны \en Lines coincide or are parallel } diff --git a/C3d/Include/cur_line3d.h b/C3d/Include/cur_line3d.h index fe39407..900a684 100644 --- a/C3d/Include/cur_line3d.h +++ b/C3d/Include/cur_line3d.h @@ -109,7 +109,6 @@ public : // \ru Вычислить габарит в локальной системе координат. \en Calculate bounding box in the local coordinate system. virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & ) const; - // \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; diff --git a/C3d/Include/cur_line_segment.h b/C3d/Include/cur_line_segment.h index d9a02c6..e1bd852 100644 --- a/C3d/Include/cur_line_segment.h +++ b/C3d/Include/cur_line_segment.h @@ -23,14 +23,14 @@ class DiskreteLengthData; /** \brief \ru Отрезок прямой в двумерном пространстве. \en Line segment in two-dimensional space. \~ \details \ru Отрезок прямой описывается начальной точкой point1 и конечной точкой point2.\n - Область определения параметра отрезка располагается в пределах от нуля до единицы. + Область определения параметра отрезка располагается в пределах от нуля до единицы. Начальной точке отрезка point1 соответствует параметр tmin=0, конечной точке отрезка point2 соответствует параметр tmax=1.\n - Радиус-вектор отрезка описывается векторной функцией\n + Радиус-вектор отрезка описывается векторной функцией\n r(t) = ((1 - t) point1) + (t point2).\n \en Line segment is described by the start point "point1" and the end point "point2". \n - Domain of a line segment is the range [0, 1]. + Domain of a line segment is the range [0, 1]. The start point of line segment corresponds to parameter tmin=0, the end point of line segment corresponds to parameter tmax=1.\n - Radius-vector of line segment is described by the vector function \n + Radius-vector of line segment is described by the vector function \n r(t) = ((1 - t) point1) + (t point2).\n \~ \ingroup Curves_2D */ diff --git a/C3d/Include/cur_nurbs.h b/C3d/Include/cur_nurbs.h index 6a64f65..337d711 100644 --- a/C3d/Include/cur_nurbs.h +++ b/C3d/Include/cur_nurbs.h @@ -62,7 +62,7 @@ class MATH_CLASS MbContour; class MATH_CLASS MbNurbs : public MbPolyCurve { private: - ptrdiff_t degree; ///< \ru Порядок В-сплайна (порядок = степень + 1). \en Order of B-spline (order = degree + 1). + size_t degree; ///< \ru Порядок В-сплайна (порядок = степень + 1). \en Order of B-spline (order = degree + 1). ptrdiff_t uppKnotsIndex; ///< \ru Последний индекс узлового вектора. \en Last index of knot vector. SArray knots; ///< \ru Узловой вектор. \en Knot vector. SArray weights; ///< \ru Множество весов контрольных точек. \en Set of weights of the control points. @@ -125,7 +125,7 @@ protected: */ template - MbNurbs( ptrdiff_t degree, bool cls, const PointsVector & points, + MbNurbs( size_t degree, bool cls, const PointsVector & points, const DoubleVector * weights, const DoubleVector * knots ); MbNurbs( const MbNurbs & ); public : @@ -138,6 +138,8 @@ public: \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs * Create( const MbNurbs & ); /** \brief \ru Создать сплайн. @@ -150,6 +152,8 @@ public: \en Set of control points. \~ \param[in] initClosed - \ru Признак замкнутости. \en A closedness attribute. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ template static MbNurbs * Create( ptrdiff_t initDegree, const PointsVector & initPoints, bool initClosed ) @@ -171,6 +175,8 @@ public: \en A closedness attribute. \~ \param[in] initWeights - \ru Набор весов для контрольных точек. \en Set of weights for control points. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ template static MbNurbs * Create( ptrdiff_t initDegree, const PointsVector & initPoints, bool initClosed, @@ -197,6 +203,8 @@ public: \en Non-decreasing sequence of weights. \~ \param[in] initForm - \ru Тип построения. \en Type of construction. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ template static MbNurbs * Create( ptrdiff_t initDegree, bool initClosed, const PointsVector & initPoints, @@ -223,8 +231,10 @@ public: \en Set of points which the spline passes through. \~ \param[in] params - \ru Последовательность узловых параметров. \en Sequence of knot parameters. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbNurbs * CreateThrough( ptrdiff_t degree, bool cls, const SArray & points, + static MbNurbs * CreateThrough( size_t degree, bool cls, const SArray & points, const SArray & params ); /** \brief \ru Заполнить NURBS по данным parasolid. \en Fill NURBS by parasolid data. \~ @@ -254,8 +264,10 @@ public: \en Count of elements in 'knots' array. \~ \param[in] scl - \ru Коэффициент масштабирования. \en A scale factor. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbNurbs * CreateParasolid( ptrdiff_t degree, bool closed, bool rational, ptrdiff_t count, + static MbNurbs * CreateParasolid( size_t degree, bool closed, bool rational, ptrdiff_t count, const CcArray & verts, ptrdiff_t vertsCount, const CcArray & mul, ptrdiff_t mulCount, const CcArray & knots, ptrdiff_t knotsCount, @@ -272,6 +284,8 @@ public: \en The final point the spline passes through. \~ \param[in] v2 - \ru Касательный вектор к кривой в конечной точке. \en A tangent vector to the curve at the end point. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs * CreateCube( const MbCartPoint & p1, const MbVector & v1, const MbCartPoint & p2, const MbVector & v2 ); /** \brief \ru Создать сплайн. @@ -282,6 +296,8 @@ public: Первая и последняя точки определяют начало и конец дуги, соответственно. \en A set of four points the section passes through. The first and last points define the beginning and ending of the arc respectively. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs * CreateArc( const SArray & points ); /** \brief \ru Создать сплайн. @@ -294,6 +310,8 @@ public: \en The starting point of the arc. \~ \param[in] p2 - \ru Конечная точка дуги. \en The end point of the arc. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs * CreateArc( double a2, const MbCartPoint & p1, const MbCartPoint & p2 ); /** \brief \ru Создать сплайн. @@ -308,6 +326,8 @@ public: \en Height of the wave. \~ \param[in] periode - \ru Период волны. \en Period of the wave. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs * CreateWavyLine( const MbCartPoint & p1, const MbCartPoint & p2, double height, double periode ); @@ -333,7 +353,7 @@ public : \en A closedness attribute. \~ */ template - bool Init( ptrdiff_t initDegree, const PointsVector & initPoints, bool initClosed ) + bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed ) { if ( ::IsValidNurbsParams( initDegree, initClosed, initPoints.size() ) ) { @@ -366,7 +386,7 @@ public : \en Set of weights for control points. \~ */ template - bool Init( ptrdiff_t initDegree, const PointsVector & initPoints, bool initClosed, + bool Init( size_t initDegree, const PointsVector & initPoints, bool initClosed, const DoubleVector * initWeights ) { if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, initWeights ) ) @@ -415,7 +435,7 @@ public : \en Type of construction. \~ */ template - bool Init( ptrdiff_t initDegree, bool initClosed, const PointsVector & initPoints, + bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, const DoubleVector & initWeights, const DoubleVector & initKnots, MbeNurbsCurveForm initForm = ncf_Unspecified ) { @@ -455,7 +475,7 @@ public : \param[in] nKnots - \ru Количество узлов. \en Count of knots. \~ */ - bool Init( ptrdiff_t degree, bool cls, const CcArray & points, + bool Init( size_t degree, bool cls, const CcArray & points, const CcArray & knots, ptrdiff_t nPoints, ptrdiff_t nKnots ); /** \brief \ru Инициализация. \en Initialization. \~ @@ -472,7 +492,7 @@ public : \param[in] params - \ru Последовательность узловых параметров. \en Sequence of knot parameters. \~ */ - bool InitThrough( ptrdiff_t degree, bool cls, const SArray & points, + bool InitThrough( size_t degree, bool cls, const SArray & points, const SArray & params ); /** \brief \ru Инициализация. @@ -580,7 +600,7 @@ public : /** \brief \ru Интерполяция. \en Interpolation. \~ \details \ru Создать плоский сплайн четвертого порядка по составному сплайну Безье четвертого порядка.\n - Внимание! Парамеризация отлична от параметризации исходной кривой Безье. + Внимание! Параметризация отлична от параметризации исходной кривой Безье. \en Create a planar spline of fourth order by composite Bezier spline of fourth order.\n If closedness is necessary - call UnClamped( bezier.IsClosed() ). \~ */ @@ -590,15 +610,15 @@ public : bool AttachG( MbPntMatingData & connectData, bool beg ); /// \ru Увеличить порядок кривой, не изменяя ее геометрическую форму и параметризацию. \en Increase order of curve without changing its geometric shape and parametrization. - bool RaiseDegree ( ptrdiff_t, double relEps = Math::paramEpsilon ); + bool RaiseDegree ( size_t, double relEps = Math::paramEpsilon ); /// \ru Уменьшить порядок кривой на 1, не изменяя ее геометрическую форму и параметризацию. \en Decrease order of curve by 1 without changing its geometric shape and parametrization. bool ReductionDegree( double relEps = Math::paramEpsilon ); /// \ru Задать порядок сплайна. \en Set the spline order. - void SetDegree( ptrdiff_t newDegree ); + void SetDegree( size_t newDegree ); /// \ru Увеличить порядок на 1. \en Increase the order by 1. void DegreeIncrease(); /// \ru Установить тип формы. \en Set the type of shape. - void SetFormType( MbeNurbsCurveForm f ) { form = f; } + void SetFormType( MbeNurbsCurveForm f ) { form = f; } /// \ru Точка на кратном узле. \en The point on a multiple knot. bool PointOnMultipleKnot( const MbCartPoint & point ) const; @@ -608,7 +628,7 @@ public : \{ */ 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 bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая other копией данной кривой? \en Whether the curve is duplicate of current curve. + 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. @@ -680,7 +700,7 @@ public : virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve * NurbsCurve( const MbNurbsParameters & tParameters ) const; // \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. - virtual MbContour * NurbsContour() const; + virtual MbContour * NurbsContour() const; virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; @@ -749,7 +769,8 @@ public : double & t, bool ext, MbRect1D * tRange = 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); virtual void GetStartPoint( MbCartPoint & ) const; virtual void GetEndPoint ( MbCartPoint & ) const; @@ -772,21 +793,30 @@ public : MbeNurbsCurveForm GetFormType() const { return form; } /// \ru Выдать порядок сплайна. \en Get the spline order. - ptrdiff_t GetDegree() const { return degree; } + size_t GetDegree() const { return degree; } /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get attribute of rationality, but no regularity of curve. bool IsRational() const; - template - void GetWeights( Weights & wts ) const { std::copy( weights.begin(), weights.end(), std::back_inserter(wts) ); } + /// \ru Получить размер весового вектора. \en Get a size of weights vector. size_t GetWeightsCount() const { return weights.size(); } + /// \ru Получить весовой вектор. \en Get a weights vector. + template + void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. double GetWeight( size_t ind ) const { return weights[ind]; } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. double & SetWeight( size_t ind ) { return weights[ind]; } - template - void GetKnots( Knots & kts ) const { std::copy( knots.begin(), knots.end(), std::back_inserter(kts) ); } + /// \ru Получить размер узлового вектора. \en Get a size of knots vector. size_t GetKnotsCount() const { return knots.size(); } + /// \ru Получить узловой вектор. \en Get a knots vector. + template + void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. double GetKnot( size_t ind ) const { return knots[ind]; } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. double & SetKnot( size_t ind ) { return knots[ind]; } + /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } // \ru BEG: для библиотеки (хорошо бы избавиться) \en BEG: for the library (it would be good to get rid of this) @@ -797,15 +827,15 @@ public : /// \ru Добавить узел в конец узлового вектора. \en Add a knot to the end of knot vector. void LtAddKnot ( double knot ) { C3D_ASSERT_UNCONDITIONAL( false ); knots.push_back( knot ); } /// \ru Задать порядок сплайна. \en Set the spline order. - void LtSetDegree( ptrdiff_t newDegree ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( newDegree >= 2 && form == ncf_Unspecified ) { degree = newDegree; } } + void LtSetDegree( size_t newDegree ) { C3D_ASSERT_UNCONDITIONAL( false ); if ( newDegree >= 2 && form == ncf_Unspecified ) { degree = newDegree; } } /// \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( ptrdiff_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 ); @@ -820,7 +850,7 @@ public : void SetWeight( ptrdiff_t pointNumber, double newWeight ); /// \ru Получить кратность узла. \en Get the knot multiplicity. - ptrdiff_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. @@ -841,7 +871,7 @@ public : // \ru Базовые операции над NURBS-кривой. \en Base operation with NURBS curve. /// \ru Добавление нового узла; возвращает количество узлов, которые удалось вставить. \en Addition of a new knots; returns the number of knots which have been inserted. - ptrdiff_t InsertKnots( double & newKnot, ptrdiff_t multiplicity, double relEps ); + size_t InsertKnots( double & newKnot, size_t multiplicity, double relEps ); /// \ru Удалить кратный внутренний узел id, num раз; вернуть количество удалений, которое удалось сделать. \en Remove multiple internal 'id' knot 'num' times, return count of removals was successfully made. ptrdiff_t RemoveKnot( ptrdiff_t id, ptrdiff_t num, double relEps = Math::paramEpsilon, double absEps = Math::lengthEpsilon ); /// \ru Удалить все внутренние узлы, если это возможно. \en Remove all internal knots if it is possible. @@ -931,25 +961,25 @@ IMPL_PERSISTENT_OPS( MbNurbs ) //------------------------------------------------------------------------------ -// конструктор математического В-сплайн +// Конструктор математического В-сплайна. // --- template -MbNurbs::MbNurbs( ptrdiff_t initDegree, bool initClosed, const PointsVector & initPoints, +MbNurbs::MbNurbs( size_t initDegree, bool initClosed, const PointsVector & initPoints, const DoubleVector * initWeights, const DoubleVector * initKnots ) : MbPolyCurve ( ) , degree ( 0 ) - , uppKnotsIndex( SYS_MAX_T ) // максимальный индекс узлового вектора + , uppKnotsIndex( SYS_MAX_T ) // Максимальный индекс узлового вектора. , knots ( ) , weights ( ) - , form ( ncf_Unspecified ) // форма В-сплайна + , form ( ncf_Unspecified ) // Форма В-сплайна. , cache ( ) { if ( ::IsValidNurbsParamsExt( initDegree, initClosed, initPoints, initWeights, initKnots ) ) { pointList.assign( initPoints.begin(), initPoints.end() ); - uppIndex = (ptrdiff_t)pointList.size() - 1; // количество точек + uppIndex = (ptrdiff_t)pointList.size() - 1; // Количество точек. closed = initClosed; - degree = initDegree; // степень В-сплайна + degree = initDegree; // Степень В-сплайна. if ( initWeights != NULL ) weights.assign( initWeights->begin(), initWeights->end() ); diff --git a/C3d/Include/cur_nurbs3d.h b/C3d/Include/cur_nurbs3d.h index e4dd3a7..e441b7a 100644 --- a/C3d/Include/cur_nurbs3d.h +++ b/C3d/Include/cur_nurbs3d.h @@ -19,6 +19,8 @@ #include #include #include +#include +#include class MATH_CLASS MbNurbs; @@ -57,7 +59,7 @@ class MATH_CLASS MbBezier3D; // --- class MATH_CLASS MbNurbs3D : public MbPolyCurve3D { private : - ptrdiff_t degree; ///< \ru Порядок В-сплайна (порядок = степень + 1). \en Order of B-spline (order = degree + 1). + size_t degree; ///< \ru Порядок В-сплайна (порядок = степень + 1). \en Order of B-spline (order = degree + 1). ptrdiff_t uppKnotsIndex; ///< \ru Последний индекс узлового вектора. \en Last index of knot vector. SArray weights; ///< \ru Множество весов контрольных точек. \en Set of weights of the control points. SArray knots; ///< \ru Узловой вектор сплайна. \en Knot vector of the spline. @@ -124,7 +126,7 @@ protected: \en Sequence of knot parameters. \~ */ - MbNurbs3D( ptrdiff_t deg, bool cls, const SArray & points, + MbNurbs3D( size_t deg, bool cls, const SArray & points, const SArray * weights = NULL, const SArray * knots = NULL ); MbNurbs3D( const MbNurbs3D & ); public : @@ -137,6 +139,8 @@ public : \en Create copy of spline. \~ \details \ru Создать копию сплайна.\n \en Create copy of spline.\n \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs3D * Create( const MbNurbs3D & ); /** \brief \ru Создать сплайн. @@ -147,6 +151,8 @@ public : \en The two-dimensional spline. \~ \param[in] place - \ru Локальная система координат сплайна. \en Local coordinate system of spline. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ static MbNurbs3D * Create( const MbNurbs & nurbs, const MbPlacement3D & place ); /** \brief \ru Создать сплайн. @@ -161,8 +167,10 @@ public : \en Closedness attribute. \~ \param[in] weights - \ru Набор весов для контрольных точек. \en Set of weights for control points. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbNurbs3D * Create( ptrdiff_t degree, const SArray & points, bool closed, + static MbNurbs3D * Create( size_t degree, const SArray & points, bool closed, const SArray * weights = NULL ); /** \brief \ru Создать сплайн. \en Create spline. \~ @@ -176,9 +184,10 @@ public : \en Set of control points. \~ \param[in] knots - \ru Неубывающая последовательность узлов. \en Nondecreasing sequence of knots. \~ - + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbNurbs3D * Create( ptrdiff_t degree, bool closed, const SArray & points, + static MbNurbs3D * Create( size_t degree, bool closed, const SArray & points, const SArray & knots ); /** \brief \ru Создать сплайн. \en Create spline. \~ @@ -196,10 +205,11 @@ public : \en Nondecreasing sequence of knots. \~ \param[in] initForm - \ru Тип построения. \en Type of construction. \~ - + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ template - static MbNurbs3D * Create( ptrdiff_t initDegree, bool initClosed, const PointsVector & initPoints, + static MbNurbs3D * Create( size_t initDegree, bool initClosed, const PointsVector & initPoints, const DoubleVector & initWeights, const DoubleVector & initKnots, MbeNurbsCurveForm initForm = ncf_Unspecified ) { @@ -224,8 +234,10 @@ public : \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( ptrdiff_t degree, bool cls, const SArray & points, + static MbNurbs3D * CreateThrough( size_t degree, bool cls, const SArray & points, const SArray & params, SArray * aKnots = NULL ); /** \brief \ru Заполнить NURBS по данным parasolid. \en Fill NURBS by parasolid data. \~ @@ -255,8 +267,10 @@ public : \en Count of elements in 'knots' array. \~ \param[in] scl - \ru Коэффициент масштабирования. \en Scale factor. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ */ - static MbNurbs3D * CreateParasolid( ptrdiff_t degree, bool closed, bool rational, ptrdiff_t count, + static MbNurbs3D * CreateParasolid( size_t degree, bool closed, bool rational, ptrdiff_t count, const CcArray & verts, ptrdiff_t vertsCount, const CcArray & mul, ptrdiff_t mulCount, const CcArray & knots, ptrdiff_t knotsCount, @@ -279,7 +293,7 @@ public: \param[in] closed - \ru Признак замкнутости. \en Closedness attribute. \~ */ - bool Init( ptrdiff_t degree, const SArray & points, bool closed, + bool Init( size_t degree, const SArray & points, bool closed, const SArray * weights = NULL ); /** \brief \ru Инициализация. \en Initialization. \~ @@ -295,7 +309,7 @@ public: \en Nondecreasing sequence of knots. \~ */ - bool Init( ptrdiff_t degree, bool closed, const SArray & points, + bool Init( size_t degree, bool closed, const SArray & points, const SArray & knots ); /** \brief \ru Инициализация. \en Initialization. \~ @@ -316,7 +330,7 @@ public: */ template - bool Init( ptrdiff_t initDegree, bool initClosed, const PointsVector & initPoints, + bool Init( size_t initDegree, bool initClosed, const PointsVector & initPoints, const DoubleVector & initWeights, const DoubleVector & initKnots, MbeNurbsCurveForm initForm = ncf_Unspecified ) { @@ -372,7 +386,7 @@ public: \param[in] endData - \ru Параметр сопряжения в конечной точке сплайна. \en Parameter of conjugation at the end point of the spline. \~ */ - bool Init( ptrdiff_t degree, const SArray & points, const SArray & weights, + bool Init( size_t degree, const SArray & points, const SArray & weights, MbPntMatingData & begData, MbPntMatingData & endData ); /** \brief \ru Инициализация. @@ -392,8 +406,8 @@ public: \param[in] endData - \ru Количество узлов. \en Count of knots. \~ */ - bool Init( ptrdiff_t degree, bool closed, const CcArray & points, - const CcArray & knots, ptrdiff_t nPoints, ptrdiff_t nKnots ); + bool Init( size_t degree, bool closed, const CcArray & points, + const CcArray & knots, size_t nPoints, size_t nKnots ); /** \brief \ru Инициализация. \en Initialization. \~ \details \ru Сплайн, проходящий через заданные точки при заданных параметрах.\n @@ -411,10 +425,10 @@ public: \param[in] aKnots - \ru Неубывающая последовательность узлов. \en Nondecreasing sequence of knots. \~ */ - bool InitThrough( ptrdiff_t degree, bool cls, const SArray & points, + bool InitThrough( size_t degree, bool cls, const SArray & points, const SArray & params, SArray * aKnots = NULL ); /// \ru Установить тип формы. \en Set the type of shape. - void SetFormType( MbeNurbsCurveForm f ) { form = f; } + void SetFormType( MbeNurbsCurveForm f ) { form = f; } // \ru Общие функции математического объекта. \en The common functions of the mathematical object. @@ -508,7 +522,8 @@ public: 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); // \ru Функции B-сплайн кривой. \en Functions of B-spline curve. /// \ru Выделить часть кривой. \en Extract a piece of a curve. @@ -520,7 +535,7 @@ public: // \ru Функции B-сплайна. \en Functions of B-spline. /// \ru Добавление нового узла с заданной кратностью. \en Add a new knot with the given multiplicity. - void InsertKnots ( double & newKnot, ptrdiff_t multiplicity, double relEps = Math::paramEpsilon ); + void InsertKnots ( double & newKnot, size_t multiplicity, double relEps = Math::paramEpsilon ); /// \ru Добавление новых узлов равномерно в промежуток от idBegin до idBegin+1. \en Add new equally spaced knots into the range from idBegin to idBegin+1. void InsertKnotsInRegion( ptrdiff_t idBegin ); @@ -536,12 +551,12 @@ public: bool DecomposeCurve(); /// \ru Увеличить порядок NURBS-кривой, не меняя ее геометрическую форму и парамеризацию. \en Increase the order of a NURBS-curve without changing its geometric shape and parameterization. - bool RaiseDegree ( ptrdiff_t, double relEps = Math::paramEpsilon ); + bool RaiseDegree ( size_t, double relEps = Math::paramEpsilon ); /// \ru Уменьшить порядок кривой на 1. \en Decrease the order of a curve by 1. bool ReductionDegree( double relEps = Math::paramEpsilon ); /// \ru Получить кратность узла с заданным номером. \en Get multiplicity of a knot with a given index. - ptrdiff_t KnotMultiplicity( ptrdiff_t knotIndex ) const; + size_t KnotMultiplicity( size_t knotIndex ) const; /// \ru Определение базисного узлового вектора. \en Definition of the basis knot vector. void DefineKnotsVector(); /// \ru Переопределение базисного узлового вектора из Close в Open. \en Redefine the basis knot vector from Close to Open. @@ -550,31 +565,42 @@ public: bool CloseKnotsVector (); /// \ru Установить область изменения параметра. \en Set the range of parameter. - bool SetLimitParam ( double pmin, double pmax ); + bool SetLimitParam( double pmin, double pmax ); /// \ru Добавить кривую в конец. \en Add a curve to the end. - void AddCurve ( MbNurbs3D &, bool bmerge = true ); + void AddCurve ( MbNurbs3D &, bool bmerge = true ); /// \ru Добавить кривые в конец. \en Add curves to the end. - void AddCurves ( const RPArray & ); + void AddCurves ( const RPArray & ); /// \ru Репераметризовать кривую в соответствии с длиной в случае, если кривая получена из набора кривых Безье. \en Reparameterize a curve according to the length if the curve is obtained from a set of Bezier curves. bool ReparamCurveInBezierForm(); /// \ru Получить форму В-сплайна. \en Get the form of B-spline. - MbeNurbsCurveForm GetFormType() const { return form; } + MbeNurbsCurveForm GetFormType() const { return form; } /// \ru Получить порядок В-сплайна. \en Get the order of B-spline. - ptrdiff_t GetDegree() const { return degree; } + size_t GetDegree() const { return degree; } /// \ru Вернуть признак рациональности, но не регулярности кривой. \en Get the attribute of rationality, but not regularity of a curve. bool IsRational() const; - size_t GetWeightsCount() const { return weights.Count(); } - void GetWeights( SArray & wts ) const { wts = weights; } + /// \ru Получить размер весового вектора. \en Get a size of weights vector. + size_t GetWeightsCount() const { return weights.size(); } + /// \ru Получить весовой вектор. \en Get a weights vector. + template + void GetWeights( WeightsVector & wts, bool justSet = true ) const { if ( justSet ) { wts.clear(); }; std::copy( weights.begin(), weights.end(), std::back_inserter( wts ) ); } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. double GetWeight( size_t ind ) const { return weights[ind]; } + /// \ru Получить значение элемента весового вектора по индексу. \en Get a weights vector element value by index. double & SetWeight( size_t ind ) { return weights[ind]; } - size_t GetKnotsCount() const { return knots.Count(); } - void GetKnots( SArray & knts ) const { knts = knots; } + /// \ru Получить размер узлового вектора. \en Get a size of knots vector. + size_t GetKnotsCount() const { return knots.size(); } + /// \ru Получить узловой вектор. \en Get a knots vector. + template + void GetKnots( KnotsVector & kts, bool justSet = true ) const { if ( justSet ) { kts.clear(); }; std::copy( knots.begin(), knots.end(), std::back_inserter( kts ) ); } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. double GetKnot ( size_t ind ) const { return knots[ind]; } + /// \ru Получить значение элемента узлового вектора по индексу. \en Get a knots vector element value by index. double & SetKnot ( size_t ind ) { return knots[ind]; } + /// \ru Вернуть максимальный индекс узлового вектора. \en Get the maximal index of knots vector. ptrdiff_t GetUppKnotsIndex() const { return uppKnotsIndex; } // \ru Функции только 3D кривой. \en Functions of 3D curve only. @@ -659,6 +685,14 @@ public: Attention! Parameterization is different from the parameterization of the source Bezier curve. \~ */ static MbNurbs3D * CreateNURBS4( const MbBezier3D & ); + /** \brief \ru Создать сплайн. + \en Create NURBS. \~ + \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 ); /** \brief \ru Разбить кривую. \en Split the curve. \~ \details \ru Разбить недифференцируемую NURBS-кривую четвертой степени в трижды кратном внутреннем узле.\n @@ -736,7 +770,7 @@ private: RPArray< MbPntMatingData > & inferredData, const SArray & arParams, const SArray & arKnots, - ptrdiff_t addCount, + size_t addCount, bool cls, MbeSplineCreateType useInitThrough, size_t deg = 4 ); diff --git a/C3d/Include/cur_nurbs_vector3d.h b/C3d/Include/cur_nurbs_vector3d.h index 869d4dd..0476a22 100644 --- a/C3d/Include/cur_nurbs_vector3d.h +++ b/C3d/Include/cur_nurbs_vector3d.h @@ -27,11 +27,15 @@ struct DoubleTriple double y; double z; + DoubleTriple() : x(0.0), y(0.0), z(0.0) {} + DoubleTriple( double xx, double yy, double zz ) : x( xx ), y( yy ), z( zz ) {} + // \ru Инициализация. \en Initialization. void Init( double xx, double yy, double zz ) { x = xx; y = yy; z = zz; } // \ru Инициализация. \en Initialization. - void Init( const DoubleTriple & ip ) { Init( ip.x, ip.y, ip.z ); } + template + void Init( const Array & o ) { x = o[0]; y = o[1]; z = o[2]; } // \ru Инициализация. \en Initialization. void Init( const DoubleTriple & ip, double iw ) { Init( ip.x * iw, ip.y * iw, ip.z * iw ); } @@ -44,8 +48,40 @@ struct DoubleTriple Init( ( p2.x - p1.x ) * kk, ( p2.y - p1.y ) * kk, ( p2.z - p1.z ) * kk ); } + // \ru Присвоение значений. \en Values assignment. + template + const DoubleTriple & operator=( const Array & o ) { + Init( o ); + return *this; + } + + /// \ru Доступ к координате по индексу. \en Access to coordinate by an index. + double & operator[]( size_t i ) { + return i < 2 ? ( i == 1 ? y : x) : z; + } + double operator[]( size_t i ) const { + return i < 2 ? ( i == 1 ? y : x) : z; + } + + /// \ru Сложить с точкой. \en Add a vector. + template + inline DoubleTriple operator + ( const Point & v ) const { + return DoubleTriple( x + v.x, y + v.y, z + v.z ); + } + + // \ru Вычесть точку. \en Subtract a point. + template + inline DoubleTriple operator - ( const Point & p ) const { + return DoubleTriple( x - p.x, y - p.y, z - p.z ); + } + }; +/// \ru Умножить DoubleTriple на число. \en Multiply DoubleTriple by number. +inline DoubleTriple operator * ( const DoubleTriple & p, const double & factor ) { + return DoubleTriple( p.x * factor, p.y * factor, p.z * factor ); +} + //------------------------------------------------------------------------------ /** \brief \ru Nurbs-вектор. \en Nurbs-vector. \~ @@ -73,6 +109,7 @@ public: void Dec( ptrdiff_t i, const MbNURBSVector & p1, ptrdiff_t ip1, const MbNURBSVector & p2, ptrdiff_t ip2, double kk ); void Set( ptrdiff_t i, const MbNURBSVector & p, ptrdiff_t ip, double kk ); void Set( ptrdiff_t i, const DoubleTriple * t, double * ww, ptrdiff_t ip ); + void Set( ptrdiff_t i, const DoubleTriple & t, double ww ); void Set( ptrdiff_t i, const DoubleTriple & t ); double& x( ptrdiff_t i ) { return _vec[i].x; } @@ -179,6 +216,13 @@ inline void MbNURBSVector::Set( ptrdiff_t i, const DoubleTriple * t, double * ww w(i) = ww[ip]; } +inline void MbNURBSVector::Set( ptrdiff_t i, const DoubleTriple & t, double ww ) +{ + _vec[i].Init( t.x , t.y , t.z ); + if ( useWeights ) + w(i) = ww; +} + inline void MbNURBSVector::Set( ptrdiff_t i, const DoubleTriple & t ) { _vec[i].Init( t.x , t.y , t.z ); diff --git a/C3d/Include/cur_offset_curve.h b/C3d/Include/cur_offset_curve.h index 81cabed..04dd602 100644 --- a/C3d/Include/cur_offset_curve.h +++ b/C3d/Include/cur_offset_curve.h @@ -25,13 +25,13 @@ class MbRegTransform; \en Offset extended curve. \~ \details \ru Эквидистантная продолженная кривая строится смещением точек базовой кривой вдоль нормали к ней. \n Параметры "offsetTmin, offsetTmax" задают смещение точек базовой кривой в точках tmin, tmax. - Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией \n + Радиус-вектор кривой в методе PointOn(double&t,MbCartPoint3D&r) описывается векторной функцией \n r(t) = basisCurve(t) + (Offset0(t) * normal(t)), где normal(t) - нормаль базовой кривой. \n Базовой кривой для эквидистантной кривой не может служить другая эквидистантная кривая. В подобной ситуации выполняется переход к первичной базовой кривой. \en Offset extended curve is constructed by shifting points of the base curve along a normal to it. \n The "offsetTmin, offsetTmax" parameters set shift of base curve on begin and end points. - Radius-vector of the curve in the method PointOn(double&t,MbCartPoint3D&r) is described by the function \n + Radius-vector of the curve in the method PointOn(double&t,MbCartPoint3D&r) is described by the function \n r(t) = basisCurve(t) + (Offset0(t) * normal(t)), where normal(t) - normal of base curve. \n Base curve for offset curve can not be other offset curve. In such situation it changes to the initial base curve. \~ @@ -106,7 +106,7 @@ public : 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 bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. + 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 /** \} */ @@ -191,7 +191,7 @@ public : \en \name Common function of curve. \{ */ virtual bool IsStraight() const; // \ru Является ли линия прямолинейной \en Whether the line is straight - virtual MbCurve * Offset( double rad ) const; // \ru Смещение смещенной кривой \en Offset of the offset curve + 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 Refresh(); // \ru Сбросить все временные данные \en Reset all temporary data virtual void PrepareIntegralData( const bool forced ) const; // \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. @@ -238,7 +238,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); void SetBasisCurve( MbCurve & ); // \ru Установить базовую кривую \en Set the base curve // \ru Тип смещения точек. \en The type of points offset. @@ -246,20 +247,29 @@ public : // \ru Постоянное ли смещение точек? \en Is const the offset type? bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } // \ru Величина смещения. \en The offset distance. - double GetDistance( size_t i = 0 ) const { - if ( i == 1 ) return offsetTmax; - return offsetTmin; + double GetDistance( size_t i ) const { + i = i % 2; + if ( i == 0 ) + return offsetTmin; + return offsetTmax; } + // \ru Средняя величина смещения. \en The average offset distance. + double GetDistance() const { return ( offsetTmin + offsetTmax ) / 2; } /** \brief \ru Установить величины смещения. \en Set offset distances. \~ \param[in] d - \ru Новая величина смещения - \en New offset distance \~ + \en New offset distance. \~ */ - void SetDistance( double d, size_t i = 0 ); + void SetDistance( double d, size_t i ); + // \ru Установить постоянную величину смещения. Set new constant offset distance. + void SetDistance( double d ); - const MbRect & GetGabarit() const { if ( rect.IsEmpty() ) CalculateGabarit( rect ); return rect; } - void SetDirtyGabarit() const { rect.SetEmpty(); } + virtual void CalculateGabarit( MbRect & ) const; // \ru Определить габаритный прямоугольник кривой. \en Detect the bounding box of a curve. + virtual double CalculateMetricLength() const; // \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. + + const MbRect & GetGabarit() const; + void SetDirtyGabarit() const; const double & GetDmin() const { return deltaTmin; } // \ru Дать расширение начала \en Get extension of start const double & GetDmax() const { return deltaTmax; } // \ru Дать расширение конца \en Get extension of end void SetDmin( double d ) { deltaTmin = d; } // \ru Установить расширение начала \en Set extension of start diff --git a/C3d/Include/cur_offset_curve3d.h b/C3d/Include/cur_offset_curve3d.h index f86fdf3..559d18a 100644 --- a/C3d/Include/cur_offset_curve3d.h +++ b/C3d/Include/cur_offset_curve3d.h @@ -1,214 +1,221 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Эквидистантная кривая в трехмерном пространстве. - \en Offset curve in three-dimensional space. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __CUR_OFFSET_CURVE3D_H -#define __CUR_OFFSET_CURVE3D_H - - -#include -#include -#include - - -class MATH_CLASS MbSpine; - - -//------------------------------------------------------------------------------ -/** \brief \ru Эквидистантная кривая в трехмерном пространстве. - \en Offset curve in three-dimensional space. \~ - \details \ru Эквидистантная кривая строится смещением точек базовой кривой вдоль некоторого вектора, - направление которого может меняться вдоль кривой. \n - Вектор offset задаёт смещение начальной точки базовой криаой. - В процессе движения вдоль кривой вектор offset сохраняет своё положение в движущейся локальной системе координат, - начало которой совпадает с текущей точкой базовой кривой. - Одна из осей движущейся локальной системы координат всегда совпадает с касательной базовой кривой, - а две другие оси ортогональны ей. - Базовой кривой для эквидистантной кривой не может служить другая эквидистантная кривая. - В подобной ситуации выполняется переход к первичной базовой кривой. - \en Offset curve is constructed by shifting points of the base curve along some vector, - direction of which can be changed along the curve. \n - Vector "offset" sets the offset of start point of the base curve. - While moving along a curve the vector "offset" keeps the position in the moving local coordinate system, - origin coincides with the current point of the base curve. - One of the axes of the moving local coordinate system is always the same as the tangent of the base curve, - and the other two axes are orthogonal to it. - Base curve for offset curve can not be other offset curve. - In this situation it changes to the initial base curve. \~ - \ingroup Curves_3D -*/ -// --- -class MATH_CLASS MbOffsetCurve3D : public MbCurve3D { -protected : - MbSpine * basisCurve; ///< \ru Базовая кривая. \en The base curve. - 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. - MbVector3D offset; ///< \ru Смещение в начальной точке. \en Offset in start point. - double factorTmin; ///< \ru Множитель смещения offset в точке tmin базовой кривой. \en The offset multiplier in point tmin of base curve. - double factorTmax; ///< \ru Множитель смещения offset в точке tmax базовой кривой. \en The offset multiplier in point tmax of base curve. - MbeOffsetType type; ///< \ru Тип смещения: константный, линейный или кубический. \en The type of offset: constant, or linear, or cubic. - double deltaTmin; ///< \ru Увеличение tmin параметра базовой кривой. \en Increase of tmin of base curve parameter. - double deltaTmax; ///< \ru Увеличение tmax параметра базовой кривой. \en Increase of tmax of base curve parameter. - mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. - -public : - /** \brief \ru Конструктор. - \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). \~ - */ - MbOffsetCurve3D( const MbCurve3D & c, const MbVector3D & off, bool same, bool ort, VERSION version = Math::DefaultMathVersion() ); -private : - MbOffsetCurve3D( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. -protected: - MbOffsetCurve3D( const MbOffsetCurve3D & init, MbRegDuplicate * ireg ); - -public : - virtual ~MbOffsetCurve3D(); - -public: - VISITING_CLASS( MbOffsetCurve3D ); - - /** \brief \ru Инициализация по смещению и приращениям параметров. - \en Initialization by offset and increments of parameters. \~ - \details \ru Смещение задано на краях параметрической области базовой кривой и может изменяться по константному, линейному и кубическому законам.\n - Приращение параметров нужно использовать для изменения области определения кривой относительно базовой кривой. - \en The offset displacement is defined in the begin and the end of the parametric region of the base curve and can be changed by constant, linear and cubic laws.\n - Increment of parameters needs to be used for change of curve domain relative to base curve. \~ - \param[in] d1 - \ru Смещение в точке Tmin базовой кривой. - \en Offset distance on point Tmin of base curve. \~ - \param[in] d2 - \ru Смещение в точке Tmax базовой кривой. - \en Offset distance on point Tmax of base curve. \~ - \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. - \en The offset type: constant, or linear, or cubic. \~ - \param[in] dt1 - \ru Изменение tmin параметра - \en The change of tmin parameter \~ - \param[in] dt2 - \ru Изменение tmax параметра - \en The change of tmax parameter \~ - */ - void Init( double d1, double d2, MbeOffsetType t, double dt1, double dt2 ); - - // \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 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 - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix - virtual void Move ( const MbVector3D &, MbRegTransform * ireg ); // \ru Сдвиг \en Translation - virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg ); // \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. - virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб \en Add bounding box into a cube - - 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. - - // \ru Общие функции кривой \en Common functions of curve - - virtual double GetTMin() const; - virtual double GetTMax() const; - virtual bool IsClosed() const; // \ru Замкнутость кривой \en A curve closedness - virtual double GetPeriod() const; // \ru Период кривой \en Curve period - // \ru Функции кривой для работы в области определения параметрической кривой \en Functions of curve for working at parametric curve domain - virtual void PointOn ( double & t, MbCartPoint3D & p ) const; // \ru Точка на кривой \en Point on curve - virtual void FirstDer ( double & t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative - virtual void SecondDer( double & t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative - virtual void ThirdDer ( double & t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to t - - // \ru ЗАКОМЕНТАРЕНО в связи с необходимостью использовать строгое продолжение по касательной \en COMMENTED because it is necessary to use a strong extension by the tangent - //virtual void _PointOn ( double t, MbCartPoint3D &p ) const; // \ru Точка на расширенной кривой \en Point on the extended curve - //virtual void _FirstDer ( double t, MbVector3D &fd ) const; // \ru Первая производная \en The first derivative - //virtual void _SecondDer( double t, MbVector3D &sd ) const; // \ru Вторая производная \en The second derivative - //virtual void _ThirdDer ( double t, MbVector3D &td ) const; // \ru Третья производная по t \en The third derivative with respect to 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 double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculation of approximation step - virtual double DeviationStep( double t, double angle ) const; - - 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 size_t GetCount() const; - virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier - virtual bool IsStraight() const; // \ru Является ли линия прямолинейной \en Whether the line is straight - 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 IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; // \ru Непрерывна ли первая производная? \en Have the first derivative the continuous? - virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. - - /// \ru Смещение в начальной точке. \en Offset in the start point. - const MbVector3D & GetOffsetVector() const { return offset; } - // \ru Тип смещения точек. \en The type of points offset. - MbeOffsetType GetOffsetType() const { return type; } - // \ru Постоянное ли смещение точек? \en Is const the offset type? - bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } - // \ru Множитель смещения. \en The offset multiplier. - double GetFactor( size_t i = 0 ) const { - if ( i == 1 ) return factorTmax; - return factorTmin; - } - - /** \brief \ru Установить множитель смещения. \en Set offset multiplier. \~ - \param[in] d - \ru Новый множитель смещения. \en New offset multiplier. \~ - */ - void SetFactor( double d, size_t i = 0 ); - // \ru Проверить факторы и тип. \en Check factors and typr. - void CheckFactor(); - - const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } // \ru Выдать габарит кривой \en Get the bounding box of curve - bool IsSelfIntersect() const; - /** \brief \ru Поиск точек излома оффсетной кривой. - \en Search of break points of the offset curve. \~ - \details \ru Для нахождения точек точек излома используется характеристическая функция Ratio(), - представляющая собой разность аналитически и численно посчитанной производной деленную - на модуль аналитической производной и величину шага, использованного для численного рассчета производной. - Увеличение этой функции на порядок по сравнению с ее значением в гладкой области означает точку излома. \n - \en To find the break points using the characteristic function Ratio(), - which represents a difference between the analytical and numerical calculated derivative divided - by module of analytical derivative and step used for numerical calculation of the derivative. - Increase of this function on the order in comparison with its value in smooth region is a break point. \n \~ - \param[out] breakParams - \ru Массив параметров точек излома - \en Parameter array of break points \~ - */ - void FindBreakParams( SArray & breakParams ) const; - int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range - -private: - // \ru Вычисление множителя смещения и его производных. \en The offset multiplier and it derivatives. - double Factor0 ( double t ) const; - double FactorT ( double t ) const; - double FactorTT ( double t ) const; - double FactorTTT( double t ) const; - - void operator = ( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurve3D ) -}; - -IMPL_PERSISTENT_OPS( MbOffsetCurve3D ) - - -#endif // __CUR_OFFSET_CURVE3D_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Эквидистантная кривая в трехмерном пространстве. + \en Offset curve in three-dimensional space. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __CUR_OFFSET_CURVE3D_H +#define __CUR_OFFSET_CURVE3D_H + + +#include +#include +#include + + +class MATH_CLASS MbSpine; + + +//------------------------------------------------------------------------------ +/** \brief \ru Эквидистантная кривая в трехмерном пространстве. + \en Offset curve in three-dimensional space. \~ + \details \ru Эквидистантная кривая строится смещением точек базовой кривой вдоль некоторого вектора, + направление которого может меняться вдоль кривой. \n + Вектор offset задаёт смещение начальной точки базовой криаой. + В процессе движения вдоль кривой вектор offset сохраняет своё положение в движущейся локальной системе координат, + начало которой совпадает с текущей точкой базовой кривой. + Одна из осей движущейся локальной системы координат всегда совпадает с касательной базовой кривой, + а две другие оси ортогональны ей. + Базовой кривой для эквидистантной кривой не может служить другая эквидистантная кривая. + В подобной ситуации выполняется переход к первичной базовой кривой. + \en Offset curve is constructed by shifting points of the base curve along some vector, + direction of which can be changed along the curve. \n + Vector "offset" sets the offset of start point of the base curve. + While moving along a curve the vector "offset" keeps the position in the moving local coordinate system, + origin coincides with the current point of the base curve. + One of the axes of the moving local coordinate system is always the same as the tangent of the base curve, + and the other two axes are orthogonal to it. + Base curve for offset curve can not be other offset curve. + In this situation it changes to the initial base curve. \~ + \ingroup Curves_3D +*/ +// --- +class MATH_CLASS MbOffsetCurve3D : public MbCurve3D { +protected : + MbSpine * basisCurve; ///< \ru Базовая кривая. \en The base curve. + 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. + MbVector3D offset; ///< \ru Смещение в начальной точке. \en Offset in start point. + double factorTmin; ///< \ru Множитель смещения offset в точке tmin базовой кривой. \en The offset multiplier in point tmin of base curve. + double factorTmax; ///< \ru Множитель смещения offset в точке tmax базовой кривой. \en The offset multiplier in point tmax of base curve. + MbeOffsetType type; ///< \ru Тип смещения: константный, линейный или кубический. \en The type of offset: constant, or linear, or cubic. + double deltaTmin; ///< \ru Увеличение tmin параметра базовой кривой. \en Increase of tmin of base curve parameter. + double deltaTmax; ///< \ru Увеличение tmax параметра базовой кривой. \en Increase of tmax of base curve parameter. + mutable MbCube cube; ///< \ru Габаритный куб. \en Bounding box. + +public : + /** \brief \ru Конструктор. + \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). \~ + */ + MbOffsetCurve3D( const MbCurve3D & c, const MbVector3D & off, bool same, bool ort, VERSION version = Math::DefaultMathVersion() ); +private : + MbOffsetCurve3D( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. +protected: + MbOffsetCurve3D( const MbOffsetCurve3D & init, MbRegDuplicate * ireg ); + +public : + virtual ~MbOffsetCurve3D(); + +public: + VISITING_CLASS( MbOffsetCurve3D ); + + /** \brief \ru Инициализация по смещению и приращениям параметров. + \en Initialization by offset and increments of parameters. \~ + \details \ru Смещение задано на краях параметрической области базовой кривой и может изменяться по константному, линейному и кубическому законам.\n + Приращение параметров нужно использовать для изменения области определения кривой относительно базовой кривой. + \en The offset displacement is defined in the begin and the end of the parametric region of the base curve and can be changed by constant, linear and cubic laws.\n + Increment of parameters needs to be used for change of curve domain relative to base curve. \~ + \param[in] d1 - \ru Смещение в точке Tmin базовой кривой. + \en Offset distance on point Tmin of base curve. \~ + \param[in] d2 - \ru Смещение в точке Tmax базовой кривой. + \en Offset distance on point Tmax of base curve. \~ + \param[in] t - \ru Тип смещения точек: константный, линейный или кубический. + \en The offset type: constant, or linear, or cubic. \~ + \param[in] dt1 - \ru Изменение tmin параметра + \en The change of tmin parameter \~ + \param[in] dt2 - \ru Изменение tmax параметра + \en The change of tmax parameter \~ + */ + void Init( double d1, double d2, MbeOffsetType t, double dt1, double dt2 ); + + // \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 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 + virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg ); // \ru Преобразовать элемент согласно матрице \en Transform element according to the matrix + virtual void Move ( const MbVector3D &, MbRegTransform * ireg ); // \ru Сдвиг \en Translation + virtual void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg ); // \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. + virtual void AddYourGabaritTo( MbCube & ) const; // \ru Добавь свой габарит в куб \en Add bounding box into a cube + + 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. + + // \ru Общие функции кривой \en Common functions of curve + + virtual double GetTMin() const; + virtual double GetTMax() const; + virtual bool IsClosed() const; // \ru Замкнутость кривой \en A curve closedness + virtual double GetPeriod() const; // \ru Период кривой \en Curve period + // \ru Функции кривой для работы в области определения параметрической кривой \en Functions of curve for working at parametric curve domain + virtual void PointOn ( double & t, MbCartPoint3D & p ) const; // \ru Точка на кривой \en Point on curve + virtual void FirstDer ( double & t, MbVector3D & fd ) const; // \ru Первая производная \en First derivative + virtual void SecondDer( double & t, MbVector3D & sd ) const; // \ru Вторая производная \en Second derivative + virtual void ThirdDer ( double & t, MbVector3D & td ) const; // \ru Третья производная по t \en Third derivative with respect to t + + // \ru ЗАКОМЕНТАРЕНО в связи с необходимостью использовать строгое продолжение по касательной \en COMMENTED because it is necessary to use a strong extension by the tangent + //virtual void _PointOn ( double t, MbCartPoint3D &p ) const; // \ru Точка на расширенной кривой \en Point on the extended curve + //virtual void _FirstDer ( double t, MbVector3D &fd ) const; // \ru Первая производная \en The first derivative + //virtual void _SecondDer( double t, MbVector3D &sd ) const; // \ru Вторая производная \en The second derivative + //virtual void _ThirdDer ( double t, MbVector3D &td ) const; // \ru Третья производная по t \en The third derivative with respect to 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 double Step( double t, double sag ) const; // \ru Вычисление шага аппроксимации \en Calculation of approximation step + virtual double DeviationStep( double t, double angle ) const; + + 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 size_t GetCount() const; + virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier + virtual bool IsStraight() const; // \ru Является ли линия прямолинейной \en Whether the line is straight + 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 IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = 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 ); + + /// \ru Смещение в начальной точке. \en Offset in the start point. + const MbVector3D & GetOffsetVector() const { return offset; } + // \ru Тип смещения точек. \en The type of points offset. + MbeOffsetType GetOffsetType() const { return type; } + // \ru Постоянное ли смещение точек? \en Is const the offset type? + bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } + // \ru Множитель смещения. \en The offset multiplier. + double GetFactor( size_t i ) const { + i = i % 2; + if ( i == 0 ) + return factorTmin; + return factorTmax; + } + // \ru Средний множитель смещения. \en The average offset multiplier. + double GetFactor() const { return ( factorTmin + factorTmax ) / 2; } + + /** \brief \ru Установить множитель смещения. \en Set offset multiplier. \~ + \param[in] d - \ru Новый множитель смещения. \en New offset multiplier. \~ + */ + void SetFactor( double d, size_t i ); + // \ru Установить постоянный множитель смещения. Set new constant offset multiplier. + void SetFactor( double d ); + // \ru Проверить факторы и тип. \en Check factors and typr. + void CheckFactor(); + + const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get the bounding box of curve + bool IsSelfIntersect() const; + /** \brief \ru Поиск точек излома оффсетной кривой. + \en Search of break points of the offset curve. \~ + \details \ru Для нахождения точек точек излома используется характеристическая функция Ratio(), + представляющая собой разность аналитически и численно посчитанной производной деленную + на модуль аналитической производной и величину шага, использованного для численного рассчета производной. + Увеличение этой функции на порядок по сравнению с ее значением в гладкой области означает точку излома. \n + \en To find the break points using the characteristic function Ratio(), + which represents a difference between the analytical and numerical calculated derivative divided + by module of analytical derivative and step used for numerical calculation of the derivative. + Increase of this function on the order in comparison with its value in smooth region is a break point. \n \~ + \param[out] breakParams - \ru Массив параметров точек излома + \en Parameter array of break points \~ + */ + void FindBreakParams( SArray & breakParams ) const; + int ExtendedParam( double &t ) const; // \ru Проверка, лежит ли параметр в пределах \en Check if parameter is in range + +private: + // \ru Вычисление множителя смещения и его производных. \en The offset multiplier and it derivatives. + double Factor0 ( double t ) const; + double FactorT ( double t ) const; + double FactorTT ( double t ) const; + double FactorTTT( double t ) const; + + void operator = ( const MbOffsetCurve3D & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbOffsetCurve3D ) +}; + +IMPL_PERSISTENT_OPS( MbOffsetCurve3D ) + + +#endif // __CUR_OFFSET_CURVE3D_H diff --git a/C3d/Include/cur_plane_curve.h b/C3d/Include/cur_plane_curve.h index 30c34cc..298a424 100644 --- a/C3d/Include/cur_plane_curve.h +++ b/C3d/Include/cur_plane_curve.h @@ -151,7 +151,8 @@ public : MbCurve * MakeCurve( const MbPlacement3D & ) const; MbCurve3D * MakeCurve() const; // \ru Дать пространственную кривую \en Get the spatial curve - void SetCurve( const MbCurve & ); // \ru Заменить плоскую кривую \en Replace the plane curve + void SetCurve( const MbCurve & ); // \ru Заменить плоскую кривую \en Replace the plane curve + bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра. \en Set range of parameter. void SetOrigin( const MbCartPoint3D & org ) { position.SetOrigin(org); } const MbPlacement3D & GetPlacement() const { return position; } @@ -163,7 +164,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); private: void operator = ( const MbPlaneCurve & ); // \ru Не реализовано. \en Not implemented. diff --git a/C3d/Include/cur_point_curve.h b/C3d/Include/cur_point_curve.h index f306747..802c30f 100644 --- a/C3d/Include/cur_point_curve.h +++ b/C3d/Include/cur_point_curve.h @@ -72,7 +72,7 @@ public : 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 - 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 IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Является ли кривая curve копией данной кривой ? \en Whether the 'curve' curve is duplicate of current curve. virtual bool IsVisibleInRect( const MbRect & r, bool exact = false ) const; // \ru Виден ли объект в заданном прямоугольнике \en Whether the object is visible in the given rectangle /** \} */ diff --git a/C3d/Include/cur_polycurve.h b/C3d/Include/cur_polycurve.h index 7c51bab..8ea51df 100644 --- a/C3d/Include/cur_polycurve.h +++ b/C3d/Include/cur_polycurve.h @@ -13,6 +13,7 @@ #include #include +#include class MbRegDuplicate; @@ -29,7 +30,7 @@ class MbRegTransform; \ingroup Curves_2D */ // --- -class MATH_CLASS MbPolyCurve : public MbCurve, public MbNestSyncItem { +class MATH_CLASS MbPolyCurve : public MbCurve { protected : SArray pointList; ///< \ru Множество контрольных точек. \en Set of control points. ptrdiff_t uppIndex; ///< \ru Количество участков кривой (равно количество контрольных точек минус единица). \en Count of curve pieces (is equal to count of control points minus one). @@ -52,7 +53,7 @@ public : virtual MbePlaneType IsA() const = 0; // \ru Тип элемента \en Type of element 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 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 @@ -115,7 +116,7 @@ public : /** \ru \name Общие функции полигональной кривой \en \name Common functions of polygonal curve \{ */ - virtual size_t GetPointsCount() const; ///< \ru Выдать количество контрольных точек. \en Get count of control points. + virtual size_t GetPointsCount() const; ///< \ru Выдать количество контрольных точек. \en Get count of control points. /** \brief \ru Выдать характерную точку. \en Get control point. \~ @@ -132,7 +133,7 @@ public : */ virtual void GetPoint( ptrdiff_t index, MbCartPoint & pnt ) const; // \ru Выдать точку \en Get point - virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get index of the point nearest to the given one. + virtual ptrdiff_t GetNearPointIndex( const MbCartPoint & pnt ) const; ///< \ru Выдать индекс точки, ближайшей к заданной. \en Get index of the point nearest to the given one. /** \brief \ru Вернуть интервал влияния точки кривой. \en Get the range of influence of point of the curve. \~ @@ -301,6 +302,7 @@ public : 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. 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. const MbCartPoint & GetPointList( size_t i ) const { return pointList[i]; } ///< \ru Вернуть характерную точку с заданным индексом. \en Get control point with the given index. MbCartPoint & SetPointList( size_t i ) { Refresh(); return pointList[i]; } ///< \ru Вернуть характерную точку с заданным индексом. \en Get control point with the given index. diff --git a/C3d/Include/cur_polycurve3d.h b/C3d/Include/cur_polycurve3d.h index d068a46..a5bdf62 100644 --- a/C3d/Include/cur_polycurve3d.h +++ b/C3d/Include/cur_polycurve3d.h @@ -25,7 +25,7 @@ \ingroup Curves_3D */ // --- -class MATH_CLASS MbPolyCurve3D : public MbCurve3D, public MbNestSyncItem { +class MATH_CLASS MbPolyCurve3D : public MbCurve3D { protected : ptrdiff_t uppIndex; ///< \ru Количество участков кривой (равно количество контрольных точек минус единица). \en Count of curve pieces (is equal to count of control points minus one). SArray pointList; ///< \ru Множество контрольных точек. \en Set of control points. @@ -115,7 +115,7 @@ public : ptrdiff_t & endPointNumber, // \ru Номер последней точки \en Index of the last point ptrdiff_t & period ) const; // \ru Количество точек в периоде \en Count of points in period - const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } // \ru Выдать габарит кривой \en Get bounding box of curve + const MbCube & GetGabarit() const; // \ru Выдать габарит кривой \en Get bounding box of curve size_t GetPointListCount() const { return pointList.Count(); } ptrdiff_t GetPointListMaxIndex() const { return pointList.MaxIndex(); } diff --git a/C3d/Include/cur_polyline.h b/C3d/Include/cur_polyline.h index fc3b585..c28e5cd 100644 --- a/C3d/Include/cur_polyline.h +++ b/C3d/Include/cur_polyline.h @@ -86,7 +86,7 @@ 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 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 @@ -176,11 +176,11 @@ public : /** \ru \name Общие функции кривой \en \name Common functions of curve \{ */ - virtual MbCurve * Offset( double rad ) const; // \ru Смещение полилинии \en Shift of polyline + virtual MbCurve * Offset( double rad ) const; // \ru Смещение полилинии \en Shift of polyline virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve * NurbsCurve( const MbNurbsParameters & ) const; - virtual MbContour * NurbsContour() const; + virtual MbContour * NurbsContour() const; virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; @@ -252,7 +252,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); 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/cur_polyline3d.h b/C3d/Include/cur_polyline3d.h index 0100dd0..6c4fba2 100644 --- a/C3d/Include/cur_polyline3d.h +++ b/C3d/Include/cur_polyline3d.h @@ -168,7 +168,8 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); bool UnClamped( bool ); void DeleteEqPoints( double absEps ); // \ru Удалить одинаковые точки \en Remove equal points diff --git a/C3d/Include/cur_projection_curve.h b/C3d/Include/cur_projection_curve.h index 4a1a994..a49155c 100644 --- a/C3d/Include/cur_projection_curve.h +++ b/C3d/Include/cur_projection_curve.h @@ -211,6 +211,8 @@ public : virtual double GetLengthEvaluation() const; // \ru Оценка метрической длины кривой. \en Estimation of metric length of the curve. // \ru Вычислить метрическую длину кривой от параметра t1 до t2. \en Calculate the metric length of unclosed curve from parameter t1 to parameter t2. virtual double CalculateLength( double t1, double t2 ) const; + /// \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. + virtual double CalculateMetricLength() const; virtual bool GetMiddlePoint( MbCartPoint & ) const; // \ru Вычислить среднюю точку кривой. \en Calculate mid-point of curve. diff --git a/C3d/Include/cur_reparam_curve.h b/C3d/Include/cur_reparam_curve.h index af0579a..7d93efb 100644 --- a/C3d/Include/cur_reparam_curve.h +++ b/C3d/Include/cur_reparam_curve.h @@ -16,6 +16,7 @@ class MbRegDuplicate; class MbRegTransform; +class MbFunction; //------------------------------------------------------------------------------ @@ -40,25 +41,23 @@ class MbRegTransform; // --- class MATH_CLASS MbReparamCurve : public MbCurve { enum MbeReparamType { - rt_Linear, ///< \ru Линейная репараметризация. \en Linear reparametrization. - rt_Quadratic, ///< \ru Квадратичная репараметризация. \en Quadratic reparametrization. - rt_Cubic ///< \ru Кубическая репараметризация. \en Quadratic reparametrization. + rt_Linear, ///< \ru Линейная репараметризация. \en Linear reparametrization. + rt_Quadratic, ///< \ru Квадратичная репараметризация. \en Quadratic reparametrization. + rt_ScaledEndDers ///< \ru Репараметризация с заданными масштабами производной на концах. \en Reparametrization with a given scale of the derivative at the ends. }; protected : - MbCurve * basisCurve; ///< \ru Базовая кривая. \en The base curve. - MbeReparamType reparamType; ///< \ru Способ репараметризации. \en Way of repatametrization. - double tmin; ///< \ru Начальный параметр. \en Start parameter. - double tmax; ///< \ru Конечный параметр. \en End parameter. - double q; ///< \ru Коэффициент при кубическом члене репараметризующего многочлена. \en The coefficient of the cubic term of the reparametrizing polynomial. - double a; ///< \ru Коэффициент при квадратичном члене репараметризующего многочлена. \en The coefficient of the quadratic term of the reparametrizing polynomial. - double b; ///< \ru Коэффициент при линейном члене репараметризующего многочлена. \en The coefficient of the linear term of the reparametrizing polynomial. - double c; ///< \ru Свободный коэффициент репараметризующего многочлена. \en The free coefficient of the reparametrizing polynomial. + MbCurve * basisCurve; ///< \ru Базовая кривая. \en The base curve. + MbeReparamType reparamType; ///< \ru Способ репараметризации. \en Way of repatametrization. + SPtr rFunc; ///< \ru Репараметризующая функция, всегда не нулевая. \en Reparametric function, always non-zero. public : + /// \ru Конструктор по кривой и новым параметрам. \en Constructor by curve and by new parametric limits. MbReparamCurve( const MbCurve &, double t1, double t2 ); + /// \ru Конструктор по кривой и новым параметрам. \en Constructor by curve and by new parametric limits. MbReparamCurve( const MbCurve &, const double t1, const double t2, const double begFirstDerValue ); - MbReparamCurve( const MbCurve &, double t1, double t2, double derBeg, double derEnd ); + /// \ru Конструктор по кривой и производным параметра на ее концах. \en Constructor for the curve and derivatives of the parameter at its ends + MbReparamCurve( double dt1, double dt2, const MbCurve & curve ); protected: MbReparamCurve( const MbReparamCurve & ); public : @@ -67,28 +66,31 @@ public : public : VISITING_CLASS( MbReparamCurve ); + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. void Init( double t1, double t2 ); + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. void Init( double t1, double t2, double begFirstDerValue ); - void Init( double t1, double t2, double der1, double der2 ); + /// \ru Установить параметрическую область кривой. \en Set curve parametric range. + void InitScaledEnds( double scaleDer1, double scaleDer2 ); /** \ru \name Общие функции геометрического объекта. \en \name Common functions of a geometric object. \{ */ 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 & 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 bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; - virtual MbCurve * Offset( double rad ) const; // \ru Смещение усеченной кривой \en Shift of a trimmed curve + 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 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 MbCurve * Trimmed( double t1, double t2, int sense ) const; - virtual MbContour * NurbsContour() const; // \ru Построить контур \en Create a contour - virtual void AddYourGabaritTo( MbRect & r ) const; // \ru Добавь свой габарит в прямой прям-к \en Add your own gabarit into the given bounding rectangle - virtual void CalculateGabarit( MbRect & r ) const; // \ru Определить габариты кривой \en Determine the bounding box of a curve - virtual bool IsVisibleInRect( const MbRect & r, bool exact = false ) const; // \ru Виден ли объект в заданном прямоугольнике \en Whether the object is visible in the given rectangle + 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 + virtual void CalculateGabarit( MbRect & ) const; // \ru Определить габариты кривой \en Determine the bounding box of a curve + virtual bool IsVisibleInRect( const MbRect &, bool exact = false ) const; // \ru Виден ли объект в заданном прямоугольнике \en Whether the object is visible in the given rectangle using MbCurve::IsVisibleInRect; /** \} */ @@ -207,7 +209,7 @@ public : virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, VERSION version = Math::DefaultMathVersion() ) const; // \ru Сдвинуть параметр t на расстояние len по направлению \en Translate parameter 't' by distance 'len' along the direction - virtual bool GetAxisPoint( MbCartPoint & p ) const; // \ru Точка для построения оси \en Point for the axis construction + virtual bool GetAxisPoint( MbCartPoint & ) 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 size_t GetCount() const; // \ru Количество разбиений для прохода в операциях \en Count of subdivisions for pass in operations /// \ru Получить границы участков кривой, на которых сохраняется непрерывность кривизны. @@ -225,13 +227,13 @@ public : virtual const MbCurve & GetBasisCurve() const; virtual MbCurve & SetBasisCurve(); - void SetBasisCurve( MbCurve & ); // \ru Заменить плоскую кривую \en Replace the planar curve - double Tmin() const { return tmin; } // \ru Начальный параметр \en Start parameter - double Tmax() const { return tmax; } // \ru Конечный параметр \en End parameter - double Dt() const { return b; } // \ru Производная параметра кривой basisCurve по параметру \en Derivative of parameter of 'basisCurve' curve by parameter - void SetTmin( double t ); - void SetTmax( double t ); - void SetDt ( double d ); + bool SetBasisCurve( const MbCurve &, const MbRect1D * tRange = 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. + bool SetTmin( double t ); + bool SetTmax( double t ); + bool SetDt ( double d ); MbeReparamType GetReparamType() const { return reparamType; } // \ru Тип параметризации. \en Parameterization type. @@ -242,13 +244,14 @@ 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 - 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 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? @@ -256,117 +259,14 @@ public : private: void operator = ( const MbReparamCurve & ); // \ru Не реализовано. \en Not implemented. - double CubicRoot( double t ) const; // \ru Решение кубического уравнения. \en Solution of cubic equation. - void Explore( double t, double * par, double * dpar, double * ddpar, double * dddpar ) const; // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. + // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. + void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReparamCurve ) }; // MbReparamCurve IMPL_PERSISTENT_OPS( MbReparamCurve ) -//------------------------------------------------------------------------------ -// \ru Перевод параметра базовой кривой в новый параметр \en Transformation of the base curve parameter to a new parameter -// --- -inline void MbReparamCurve::ParameterInto( double & t ) const { - if ( reparamType == rt_Linear ) - t = ( t - c ) / b; - else if ( reparamType == rt_Quadratic ) { - C3D_ASSERT( ::fabs(a) > NULL_EPSILON ); - const double discriminant = b * b + 4.0 * a * (t - c); - if ( discriminant > EXTENT_EQUAL ) - t = 0.5 * ( ::sqrt(discriminant) - b ) / a; - else - t = -0.5 * b / a; - } - else if( reparamType == rt_Cubic ) { - bool close = basisCurve->IsClosed(); - double bTmin = basisCurve->GetTMin(), bTmax = basisCurve->GetTMax(); - if ( !close && ( t < bTmin || t > bTmax ) ) { - double t0 = ( t < bTmin ) ? tmin : tmax; - double par = ( t < bTmin ) ? bTmin : bTmax; - double dpar = 3.0 * q * t0 * t0 + 2.0 * a * t0 + b; - t = t0 + ( t - par ) / dpar; - } - else { - double n = 0.0; - if ( close ) { - double period = bTmax - bTmin; - n = ::floor( (t - bTmin) / period ); - t -= n * period; - } - t = CubicRoot( t ); - if( n != 0.0 ) - t += n * ( tmax - tmin ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Перевод нового параметра в параметр базовой кривой \en Transformation of a new parameter to the base curve parameter -// --- -inline void MbReparamCurve::ParameterFrom( double & t ) const { - if ( reparamType == rt_Linear ) - t = b * t + c; - else if ( reparamType == rt_Quadratic ) - t = a * t * t + b * t + c; - else if ( reparamType == rt_Cubic ) - Explore( t, &t, 0, 0, 0 ); -} - - -//------------------------------------------------------------------------------ -// \ru Перевод точности параметра базовой кривой в точность локального параметра \en Transformation of the base curve parameter tolerance to a local parameter tolerance -// --- -inline double MbReparamCurve::EpsilonInto( double eps ) const { - double res = 0.0; - - if ( reparamType == rt_Linear ) { - if ( ::fabs(b) > Math::paramEpsilon ) - res = eps / b; - } - else if ( reparamType == rt_Quadratic ) { - const double bmin = 2.0 * a * tmin + b; - const double bmax = 2.0 * a * tmax + b; - const double div = std_max( bmin, bmax ); - if ( ::fabs(div) > Math::paramEpsilon ) - res = eps / div; - } - else if ( reparamType == rt_Cubic ) { - const double bmin = 3.0 * q * tmin * tmin + 2.0 * a * tmin + b; - const double bmax = 3.0 * q * tmax * tmax + 2.0 * a * tmax + b; - const double div = std_max( bmin, bmax ); - if ( ::fabs( div ) > Math::paramEpsilon ) - res = eps / div; - } - - return res; -} - - -//------------------------------------------------------------------------------ -// \ru Перевод точности локального параметра в точность параметра базовой кривой \en Transformation of a local parameter tolerance to the base curve parameter tolerance -// --- -inline double MbReparamCurve::EpsilonFrom( double eps ) const { - double res = 0.0; - - if ( reparamType == rt_Linear ) - return eps * b; - else if ( reparamType == rt_Quadratic ) { - const double bmin = 2.0 * a * tmin + b; - const double bmax = 2.0 * a * tmax + b; - const double mul = std_min( bmin, bmax ); - res = eps * mul; - } - else if ( reparamType == rt_Cubic ) { - const double bmin = 3.0 * q * tmin * tmin + 2.0 * a * tmin + b; - const double bmax = 3.0 * q * tmax * tmax + 2.0 * a * tmax + b; - const double mul = std_min( bmin, bmax ); - res = eps * mul; - } - - return res; -} #endif // __CUR_REPARAM_CURVE_H diff --git a/C3d/Include/cur_reparam_curve3d.h b/C3d/Include/cur_reparam_curve3d.h index f8d8e1c..caccd3c 100644 --- a/C3d/Include/cur_reparam_curve3d.h +++ b/C3d/Include/cur_reparam_curve3d.h @@ -13,6 +13,7 @@ #include +class MbFunction; //------------------------------------------------------------------------------ /** \brief \ru Репараметризованная кривая в трехмерном пространстве. @@ -40,29 +41,27 @@ // --- class MATH_CLASS MbReparamCurve3D : public MbCurve3D { enum MbeReparamType { - rt_Linear, ///< \ru Линейная репараметризация. \en Linear reparametrization. - rt_Quadratic, ///< \ru Квадратичная репараметризация. \en Quadratic reparametrization. - rt_Cubic ///< \ru Кубическая репараметризация. \en Quadratic reparametrization. + rt_Linear, ///< \ru Линейная репараметризация. \en Linear reparametrization. + rt_Quadratic, ///< \ru Квадратичная репараметризация. \en Quadratic reparametrization. + rt_ScaledEndDers ///< \ru Репараметризация с заданными масштабами производной на концах. \en Reparametrization with a given scale of the derivative at the ends. }; protected: - MbCurve3D * basisCurve; ///< \ru Базовая кривая. \en The base curve. - MbeReparamType reparamType; ///< \ru Способ репараметризации. \en Way of repatametrization. - double tmin; ///< \ru Начальный параметр. \en Start parameter. - double tmax; ///< \ru Конечный параметр. \en End parameter. - double q; ///< \ru Коэффициент при кубическом члене репараметризующего многочлена. \en The coefficient of the cubic term of the reparametrizing polynomial. - double a; ///< \ru Коэффициент при квадратичном члене репараметризующего многочлена. \en The coefficient of the quadratic term of the reparametrizing polynomial. - double b; ///< \ru Коэффициент при линейном члене репараметризующего многочлена. \en The coefficient of the linear term of the reparametrizing polynomial. - double c; ///< \ru Свободный коэффициент репараметризующего многочлена. \en The free coefficient of the reparametrizing polynomial. + MbCurve3D * basisCurve; ///< \ru Базовая кривая. \en The base curve. + MbeReparamType reparamType; ///< \ru Способ репараметризации. \en Way of repatametrization. + SPtr rFunc; ///< \ru Репараметризующая функция, всегда не нулевая. \en Reparametric function, always non-zero. protected: MbReparamCurve3D( const MbReparamCurve3D &, MbRegDuplicate * ); private : MbReparamCurve3D( const MbReparamCurve3D & ); // \ru Не реализовано. \en Not implemented. public : + /// \ru Конструктор по кривой и новым параметрам. \en Constructor by curve and by new parametric limits. MbReparamCurve3D( const MbCurve3D &, double t1, double t2 ); + /// \ru Конструктор по кривой и новым параметрам. \en Constructor by curve and by new parametric limits. MbReparamCurve3D( const MbCurve3D &, double t1, double t2, double begFirstDerValue ); - MbReparamCurve3D( const MbCurve3D &, double t1, double t2, double derBeg, double derEnd ); + /// \ru Конструктор по кривой и производным параметра на ее концах. \en Constructor for the curve and derivatives of the parameter at its ends + MbReparamCurve3D( double dt1, double dt2, const MbCurve3D & curve ); virtual ~MbReparamCurve3D(); @@ -71,7 +70,7 @@ public : void Init( double t1, double t2 ); void Init( double t1, double t2, double begFirstDerValue ); - void Init( double t1, double t2, double der1, double der2 ); + void InitScaledEnds( double scaleDer1, double scaleDer2 ); // \ru Общие функции математического объекта \en Common functions of the mathematical object @@ -175,9 +174,9 @@ public : void ParameterFrom( double & ) const; // \ru Перевод локального параметра в параметр базовой кривой \en Transformation of a local parameter to the base curve parameter void SetBasisCurve( MbCurve3D & ); // \ru Заменить плоскую кривую \en Replace the planar curve - double Tmin() const { return tmin; } // \ru Начальный параметр \en Start parameter - double Tmax() const { return tmax; } // \ru Конечный параметр \en End parameter - double Dt() const { return b; } // \ru Производная параметра кривой basisCurve по параметру \en Derivative of parameter of 'basisCurve' curve by parameter + 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. void SetTmin( double t ); void SetTmax( double t ); void SetDt ( double d ); @@ -200,68 +199,20 @@ public : 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); bool IsLinear() const { return (reparamType == rt_Linear); } // \ru Является ли репараметризация линейной? \en Is the re-parametrization linear? private: void operator = ( const MbReparamCurve3D & ); // \ru Не реализовано. \en Not implemented. - double CubicRoot( double t ) const; // \ru Решение кубического уравнения. \en Solution of cubic equation. - void Explore( double t, double * par, double * dpar, double * ddpar, double * dddpar ) const; // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. + // \ru Параметр базовой кривой и его производные. \en The base curve parameter and its derivatives. + void Explore( double & t, bool ext, double & par, double & dpar, double * ddpar, double * dddpar ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbReparamCurve3D ) }; // MbReparamCurve3D IMPL_PERSISTENT_OPS( MbReparamCurve3D ) -//------------------------------------------------------------------------------ -/// \ru Перевод параметра базовой кривой в новый параметр. \en Transformation of the base curve parameter to a new parameter. -// --- -inline void MbReparamCurve3D::ParameterInto( double & t ) const { - if ( reparamType == rt_Linear ) - t = ( t - c ) / b; - else if( reparamType == rt_Quadratic ){ - C3D_ASSERT( ::fabs(a) > NULL_EPSILON ); - const double discriminant = b * b + 4.0 * a * (t - c); - if ( discriminant > EXTENT_EQUAL ) - t = 0.5 * ( ::sqrt(discriminant) - b ) / a; - else - t = -0.5 * b / a; - } - else if ( reparamType == rt_Cubic ) { - bool close = basisCurve->IsClosed(); - double bTmin = basisCurve->GetTMin(), bTmax = basisCurve->GetTMax(); - if ( !close && ( t < bTmin || t > bTmax ) ) { - double t0 = ( t < bTmin ) ? tmin : tmax; - double par = ( t < bTmin ) ? bTmin : bTmax; - double dpar = 3.0 * q * t0 * t0 + 2.0 * a * t0 + b; - t = t0 + ( t - par ) / dpar; - } - else { - double n = 0.0; - if ( close ) { - double period = bTmax - bTmin; - n = ::floor( (t - bTmin) / period ); - t -= n * period; - } - t = CubicRoot( t ); - if ( n != 0.0 ) - t += n * ( tmax - tmin ); - } - } -} - -//------------------------------------------------------------------------------ -/// \ru Перевод нового параметра в параметр базовой кривой. \en Transformation of a new parameter to the base curve parameter. -// --- -inline void MbReparamCurve3D::ParameterFrom( double & t ) const { - if ( reparamType == rt_Linear ) - t = b * t + c; - else if( reparamType == rt_Quadratic ) - t = a * t * t + b * t + c; - else if ( reparamType == rt_Cubic ) - Explore( t, &t, 0, 0, 0 ); -} - #endif // __CUR_REPARAM_CURVE3D_H diff --git a/C3d/Include/cur_silhouette_curve.h b/C3d/Include/cur_silhouette_curve.h index abee7d9..fff5ad0 100644 --- a/C3d/Include/cur_silhouette_curve.h +++ b/C3d/Include/cur_silhouette_curve.h @@ -11,12 +11,9 @@ #define __CUR_SILHOUETTE_CURVE_H -#include #include -struct AuxiliarySilhouetteData; -struct CurvaturePointData; //------------------------------------------------------------------------------ /** \brief \ru Линия очерка или силуэтная кривая поверхности. @@ -74,8 +71,6 @@ protected: MbCurve3D * approxCurve; ///< \ru Пространственное представление линии очерка. \en The spatial representation of isocline curve. bool approxExact; ///< \ru Точная ли кривая approxCurve. \en Is exact approxCurven. - AuxiliarySilhouetteData * silhData; ///< \ru Общие параметры силуэтной линии, используемые в алгоритмах ее точного представления. - ///< \en General parameters of a silhouette line used in its exact presentation algorithms. public : /// \ru Конструктор по поверхности, двумерной кривой, типу кривой, матрице и флагу перспективы. \en Constructor by surface, two-dimensional curve, type of curve, matrix and flag of perspective. MbSilhouetteCurve( const MbSurface & surf, const MbCurve & crv, MbeCurveBuildType _species, @@ -114,20 +109,14 @@ public: 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 main normal vector (normalized) at curve and its extension. - virtual void Normal( double & t, MbVector3D & ) const; // \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 main normal vector (normalized) at curve and its extension. - virtual void _Normal( double t, MbVector3D & ) const; // \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; - /// \ru Вычислить кривизну кривой. \en Calculate curvature of curve. - virtual double Curvature( double t ) const; // \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; @@ -141,6 +130,9 @@ public: virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) 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; + // \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). @@ -177,42 +169,7 @@ public: // \ru Получить текущую точку на кривой по параметру. \en Get current point on a curve by a parameter. virtual bool GetCurvePoint( double & t, MbCartPoint & cPoint ) const; - // \ru Найти все особые точки функции кривизны кривой. \en Find all the special points of the curvature function of the curve. - virtual void GetCurvatureSpecialPoints( std::vector & points ) const; - private: - // Расчитать точку обрезки луча pnt0 - pnt границами поверхности surface. - bool IsCutBounds( const MbCartPoint * pnt0, MbCartPoint & pnt ) const; - // Вычислить параметр видимости в точке и его градиент. - void CalcVisibilityParam( const MbCartPoint & p, double & val, MbVector * der = NULL ) const; - // Ищем интервал между точками p1 и p2, на котором произойдет смена видимости, последовательно прибавляя в заданную сторону вектор w. - void GoToOneSide( const MbVector & w, MbCartPoint & p1, MbCartPoint & p2, double & vis1, double & vis2, MbVector &der1, MbVector & der2, int nIter, bool move1 ) const; - // Найти точку на силуэтной линии на отрезке [pnt0 - w, pnt0 + w]. - bool GetPointOnSilhouette( const MbCartPoint &pnt0, const MbVector & w, int nIter, double zEps, double & zEpsOut, MbCartPoint & silhPoint ) const; - // Найти проекцию точки на аппроксимационном сплайне на силуэтную линию по нормали к аппроксимационному сплайну. - void ExactSilhouettePoint( double h, double t, int pos, MbCartPoint & point2D ) const; - // Расчет производной через конечные разности. - void CalcFiniteDifference( double tmin, double tmax, double h, double t, int pos, int order, - std::map & points2D, std::map & points3D, std::map( &ders )[3] ) const; - // Суммирование слагаемых конечной разности. - void CalcDifference( double tmin, double tmax, double h, double t, int pos0, int order, int pos, const double( &kf )[5], double zn, - std::map & points2D, std::map & points3D, std::map( &ders )[3] ) const; - // Расчет по параметру на сплайне точной точки на силуэтной линии, а также первой и второй производной, вычисленных через конечные разности. - void AccurateExplore( double t, MbCartPoint & pnt, MbVector3D & fir, MbVector3D & sec ) const; - // Расчет параметров, используемых в алгоритмах для кривизны, в точке (положение на кривой, кривизна, нормаль, шаг). - void CurvatureExplore( double t, CurvaturePointData & cpd ) const; - // Расчет на поверхности кривизны в направлении seg. - void CurvatureOnSurfaceLine( const MbVector & seg, const MbCartPoint & p, double & curv, double & dcurv ) const; - // Анализ разрыва кривизны на поверхности на отрезке между точками p1 и p2. - bool IsCurvatureRapture( const MbCartPoint & p1, const MbCartPoint & p2 ) const; - // Поиск экстремума на интервале pd1 - pd2 методом золотого сечения. Начиная с точки prev до точки pd2, кривизна монотоно убывает/возрастает. - void CurvatureExtremeBinarySearch( const CurvaturePointData & pd1, const CurvaturePointData & pd2, CurvaturePointData & prev, - bool isMax, double eps, std::vector & spPoints ) const; - // Проверка интервала на кривой на разрыв кривизны. - void CheckRapture( double t1, double t2, std::vector & spPoints ) const; - // Найти разрывы кривизны на участке кривой pd1 - pd2. Начиная с точки prev до точки pd2, кривизна монотоно убывает/возрастает. - void FindCurvatureRaptures( const CurvaturePointData & pd1, const CurvaturePointData & pd2, CurvaturePointData & prev, - double paramAccuracy, std::vector & points ) const; // \ru Проверить параметр и вычислить параметрическую точки. \en Check parameter and calculate parametric points. bool CorrectPoint( double & t, bool ext, MbCartPoint & cPoint, MbVector & cFirst, MbVector * cSecond, MbVector * cThird ) const; void CalculatePoint ( double & t, bool ext, MbCartPoint3D & ) const; // \ru Вычислить точку на расширенной кривой. \en Calculate a point on the extended curve. diff --git a/C3d/Include/cur_spiral.h b/C3d/Include/cur_spiral.h index d5aa2c7..bca6c0d 100644 --- a/C3d/Include/cur_spiral.h +++ b/C3d/Include/cur_spiral.h @@ -33,50 +33,79 @@ protected: /** \brief \ru Метрическая длина кривой. \en Metric length of a curve. \~ - \details \ru Метрическая длина кривой расчитывается только при запросе длины объекта. Метрическая длина кривой в конструкторе кривой и после модификации кривой принимает отрицательное значение. + \details \ru Метрическая длина кривой, рассчитывается только при запросе длины объекта. Метрическая длина кривой в конструкторе кривой и после модификации кривой принимает отрицательное значение. \en Metric length of a curve is calculated only at the request. Metric length of a curve is undefined (negative) after object constructor and after object modifications. \n \~ */ mutable double metricLength; /** \brief \ru Габаритный куб кривой. \en Bounding box of a curve. \~ - \details \ru Габаритный куб кривой расчитывается только при запросе габарита объекта. Габаритный куб в конструкторе кривой и после модификации кривой принимает неопределенное значение. + \details \ru Габаритный куб кривой, рассчитывается только при запросе габарита объекта. Габаритный куб в конструкторе кривой и после модификации кривой принимает неопределенное значение. \en Bounding box of a curve is calculated only at the request. Bounding box of a curve is undefined after object constructor and after object modifications. \n \~ */ mutable MbCube cube; protected: - MbSpiral() : position(), step( 1.0 ), tmin( 0.0 ), tmax( M_PI2 ), metricLength( -1.0 ), cube() {} - MbSpiral( const MbPlacement3D & pl ) : position( pl ), step( 0.0 ), tmin( 0.0 ), tmax( 0.0 ), metricLength( -1.0 ), cube() {} - MbSpiral( const MbPlacement3D & pl, double height, double st ); // \ru По высоте и шагу \en By height and pitch - MbSpiral( const MbPlacement3D & pl, double s, double t1, double t2 ); - MbSpiral( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, double st, bool left = false ); - MbSpiral( const MbSpiral & init ); + /// \ru Конструктор по умолчанию. \en The default constructor. + MbSpiral() : position(), step( 1.0 ), tmin( 0.0 ), tmax( M_PI2 ), metricLength( -1.0 ), cube() {} + /// \ru Конструктор по локальной системе координат. \en The constructor by local coordinate system. + MbSpiral( const MbPlacement3D & pl ) : position( pl ), step( 1.0 ), tmin( 0.0 ), tmax( M_PI2 ), metricLength( -1.0 ), cube() {} +protected: + /// \ru Конструктор по локальной системе координат, высоте и шагу между витками. \en The constructor by local coordinate system, height and step between coils of spiral. + MbSpiral( const MbPlacement3D &, double height, double step ); + /** \brief \ru Конструктор по локальной системе координат, шагу между витками и параметрам. + \en The constructor by local coordinate system, step between coils of spiral and parameters. \~ + \details \ru Конструктор по локальной системе координат, шагу между витками, начальному и конечному параметрам. + \en The constructor by local coordinate system, step between coils of spiral, starting and ending parameters. \n \~ + */ + MbSpiral( const MbPlacement3D &, double step, double t1, double t2 ); + /** \brief \ru Конструктор по трем разным точкам и ненулевому шагу. + \en The constructor by three different points and non-zero step. \~ + \details \ru Конструктор по трем разным точкам и ненулевому шагу. \n + \en The constructor by three different points and non-zero step. \n \~ + \param[in] p0 - \ru Начало локальной системы координат. + \en Origin point of the local coordinate system. \~ + \param[in] p1 - \ru Точка в направлении оси Z, определяющая высоту спирали. + \en Point in the direction of the Z axis determining the height of the spiral. \~ + \param[in] p2 - \ru Точка в направлении оси X. + \en Point in the direction of the X axis. \~ + \param[in] st - \ru Шаг между витками спирали. + \en Step between coils of spiral. \~ + \param[in] left - \ru Признак левой системы координат. + \en Flag of the left coordinate system. \~ + */ + MbSpiral( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, double step, bool left = false ); + /// \ru Конструктор по другой спирали. \en Constructor by another spiral. + MbSpiral( const MbSpiral & ); public : virtual ~MbSpiral(); public : VISITING_CLASS( MbSpiral ); - void Init( const MbSpiral & init ); - void Init( const MbPlacement3D & place ); - void Init( double height, double st ); // \ru Установить высоту и шаг \en Set height and pitch - void Init( const MbPlacement3D & place, double height, double st ); + /// \ru Установить параметры спирали по другой спирали. \en Set spiral parameters by another spiral. + void Init( const MbSpiral & ); + /// \ru Установить другую локальную систему координат. \en Replace local coordinate system. + void Init( const MbPlacement3D & ); + /// \ru Установить высоту и шаг. \en Set height and step between coils of spiral. + bool Init( double height, double st ); + /// \ru Установить локальную систему координат, высоту и шаг спирали. \en Set local coordinates system, height and step of spiral. + bool Init( const MbPlacement3D & place, double height, double st ); // \ru Общие функции математического объекта \en Common functions of the mathematical object 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 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 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 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. - 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 + 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 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. @@ -110,7 +139,7 @@ public : virtual size_t GetCount() const; double GetSpiralPeriod() const; // \ru Вернуть период \en Get period - // \ru Заполнить плейсемент, ести кривая плоская \en Fill the placement if the curve is planar + // \ru Заполнить плейсемент, если кривая плоская \en Fill the placement if the curve is planar virtual bool GetPlacement( MbPlacement3D & place, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Является ли объект смещением \en Whether the object is a shift @@ -119,33 +148,76 @@ public : // \ru Функции спирали \en Functions of spiral - virtual void SetStep( double s ) = 0; // \ru Изменить шаг \en Change step + virtual bool SetStep( double s ) = 0; // \ru Изменить шаг \en Change step virtual double GetSpiralRadius ( double t ) const = 0; // \ru Выдать физический радиус спирали \en Get physical radius of spiral - inline void CheckParam( double & t ) const; + + void CheckParam( double & t ) const; + /// \ru Дать направление спирали. \en Get direction of spiral. void GetDirection ( MbVector3D & v ) const { v = position.GetAxisZ(); } - bool GetAxis( MbAxis3D & axis ) const; // \ru Дать ось спирали \en Get axis of spiral - double GetStep() const { return step; } // \ru Выдать шаг \en Get step - double GetSpiralStep() const; // \ru Выдать физический шаг спирали \en Get physical pitch of spiral - double GetAngle() const { return tmax-tmin; } // \ru Выдать полный угол спирали \en Get full angle of spiral - void SetTMin( double t ) { tmin = t; Refresh(); } // \ru Изменить граничный угол \en Change boundary angle - void SetTMax( double t ) { tmax = t; Refresh(); } // \ru Изменить граничный угол \en Change boundary angle - void SetLimit( double t1, double t2 ) { tmin = std_min( t1, t2 ); tmax = std_max( t1, t2 ); Refresh(); } + /// \ru Дать ось спирали. \en Get axis of spiral. + bool GetAxis( MbAxis3D & axis ) const; + /// \ru Выдать шаг. \en Get step. + double GetStep() const { return step; } + /// \ru Выдать физический шаг спирали. \en Get physical pitch of spiral. + double GetSpiralStep() const; + /// \ru Выдать полный угол спирали \en Get full angle of spiral + double GetAngle() const { return tmax-tmin; } + /// \ru Изменить граничный угол. \en Change boundary angle. + bool SetTMin( double t ) + { + C3D_ASSERT( t < tmax ); + if ( t < tmax ) { + tmin = t; + Refresh(); + return true; + } + return false; + } + /// \ru Изменить граничный угол. \en Change boundary angle. + bool SetTMax( double t ) + { + C3D_ASSERT( t > tmin ); + if ( t > tmin ) { + tmax = t; + Refresh(); + return true; + } + return false; + } + /// \ru Изменить граничные углы. \en Change boundary angles. + bool SetLimit( double t1, double t2 ) + { + if ( t1 > t2 ) + std::swap( t1, t2 ); + C3D_ASSERT( t1 < t2 ); + if ( t1 < t2 ) { + tmin = t1; + tmax = t2; + Refresh(); + return true; + } + return false; + } const MbPlacement3D & GetPlacement() const { return position; } bool IsPositionNormal() const { return ( !position.IsAffine() ); } +protected: + static bool IsNonZeroStep( double s ) { return (::fabs( s ) >= METRIC_EPSILON); } private: void operator = ( const MbSpiral & ); // \ru Не реализовано. \en Not implemented. - DECLARE_PERSISTENT_CLASS( MbSpiral ) +DECLARE_PERSISTENT_CLASS( MbSpiral ) }; IMPL_PERSISTENT_OPS( MbSpiral ) + //------------------------------------------------------------------------------ // \ru Проверка параметра кривой \en Check parameter of curve //--- -inline void MbSpiral::CheckParam( double & t ) const +inline +void MbSpiral::CheckParam( double & t ) const { if ( t < tmin ) t = tmin; @@ -157,7 +229,8 @@ inline void MbSpiral::CheckParam( double & t ) const //------------------------------------------------------------------------------ // \ru Выдать физический шаг спирали \en Get physical pitch of spiral //--- -inline double MbSpiral::GetSpiralStep() const +inline +double MbSpiral::GetSpiralStep() const { if ( position.IsNormal() ) return step; diff --git a/C3d/Include/cur_surface_curve.h b/C3d/Include/cur_surface_curve.h index 774ec95..c2a3425 100644 --- a/C3d/Include/cur_surface_curve.h +++ b/C3d/Include/cur_surface_curve.h @@ -35,7 +35,7 @@ class MbCurveIntoNurbsInfo; \details \ru Кривая на поверхности строится путём введения зависимости параметров поверхности u и v от некоторого общего для них параметра t: u=u(t), v=v(t). \n Параметры поверхности u и v являются координатами двумерной точки в пространстве параметров поверхности. - Кривая на поверхности описывается поверхностью surface и двумерной кривой в пространстве параметров curve. + Кривая на поверхности описывается поверхностью surface и двумерной кривой в пространстве параметров curve. Поверхностью surface может быть любая поверхность, кроме MbCurveBoundedSurface. \n Для заданного параметра t кривой curve вычисляется двумерная точка w=[u v] области параметров поверхности, далее для параметров u и v поверхностью surface вычисляется точка кривой на поверхности. @@ -47,7 +47,7 @@ class MbCurveIntoNurbsInfo; \en Curve on surface is constructed by introduction of dependence of u and v surface parameters from some parameter t common for them: u=u(t), v=v(t). \n u and v surface parameters are coordinates of two-dimensional point in space of surface parameters. - Curve on surface is described by 'surface' surface and two-dimensional curve 'curve' in space of parameters. + Curve on surface is described by 'surface' surface and two-dimensional curve 'curve' in space of parameters. Any surface except MbCurveBoundedSurface can be surface 'surface'. \n two-dimensional point w=[u v] of region of surface parameters is calculated for a given parameter t of curve 'curve', further, a point of curve on surface is calculated for u and v parameters of 'surface' surface. @@ -105,7 +105,7 @@ protected : public : /// \ru Конструктор кривой на поверхности. \en Constructor of curve on surface. - MbSurfaceCurve( const MbSurface &, const MbCurve &, bool same, MbRegDuplicate * iReg = NULL ); + MbSurfaceCurve( const MbSurface &, const MbCurve &, bool sameCurve, MbRegDuplicate * iReg = 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. @@ -243,7 +243,8 @@ public: virtual void GetCurvatureContinuityBounds( 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 SetContinuousDerivativeLength( double epsilon = EPSILON ); // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + // \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /** \} */ @@ -251,6 +252,10 @@ public: bool IsSameCurvePoints( const MbSurfaceCurve * scurve, double accuracy, bool sameSense ) const; /// \ru Вычислить нормаль к поверхности. \en Calculate surface normal. void SurfaceNormal( double & t, MbVector3D &, bool ext = false ) const; + /// \ru Нормаль к поверхности, первая и вторая производная нормали поверхности по t. \en Calculation of the normal, first, and second derivative of the surface normal. + void SurfaceNormal( double & t, MbVector3D & n, MbVector3D & fd, MbVector3D & sd, bool ext = false ) const; + /// \ru Кривизна поверхности в поперечном направлении к вектору tau. \en The surface curvature in the transverse direction to the vector tau. + double SurfaceTransversalCurvature( double t, const MbVector3D & tau ) const; /// \ru Получить параметры поверхности по параметру на кривой. \en Get surface parameters by a parameter on the curve. void SurfaceParams( double & t, double & u, double & v, bool ext = false ) const; /// \ru Вычислить параметрический габарит кривой. \en Calculate parametric bounding box of the curve. @@ -261,9 +266,9 @@ public: void GetVPairs( double u, SArray & v, SArray & t ) const; /// \ru Построить участок пространственной копии кривой. \en Construct a piece of a spatial curve copy. - MbCurve3D * MakeCurve( double t1, double t2 ) const; + MbCurve3D * MakeCurve( double t1, double t2, VERSION version ) const; /// \ru Построить пространственную копию кривой. \en Construct a spatial curve copy. - MbCurve3D * MakeCurve() const; + MbCurve3D * MakeCurve( VERSION version ) const; /// \ru Построить точную пространственную копию кривой. \en Construct the exact spatial curve copy. MbCurve3D * CreateCurve() const; /// \ru Создать пространственную кривую по линии u, v. \en Create a spatial curve by u, v lines. diff --git a/C3d/Include/cur_surface_intersection.h b/C3d/Include/cur_surface_intersection.h index 7a2a469..4bf85ea 100644 --- a/C3d/Include/cur_surface_intersection.h +++ b/C3d/Include/cur_surface_intersection.h @@ -368,9 +368,9 @@ public: virtual void CalculateGabarit( MbCube & c ) const; // \ru Вычислить габарит кривой. \en Calculate bounding box of a curve. // \ru Получить габарит кривой. \en Get bounding box of curve. - const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } + const MbCube & GetGabarit() const; // \ru Сбросить габаритный куб. \en Reset bounding box. - void SetDirtyGabarit() const { cube.SetEmpty(); } + void SetDirtyGabarit() const; virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::metricPrecision, VERSION version = Math::DefaultMathVersion() ) const; // \ru Сдвинуть параметр t на расстояние len по направлению. \en Translate parameter 't' on the distance 'len' by the direction. @@ -414,7 +414,7 @@ public: /// \ru Установить тип кривой по топологии. \en Set a curve type by topology. void SetGlueType( MbeCurveGlueType type ) { glueType = type; } /// \ru Установить тип кривой по топологии. \en Set a curve type by topology. - void SetPoleGlueType() const { glueType = cgt_Pole; } + void SetPoleGlueType() const; /// \ru Получить тип кривой по построению. \en Get a curve type by construction. MbeCurveBuildType GetBuildType() const { return buildType; } diff --git a/C3d/Include/cur_trimmed_curve.h b/C3d/Include/cur_trimmed_curve.h index 4890dcf..a5915a0 100644 --- a/C3d/Include/cur_trimmed_curve.h +++ b/C3d/Include/cur_trimmed_curve.h @@ -74,12 +74,13 @@ public : virtual MbePlaneType Type() const; // \ru Вернуть тип кривой \en Get type of curve 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 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 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 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. @@ -172,7 +173,7 @@ public : virtual MbeState DeletePart( double t1, double t2, MbCurve *& part2 ); // \ru Удалить часть усеченной кривой между параметрами t1 и t2 \en Delete a part of a trimmed curve between parameters t1 and t2 virtual MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ); // \ru Оставить часть усеченной кривой между параметрами t1 и t2 \en Keep a part of the trimmed curve between parameters t1 and t2 virtual MbCurve * Trimmed( double t1, double t2, int sense ) const; - virtual MbCurve * Offset( double rad ) const; // \ru Смещение усеченной кривой \en Shift of a trimmed curve + virtual MbCurve * Offset( double rad ) const; // \ru Смещение усеченной кривой \en Shift of a trimmed curve virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & ) const; virtual MbCurve * NurbsCurve( const MbNurbsParameters & ) const; // \ru Построить NURBS-копию кривой \en Create a NURBS-copy of the curve diff --git a/C3d/Include/curve.h b/C3d/Include/curve.h index 2eee6c9..886baf7 100644 --- a/C3d/Include/curve.h +++ b/C3d/Include/curve.h @@ -73,7 +73,7 @@ typedef std::vector ConstPlaneCurvesSPtrVector; \ingroup Curves_2D */ // --- -class MATH_CLASS MbCurve : public MbPlaneItem { +class MATH_CLASS MbCurve : public MbPlaneItem, public MbNestSyncItem { protected: SimpleName name; ///< \ru Имя кривой. \en A curve name. @@ -1271,8 +1271,10 @@ public : \en Eliminate the discontinuities of the first derivatives of the length. \n \~ \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ + \param[in] version - \ru Версия математики. + \en Math version. \~ */ - virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /** \brief \ru Определить, близки ли две кривые метрически. \en Check whether the two curves are metrically close. \~ diff --git a/C3d/Include/curve3d.h b/C3d/Include/curve3d.h index 8a4fbdd..e345f21 100644 --- a/C3d/Include/curve3d.h +++ b/C3d/Include/curve3d.h @@ -41,14 +41,24 @@ struct MbNurbsParameters; class MATH_CLASS MbCurve3D; namespace c3d // namespace C3D { -typedef SPtr SpaceCurveSPtr; -typedef SPtr ConstSpaceCurveSPtr; +typedef SPtr SpaceCurveSPtr; +typedef SPtr ConstSpaceCurveSPtr; -typedef std::vector SpaceCurvesVector; -typedef std::vector ConstSpaceCurvesVector; +typedef std::vector SpaceCurvesVector; +typedef std::vector ConstSpaceCurvesVector; -typedef std::vector SpaceCurvesSPtrVector; -typedef std::vector ConstSpaceCurvesSPtrVector; +typedef std::vector SpaceCurvesSPtrVector; +typedef std::vector ConstSpaceCurvesSPtrVector; + +typedef std::set SpaceCurvesSet; +typedef SpaceCurvesSet::iterator SpaceCurvesSetIt; +typedef SpaceCurvesSet::const_iterator SpaceCurvesSetConstIt; +typedef std::pair SpaceCurvesSetRet; + +typedef std::set ConstSpaceCurvesSet; +typedef ConstSpaceCurvesSet::iterator ConstSpaceCurvesSetIt; +typedef ConstSpaceCurvesSet::const_iterator ConstSpaceCurvesSetConstIt; +typedef std::pair ConstSpaceCurvesSetRet; } @@ -68,7 +78,7 @@ typedef std::vector ConstSpaceCurvesSPtrVector; \ingroup Curves_3D */ // --- -class MATH_CLASS MbCurve3D : public MbSpaceItem { +class MATH_CLASS MbCurve3D : public MbSpaceItem, public MbNestSyncItem { protected: SimpleName name; ///< \ru Имя кривой. \en A curve name. @@ -781,8 +791,10 @@ public : \en Eliminate the discontinuities of the first derivatives of the length. \n \~ \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ + \param[in] version - \ru Версия математики. + \en Math version. \~ */ - virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); + virtual bool SetContinuousDerivativeLength( VERSION version, double epsilon = EPSILON ); /** \brief \ru Определить, близки ли две кривые метрически. \en Check whether the two curves are metrically close. \~ @@ -848,7 +860,7 @@ public : Point with greater curvature is inserted with a plus sign, a point with a lower curvature is inserted with a minus sign. \n \ingroup Curves_3D */ - virtual void GetCurvatureSpecialPoints( std::vector & points ) const; + virtual void GetCurvatureSpecialPoints( std::vector & points ) const; /** \brief \ru Получить границы участков кривой, на которых сохраняется непрерывность кривизны. \en Get the boundaries of the sections of the curve on which the continuity of curvature is preserved. \~ @@ -860,7 +872,7 @@ public : \en The points at which the curvature has a discontinuity. \~ \ingroup Curves_3D */ - virtual void GetCurvatureContinuityBounds( std::vector & params ) const; + virtual void GetCurvatureContinuityBounds( std::vector & params ) const; /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ @@ -872,7 +884,7 @@ public : \en A calculated point. \~ \ingroup Curves_3D */ - MbCartPoint3D GetLimitPoint( ptrdiff_t number ) const; // \ru number <= 1 : в начале, инача - в конце \en Number <= 1 : at start, otherwise - at end + MbCartPoint3D GetLimitPoint( ptrdiff_t number ) const; // \ru number <= 1 : в начале, иначе - в конце \en Number <= 1 : at start, otherwise - at end /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ @@ -915,7 +927,7 @@ public : \return \ru true, если точки равны. \en Returns true if points are equal. \~ */ - bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } + bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } /// \ru Загнать в параметрическую область. \en Move to the parametric region. bool SetInParamRegion( double & t ) const; @@ -1084,15 +1096,18 @@ MATH_FUNC (MbeNewtonResult) NearestPoints( const MbCurve3D & curve1, bool ext1, \en Parameter of the curve 1 for the intersection point (the initial approximation at input). \~ \param[in, out] t2 - \ru Параметр кривой 2 для точки пересечения (начальное приближение на входе). \en Parameter of the curve 2 for the intersection point (the initial approximation at input). \~ + \param[in] correctNewtonParam - \ru Выполнять корректировку приращения параметра по предыщушему приращению параметра. + \en Modify current parameter changes by previous parameter changes. \~ \return \ru Код ошибки: случае успешного определения nr_Success (+1), nr_Special(0) или nr_Failure(-1) - в случае неудачи. \en Error code: in a case of successful defining nr_Success (+1), nr_Special(0) or nr_Failure(-1) - in a case of failure. \~ \ingroup Curves_3D */ // --- -MATH_FUNC (MbeNewtonResult) CurveCrossNewton( const MbCurve3D & curve1, bool ext1, - const MbCurve3D & curve2, bool ext2, +MATH_FUNC (MbeNewtonResult) CurveCrossNewton( const MbCurve3D & curve1, bool ext1, + const MbCurve3D & curve2, bool ext2, double funcEpsilon, size_t iterLimit, - double & t1, double & t2 ); + double & t1, double & t2, + bool correctNewtonParam = true ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/dxf_data.h b/C3d/Include/dxf_data.h index 3f5f03d..fe772cf 100644 --- a/C3d/Include/dxf_data.h +++ b/C3d/Include/dxf_data.h @@ -9,12 +9,12 @@ #ifndef __DXF_DATA_H #define __DXF_DATA_H -#include #include #include #include #include #include +#include #include diff --git a/C3d/Include/func_analytical_function.h b/C3d/Include/func_analytical_function.h index 4bc8804..8b19060 100644 --- a/C3d/Include/func_analytical_function.h +++ b/C3d/Include/func_analytical_function.h @@ -43,9 +43,13 @@ private : public : /// \ru Конструктор. \en Constructor. - MdCharacterFunction( const MbMathematicalNode & expression_, const MbListVars & vars, - const c3d::string_t & data_, const c3d::string_t & argument_, - double tmin_, double tmax_, bool sense_ ); + MdCharacterFunction( const MbMathematicalNode & expression, + const MbListVars & vars, + const c3d::string_t & data, + const c3d::string_t & argument, + double tmin, + double tmax, + bool sense ); virtual ~MdCharacterFunction(); private: @@ -132,7 +136,7 @@ private: public : // \ru Конструктор. \en Constructor. - MdAnalyticalFunction( MbUserFunc & ufunc, double tmin_, double tmax_, bool sense_ = true ); + MdAnalyticalFunction( const MbUserFunc & ufunc, bool sameFunc, double tmin, double tmax, bool sense ); public: virtual ~MdAnalyticalFunction(); @@ -181,12 +185,12 @@ public : // \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 ); - virtual bool IsCos ( double &a, double& b ) const; ///< \ru Имеет ли функция вид a * cos() + b. \en Function looks like a * cos() + b. + virtual bool IsCos ( double & a, double & b ) const; ///< \ru Имеет ли функция вид a * cos() + b. \en Function looks like a * cos() + b. private: /// \ru Производные по параметру: параметр, значение, первая, вторая и третья производные \en Derivatives with respect to the parameter: parameter, value, first, second and third derivatives - void Derivates ( double & t, DerivateData* data ) const; + void Derivates ( double & t, DerivateData * data ) const; void CheckParam( double & t ) const; void ResetTCalc() const; // \ru Сбросить временные данные \en Reset temporary data void operator = ( const MdAnalyticalFunction & ); // \ru Не реализовано. \en NOT ALLOWED !!! diff --git a/C3d/Include/func_cubic_function.h b/C3d/Include/func_cubic_function.h index 14a14d5..7e4d4a4 100644 --- a/C3d/Include/func_cubic_function.h +++ b/C3d/Include/func_cubic_function.h @@ -15,7 +15,7 @@ #include -#define FUNC_NUMB 4 ///< \ru Количество элементов расчетного массива кубической функции Эрмита. \en The number of elements of calculation array of a cubic Hermite function. +const_expr size_t FUNC_NUMB = 4; ///< \ru Количество элементов расчетного массива кубической функции Эрмита. \en The number of elements of calculation array of a cubic Hermite function. //------------------------------------------------------------------------------ @@ -80,6 +80,8 @@ public: // \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; + // \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 double Step( double t, double sag ) const; @@ -112,6 +114,10 @@ public: size_t GetValuesCount() const; // \ru Выдать количество опорных точек \en Get the number of control points double GetParam( size_t index ) const; // \ru Дать значение параметра точки по номеру \en Get the value of point parameter by its number double GetValue( size_t index ) const; // \ru Дать значение точки по номеру \en Get the value of point by its number + double GetDerive( size_t index ) const; // \ru Дать значение производной по номеру \en Get the value of derivative by its number + // \ru Получить коэффициенты кубической функции на указанном интервале. + // \en Get the coefficients of the cubic function on the specified interval. + void GetCubicFactors( size_t index, double & a, double & b, double & c, double & d ) const; private: bool CalculateDerivatives(); // \ru Расчет производных. \en Calculation of derivatives diff --git a/C3d/Include/func_line_function.h b/C3d/Include/func_line_function.h index ad9432c..137012d 100644 --- a/C3d/Include/func_line_function.h +++ b/C3d/Include/func_line_function.h @@ -64,6 +64,8 @@ public: // \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; + // \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 double Step( double t, double sag ) const; @@ -95,4 +97,5 @@ private: IMPL_PERSISTENT_OPS( MbLineFunction ) + #endif // __FUNC_LINE_FUNCTION_H diff --git a/C3d/Include/func_serve_function.h b/C3d/Include/func_serve_function.h new file mode 100644 index 0000000..3c4072d --- /dev/null +++ b/C3d/Include/func_serve_function.h @@ -0,0 +1,142 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Служебная функция. + \en Service function. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __FUNC_SERVE_FUNCTION_H +#define __FUNC_SERVE_FUNCTION_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Монотонно возрастающая служебная функция. + \en The monotonically increasing service function. \~ + \details \ru Функция служит для изменения параметризации кривых, обеспечивающей непрерывномть производных составных кривых. \n + \en The function is used to change the parameterization of curves, which provides a continuous flow of derivatives of composite curves. \n \~ + \ingroup Functions +*/ +// --- +class MATH_CLASS MbServeFunction : public MbFunction { +public : + double a; ///< \ru Коэффициент при квадратичном члене репараметризующего многочлена. \en The coefficient of the quadratic term of the reparametrizing polynomial. + double b; ///< \ru Коэффициент при линейном члене репараметризующего многочлена. \en The coefficient of the linear term of the reparametrizing polynomial. + double c; ///< \ru Свободный коэффициент репараметризующего многочлена. \en The free coefficient of the reparametrizing polynomial. + double tmin; ///< \ru Начальный параметр. \en Start parameter. + double tmax; ///< \ru Конечный параметр. \en End parameter. + +public : + ///< \ru Конструктор по умолчанию. \en Default constructor. + MbServeFunction(); +private: + ///< \ru Конструктор по параметрам. \en Constructor by parameters. + MbServeFunction( double ka, double kb, double kc, double t1, double t2 ); + ///< \ru Конструктор копировния. \en Copy constructor. + MbServeFunction( const MbServeFunction & ); +public : + virtual ~MbServeFunction(); +public: + /** \brief \ru Инициализация переменных для линейной репараметризации. + \en Initialization of variables for linear reparameterization. \~ + \param[in] basisTMin, basisTMin - \ru Область определения базовой кривой. + \en Parametric region of the base curve.. \~ + \param[in] t1, t2 - \ru Область определения репараметризованной кривой + \en Parametric region of the reparameterized curve. \~ + */ + 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. \~ + \param[in] basisTMin, basisTMin - \ru Область определения базовой кривой. + \en Parametric region of the base curve.. \~ + \param[in] t1, t2 - \ru Область определения репараметризованной кривой + \en Parametric region of the reparameterized curve. \~ + \param[in] begDer - \ru Производная параметра базовой кривой в начале кривой. + \en The derivative of the base curve parameter at the beginning of the curve. \~ + \return - \ru true - если репараметризация выполнена успешно, + false - если репараметризация оказалась вырожденной и была сведена к линейной. + \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 ); + + /** \brief \ru Репараметризация, обеспечивающая на концах новой кривой указаные производные параметра. + \en Reparametrization providing the indicated derivatives of the parameter at the ends of the new curve. \~ + \details \ru Параметрическая ширина будет подобрана автоматически, исходя из значений производных. + \en The parametric width will be automatically selected based on the values of the derivatives. \~ + \param[in] basisTMin, basisTMin - \ru Область определения базовой кривой. + \en Parametric region of the base curve.. \~ + \param[in] dt1, dt2 - \ru Производные параметра базовой кривой в начале и в конце кривой. + \en Derivatives of the base curve parameter at the beginning and end of the curve. \~ + \return - \ru true - репараметризация выполнена успешно, + false - репараметризация оказалась вырожденной и была сведена к линейной. + \en true - reparameterization is successful, + false - reparametrization is degenerate and reduced to linear. \~ + */ + 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 + 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 the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the 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 closedness + virtual void SetClosed( bool cl ); // \ru Замкнутость функции \en A function closedness + + 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; + // \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 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; + + // \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 ); + + virtual void SetOffsetFunc( double distOld, double distNew ); // \ru Сместить функцию \en Shift a function + virtual bool SetLimitParam( double newTMin, double newTMax ); // \ru Установить область изменения параметра \en Set range of parameter + virtual void SetLimitValue( size_t n, double newValue ); // \ru Установить значение на конце ( 1 - в начале, 2 - в конце) \en Set the value at the end (1 - at beginning, 2 - at ending) + virtual double GetLimitValue( size_t n ) const; // \ru Дать значение на конце ( 1 - в начале, 2 - в конце) \en Get the value at the end (1 - at beginning, 2 - at ending) + +private: + void operator = ( const MbServeFunction & ); // \ru Не реализовано \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbServeFunction ) +}; + +IMPL_PERSISTENT_OPS( MbServeFunction ) + + +#endif // __FUNC_SERVE_FUNCTION_H diff --git a/C3d/Include/function.h b/C3d/Include/function.h index 4a46e7c..59e88eb 100644 --- a/C3d/Include/function.h +++ b/C3d/Include/function.h @@ -40,6 +40,7 @@ enum MbeFunctionType { ft_CubicSplineFunction = 5, ///< \ru Кубическая сплайновая функция. \en A cubic spline function. ft_PowerFunction = 6, ///< \ru Степенная функция. \en Power function. ft_SinusFunction = 7, ///< \ru Синусоидальная функция. \en Sinusoidal function. + ft_ServeFunction = 8, ///< \ru Служебная функция. \en Service function. ft_CharacterFunction = 101, ///< \ru Символьная функция. \en A symbolic function. ft_AnalyticalFunction = 102, ///< \ru Символьная функция на модельном выражении. \en A symbolic function in model expression. @@ -136,6 +137,11 @@ public: */ virtual void Explore( double & t, bool ext, double & val, double & fir, double * sec, double * thr ) const; + // Hахождениe аргумента t по значению функции value. \en Calculate the argument t by the function value. + MbeNewtonResult ArgumentNewton( double value, bool ext, double funcEpsilon, + size_t iterLimit, double & t ) const; + // \ru Вычислить аргумент t по значению функции. \en Calculate the argument t by the function value. + virtual double Argument( double & val ) const; /// \ru Изменить направление. \en Change direction. virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; @@ -190,7 +196,7 @@ public: /// \ru Находится ли параметр в области определения функции. \en Whether the parameter belongs to the function domain. bool IsParamOn( double t, double eps ) const { return ( GetTMin()-eps <= t && t <= GetTMax()+eps ); } /// \ru Подготовить к записи регистрируемый объект. \en Prepare for writing the registered object. - void PrepareWrite() { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } private: void operator = ( const MbFunction & ); // \ru Не реализовано \en Not implemented diff --git a/C3d/Include/function_factory.h b/C3d/Include/function_factory.h index 74f757f..fda2a4d 100644 --- a/C3d/Include/function_factory.h +++ b/C3d/Include/function_factory.h @@ -30,7 +30,7 @@ class MATH_CLASS MbMathematicalNode; \ingroup Functions */ // --- -class MATH_CLASS MbFunctionFactory { +class MATH_CLASS MbFunctionFactory : public MbSyncItem { private: mutable MbResultType status; ///< \ru Результат создания. \en The result of creation. diff --git a/C3d/Include/gc_api.h b/C3d/Include/gc_api.h index 26df62d..896687c 100644 --- a/C3d/Include/gc_api.h +++ b/C3d/Include/gc_api.h @@ -169,6 +169,22 @@ GCE_FUNC(constraint_item) GCE_FormCirDimension( GCE_system gcContext, geom_item // --- GCE_FUNC(void) GCE_ResetMovingMode( GCE_system ); +//---------------------------------------------------------------------------------------- +/** + \details + \ru По этому вызову солвер запоминает текущее состояние замороженных объектов, + как обязательное к исполнению и перераспределяет их начальное приближение для + минимизации неудовлетворенных ограничений. После успешного вызова GCE_Evaluate + замороженные объекты снова займут свое обязательное положение. Незамороженные + объекты подстроятся под замороженные в соотвествии с заданными ограничениями. + + \note + \ru Данный вызов обеспечивает поддержку старого поведения при переоценке координат замороженных объектов. + \en The call is intended to replay an old-version evaluation for the start values of the frozen coordinates. +*/ +//--- +GCE_FUNC( bool ) GCE_InitFrozenCoords( GCE_system gSys ); + /** \} Constraints2D_API @@ -271,6 +287,13 @@ GCE_FUNC(GCE_system) GCE_RestoreFromJournal( const char * fName ); //--- GCE_FUNC(const GCE_diagnostic_pars &) GCE_DiagnosticPars( GCE_system gSys ); +//---------------------------------------------------------------------------------------- +/** + \note Used only for testing +*/ +// --- +GCE_FUNC(size_t) GCT_InConstraintsFullCount( GCE_system gSys ); + //---------------------------------------------------------------------------------------- // Measure a dimension value (it used for testing purposes only) //--- diff --git a/C3d/Include/gce_api.h b/C3d/Include/gce_api.h index 8a90053..7231e8d 100644 --- a/C3d/Include/gce_api.h +++ b/C3d/Include/gce_api.h @@ -124,12 +124,12 @@ GCE_FUNC(void) GCE_ClearSystem( GCE_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. \~ + \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 @@ -1186,6 +1186,27 @@ GCE_FUNC(constraint_item) GCE_AddRadiusDimension( GCE_system gSys, geom_item cir //--- 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" \~ @@ -1227,8 +1248,11 @@ GCE_FUNC(constraint_item) GCE_FixGeom( GCE_system gSys, geom_item g ); \en Descriptor of segment. \~ \return \ru Дескриптор нового ограничения. \en Descriptor of a new constraint. \~ - \details \ru Ограничение применимо пока только для отрезков. - \en The constraint is applicable only for segments so far. \~ + + \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 ); @@ -1725,6 +1749,21 @@ GCE_FUNC(GCE_result) GCE_MovePoint( GCE_system gcSys, GCE_point curXY ); \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 ); @@ -1732,6 +1771,16 @@ GCE_FUNC(GCE_result) GCE_DynamicTransform( GCE_system gSys, const std::vector #include -#define GC_GOLDEN_SECTION 0.381966011250105 // \ru Золотое сечение. \en Golden ratio. +const_expr double GC_GOLDEN_SECTION = 0.381966011250105; // \ru Золотое сечение. \en Golden ratio. /** \addtogroup Constraints2D_API @@ -37,38 +37,37 @@ struct MbGeomTol ////////////////////////////////////////////////////////////////////////////////////////// // -/** \brief \ru Фиксированные точности решения задач двумерной параметризации и иные константы. - \en Fixed tolerances of two-dimensional parametrization problems solving and other constants \~ - \details \ru Класс инкапсулирует все точности и прочие константы, распространяющиеся на задачи - двумерной параметризации. - \n - 1. При проверке метрических величин или инцидентности точек в 2D-пространстве +/** \brief \ru Точности для решения двухмерных ограничений и иные константы. + \en Tolerances of 2D-constraint solving and other constants. \~ + + \details \ru Класс инкапсулирует все точности и прочие константы для решения систем + 2D-ограничений. \n + + 1. При проверке линейных размеров или совпадения точек в 2D-пространстве используется точность GcPrecision::lengthRegion. Т.е. любые две точки, не совпадающие с погрешностью GcPrecision::lengthRegion считаютя разными.\n 2. Для итерационных решателей используется точность параметра GcPrecision::newtonEpsilon, эта величина на 1-2 порядка выше, чем неразличимая область (lengthRegion, angleRegion).\n - 3. Любое угловое, метрическое или параметрическое значение меньшее - GcPrecision::tolerance считается нулем.\n - 4. Величина newtonEpsilon всегда меньше либо равна lengthEpsilon и angleEpsilon.\n + 3. Любое угловое, метрическое или параметрическое значение, меньшее GcPrecision::tolerance + считается нулем.\n + 4. Величина newtonEpsilon всегда меньше либо равна min(lengthEpsilon, angleEpsilon).\n 5. Любой элемент матрицы меньший по модулю, чем GcPrecision::m_null - считается нулем. Барьер GcPrecision::m_null влияет на быстродействие и точность разложения - и перемножения матриц. Чем выше m_null, тем быстрее может работать разложение, в ущерб - вычислительной устойчивости.\n + и перемножения матриц. \n + \en The class encapsulates all tolerances and other constants related to - two-dimensional parametrization problems. - \n - 1. For check of metric values or points coincidence in 2D space - tolerance GcPrecision::lengthRegion is used. I.e. any two points - which are not coincident with tolerance GcPrecision::lengthRegion are considered to be different.\n + two-dimensional constraint solving.\n + + 1. For check of distance values or points coincidence in 2D space tolerance + GcPrecision::lengthRegion is used. I.e. any two points which are not coincident with + tolerance GcPrecision::lengthRegion are considered to be different.\n 2. For iterative solvers tolerance of parameter GcPrecision::newtonEpsilon is used. This value is 1-2 orders higher than undistinguishable domain (lengthRegion, angleRegion).\n - 3. Any angular,metric or parametric value less than - GcPrecision::tolerance is considered to be zero.\n - 4. Value newtonEpsilon is always less or equal to lengthEpsilon and angleEpsilon.\n + 3. Any angular, length or parametric value less than GcPrecision::tolerance + is considered to be zero.\n + 4. Value newtonEpsilon is always less or equal to (lengthEpsilon, angleEpsilon).\n 5. Any element of matrix less than GcPrecision::m_null by absolute value is considered - to be zero. Threshold GcPrecision::m_null influences on performance and accuracy of decomposition - and multiplication of matrices. The higher m_null the faster the decomposition can work, to the prejudice of - computational stability.\n \~ + to be zero. \n \~ \nosubgrouping */ // @@ -82,20 +81,20 @@ struct GCE_CLASS GcPrecision \{ */ - const static double m_null; ///< \ru Абсолютная точность, с которой определяется четкий нуль в матрице; \en Absolute tolerance with which the clear zero is determined in matrix; - const static double grshTol; ///< \ru Относительная точность для оценки линейной зависимости при ортогонализации (Грамм-Шмидт) \en Relative tolerance for estimation of linear dependence during orthogonalizaiton (Gram-Schmidt) - const static double tolerance; ///< \ru Точность для проверки на нуль вещественного числа (углового или метрического); \en Tolerance for checking a real number (angular or metric) for zero; - const static double degMetricEps; ///< \ru Метрическая точность для проверки вырожденной геометрии; \en Metric tolerance for checking the geometry for degeneracy; - const static double lengthEpsilon; ///< \ru Вычислительная точность итерационных решателей и конструирования локусов пересечения ( линейная ); \en Computational tolerance of iterative solvers and intersection loci construction (linear); - const static double angleEpsilon; ///< \ru Вычислительная точность итерационных решателей и конструирования локусов пересечения ( угловая ); \en Computational tolerance of iterative solvers and intersection loci construction (angular); + const static double m_null; ///< \ru Абсолютная точность, с которой определяется четкий нуль в матрице. \en Absolute tolerance with which the clear zero is determined in matrix. + const static double grshTol; ///< \ru Относительная точность для оценки линейной зависимости при ортогонализации (Грамм-Шмидт). \en Relative tolerance for estimation of linear dependence during orthogonalizaiton (Gram-Schmidt). + const static double tolerance; ///< \ru Точность для проверки на нуль вещественного числа (углового или метрического). \en Tolerance for checking a real number (angular or metric) for zero. + const static double degMetricEps; ///< \ru Метрическая точность для проверки вырожденной геометрии. \en Metric tolerance for checking the geometry for degeneracy. + const static double lengthEpsilon; ///< \ru Вычислительная точность итерационных решателей в единицах длины. \en Computational tolerance of iterative solvers in the length units. + const static double angleEpsilon; ///< \ru Угловая точность вычислений для итерационных решателей в радианах. \en Angular tolerance in radians for iterative computation. const static double lengthRegion; ///< \ru Неразличимая метрическая область (проверочная точность). \en Indistinguishable metric domain (satisfactory tolerance). const static double angleRegion; ///< \ru Неразличимая угловая область (проверочная точность). \en Indistinguishable angular domain (satisfactory tolerance). - const static double newtonEpsilon; ///< \ru Целевая точность итерационного решателя. \en Target accuracy of the iterative solver. + const static double newtonEpsilon; ///< \ru Целевая точность результата итерационных вычислений. \en Target accuracy of the iterative solution result. const static double newtonRegion; ///< \ru Удовлетворительная точность итерационного решения. \en Satisfactory accuracy of the iterative solution. - const static double paramRegion; ///< \ru Проверочная точность параметра \en Parameter checking tolerance - const static double maxRadius; ///< \ru Максимально возможный радиус для 2d-эскиза \en Maximal possible radius for cutting of 2d-sketch - const static MbGeomTol satisfying; ///< \ru Точность удовлетворенных ограничений; \en Satisfactory accuracy; - const static MbGeomTol newtonTol; ///< \ru Точность решения системы уравнений итерационными методами; \en Tolerance of solving the equation system by iterative methods; + const static double paramRegion; ///< \ru Проверочная точность параметра. \en Parameter checking tolerance. + const static double maxRadius; ///< \ru Максимально возможный радиус для 2d-эскиза. \en Maximal possible radius to deal with a circle in 2d-sketch. + const static MbGeomTol satisfying; ///< \ru Точность удовлетворенных ограничений. \en Satisfactory tolerance. + const static MbGeomTol newtonTol; ///< \ru Точность решения системы уравнений итерационными методами. \en Tolerance of solving the equation system by iterative methods. /** \} @@ -105,10 +104,10 @@ struct GCE_CLASS GcPrecision */ const static double pi2; ///< 2*M_PI (6.18...) - const static double lastReal; ///< \ru "Самое большое" число с плавающей точкой \en "The greatest" float number - const static int iterLimitCount; ///< \ru Предельное количество итераций в численном методе Ньютона \en Limit of iterations in numerical Newton's method + const static double lastReal; ///< \ru "Самое большое" число с плавающей точкой. \en "The greatest" float number. + const static int iterLimitCount; ///< \ru Предельное количество итераций в численном методе Ньютона. \en Limit of iterations in numerical Newton's method. const static int wellIterLimit; ///< \ru Предельное количество итераций в хорошо-сходящихся процессах. \en Limit number of iterations in well-convergent processes. - static TCHAR buff_512[512]; ///< \ru Текстовый буфер размером в 512 байт \en Text buffer of 512 bytes + static TCHAR buff_512[512]; ///< \ru Текстовый буфер размером в 512 байт. \en Text buffer of 512 bytes. /** \} */ diff --git a/C3d/Include/gce_types.h b/C3d/Include/gce_types.h index 39f0c4d..37ffdb4 100644 --- a/C3d/Include/gce_types.h +++ b/C3d/Include/gce_types.h @@ -226,7 +226,7 @@ typedef enum 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_NonUnitScalingFactor = 16, ///< \ru Неединичный коэффициент масштабирования. \en Non unit scaling factor. + GCE_RESULT_AnisotropicScaling = 16, ///< \ru Анизотропное масштабирование. \en Anisotropic scaling. } GCE_result; //---------------------------------------------------------------------------------------- @@ -254,10 +254,9 @@ typedef enum The status of a constraint implies the division of the system into subsets, which are labeled as follows: \n - Constraints marked with the GCE_STATUS_WellConditioned and GCE_STATUS_IllConditioned - statuses together form a group of interrelated constraints, which are usually resolved - without contradiction, but can potentially contradict each other with the presence of - dimensions. \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. @@ -376,7 +375,7 @@ struct GCE_circle }; //---------------------------------------------------------------------------------------- -/// \ru Координаты эллипса. \en Coordinates of a ellipse. +/// \ru Координаты эллипса. \en Coordinates of an ellipse. //--- struct GCE_ellipse { @@ -623,7 +622,7 @@ 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 ) {} + GCE_diagnostic_pars() : consCount( 0 ), inConsCount( 0 ), reductCoef( 0. ) {} }; //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/gcm_blackbox.h b/C3d/Include/gcm_blackbox.h index 52ad5a6..681c31f 100644 --- a/C3d/Include/gcm_blackbox.h +++ b/C3d/Include/gcm_blackbox.h @@ -40,11 +40,11 @@ //--- struct ItGCBlackbox { - /// \ru Выдать независимые геометрические объекты. \en The function collects in the array independent geoms of a blackbox. - virtual void CollectMyInGeoms( IFC_Array & ) const = 0; - /// \ru Выдать зависимые геометрические объекты. \en The function collects in the array dependent geoms of a blackbox. - virtual void CollectMyOutGeoms( IFC_Array & ) const = 0; - /** \brief \ru Рассчитать положение зависимого объекта. + /// \ru Выдать независимые геометрические объекты. \en The function collects in the array independent geoms of a blackbox. + virtual void CollectMyInGeoms( IFC_Array & ) const = 0; + /// \ru Выдать зависимые геометрические объекты. \en The function collects in the array dependent geoms of a blackbox. + virtual void CollectMyOutGeoms( IFC_Array & ) const = 0; + /** \brief \ru Рассчитать положение зависимого объекта. \en Calculate position of a dependent geometric object. \~ \param[in] inPlaces - \ru Позиции независимых объектов, получаемых методом #ItGCBlackbox::CollectMyInGeoms. \en Positions of independed geoms, which are got by #ItGCBlackbox::CollectMyInGeoms.\~ @@ -55,11 +55,11 @@ struct ItGCBlackbox \return \ru true, если функция корректно исполнена. \en true if the function performed succeeded. \~ */ - virtual bool Calculate( const SArray & inPlaces + virtual bool Calculate( const SArray & inPlaces , const ItGeom & depGeom , MbPlacement3D & depPlace ) const = 0; - /// \ru Является ли данный объект зависимым для черного ящика? \en Check if the given geometric item is dependent - virtual bool IsMyOutGeom( const ItGeom & ) const = 0; + /// \ru Является ли данный объект зависимым для черного ящика? \en Check if the given geometric item is dependent + virtual bool IsMyOutGeom( const ItGeom & ) const = 0; /** \brief \ru Сформулировать ограничения для зависимого геометрического объекта. \en Formulate constraints for the dependent geometric object. \~ diff --git a/C3d/Include/gcm_constraint.h b/C3d/Include/gcm_constraint.h index f6e01d2..1a76ff3 100644 --- a/C3d/Include/gcm_constraint.h +++ b/C3d/Include/gcm_constraint.h @@ -229,6 +229,9 @@ public: // (!) The constants below will be removed in a future version (V17 or l static const GCM_angle_type at_Planar = GCM_2D_ANGLE; static const GCM_angle_type at_3D = GCM_3D_ANGLE; +protected: + virtual GCM_scale _ScaleType() const { return GCM_NO_SCALE; } + protected: ItConstraintItem() : m_args() {} ~ItConstraintItem() {} @@ -298,6 +301,7 @@ inline void ItConstraintItem::GetParams( GCM_c_params & pars ) const pars.m_TanChoice = TangencyChoice(); pars.m_AngType = AngleType(); pars.m_RealPar = DimParameter(); + pars.m_scale = _ScaleType(); } //---------------------------------------------------------------------------------------- diff --git a/C3d/Include/gcm_manager.h b/C3d/Include/gcm_manager.h index 96ba797..a7c3f59 100644 --- a/C3d/Include/gcm_manager.h +++ b/C3d/Include/gcm_manager.h @@ -330,7 +330,14 @@ public: /// \ru Добавить геометрический объект в паттерн. \en Add a geometric object to the pattern. MtConstraintId AddGeomToPattern( MtPatternId ptrn, MtArgument ptrnObj, MtParVariant par1 = MtParVariant::undef, MtParVariant par2 = MtParVariant::undef, GCM_scale scale=GCM_RIGID ); - /// \ru Добавить ограничение. \en Add constraint. + /** + \brief \ru Добавить ограничение. + \en Add constraint. + \return \ru Вернет GCM_RESULT_Ok, если ограничение успешно добавлено, + в противном случае вернет код ошибки. + \en Returns GCM_RESULT_Ok if the constraint is successfully added, + otherwise it will return an error code. + */ MtResultCode3D AddConstraintItem( ItConstraintItem & ); /** \brief \ru Добавить сопряжение для пары геометрических объектов(ограничение). @@ -408,7 +415,7 @@ public: */ ItGeom * CreateCluster( std::vector & ); /// \ru Зафиксировать геометрический объект в ГСК. \en Fix geometric object in the WCS. - MtResultCode3D FixGeom( ItGeom & ); + MtResultCode3D FixGeom( const ItGeom * ); /// \ru Узнать зафиксирован ли геометрический объект? \en Check if a geometric object is fixed? bool IsFixed( const ItGeom * ); /// \ru Очистить систему ограничений. \en Clear the system constraint. @@ -620,14 +627,17 @@ public: */ /// \ru Функция будет удалена из API. Использовать ChangeDefinition(). \en The call is deprecated. Use ChangeDefinition() instead this. - MtResultCode3D ChangeAlignCondition( ItConstraintItem & ); - /// \ru Функция будет удалена из API. Использовать Evalute(). \en The call is deprecated. Use ChangeDefinition() instead this. - MtResultCode3D Solve( bool diagQuery ); + MtResultCode3D ChangeAlignCondition( ItConstraintItem & ); + MtResultCode3D FixGeom( ItGeom & ); /** \} */ +//protected: + /// \ru Функция будет удалена из API. Использовать Evalute(). \en The call is deprecated. Use ChangeDefinition() instead this. + MtResultCode3D Solve( bool diagQuery ); + protected: MtGeomSolver(); ~MtGeomSolver(); diff --git a/C3d/Include/gcm_reposition.h b/C3d/Include/gcm_reposition.h index 80a1b2f..b9dc5f3 100644 --- a/C3d/Include/gcm_reposition.h +++ b/C3d/Include/gcm_reposition.h @@ -79,6 +79,9 @@ struct ItPositionManager virtual refcount_t AddRef() const = 0; /// \ru Удалить ссылку \en Release reference virtual refcount_t Release() const = 0; + +protected: + ~ItPositionManager() {} }; /** \} */ // GCM_3D_ObjectAPI diff --git a/C3d/Include/gcm_res_code.h b/C3d/Include/gcm_res_code.h index 8f33b3a..71eb7e4 100644 --- a/C3d/Include/gcm_res_code.h +++ b/C3d/Include/gcm_res_code.h @@ -53,7 +53,7 @@ inline int PriorityLevel( GCM_result resCode ) 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. + case GCM_RESULT_DependedGeomCantBeFixed: // The depended geom can't be fixed. return 8; case GCM_RESULT_CyclicDependence: // \ru Задана циклическая зависимость \en Given a cyclic dependence diff --git a/C3d/Include/generic_utility.h b/C3d/Include/generic_utility.h index 569bab2..1f5712b 100644 --- a/C3d/Include/generic_utility.h +++ b/C3d/Include/generic_utility.h @@ -1111,6 +1111,15 @@ 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 @@ -1120,6 +1129,20 @@ namespace c3d 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; +}; + //---------------------------------------------------------------------------------------- // Диапазон итераторов //--- @@ -1127,18 +1150,20 @@ template struct range : public std::pair { typedef std::pair _Pair; - typedef typename Iterator::value_type value_type; + 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() { return _Pair::first; } - Iterator end() { return _Pair::second; } + 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; } - //value_type & front() { return *first; } - const value_type & front() const { return *_Pair::first; } + range & move_front() { ++_Pair::first; return *this; } + + const value_type & front() const { return (*begin()); } + const value_type & back() const { return (*(end() - 1)); } }; //---------------------------------------------------------------------------------------- @@ -1151,6 +1176,16 @@ range range_of( const _Cont & list ) 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 diff --git a/C3d/Include/hash32.h b/C3d/Include/hash32.h index be2eeda..992f359 100644 --- a/C3d/Include/hash32.h +++ b/C3d/Include/hash32.h @@ -19,11 +19,12 @@ class reader; //////////////////////////////////////////////////////////////////////////////// // -// \ru Oпределение простого имени \en Definition of simple name +// \ru Определение простого имени \en Definition of simple name // //////////////////////////////////////////////////////////////////////////////// -// Activate to check compilation // #define SIMPLENAME_AS_CLASS +// Activate to check compilation +// #define SIMPLENAME_AS_CLASS #ifndef SIMPLENAME_AS_CLASS @@ -43,7 +44,10 @@ typedef uint32 SimpleName; \ingroup Base_Tools */ // --- -inline int SimpleNameCompare( const SimpleName & h1, const SimpleName & h2 ) { return ( (h1 > h2) ? 1 : ( (h1 < h2) ? -1 : 0 ) ); } +inline +int SimpleNameCompare( const SimpleName & h1, const SimpleName & h2 ) { + return ( (h1 > h2) ? 1 : ( (h1 < h2) ? -1 : 0 ) ); +} //------------------------------------------------------------------------------ @@ -59,7 +63,9 @@ bool IsGoodSimpleName( const SimpleName & s ) { #else // SIMPLENAME_AS_CLASS -// \ru При активации этой ветки обязательно собрать проект с активацией максимального уровеня предупреждений \en When this branch is activated, the project must be rebuilt with the highest level of warnings activated +#include + +// \ru При активации этой ветки обязательно собрать проект с активацией максимального уровня предупреждений \en When this branch is activated, the project must be rebuilt with the highest level of warnings activated class SimpleName { protected: @@ -71,7 +77,7 @@ public: SimpleName( const SimpleName & other ) : body( SYS_MAX_UINT32 ) { body = other.body; } SimpleName( size_t other ) : body( SYS_MAX_UINT32 ) { body = other; } - // \ru операторы копирования \en copy operators + // \ru операторы копирования \en copy operators SimpleName & operator = ( const SimpleName & other ) { body = other.body; return *this; } SimpleName & operator = ( size_t other ) { body = other; return *this; } @@ -84,16 +90,23 @@ public: bool operator <= ( const SimpleName & other ) const { return Сompare( other.body ) <= 0; } SimpleName operator + ( size_t other ) const { return SimpleName( body + (size_t)other ); } - SimpleName operator * ( size_t other ) const { return SimpleName( body * (size_t)other ); } + SimpleName operator - ( size_t other ) const + { + C3D_ASSERT( body >= other ); + return SimpleName( body - (size_t)other ); + } + + SimpleName operator * ( size_t other ) const { return SimpleName( body * other ); } SimpleName & operator += ( size_t other ) { body += (size_t)other; return *this; } SimpleName & operator *= ( size_t other ) { body *= (size_t)other; return *this; } SimpleName & operator |= ( size_t other ) { body |= (size_t)other; return *this; } - SimpleName & operator ++ () { ++body; return *this; } // pre increment - SimpleName operator ++ ( int ) { size_t _tmp = body; ++body; return _tmp; } // post increment + SimpleName & operator ++ () { ++body; return *this; } // pre increment + SimpleName operator ++ ( int ) { size_t _tmp = body; ++body; return _tmp; } // post increment // \ru доступ к данным \en access to data operator bool () const { return body != 0 && body != SYS_MAX_UINT32; } operator size_t() const { return (size_t)body; } + operator ptrdiff_t() const { return (ptrdiff_t)body; } // service int Сompare( const SimpleName & other ) const { return Сompare( other.body ); } // return value [-1; 0; +1] protected: @@ -110,6 +123,9 @@ inline void SwapIT( SimpleName & a, SimpleName & b ) { SimpleName tmp = a; a = b #endif // SIMPLENAME_AS_CLASS +namespace c3d // namespace C3D +{ + /** \addtogroup Base_Tools \{ */ @@ -119,21 +135,21 @@ inline void SwapIT( SimpleName & a, SimpleName & b ) { SimpleName tmp = a; a = b \en Maximum allowable simple name. \~ */ //--- -const SimpleName SIMPLENAME_MAX = SYS_MAX_UINT32; +const SimpleName SIMPLENAME_MAX = size_t(SYS_MAX_UINT32); //------------------------------------------------------------------------------ /** \brief \ru Значение используемое, в качестве "неопределенного", еще не назначенного имени. \en A value is used as "undefined", not yet assigned name. \~ */ //--- -const SimpleName UNDEFINED_SNAME = SYS_MAX_UINT32; +const SimpleName UNDEFINED_SNAME = size_t(SYS_MAX_UINT32); //------------------------------------------------------------------------------ /** \brief \ru Начальное число для хэш-функции. \en The initial value for the hash-function. \~ */ // --- -const SimpleName INIT_HASH32_VAL = 31415926; +const SimpleName INIT_HASH32_VAL = size_t( 31415926 ); //------------------------------------------------------------------------------ @@ -141,7 +157,7 @@ const SimpleName INIT_HASH32_VAL = 31415926; \en Golden section - an arbitrary number for hash-function. \~ */ // --- -#define GOLDENRATIO 0x9e3779b9 +const_expr uint GOLDENRATIO = 0x9e3779b9; /** \} @@ -158,7 +174,8 @@ const SimpleName INIT_HASH32_VAL = 31415926; // \ru Обратимая 32-битная смесь для любых трёх 32-битных чисел a, b, c. \en Invertible 32-bit mixture for any three 32-bit numbers a, b, c. // \ru Вероятность изменения значений в любом случае равна как минимум одной четвёртой. \en In any case the probability of values modification is equal to 1/4 at least. // --- -static void mix( uint & a, uint & b, uint & c ) +inline +void mix( uint & a, uint & b, uint & c ) { a -= b; a -= c; a ^= (c >> 13); b -= c; b -= a; b ^= (a << 8 ); @@ -175,7 +192,7 @@ static void mix( uint & a, uint & b, uint & c ) //------------------------------------------------------------------------------ /** \brief \ru Хэш-функция. \en Hash-function. \~ - \details \ru Хэш по последовательности байти и предыдущему хэшу. \n + \details \ru Хэш по последовательности байт и предыдущему хэшу. \n Каждый бит k влияет на возвращаемое значение. \n Функция плохо подходит для использования в криптографии. \n k - Указатель на начало последовательности байт. \n @@ -192,7 +209,8 @@ static void mix( uint & a, uint & b, uint & c ) \ingroup Base_Tools */ // --- -inline SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_VAL ) +inline +SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_VAL ) { PRECONDITION( HiUint32( length ) == 0 ); @@ -244,9 +262,6 @@ inline SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_ } -#undef GOLDENRATIO - - //------------------------------------------------------------------------------ /** \brief \ru Хэш указателя. \en Hash of the pointer. \~ @@ -256,7 +271,7 @@ inline SimpleName Hash32( uint8 * k, size_t length, SimpleName _c = INIT_HASH32_ */ // --- template -SimpleName Hash32Ptr( T * k ) { return ::Hash32( reinterpret_cast(&k), sizeof(T*) ); } +SimpleName Hash32Ptr( T * k ) { return c3d::Hash32( reinterpret_cast(&k), sizeof(T*) ); } //------------------------------------------------------------------------------ @@ -267,8 +282,9 @@ SimpleName Hash32Ptr( T * k ) { return ::Hash32( reinterpret_cast(&k), \ingroup Base_Tools */ // --- -inline SimpleName HashStr( const c3d::string_t & str ) { - return ::Hash32( (uint8*)str.c_str(), str.length() * sizeof(TCHAR) ); +inline +SimpleName HashStr( const c3d::string_t & str ) { + return c3d::Hash32( (uint8*)str.c_str(), str.length() * sizeof(TCHAR) ); } @@ -284,7 +300,7 @@ inline SimpleName HashStr( const char * c_str ) { PRECONDITION( c_str ); - return ::Hash32( (uint8*)c_str, strlen(c_str) * sizeof(char) ); + return c3d::Hash32( (uint8*)c_str, strlen(c_str) * sizeof(char) ); } @@ -301,11 +317,11 @@ SimpleName HashStr( const wchar_t * w_str ) { PRECONDITION( w_str ); #ifndef __MOBILE_VERSION__ - return ::Hash32( (uint8*)w_str, wcslen(w_str) * sizeof(wchar_t) ); + return c3d::Hash32( (uint8*)w_str, wcslen(w_str) * sizeof(wchar_t) ); #else // __MOBILE_VERSION__ uint16 * hashBuf = Ucs4ToUtf16((uint32*)w_str); uint16 * hashBufPointer = hashBuf; - SimpleName hash = ::Hash32( (uint8*)hashBufPointer, wcslen(w_str) * 2 ); + SimpleName hash = c3d::Hash32( (uint8*)hashBufPointer, wcslen(w_str) * 2 ); delete[] hashBuf; return hash; #endif // __MOBILE_VERSION__ @@ -322,7 +338,7 @@ SimpleName HashStr( const wchar_t * w_str ) \ingroup Base_Tools */ // --- -class StrHash { +class StrHash { public: /// \ru Тип строки-источника имени. \en Type of the source string of name. enum StrHashType { @@ -342,13 +358,13 @@ public: {} /// \ru Конструктор по строке. \en Constructor by string. StrHash ( const char * str ) - : m_val ( ::HashStr(str) ) - , m_type( htp_char ) + : m_val ( c3d::HashStr(str) ) + , m_type( htp_char ) {} /// \ru Конструктор по строке. \en Constructor by string. StrHash ( const wchar_t * str ) - : m_val ( ::HashStr(str) ) - , m_type( htp_wchar ) + : m_val ( c3d::HashStr(str) ) + , m_type( htp_wchar ) {} SimpleName GetVal() const { return m_val; } ///< \ru Получить значение. \en Get the value. @@ -359,8 +375,8 @@ public: int operator == ( const wchar_t * with ) const; ///< \ru Оператор равенства. \en Equality operator. // \ru Чтение-запись \en Reading-writing - friend writer & operator << ( writer &, const StrHash & strHash ); ///< \ru Оператор записи. \en Write operator. - friend reader & operator >> ( reader &, StrHash & strHash ); ///< \ru Оператор чтения. \en Read operator. + friend writer & operator << ( writer &, const c3d::StrHash & strHash ); ///< \ru Оператор записи. \en Write operator. + friend reader & operator >> ( reader &, c3d::StrHash & strHash ); ///< \ru Оператор чтения. \en Read operator. }; @@ -372,7 +388,7 @@ public: \ingroup Base_Tools */ // --- -#define NullStrHash StrHash( 0, StrHash::htp_undef ) +const StrHash NullStrHash( 0, StrHash::htp_undef ); //------------------------------------------------------------------------------ @@ -383,7 +399,7 @@ public: \ingroup Base_Tools */ // --- -#define UndefStrHash StrHash( -1, StrHash::htp_undef ) +const StrHash UndefStrHash( -1, StrHash::htp_undef ); //------------------------------------------------------------------------------ @@ -396,7 +412,8 @@ public: \ingroup Base_Tools */ // --- -inline SimpleName Hash32SN( SimpleName k1, SimpleName k2 ) +inline +SimpleName Hash32SN( SimpleName k1, SimpleName k2 ) { //SimpleName array[] = { k1, k2 }; uint arr[2]; @@ -407,7 +424,7 @@ inline SimpleName Hash32SN( SimpleName k1, SimpleName k2 ) arr[0] = LoUint32( (size_t)k1 ); arr[1] = LoUint32( (size_t)k2 ); #endif // SIMPLENAME_AS_CLASS - return ::Hash32( (uint8*)arr, 2 * sizeof(uint) ); // \ru длина - 4 * 2 = 8 \en length - 4 * 2 = 8 + return c3d::Hash32( (uint8*)arr, 2 * sizeof(uint) ); // \ru длина - 4 * 2 = 8 \en length - 4 * 2 = 8 } @@ -451,6 +468,8 @@ inline int StrHash::operator == ( const wchar_t * with ) const return *this == StrHash( with ); } +} // namespace C3D + #endif // __HASH32_H diff --git a/C3d/Include/iges_basic.h b/C3d/Include/iges_basic.h index d09ffea..e1bcdaf 100644 --- a/C3d/Include/iges_basic.h +++ b/C3d/Include/iges_basic.h @@ -217,7 +217,7 @@ struct DirEntryParameter { } bool operator == ( DirEntryParameter & o ) const { return numbString == o.numbString; } - bool operator < ( DirEntryParameter & o ) const { return numbString < o.numbString; } + bool operator < ( DirEntryParameter & o ) const { return numbString < o.numbString; } }; diff --git a/C3d/Include/instance.h b/C3d/Include/instance.h index e608a0e..4f883dd 100644 --- a/C3d/Include/instance.h +++ b/C3d/Include/instance.h @@ -1,185 +1,185 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Вставка объекта. - \en Instance of object. \~ - \details \ru Вставка объекта геометрической модели MbItem в локальной системе координат MbPlacement3D - позволяет накладывать геометрические ограничения на объект в сборке и позиционоровать объект. - Вставка не может содержать другую вставку. \n - \en The instance of geometric model MbItem object in local coordinate system MbPlacement3D - allows to define constraints for an object in the assembly and to locate the object. - The instance cannot contain another instance. \n \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __INSTANCE_H -#define __INSTANCE_H - -#include -#include - - -class MATH_CLASS MbSolid; -class MATH_CLASS MbInstance; -class MATH_CLASS MbAssembly; - -namespace c3d // namespace C3D -{ -typedef SPtr InstanceSPtr; -typedef SPtr ConstInstanceSPtr; - -typedef std::vector InstancesVector; -typedef std::vector ConstInstancesVector; - -typedef std::vector InstancesSPtrVector; -typedef std::vector ConstInstancesSPtrVector; -} - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вставка объекта. - \en Instance of object. \~ - \details \ru Вставка объекта геометрической модели MbItem в локальной системе координат MbPlacement3D - позволяет накладывать геометрические ограничения на объект в сборке и позиционоровать объект. - Вставка не может содержать другую вставку. \n - \en The instance of geometric model MbItem object in local coordinate system MbPlacement3D - allows to define constraints for an object in the assembly and to locate the object. - The instance cannot contain another instance. \n \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbInstance : public MbItem -{ - MbPlacement3D place; ///< \ru Локальная система координат объекта. \en Local coordinate system of the object. - SPtr item; ///< \ru Геометрический объект. \en A geometric object. - -protected : - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbInstance( const MbInstance &, MbRegDuplicate * ); - -public : - /// \ru Конструктор по объекту и его системе координат. \en The constructor by an object and its coordinate system. - MbInstance( MbItem &, const MbPlacement3D & ); - /// \ru Деструктор. \en Destructor. - virtual ~MbInstance(); - -public : - VISITING_CLASS( MbInstance ); - - // \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 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. - virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. - 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 MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create own 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. - - // \ru Получить систему координат объекта. \en Get the coordinate system of an item. - virtual bool GetPlacement( MbPlacement3D & ) const; - // \ru Установить систему координат объекта. \en Set the coordinate system of an item. - virtual bool SetPlacement( const MbPlacement3D & ); - - // \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 Добавить полигонную сетку объекта. \en Add a polygon mesh of the object. - virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; - // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. - virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; - // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. - 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; - // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ - virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, - RPArray & items, SArray & matrs ); - // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ - virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; - // \ru Дать объект по его пути положения в модели и матрицу преобразования объекта в глобальную систему координат. \en Get the object by its path in the model and get the matrix of transformation of the object to the global coordinate system. - virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; - - // \ru Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Найти объект и матрицу его преобразования в глобальную систему координат. \en Find the object and the matrix of its transformation to the global coordinate system. - virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Дать объект с заданным именем и матрицу его преобразования в глобальную систему координат. \en Get the object with the specified name and the matrix of its transformation to the global coordinate system. - 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 ); - // \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 ); - // \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 ); - - /// \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 \name Функции вставки объекта. - \en \name Functions of the object instance. - \{ */ - /// \ru Выдать геометрический объект. \en Get the geometric object. - const MbItem * GetItem() const { return item; } - /// \ru Выдать геометрический объект для модификации. \en Get the geometric object for modification. - MbItem * SetItem() { return item; } - /// \ru Установить другой геометрический объект. \en Set another geometric object. - void SetItem( MbItem * init ); - - /** \brief \ru Заменить объект. - \en Replace an item. \~ - \details \ru Заменить объект новым. - \en Replace an item by a new one. \~ - \param[in] item - \ru Заменяемый объект. - \en An item to be replaced. \~ - \param[in] newItem - \ru Новый объект. - \en A new item. \~ - \return \ru Возвращает true, если замена была выполнена. - \en Returns true if the replacement has been performed. \~ - */ - bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); - - /// \ru Выдать количество граней. \en Get the number of faces. - size_t GetFacesCount() const; - /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. - template - void GetFacesSet( FacesVector & faces ) const; - /// \ru Выдать систему координат объекта. \en Get the coordinate system of an item. - const MbPlacement3D & GetPlacement() const { return place; } - /// \ru Выдать систему координат объекта для редактирования. \en Get the coordinate system of an assembly item for editing. - MbPlacement3D & SetPlacement() { return place; } - - /** \} */ - -private: - // Найти объект по геометрическому объекту - template - const MbItem * _FindItem( const _ItemType * s, MbPath & path, MbMatrix3D & from ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbInstance ) ; - OBVIOUS_PRIVATE_COPY( MbInstance ); -}; - -IMPL_PERSISTENT_OPS( MbInstance ) - - -#endif +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вставка объекта. + \en Instance of object. \~ + \details \ru Вставка объекта геометрической модели MbItem в локальной системе координат MbPlacement3D + позволяет накладывать геометрические ограничения на объект в сборке и позиционоровать объект. + Вставка не может содержать другую вставку. \n + \en The instance of geometric model MbItem object in local coordinate system MbPlacement3D + allows to define constraints for an object in the assembly and to locate the object. + The instance cannot contain another instance. \n \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __INSTANCE_H +#define __INSTANCE_H + +#include +#include + + +class MATH_CLASS MbSolid; +class MATH_CLASS MbInstance; +class MATH_CLASS MbAssembly; + +namespace c3d // namespace C3D +{ +typedef SPtr InstanceSPtr; +typedef SPtr ConstInstanceSPtr; + +typedef std::vector InstancesVector; +typedef std::vector ConstInstancesVector; + +typedef std::vector InstancesSPtrVector; +typedef std::vector ConstInstancesSPtrVector; +} + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вставка объекта. + \en Instance of object. \~ + \details \ru Вставка объекта геометрической модели MbItem в локальной системе координат MbPlacement3D + позволяет накладывать геометрические ограничения на объект в сборке и позиционоровать объект. + Вставка не может содержать другую вставку. \n + \en The instance of geometric model MbItem object in local coordinate system MbPlacement3D + allows to define constraints for an object in the assembly and to locate the object. + The instance cannot contain another instance. \n \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbInstance : public MbItem +{ + MbPlacement3D place; ///< \ru Локальная система координат объекта. \en Local coordinate system of the object. + SPtr item; ///< \ru Геометрический объект. \en A geometric object. + +protected : + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbInstance( const MbInstance &, MbRegDuplicate * ); + +public : + /// \ru Конструктор по объекту и его системе координат. \en The constructor by an object and its coordinate system. + MbInstance( MbItem &, const MbPlacement3D & ); + /// \ru Деструктор. \en Destructor. + virtual ~MbInstance(); + +public : + VISITING_CLASS( MbInstance ); + + // \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 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. + virtual double DistanceToPoint ( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add own bounding box to the bounding box. + 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 MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create own 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. + + // \ru Получить систему координат объекта. \en Get the coordinate system of an item. + virtual bool GetPlacement( MbPlacement3D & ) const; + // \ru Установить систему координат объекта. \en Set the coordinate system of an item. + virtual bool SetPlacement( const MbPlacement3D & ); + + // \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 Добавить полигонную сетку объекта. \en Add a polygon mesh of the object. + virtual bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; + // \ru Разрезать полигональный объект одной или двумя параллельными плоскостями. \en Cut the polygonal object by one or two parallel planes. + virtual MbItem * CutMesh( const MbPlacement3D & cutPlace, double distance ) const; + // \ru Найти ближайший объект или имя ближайшего объекта. \en Find the closest object or its name. + 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; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + RPArray & items, SArray & matrs ); + // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ + virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; + // \ru Дать объект по его пути положения в модели и матрицу преобразования объекта в глобальную систему координат. \en Get the object by its path in the model and get the matrix of transformation of the object to the global coordinate system. + virtual const MbItem * GetItemByPath( const MbPath & path, size_t ind, MbMatrix3D & from, size_t currInd = 0 ) const; + + // \ru Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Найти объект и матрицу его преобразования в глобальную систему координат. \en Find the object and the matrix of its transformation to the global coordinate system. + virtual const MbItem * FindItem( const MbItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Дать объект с заданным именем и матрицу его преобразования в глобальную систему координат. \en Get the object with the specified name and the matrix of its transformation to the global coordinate system. + 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 ); + // \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 ); + // \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 ); + + /// \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 \name Функции вставки объекта. + \en \name Functions of the object instance. + \{ */ + /// \ru Выдать геометрический объект. \en Get the geometric object. + const MbItem * GetItem() const { return item; } + /// \ru Выдать геометрический объект для модификации. \en Get the geometric object for modification. + MbItem * SetItem() { return item; } + /// \ru Установить другой геометрический объект. \en Set another geometric object. + void SetItem( MbItem * init ); + + /** \brief \ru Заменить объект. + \en Replace an item. \~ + \details \ru Заменить объект новым. + \en Replace an item by a new one. \~ + \param[in] item - \ru Заменяемый объект. + \en An item to be replaced. \~ + \param[in] newItem - \ru Новый объект. + \en A new item. \~ + \return \ru Возвращает true, если замена была выполнена. + \en Returns true if the replacement has been performed. \~ + */ + bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); + + /// \ru Выдать количество граней. \en Get the number of faces. + size_t GetFacesCount() const; + /// \ru Заполнить контейнер гранями тела. \en Fill container by solid faces. + template + void GetFacesSet( FacesVector & faces ) const; + /// \ru Выдать систему координат объекта. \en Get the coordinate system of an item. + const MbPlacement3D & GetPlacement() const { return place; } + /// \ru Выдать систему координат объекта для редактирования. \en Get the coordinate system of an assembly item for editing. + MbPlacement3D & SetPlacement() { return place; } + + /** \} */ + +private: + // Найти объект по геометрическому объекту + template + const MbItem * _FindItem( const _ItemType * s, MbPath & path, MbMatrix3D & from ) const; + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbInstance ) +OBVIOUS_PRIVATE_COPY( MbInstance ) +}; + +IMPL_PERSISTENT_OPS( MbInstance ) + + +#endif diff --git a/C3d/Include/io_memory_buffer.h b/C3d/Include/io_memory_buffer.h index ececdfb..5a19467 100644 --- a/C3d/Include/io_memory_buffer.h +++ b/C3d/Include/io_memory_buffer.h @@ -25,13 +25,6 @@ class reader; class writer; -//------------------------------------------------------------------------------ -/// \ru Размер кластера по умолчанию. \en Cluster size by default. \~ \ingroup Base_Tools_IO -//--- -const uint16 DEFCLSIZE = 0x1000; -// \ru САА K13 12.5.2011 Увеличил размер кластера по умолчанию - параллельное перестроение видов. \en САА K13 12.5.2011 Increased cluster size by default - parallel rebuilding of views. -// \ru САА K13 12.5.2011 const uint16 DEFCLSIZE = 256; \en САА K13 12.5.2011 const uint16 DEFCLSIZE = 256; - //------------------------------------------------------------------------------ /** \brief \ru Потоковый буфер памяти. @@ -103,7 +96,7 @@ public: /// 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. - size_t toMemory( const char *& memory, size_t addSize = 0 ) const; + size_t toMemory( const char *& memory, size_t addSize = 0 ) const; /// \ru Прочитать из непрерывной памяти. \en Read from the contiguous memory. bool fromMemory( const char * memory ); /// \ru Вычислить необходимую длину непрерывного куска памяти для буфера. \en Compute the necessary length of the contiguous memory block for a buffer. diff --git a/C3d/Include/io_tape.h b/C3d/Include/io_tape.h index b0cc193..9639de6 100644 --- a/C3d/Include/io_tape.h +++ b/C3d/Include/io_tape.h @@ -1252,40 +1252,7 @@ void WriteVBase( writer & out, const Base * base ) \ingroup Base_Tools_IO */ // --- -#ifdef __BORLANDC__ -#define IMPL_PERSISTENT_OPS( Class ) \ - inline reader & CALL_DECLARATION operator >> ( reader & in, Class & ref ) { \ - in.readObject( dynamic_cast(&ref) ); \ - return in; \ - } \ - inline reader & CALL_DECLARATION operator >> ( reader & in, Class *& ptr ) { \ - ptr = dynamic_cast( in.readObjectPointer() ); \ - return in; \ - } \ - inline reader & CALL_DECLARATION operator >> ( reader & in, const Class *& ptr ) \ - { \ - ptr = dynamic_cast( in.readObjectPointer() ); \ - return in; \ - } \ - inline writer & CALL_DECLARATION operator << ( writer & out, const Class & ref ) { \ - out.writeObject( dynamic_cast(&ref) ); \ - return out; \ - } \ - inline writer & CALL_DECLARATION operator << ( writer & out, const Class * ptr ) { \ - out.writeObjectPointer( dynamic_cast(ptr) ); \ - return out; \ - } \ - inline writer & CALL_DECLARATION operator << ( writer & out, Class & ref ) { \ - out.writeObject( dynamic_cast(&ref) ); \ - return out; \ - } \ - inline writer & CALL_DECLARATION operator << ( writer& out, Class * ptr ) { \ - out.writeObjectPointer( dynamic_cast(ptr) ); \ - return out; \ - } -#else #define IMPL_PERSISTENT_OPS( Class ) -#endif //---------------------------------------------------------------------------------------- /** @@ -1492,7 +1459,21 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version // \ru или ptr->operator Class*()->F(); \n \en or ptr->operator Class*()->F(); \n // \ru Для ссылок так же. \en Similarly for references. // --- - #define DECLARE_NEW_DELETE_CLASS( Class ) \ + #define DECLARE_NEW_DELETE_CLASS( Class ) + + //-------------------------------------------------------------------------------------- + /// \ru Реализация функций new, delete и операторов доступа. \en Implementation of functions new, delete and access operators. \~ \ingroup Base_Tools_IO + // --- + #define IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) + + //-------------------------------------------------------------------------------------- + /// \ru Объявление операторов new и delete, обеспечивающих последовательное обращение + /// к функциям выделения/освобождения памяти из разных потоков. + /// \en Declaration of new and delete operators which provide sequential access + /// to the allocation/deallocation functions from different threads. \~ + /// \ingroup Base_Tools_IO + // --- + #define DECLARE_NEW_DELETE_CLASS_EX( Class ) \ public: \ void * operator new ( size_t ); \ void operator delete ( void *, size_t ); \ @@ -1500,9 +1481,13 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version void operator delete [] ( void * ); //-------------------------------------------------------------------------------------- - /// \ru Реализация функций new, delete и операторов доступа. \en Implementation of functions new, delete and access operators. \~ \ingroup Base_Tools_IO + /// \ru Реализация операторов new и delete, обеспечивающих последовательное обращение + /// к функциям выделения/освобождения памяти из разных потоков. + /// \en Implementation of new and delete operators which provide sequential access + /// to the allocation/deallocation functions from different threads. \~ + /// \ingroup Base_Tools_IO // --- - #define IMP_PERSISTENT_NEW_DELETE_CLASS( Class ) \ + #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) \ void * Class::operator new( size_t size ) { \ return ::Allocate( size, typeid(Class).name() ); } \ void Class::operator delete ( void *ptr, size_t size ) { \ @@ -1513,24 +1498,6 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version void Class::operator delete[] ( void *ptr ) { \ ::FreeArray( ptr, typeid(Class[]).name() ); } - //-------------------------------------------------------------------------------------- - /// \ru Объявление операторов new и delete, обеспечивающих последовательное обращение - /// к функциям выделения/освобождения памяти из разных потоков. - /// \en Declaration of new and delete operators which provide sequential access - /// to the allocation/deallocation functions from different threads. \~ - /// \ingroup Base_Tools_IO - // --- - #define DECLARE_NEW_DELETE_CLASS_EX( Class ) - - //-------------------------------------------------------------------------------------- - /// \ru Реализация операторов new и delete, обеспечивающих последовательное обращение - /// к функциям выделения/освобождения памяти из разных потоков. - /// \en Implementation of new and delete operators which provide sequential access - /// to the allocation/deallocation functions from different threads. \~ - /// \ingroup Base_Tools_IO - // --- - #define IMP_PERSISTENT_NEW_DELETE_CLASS_EX( Class ) - #else // __DEBUG_MEMORY_ALLOCATE_FREE_ //-------------------------------------------------------------------------------------- /// \ru Объявление функций new, delete и операторов доступа. \en Declaration of functions new, delete and access operators. \~ \ingroup Base_Tools_IO @@ -1663,8 +1630,6 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version \ingroup Base_Tools_IO */ // --- -#ifndef __BORLANDC__ - #define DECLARE_PERSISTENT_CLASS( Class ) \ DECLARE_PERSISTENT_FUNCS( Class ); \ DECLARE_PERSISTENT_OPS( Class ); \ @@ -1672,17 +1637,6 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version DECLARE_NEW_DELETE_CLASS( Class ); \ DECLARE_CLASS_DESC_FUNC(Class) -#else // __BORLAND__ - -#define DECLARE_PERSISTENT_CLASS( Class ) \ - DECLARE_PERSISTENT_FUNCS( Class ); \ - DECLARE_PERSISTENT_OPS_B( Class ); \ - DECLARE_PERSISTENT_CTOR( Class ); \ - DECLARE_NEW_DELETE_CLASS( Class ); \ - DECLARE_CLASS_DESC_FUNC(Class) - -#endif // __BORLAND__ - /** \brief \ru Аналог макроса DECLARE_PERSISTENT_CLASS с возможностью перегрузки операторов new/delete, обеспечивающий последовательное обращение к функциям @@ -1958,7 +1912,6 @@ ClassDescriptor TapeClassForNewObjects::GetPackedClassNameForWrite( long version // \ru Выдаваемые значения \en Returned values // MS Visual C++ 6.0 ... 2010: "class CLASS_A" // gcc (Linux): "7CLASS_A" -// BORLAND C++ 5.0: "CLASS_A" // Embarcadero C++ 7.20 for Win32 "$CLASS_A" // \ru Интересующая нас функция должна выдавать "CLASS_A" \en The desired function must write "CLASS_A" // --- @@ -1971,11 +1924,6 @@ inline const char * pureName( const char * name ) ptrdiff_t i = strlen(name) - 1; for ( ; i >= 0 && name[i] != ' '; i-- ); return ((i >= 0) && (name[i] == ' ')) ? &(name[i+1]) : name; -#elif __BORLANDC__ - // \ru убираем "$" в начале строки \en remove "$" at the beginning of the string - for ( size_t i = 0, c = strlen(name); i < c; i++ ) - if ( name[i] != '$' ) - return &(name[i]); #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++ ) @@ -2098,9 +2046,9 @@ inline reader & __readWchar( reader & ps, TCHAR * & s ) #if __SIZEOF_WCHAR_T__ == 2 // sizeof(wchar_t) == sizeof(uint16) s = wcsnewmbs( (const wchar_t*)readBuf ); // \ru Конвертировать WCHAR в CHAR строку. \en Convert WCHAR-string to CHAR-string. #else // sizeof(wchar_t) == sizeof(uint32) - uint32* readBuf32 = Utf16ToUcs4(readBuf); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR - s = wcsnewmbs( (const wchar_t*)readBuf32 ); // \ru Конвертировать WCHAR в CHAR строку. \en Convert WCHAR-string to CHAR-string. - delete [] readBuf32; + uint32* readBuf32 = Utf16ToUcs4(readBuf); // \ru Конвертировать UTF-16 в WCHAR \en Convert from UTF-16 to WCHAR + s = wcsnewmbs( (const wchar_t*)readBuf32 ); // \ru Конвертировать WCHAR в CHAR строку. \en Convert WCHAR-string to CHAR-string. + delete [] readBuf32; #endif delete [] readBuf; #endif // _UNICODE @@ -3000,7 +2948,7 @@ inline size_t ReadCOUNT ( void * in, VERSION version ) MATH_FUNC (ClassDescriptor) GetPackedClassName( const ClassDescriptor &, const VersionContainer & ver ); -#ifdef STANDARD_C11 +#ifdef C3D_STANDARD_CXX_11_PARTIAL //---------------------------------------------------------------------------------------- /** Добавить новое соответствие значения хэша записанного в поток упакованному имени класса @@ -3012,44 +2960,7 @@ MATH_FUNC (ClassDescriptor) GetPackedClassName( const ClassDescriptor &, const V */ // --- MATH_FUNC (void) AddPackedClassNameForVersion( const ClassDescriptor & newClassName, const ClassDescriptor & oldClassName, uint appIndex, VERSION lowVersion, VERSION highVersion ); -#endif //STANDARD_C11 - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru для получения дампа значений Hash Value в файле hash_GRP.txt(hash_VIE.txt) \en for getting dump of Hash Value values in file hash_GRP.txt(hash_VIE.txt) -// \ru необходимо раскоментарить этот комментарий \en this comment should be uncommented -// -//////////////////////////////////////////////////////////////////////////////// -#ifdef C3D_DEBUG -//#define HASH_DOCUMENTATION -#endif - -#ifdef HASH_DOCUMENTATION - -#include - -inline void HashDocumentationOut( uint16 hashValue, const char * name, bool unique ) -{ - static uint st_calls = 0; - - const char * outName = "C:\\Logs\\hash_GRP.txt"; - std::ofstream out( outName, st_calls ? (std::ios::out|std::ios::app) : std::ios::out ); - - std::string sname( name ); - - out << _T("\t") << uint16(hashValue) << _T("\t\t") << sname.c_str(); - if ( !unique ) - out << _T("\tNOT UNIQUE!!!"); - out << _T("\n"); - - st_calls++; -} - -#endif // HASH_DOCUMENTATION - -#undef HASH_DOCUMENTATION - +#endif // C3D_STANDARD_CXX_11_PARTIAL #ifndef SIMPLENAME_AS_CLASS @@ -3069,7 +2980,8 @@ inline SimpleName ReadSimpleName( reader & in ) { SimpleName s = 0; in >> s; ret //---------------------------------------------------------------------------------------- /// \ru Запись простого имени. \en Writing of a simple name. \~ \ingroup Base_Tools_IO // --- -inline void WriteSimpleName( writer & out, const SimpleName & s ) +inline +void WriteSimpleName( writer & out, const SimpleName & s ) { size_t sn = s; WriteCOUNT( out, sn ); @@ -3078,7 +2990,8 @@ inline void WriteSimpleName( writer & out, const SimpleName & s ) //---------------------------------------------------------------------------------------- /// \ru Чтение простого имени. \en Reading of a simple name. \~ \ingroup Base_Tools_IO // --- -inline SimpleName ReadSimpleName( reader & in ) +inline +SimpleName ReadSimpleName( reader & in ) { size_t sn = ReadCOUNT( in ); return SimpleName(sn); @@ -3086,6 +2999,8 @@ inline SimpleName ReadSimpleName( reader & in ) #endif // SIMPLENAME_AS_CLASS +namespace c3d // namespace C3D +{ //---------------------------------------------------------------------------------------- /// \ru Оператор записи хэша. \en Operator of writing hash. \~ \ingroup Base_Tools_IO @@ -3093,7 +3008,7 @@ inline SimpleName ReadSimpleName( reader & in ) inline writer & operator << ( writer & out, const StrHash & strHash ) { // \ru Нельзя допускать хеш с неопределенным типом и с определенным значением \en Hash with undefined type and with specified value cannot be allowed - PRECONDITION( !(IsGoodSimpleName(strHash.m_val) && strHash.m_type == StrHash::htp_undef) ); + PRECONDITION( !(IsGoodSimpleName(strHash.m_val) && strHash.m_type == c3d::StrHash::htp_undef) ); WriteSimpleName( out, strHash.m_val ); @@ -3102,11 +3017,10 @@ inline writer & operator << ( writer & out, const StrHash & strHash ) return out; } - //---------------------------------------------------------------------------------------- /// \ru Оператор чтения хэша. \en Operator of hash reading. \~ \ingroup Base_Tools_IO //--- -inline reader & operator >> ( reader& in, StrHash & strHash ) +inline reader & operator >> ( reader & in, c3d::StrHash & strHash ) { strHash.m_val = ReadSimpleName( in ); @@ -3114,16 +3028,18 @@ inline reader & operator >> ( reader& in, StrHash & strHash ) if ( in.MathVersion() >= 0x0A001005L /*\ru введена запись типа хеша \en record of hash type is set */) in >> strHash.m_type; else - strHash.m_type = StrHash::htp_wchar; // \ru !!! Переходный период, могут быть разные \en !!! Period of transition, may be different + strHash.m_type = c3d::StrHash::htp_wchar; // \ru !!! Переходный период, могут быть разные \en !!! Period of transition, may be different else - strHash.m_type = StrHash::htp_char; + strHash.m_type = c3d::StrHash::htp_char; // \ru Нельзя допускать хеш с неопределенным типом и с определенным значением \en Hash with undefined type and with specified value cannot be allowed - PRECONDITION( !(IsGoodSimpleName(strHash.m_val) && strHash.m_type == StrHash::htp_undef) ); + PRECONDITION( !(IsGoodSimpleName(strHash.m_val) && strHash.m_type == c3d::StrHash::htp_undef) ); return in; } +} // namespace C3D + //---------------------------------------------------------------------------------------- /// \ru Запись строки в поток. \en Writing a string to the stream. \~ \ingroup Base_Tools_IO @@ -3372,3 +3288,4 @@ inline size_t ReadClusterBody( void * in, VERSION version, Cluster & obj, uint16 } #endif // __IO_TAPE_H + diff --git a/C3d/Include/io_tree.h b/C3d/Include/io_tree.h index ad57c61..581989d 100644 --- a/C3d/Include/io_tree.h +++ b/C3d/Include/io_tree.h @@ -1,301 +1,301 @@ -//////////////////////////////////////////////////////////////////////////////// -/** -\file -\brief \ru Дерево геометрической модели. - \en Tree of geometric model. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IO_TREE_H -#define __IO_TREE_H - -#include -#include -#include -#include - -class reader; -class writer; -struct ClusterReference; -class TapeBase; - -namespace c3d // namespace C3D -{ - -//---------------------------------------------------------------------------------------- -// \ru Предварительное объявление структуры для данных узла дерева. -// \en The forward declaration of a structure for the tree node data. \~ -// --- -struct MbItemData; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Узел дерева модели. - \en Model tree node. \~ - \details \ru Узел дерева модели (может иметь несколько потомков). - Умеет записывать в поток и читаться из потока. \n - \en Model tree node (can have several children). - Can be written to a stream and read from a stream. \n \~ - \ingroup Base_Tools_IO -*/ -// --- -class IModelTreeNode -{ -protected: - // \ru Непосредственные потомки узла. \en The immediate children of the node. - std::set m_children; - // \ru Непосредственные предки узла. \en The immediate parents of the node. - std::set m_parents; -public: - IModelTreeNode() {} - virtual ~IModelTreeNode() {} - - // \ru Доступ к непосредственным предкам узла. \en Access to the immediate node parents. - std::set& GetParents() { return m_parents; } - const std::set& GetParents() const { return m_parents; } - - // \ru Доступ к непосредственным потомкам узла. \en Access to the immediate node children. - std::set& GetChildren() { return m_children; } - const std::set& GetChildren() const { return m_children; } - - // \ru Добавить предка. \en Add a parent. - void AddParent( IModelTreeNode* parent ) { if (parent) m_parents.insert(parent); } - - // \ru Добавить потомка. \en Add a child. - void AddChild( IModelTreeNode* child ) { if (child) { m_children.insert(child); child->AddParent(this); } } - - // \ru Доступ к данным узла. \en Access to the node data. - virtual MbItemData& GetData() = 0; - virtual const MbItemData& GetData() const = 0; - - // \ru Доступ к позиции чтения/записи узла. \en Access to the node read/write position. - virtual ClusterReference& GetPosition() = 0; - virtual const ClusterReference& GetPosition() const = 0; - - // \ru Признак частичного или полного чтения узла. - // При чтении объекта может возникнуть необходимость чтения некоторых данных его родителя. - // В этом случае объект родителя читается частично и имеет соответствующий флаг. - // \en Indicator of partial reading of the current node. - // While reading an object there can be a need to read some data from its parent. - // In this case the parent object is read partially and has a corresponding flag. - // \ru Узнать, читать ли только часть узла. - // \en Check whether to read the node partially. - virtual bool PartialRead() const = 0; - // \ru Установить признак частичного или полного чтения узла. - // \en Set indication of full or partial node reading. - virtual void SetPartialRead ( bool partial ) const = 0; - - // \ru Записать узел. \en Write the node. - virtual writer & operator >> ( writer & ) = 0; - // \ru Прочитать узел. \en Read the node. - virtual reader & operator << ( reader & ) = 0; - - // \ru Операторы для записи узла дерева поток в xml формате. \en Operators to output tree node to a stream in xml format. - friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, IModelTreeNode& node ); - friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, const IModelTreeNode& node ); - -OBVIOUS_PRIVATE_COPY(IModelTreeNode) -}; - -//---------------------------------------------------------------------------------------- -// \ru Предварительное объявление Дерева Исполнений. -// \en The forward declaration of Embodiments Tree. \~ -// --- -class IEmbodimentTree; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Обобщенное дерево модели. - \en Generic model tree. \~ - \details \ru Обобщенное дерево модели (может иметь несколько корней). - Умеет записываться в поток и читаться из потока. \n - Дерево Модели отражает иерархию стандартной модели (объекта MbModel). - \en Generic model tree (can have several roots). - Can be written to a stream and read from a stream. \n \~ - Model Tree presents a hierarchy of a standard model (MbModel object). - \ingroup Base_Tools_IO -*/ -// --- -class IModelTree -{ -public: - enum TreeType - { - mtt_Model, // \ru Дерево содержит модель. \en Tree contains model. - mtt_Embodiment // \ru Дерево содержит исполнения. \en Tree contains embodiments. - }; - - // \ru Тип, представляющий листовой узел с ветвью дерева, ведущей к нему, начиная с корневого узла дерева. - // \en A type which represents a leaf node with the tree branch, leading to it, starting from the root of the tree. - typedef std::pair > NodeBranch; - - // \ru Тип функции для выбора узлов дерева по фильтрам. - // \en The type of a function for selecting tree nodes by filters. - typedef bool ( CALL_DECLARATION * FilterNodesFunc ) ( std::vector&, const std::vector&, const IModelTree* ); - - // \ru Тип функции для определения, нужно ли добавлять объект в дерево модели, и заполнения данных узла. - // \en The type of a function for determining, whether to add the object to the model tree, and filling the node data. - typedef bool ( CALL_DECLARATION *NodeToAddFunc ) ( const TapeBase* mem, MbItemData& data ); - -protected: - // \ru Тип дерева. \en Tree type. - TreeType m_type; - - // \ru Функция для определения, нужно ли добавлять объект в дерево модели, и заполнения данных узла. - // \en A function for determining, whether to add the object to the model tree, and filling the node data. - NodeToAddFunc m_nodeToAddFunc; - - // \ru Функция для выбора объектов по фильтрам. - // \en A function for for selecting objects by filters. - FilterNodesFunc m_filterFunc; - - // \ru Корни дерева. \en The tree roots. - std::vector m_roots; - -public: - - IModelTree() : m_type ( mtt_Model ), m_nodeToAddFunc( NULL ), m_filterFunc( NULL ) {} - virtual ~IModelTree() {} - - // \ru Выдать тип дерева. \en Get the tree type. - TreeType GetType() const { return m_type; } - // \ru Установить тип дерева. \en Set the tree type. - void SetType( TreeType type ) { m_type = type; } - - // \ru Построить дерево из узлов, выбранных по фильтрам. В случае дерева исполнений, функция работает с первым исполнением. - // \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). - 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). - virtual const IEmbodimentTree* GetEmbodimentsTree() const = 0; - - // \ru Добавить узел. \en Add a node. - virtual void AddNode ( const TapeBase* mem, const ClusterReference& ref ) = 0; - - // \ru Нотификация об окончании чтения/записи текущего узла. - // \en Notification about the end of current node writing/reading. - virtual void CloseNode( const TapeBase* mem ) = 0; - - // \ru Установить функцию для выбора геометрического объекта для добавления в дерево модели, и заполнения данных узла. - // \en Define a function for selecting a geometric object for adding to the model tree, and filling the node data. - virtual void SetNodeToAddFunction( NodeToAddFunc callback ) { if ( callback ) m_nodeToAddFunc = callback; } - - // \ru Установить функцию для выбора узлов из дерева модели. - // \en Define a function for selecting nodes from the model tree. - virtual void SetFilterFunction( FilterNodesFunc callback ) { if ( callback ) m_filterFunc = callback; } - - // \ru Записать дерево. \en Write the tree. - virtual writer & operator >> ( writer & ) = 0; - // \ru Прочитать дерево. \en Read the tree. - virtual reader & operator << ( reader & ) = 0; - - - // \ru Доступ к корням дерева. - // Узел дерева может быть рекурсивно вложен - // (например, Instance может содержать сборку, которая содержит другой Instance, ссылающийся на эту же сборку). - // \en Access to the tree roots. - // Tree node could be nested recursively - // (e.g. Instance can contain an Assembly which contains another Instance which includes this Assembly). - const std::vector& GetRoots() const { return m_roots; } - std::vector& GetRoots() { return m_roots; } - - // \ru Версия дерева. \en Tree version. - virtual VERSION GetVersion() = 0; - virtual void SetVersion( VERSION ) = 0; - - // \ru Построить поддерево из потомков заданного узла. - // \en Build a tree from children of a given node. - static EXPORT_DECLARATION std_unique_ptr GetSubtree ( const IModelTreeNode* node ); - - // \ru Получить значимые узлы поддерева с указанным корнем (исключив узлы, которые добавлены для восстановления иерархии дерева). - // Возвращает количество значимых узлов. - // \en Get significant nodes in a subtree with the given root (excluding nodes that were added to reconstruct the tree hierarchy). - // Return a number of significant nodes. - static EXPORT_DECLARATION size_t GetSubtreeSignificantNodes ( const c3d::IModelTreeNode* node, std::set& nodes ); - - // \ru Создать экземпляр дерева. \en Create a tree instance. - static EXPORT_DECLARATION IModelTree* CreateModelTree(); - - // \ru Операторы для записи дерева в поток в xml формате. \en Operators to output a tree to a stream in xml format. - friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, IModelTree& tree ); - friend MATH_FUNC( c3d::t_ofstream & ) CALL_DECLARATION operator << ( c3d::t_ofstream& file, const IModelTree& tree ); - -OBVIOUS_PRIVATE_COPY(IModelTree) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Узел дерева исполнений. - \en Embodiments tree node. \~ - \details \ru Узел дерева исполнений (может иметь несколько потомков). - \en Embodiments tree node (can have several children). - \ingroup Base_Tools_IO -*/ -// --- -class IEmbodimentNode -{ -protected: - // \ru Непосредственные потомки узла. \en The immediate children of the node. - std::set m_children; -public: - IEmbodimentNode() {} - virtual ~IEmbodimentNode() { - for ( std::set::iterator i = m_children.begin(); i != m_children.end(); ++i ) - if ( *i != NULL ) delete *i; - } - - // \ru Построить поддерево модели, содержащееся в данном исполнении. - // \en Build a subtree of a model tree which is contained in a given embodiment. - virtual std_unique_ptr GetEmbodiment() const = 0; - - // \ru Выдать узел дерева модели, соответствующий данному исполнению. - // \en Get a model tree node which corresponds to a given embodiment. - virtual const IModelTreeNode * GetModelTreeNode() const = 0; - - // \ru Доступ к информации об исполнении. \en Access to the embodiment info. - virtual const MbItemData& GetEmbodimentData() const = 0; - - // \ru Доступ к непосредственным потомкам узла. \en Access to the immediate node children. - std::set& GetChildren() { return m_children; } - const std::set& GetChildren() const { return m_children; } - - // \ru Добавить потомка. \en Add a child. - void AddChild( IEmbodimentNode* child ) { if ( child ) m_children.insert( child ); } - - OBVIOUS_PRIVATE_COPY( IEmbodimentNode ) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Дерево Исполнений. - \en Embodiment Tree. \~ - \details \ru Дерево Исполнений отражает иерархию вариантов реализации модели (исполнений). - Каждый узел дерева представляет одно исполнение. - Подразумевается, что в геометрической модели исполнение хранится, - как объект MbAssembly с выставленным атрибутом типа at_Embodiment.\n - \en Embodiment Tree presents a hierarchy of variants of model implementation (embodiments). - Each node of the tree presents an embodiment. - It is assumed that in a geometric model an embodiment is stored as - MbAssembly object with an attribute of type at_Embodiment. \n \~ - \ingroup Base_Tools_IO -*/ -class IEmbodimentTree -{ -protected: - std::vector m_roots; - -public: - IEmbodimentTree() {} - virtual ~IEmbodimentTree() {} - - // \ru Доступ к корням дерева. \en Access to the tree roots. - const std::vector& GetRoots() const { return m_roots; } - std::vector& GetRoots() { return m_roots; } - -}; - -} //namespace c3d - -#endif // __IO_TREE_H +//////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief \ru Дерево геометрической модели. + \en Tree of geometric model. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IO_TREE_H +#define __IO_TREE_H + +#include +#include +#include +#include + +class reader; +class writer; +struct ClusterReference; +class TapeBase; + +namespace c3d // namespace C3D +{ + +//---------------------------------------------------------------------------------------- +// \ru Предварительное объявление структуры для данных узла дерева. +// \en The forward declaration of a structure for the tree node data. \~ +// --- +struct MbItemData; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Узел дерева модели. + \en Model tree node. \~ + \details \ru Узел дерева модели (может иметь несколько потомков). + Умеет записывать в поток и читаться из потока. \n + \en Model tree node (can have several children). + Can be written to a stream and read from a stream. \n \~ + \ingroup Base_Tools_IO +*/ +// --- +class IModelTreeNode +{ +protected: + // \ru Непосредственные потомки узла. \en The immediate children of the node. + std::set m_children; + // \ru Непосредственные предки узла. \en The immediate parents of the node. + std::set m_parents; +public: + IModelTreeNode() {} + virtual ~IModelTreeNode() {} + + // \ru Доступ к непосредственным предкам узла. \en Access to the immediate node parents. + std::set& GetParents() { return m_parents; } + const std::set& GetParents() const { return m_parents; } + + // \ru Доступ к непосредственным потомкам узла. \en Access to the immediate node children. + std::set& GetChildren() { return m_children; } + const std::set& GetChildren() const { return m_children; } + + // \ru Добавить предка. \en Add a parent. + void AddParent( IModelTreeNode* parent ) { if (parent) m_parents.insert(parent); } + + // \ru Добавить потомка. \en Add a child. + void AddChild( IModelTreeNode* child ) { if (child) { m_children.insert(child); child->AddParent(this); } } + + // \ru Доступ к данным узла. \en Access to the node data. + virtual MbItemData& GetData() = 0; + virtual const MbItemData& GetData() const = 0; + + // \ru Доступ к позиции чтения/записи узла. \en Access to the node read/write position. + virtual ClusterReference& GetPosition() = 0; + virtual const ClusterReference& GetPosition() const = 0; + + // \ru Признак частичного или полного чтения узла. + // При чтении объекта может возникнуть необходимость чтения некоторых данных его родителя. + // В этом случае объект родителя читается частично и имеет соответствующий флаг. + // \en Indicator of partial reading of the current node. + // While reading an object there can be a need to read some data from its parent. + // In this case the parent object is read partially and has a corresponding flag. + // \ru Узнать, читать ли только часть узла. + // \en Check whether to read the node partially. + virtual bool PartialRead() const = 0; + // \ru Установить признак частичного или полного чтения узла. + // \en Set indication of full or partial node reading. + virtual void SetPartialRead ( bool partial ) const = 0; + + // \ru Записать узел. \en Write the node. + virtual writer & operator >> ( writer & ) = 0; + // \ru Прочитать узел. \en Read the node. + virtual reader & operator << ( reader & ) = 0; + + // \ru Операторы для записи узла дерева поток в xml формате. \en Operators to output tree node to a stream in xml format. + friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, IModelTreeNode& node ); + friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, const IModelTreeNode& node ); + +OBVIOUS_PRIVATE_COPY(IModelTreeNode) +}; + +//---------------------------------------------------------------------------------------- +// \ru Предварительное объявление Дерева Исполнений. +// \en The forward declaration of Embodiments Tree. \~ +// --- +class IEmbodimentTree; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Обобщенное дерево модели. + \en Generic model tree. \~ + \details \ru Обобщенное дерево модели (может иметь несколько корней). + Умеет записываться в поток и читаться из потока. \n + Дерево Модели отражает иерархию стандартной модели (объекта MbModel). + \en Generic model tree (can have several roots). + Can be written to a stream and read from a stream. \n \~ + Model Tree presents a hierarchy of a standard model (MbModel object). + \ingroup Base_Tools_IO +*/ +// --- +class IModelTree +{ +public: + enum TreeType + { + mtt_Model, // \ru Дерево содержит модель. \en Tree contains model. + mtt_Embodiment // \ru Дерево содержит исполнения. \en Tree contains embodiments. + }; + + // \ru Тип, представляющий листовой узел с ветвью дерева, ведущей к нему, начиная с корневого узла дерева. + // \en A type which represents a leaf node with the tree branch, leading to it, starting from the root of the tree. + typedef std::pair > NodeBranch; + + // \ru Тип функции для выбора узлов дерева по фильтрам. + // \en The type of a function for selecting tree nodes by filters. + typedef bool ( CALL_DECLARATION * FilterNodesFunc ) ( std::vector&, const std::vector&, const IModelTree* ); + + // \ru Тип функции для определения, нужно ли добавлять объект в дерево модели, и заполнения данных узла. + // \en The type of a function for determining, whether to add the object to the model tree, and filling the node data. + typedef bool ( CALL_DECLARATION *NodeToAddFunc ) ( const TapeBase* mem, MbItemData& data ); + +protected: + // \ru Тип дерева. \en Tree type. + TreeType m_type; + + // \ru Функция для определения, нужно ли добавлять объект в дерево модели, и заполнения данных узла. + // \en A function for determining, whether to add the object to the model tree, and filling the node data. + NodeToAddFunc m_nodeToAddFunc; + + // \ru Функция для выбора объектов по фильтрам. + // \en A function for for selecting objects by filters. + FilterNodesFunc m_filterFunc; + + // \ru Корни дерева. \en The tree roots. + std::vector m_roots; + +public: + + IModelTree() : m_type ( mtt_Model ), m_nodeToAddFunc( NULL ), m_filterFunc( NULL ) {} + virtual ~IModelTree() {} + + // \ru Выдать тип дерева. \en Get the tree type. + TreeType GetType() const { return m_type; } + // \ru Установить тип дерева. \en Set the tree type. + void SetType( TreeType type ) { m_type = type; } + + // \ru Построить дерево из узлов, выбранных по фильтрам. В случае дерева исполнений, функция работает с первым исполнением. + // \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). + 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). + virtual const IEmbodimentTree* GetEmbodimentsTree() const = 0; + + // \ru Добавить узел. \en Add a node. + virtual void AddNode ( const TapeBase* mem, const ClusterReference& ref ) = 0; + + // \ru Нотификация об окончании чтения/записи текущего узла. + // \en Notification about the end of current node writing/reading. + virtual void CloseNode( const TapeBase* mem ) = 0; + + // \ru Установить функцию для выбора геометрического объекта для добавления в дерево модели, и заполнения данных узла. + // \en Define a function for selecting a geometric object for adding to the model tree, and filling the node data. + virtual void SetNodeToAddFunction( NodeToAddFunc callback ) { if ( callback ) m_nodeToAddFunc = callback; } + + // \ru Установить функцию для выбора узлов из дерева модели. + // \en Define a function for selecting nodes from the model tree. + virtual void SetFilterFunction( FilterNodesFunc callback ) { if ( callback ) m_filterFunc = callback; } + + // \ru Записать дерево. \en Write the tree. + virtual writer & operator >> ( writer & ) = 0; + // \ru Прочитать дерево. \en Read the tree. + virtual reader & operator << ( reader & ) = 0; + + + // \ru Доступ к корням дерева. + // Узел дерева может быть рекурсивно вложен + // (например, Instance может содержать сборку, которая содержит другой Instance, ссылающийся на эту же сборку). + // \en Access to the tree roots. + // Tree node could be nested recursively + // (e.g. Instance can contain an Assembly which contains another Instance which includes this Assembly). + const std::vector& GetRoots() const { return m_roots; } + std::vector& GetRoots() { return m_roots; } + + // \ru Версия дерева. \en Tree version. + virtual VERSION GetVersion() = 0; + virtual void SetVersion( VERSION ) = 0; + + // \ru Построить поддерево из потомков заданного узла. + // \en Build a tree from children of a given node. + static EXPORT_DECLARATION std_unique_ptr GetSubtree ( const IModelTreeNode* node ); + + // \ru Получить значимые узлы поддерева с указанным корнем (исключив узлы, которые добавлены для восстановления иерархии дерева). + // Возвращает количество значимых узлов. + // \en Get significant nodes in a subtree with the given root (excluding nodes that were added to reconstruct the tree hierarchy). + // Return a number of significant nodes. + static EXPORT_DECLARATION size_t GetSubtreeSignificantNodes ( const c3d::IModelTreeNode* node, std::set& nodes ); + + // \ru Создать экземпляр дерева. \en Create a tree instance. + static EXPORT_DECLARATION IModelTree* CreateModelTree(); + + // \ru Операторы для записи дерева в поток в xml формате. \en Operators to output a tree to a stream in xml format. + friend MATH_FUNC( c3d::t_ofstream & ) operator << ( c3d::t_ofstream& file, IModelTree& tree ); + friend MATH_FUNC( c3d::t_ofstream & ) CALL_DECLARATION operator << ( c3d::t_ofstream& file, const IModelTree& tree ); + +OBVIOUS_PRIVATE_COPY(IModelTree) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Узел дерева исполнений. + \en Embodiments tree node. \~ + \details \ru Узел дерева исполнений (может иметь несколько потомков). + \en Embodiments tree node (can have several children). + \ingroup Base_Tools_IO +*/ +// --- +class IEmbodimentNode +{ +protected: + // \ru Непосредственные потомки узла. \en The immediate children of the node. + std::set m_children; +public: + IEmbodimentNode() {} + virtual ~IEmbodimentNode() { + for ( std::set::iterator i = m_children.begin(); i != m_children.end(); ++i ) + if ( *i != NULL ) delete *i; + } + + // \ru Построить поддерево модели, содержащееся в данном исполнении. + // \en Build a subtree of a model tree which is contained in a given embodiment. + virtual std_unique_ptr GetEmbodiment() const = 0; + + // \ru Выдать узел дерева модели, соответствующий данному исполнению. + // \en Get a model tree node which corresponds to a given embodiment. + virtual const IModelTreeNode * GetModelTreeNode() const = 0; + + // \ru Доступ к информации об исполнении. \en Access to the embodiment info. + virtual const MbItemData& GetEmbodimentData() const = 0; + + // \ru Доступ к непосредственным потомкам узла. \en Access to the immediate node children. + std::set& GetChildren() { return m_children; } + const std::set& GetChildren() const { return m_children; } + + // \ru Добавить потомка. \en Add a child. + void AddChild( IEmbodimentNode* child ) { if ( child ) m_children.insert( child ); } + + OBVIOUS_PRIVATE_COPY( IEmbodimentNode ) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Дерево Исполнений. + \en Embodiment Tree. \~ + \details \ru Дерево Исполнений отражает иерархию вариантов реализации модели (исполнений). + Каждый узел дерева представляет одно исполнение. + Подразумевается, что в геометрической модели исполнение хранится, + как объект MbAssembly с выставленным атрибутом типа at_Embodiment.\n + \en Embodiment Tree presents a hierarchy of variants of model implementation (embodiments). + Each node of the tree presents an embodiment. + It is assumed that in a geometric model an embodiment is stored as + MbAssembly object with an attribute of type at_Embodiment. \n \~ + \ingroup Base_Tools_IO +*/ +class IEmbodimentTree +{ +protected: + std::vector m_roots; + +public: + IEmbodimentTree() {} + virtual ~IEmbodimentTree() {} + + // \ru Доступ к корням дерева. \en Access to the tree roots. + const std::vector& GetRoots() const { return m_roots; } + std::vector& GetRoots() { return m_roots; } + +}; + +} //namespace c3d + +#endif // __IO_TREE_H diff --git a/C3d/Include/io_version_container.h b/C3d/Include/io_version_container.h index 379869c..96cb5d4 100644 --- a/C3d/Include/io_version_container.h +++ b/C3d/Include/io_version_container.h @@ -1,75 +1,75 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контейнер версий. - \en Container of versions. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IO_VERSION_CONTAINER_H -#define __IO_VERSION_CONTAINER_H - - -#include -#include - - -//----------------------------------------------------------------------------- -/** \brief \ru Контейнер версий. - \en Container of versions. \~ - \details \ru Контейнер версий объектов. \n - \en Container of versions of objects. \n \~ - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS VersionContainer -{ -private: - // \ru static VersionContainer iobuf_defaultVersionCont; // Версия по умолчанию. \en static VersionContainer iobuf_defaultVersionCont; // Default version. - static VersionContainer & StaticVersionContainer(); -protected: - SArray m_self; ///< \ru Массив версий. \en Array of versions. -protected: - /// \ru Конструктор. \en Constructor. - VersionContainer( VERSION/*firstInit*/ ); -public: - /// \ru Конструктор. \en Constructor. - VersionContainer(); - /// \ru Конструктор копирования. \en Copy-constructor. - VersionContainer( const VersionContainer & other ); - /// \ru Деструктор. \en Destructor. - virtual ~VersionContainer(); - - /// \ru Получить экземпляр контейнера версий. \en Get the instance of version container. - static const VersionContainer & defaultVersionContainer(); - /// \ru Установить версии из другого контейнера \en Set versions from another container - static void SetDefaultVersion( const VersionContainer & v ); - - // \ru Вернуть главную версию (математического ядра). \en Return the main version (of the mathematical kernel). - VERSION GetMathVersion() const; - // \ru Вернуть дополнительную версию (конечного приложения). \en Return the additional version (of the target application). - VERSION GetAppVersion ( size_t ind = -1 ) const; - // \ru Очистить контейнер. \en Flush the container. - void Flush (); - // \ru Установить версию по индексу. \en Set the version by the index. - void SetVersion ( size_t index, VERSION ver ); - // \ru Записать в кусок памяти. \en Write to the memory block. - size_t ToMemory ( const char *& memory ) const; - // \ru Прочитать из куска памяти. \en Read from the memory block. - size_t FromMemory ( const char * memory ); - - /// \ru Оператор присваивания. \en An assignment operator. - VersionContainer & operator = ( const VersionContainer & other ); - - /// \ru Оператор чтения. \en Read operator. - friend MATH_FUNC (reader &) operator >> ( reader &, VersionContainer & ); - /// \ru Оператор записи. \en Write operator. - friend MATH_FUNC (writer &) operator << ( writer &, const VersionContainer & ); - -protected: - /// \ru Функция инициализации по другому контейнеру. \en Function of initialization by another container. - void Init( const VersionContainer & ); -}; - -#endif //__IO_VERSION_CONTAINER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контейнер версий. + \en Container of versions. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IO_VERSION_CONTAINER_H +#define __IO_VERSION_CONTAINER_H + + +#include +#include + + +//----------------------------------------------------------------------------- +/** \brief \ru Контейнер версий. + \en Container of versions. \~ + \details \ru Контейнер версий объектов. \n + \en Container of versions of objects. \n \~ + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS VersionContainer +{ +private: + // \ru static VersionContainer iobuf_defaultVersionCont; // Версия по умолчанию. \en static VersionContainer iobuf_defaultVersionCont; // Default version. + static VersionContainer & StaticVersionContainer(); +protected: + SArray m_self; ///< \ru Массив версий. \en Array of versions. +protected: + /// \ru Конструктор. \en Constructor. + VersionContainer( VERSION/*firstInit*/ ); +public: + /// \ru Конструктор. \en Constructor. + VersionContainer(); + /// \ru Конструктор копирования. \en Copy-constructor. + VersionContainer( const VersionContainer & other ); + /// \ru Деструктор. \en Destructor. + virtual ~VersionContainer(); + + /// \ru Получить экземпляр контейнера версий. \en Get the instance of version container. + static const VersionContainer & defaultVersionContainer(); + /// \ru Установить версии из другого контейнера \en Set versions from another container + static void SetDefaultVersion( const VersionContainer & v ); + + // \ru Вернуть главную версию (математического ядра). \en Return the main version (of the mathematical kernel). + VERSION GetMathVersion() const; + // \ru Вернуть дополнительную версию (конечного приложения). \en Return the additional version (of the target application). + VERSION GetAppVersion ( size_t ind = -1 ) const; + // \ru Очистить контейнер. \en Flush the container. + void Flush (); + // \ru Установить версию по индексу. \en Set the version by the index. + void SetVersion ( size_t index, VERSION ver ); + // \ru Записать в кусок памяти. \en Write to the memory block. + size_t ToMemory ( const char *& memory ) const; + // \ru Прочитать из куска памяти. \en Read from the memory block. + size_t FromMemory ( const char * memory ); + + /// \ru Оператор присваивания. \en An assignment operator. + VersionContainer & operator = ( const VersionContainer & other ); + + /// \ru Оператор чтения. \en Read operator. + friend MATH_FUNC (reader &) operator >> ( reader &, VersionContainer & ); + /// \ru Оператор записи. \en Write operator. + friend MATH_FUNC (writer &) operator << ( writer &, const VersionContainer & ); + +protected: + /// \ru Функция инициализации по другому контейнеру. \en Function of initialization by another container. + void Init( const VersionContainer & ); +}; + +#endif //__IO_VERSION_CONTAINER_H diff --git a/C3d/Include/io_version_container_rw.h b/C3d/Include/io_version_container_rw.h index edb672f..e1aa717 100644 --- a/C3d/Include/io_version_container_rw.h +++ b/C3d/Include/io_version_container_rw.h @@ -1,29 +1,29 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контейнер версий. Чтение/запись. - \en Container of versions. Reading/writing. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __IO_VERSION_CONTAINER_RW_H -#define __IO_VERSION_CONTAINER_RW_H - -#include -#include - - -//----------------------------------------------------------------------------- -/// \ru Оператор чтения контейнера версий. \en Operator of version container reading. \~ \ingroup Base_Tools_IO -// --- -MATH_FUNC (reader &) operator >> ( reader &, VersionContainer & ); - - -//----------------------------------------------------------------------------- -/// \ru Оператор записи контейнера версий. \en Operator of version container writing. \~ \ingroup Base_Tools_IO -// --- -MATH_FUNC (writer &) operator << ( writer &, const VersionContainer & ); - - -#endif //__IO_VERSION_CONTAINER_RW_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контейнер версий. Чтение/запись. + \en Container of versions. Reading/writing. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __IO_VERSION_CONTAINER_RW_H +#define __IO_VERSION_CONTAINER_RW_H + +#include +#include + + +//----------------------------------------------------------------------------- +/// \ru Оператор чтения контейнера версий. \en Operator of version container reading. \~ \ingroup Base_Tools_IO +// --- +MATH_FUNC (reader &) operator >> ( reader &, VersionContainer & ); + + +//----------------------------------------------------------------------------- +/// \ru Оператор записи контейнера версий. \en Operator of version container writing. \~ \ingroup Base_Tools_IO +// --- +MATH_FUNC (writer &) operator << ( writer &, const VersionContainer & ); + + +#endif //__IO_VERSION_CONTAINER_RW_H diff --git a/C3d/Include/item_registrator.h b/C3d/Include/item_registrator.h index 423cc2f..53ee5d6 100644 --- a/C3d/Include/item_registrator.h +++ b/C3d/Include/item_registrator.h @@ -55,7 +55,7 @@ if ( iReg == NULL || !iReg->IsReg( this, copyItem ) ) { \ Registrar is used to prevent multiple copying of the object. Registrator consists of two synchronous arrays. The first array contains pointers to copied objects, the second array contains pointers to their copies. \n - When copying the object using the registrator, the existance of the copied object inside the first array is verified. + When copying the object using the registrator, the existence of the copied object inside the first array is verified. If such object exists, then the pointer to its copy is given from the second array. If such objects is absent, then it is stored in the first array, after that its copy is stored in the second array and then this copy is returned. \~ \ingroup Base_Algorithms @@ -135,7 +135,7 @@ OBVIOUS_PRIVATE_COPY( MbAutoRegDuplicate ) which contain pointers to other geometries. \n Object pointer can be contained in several other objects for transformations. Registrar is used to prevent multiple transformation of object. - When transforming the object with registrator, the existance of the object inside the registrator is verified. + When transforming the object with registrator, the existence of the object inside the registrator is verified. If such object is absent, it is stored to the registrator and transformed, otherwise, a transformation of the object is not performed. \~ \ingroup Base_Algorithms diff --git a/C3d/Include/last.h b/C3d/Include/last.h index 57daf20..da20d66 100644 --- a/C3d/Include/last.h +++ b/C3d/Include/last.h @@ -1,38 +1,38 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контроль утечек памяти. - \en Control of memory leaks. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef _LAST_H_ -#define _LAST_H_ - -#include "math_cfg.h" // There are modules without defined paths to C3D - -#ifdef ENABLE_VLD - #include // \ru KVA V14 16.1.2012 Для компиляции КОМПАС \en KVA V14 16.1.2012 To compile the COMPAS - #include -#else - #ifdef C3D_WINDOWS //_MSC_VER - #ifdef __AFX_H__ - #ifdef _DEBUG - #define new DEBUG_NEW - #undef THIS_FILE - #define THIS_FILE __FILE__ - #endif - #else // __AFX_H__ - #define _CRTDBG_MAP_ALLOC - #include - #include - - #ifdef _DEBUG - #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) - #endif - #endif // __AFX_H__ - #endif // C3D_WINDOWS -#endif // ENABLE_VLD - -#endif // _LAST_H_ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контроль утечек памяти. + \en Control of memory leaks. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef _LAST_H_ +#define _LAST_H_ + +#include "math_cfg.h" // There are modules without defined paths to C3D + +#ifdef ENABLE_VLD + #include // \ru KVA V14 16.1.2012 Для компиляции КОМПАС \en KVA V14 16.1.2012 To compile the COMPAS + #include +#else + #ifdef C3D_WINDOWS //_MSC_VER + #ifdef __AFX_H__ + #ifdef _DEBUG + #define new DEBUG_NEW + #undef THIS_FILE + #define THIS_FILE __FILE__ + #endif + #else // __AFX_H__ + #define _CRTDBG_MAP_ALLOC + #include + #include + + #if defined(_DEBUG) && !defined(__DEBUG_MEMORY_ALLOCATE_FREE_) + #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) + #endif + #endif // __AFX_H__ + #endif // C3D_WINDOWS +#endif // ENABLE_VLD + +#endif // _LAST_H_ diff --git a/C3d/Include/legend.h b/C3d/Include/legend.h index fcd271a..f70eb86 100644 --- a/C3d/Include/legend.h +++ b/C3d/Include/legend.h @@ -1,64 +1,64 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Вспомогательный геометрический объект в трехмерном пространстве. - \en Auxiliary geometric object in the three-dimensional space. \~ - \details \ru Базовый абстрактный класс вспомогательного геометрического объекта. \n - \en Base abstract class of auxiliary geometric object. \n \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __LEGEND_H -#define __LEGEND_H - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Вспомогательный геометрический объект. - \en Auxiliary geometric object. \~ - \details \ru Базовый абстрактный класс вспомогательного геометрического объекта. \n - Вспомогательные объекты описывают базовые точки других объектов, резьбу, выносные линии, шероховатости и условные обозначения.\n - \en Base abstract class of auxiliary geometric object. \n - Auxiliary objects describe base points of other objects: thread, extension lines, roughness and notation conventions. \n \~ - \ingroup Legend -*/ -// --- -class MATH_CLASS MbLegend : public MbSpaceItem -{ -protected : - /// \ru Конструктор. \en Constructor. - MbLegend(); -public: - /// \ru Деструктор. \en Destructor. - virtual ~MbLegend(); - -public: /* \ru Общие функции геометрического объекта. \en Common functions of a geometric object. */ - - 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 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. - 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; // \ru Рассчитать габарит в локальной системы координат. \en Calculate the bounding box in a local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const = 0; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - virtual MbProperty & CreateProperty( MbePrompt n ) const = 0; // \ru Создать собственное свойство. \en Create a custom property. - 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. - - DECLARE_PERSISTENT_CLASS( MbLegend ); - OBVIOUS_PRIVATE_COPY( MbLegend ); -}; - -IMPL_PERSISTENT_OPS( MbLegend ) - - -#endif // __LEGEND_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вспомогательный геометрический объект в трехмерном пространстве. + \en Auxiliary geometric object in the three-dimensional space. \~ + \details \ru Базовый абстрактный класс вспомогательного геометрического объекта. \n + \en Base abstract class of auxiliary geometric object. \n \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __LEGEND_H +#define __LEGEND_H + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Вспомогательный геометрический объект. + \en Auxiliary geometric object. \~ + \details \ru Базовый абстрактный класс вспомогательного геометрического объекта. \n + Вспомогательные объекты описывают базовые точки других объектов, резьбу, выносные линии, шероховатости и условные обозначения.\n + \en Base abstract class of auxiliary geometric object. \n + Auxiliary objects describe base points of other objects: thread, extension lines, roughness and notation conventions. \n \~ + \ingroup Legend +*/ +// --- +class MATH_CLASS MbLegend : public MbSpaceItem +{ +protected : + /// \ru Конструктор. \en Constructor. + MbLegend(); +public: + /// \ru Деструктор. \en Destructor. + virtual ~MbLegend(); + +public: /* \ru Общие функции геометрического объекта. \en Common functions of a geometric object. */ + + 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 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. + 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; // \ru Рассчитать габарит в локальной системы координат. \en Calculate the bounding box in a local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const = 0; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + virtual MbProperty & CreateProperty( MbePrompt n ) const = 0; // \ru Создать собственное свойство. \en Create a custom property. + 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. + + DECLARE_PERSISTENT_CLASS( MbLegend ); + OBVIOUS_PRIVATE_COPY( MbLegend ); +}; + +IMPL_PERSISTENT_OPS( MbLegend ) + + +#endif // __LEGEND_H diff --git a/C3d/Include/lump.h b/C3d/Include/lump.h index ef64638..1219c08 100644 --- a/C3d/Include/lump.h +++ b/C3d/Include/lump.h @@ -68,9 +68,9 @@ typedef std::pair ConstLumpsSPtrSetRet; struct MATH_CLASS MbLump: public MbRefItem { protected: c3d::ConstSolidSPtr solid; ///< \ru Тело (всегда не NULL). \en Solid (always not 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. - MbMatrix3D from; ///< \ru Матрица преобразования из локальной системы координат. \en A transformation matrix from the local coordinate system. private: bool changed; ///< \ru Флаг необходимости обработки компонента. \en Component processing flag. @@ -79,7 +79,7 @@ private: MbLump( const MbLump & other, MbRegDuplicate * iReg ); public: /// \ru Пустой конструктор. \en Empty constructor. - MbLump() : solid( NULL ), component( 0 ), identifier( SYS_MAX_T ), from(), changed( true ) {} + MbLump() : solid( 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. diff --git a/C3d/Include/m2b_mesh_curvature.h b/C3d/Include/m2b_mesh_curvature.h index 86f9244..cf269b9 100644 --- a/C3d/Include/m2b_mesh_curvature.h +++ b/C3d/Include/m2b_mesh_curvature.h @@ -1,40 +1,40 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Структура для хранения кривизн, их направлений и нормалей в вершине сетки. - \en Struct to store curvatures, principal curvature directions and normals at mesh vertex. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __M2B_MESH_CURVATURE_H -#define __M2B_MESH_CURVATURE_H - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные о кривизне и главных направлениях изменений кривизны. - \en Curvature and principal curvature direction data. \~ - \details \ru Структура для хранения информации о кривизне и главных направлениях изменений кривизны поверхности, - рассчитанной в вершине полигональной сетки. - \en Structure for store curvature and principal curvature direction data calculated at the polygon vertex. \~ - \ingroup Polygonal_Objects -*/ -// --- -struct MATH_CLASS MbCurvature -{ - double k_h; ///< \ru Средняя кривизна. \en Mean curvature. - double k_g; ///< \ru Гауссова кривизна. \en Gaussian curvature. - double k1; ///< \ru Максимальная кривизна. \en Maximum principal curvature. - double k2; ///< \ru Минимальная кривизна. \en Minimum principal curvature. - MbVector3D normal; ///< \ru Нормаль (вычислена по оператору кривизны). \en Normal (calculated by curvature operator). - MbVector3D meanNormal; ///< \ru Нормаль (вычислена как взвешенное среднее нормалей соседних граней). \en Normal (calculated as weighted mean of the normals of neighboring faces). - MbVector3D cdir1; ///< \ru Направление максимальной кривизны. \en Maximum principal curvature direction. - MbVector3D cdir2; ///< \ru Направление минимальной кривизны. \en Minimum principal curvature direction. - /// \ru Конструктор по умолчанию. \en Default constructor. - MbCurvature() : k_h( 0.0 ), k_g( 0.0 ), k1 ( 0.0 ), k2 ( 0.0 ) {} -}; - - -#endif // __M2B_MESH_CURVATURE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Структура для хранения кривизн, их направлений и нормалей в вершине сетки. + \en Struct to store curvatures, principal curvature directions and normals at mesh vertex. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __M2B_MESH_CURVATURE_H +#define __M2B_MESH_CURVATURE_H + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные о кривизне и главных направлениях изменений кривизны. + \en Curvature and principal curvature direction data. \~ + \details \ru Структура для хранения информации о кривизне и главных направлениях изменений кривизны поверхности, + рассчитанной в вершине полигональной сетки. + \en Structure for store curvature and principal curvature direction data calculated at the polygon vertex. \~ + \ingroup Polygonal_Objects +*/ +// --- +struct MATH_CLASS MbCurvature +{ + double k_h; ///< \ru Средняя кривизна. \en Mean curvature. + double k_g; ///< \ru Гауссова кривизна. \en Gaussian curvature. + double k1; ///< \ru Максимальная кривизна. \en Maximum principal curvature. + double k2; ///< \ru Минимальная кривизна. \en Minimum principal curvature. + MbVector3D normal; ///< \ru Нормаль (вычислена по оператору кривизны). \en Normal (calculated by curvature operator). + MbVector3D meanNormal; ///< \ru Нормаль (вычислена как взвешенное среднее нормалей соседних граней). \en Normal (calculated as weighted mean of the normals of neighboring faces). + MbVector3D cdir1; ///< \ru Направление максимальной кривизны. \en Maximum principal curvature direction. + MbVector3D cdir2; ///< \ru Направление минимальной кривизны. \en Minimum principal curvature direction. + /// \ru Конструктор по умолчанию. \en Default constructor. + MbCurvature() : k_h( 0.0 ), k_g( 0.0 ), k1 ( 0.0 ), k2 ( 0.0 ) {} +}; + + +#endif // __M2B_MESH_CURVATURE_H diff --git a/C3d/Include/map_create.h b/C3d/Include/map_create.h index c6a4170..49aecba 100644 --- a/C3d/Include/map_create.h +++ b/C3d/Include/map_create.h @@ -268,18 +268,21 @@ OBVIOUS_PRIVATE_COPY( GetVestigesTransData ) \en Merge same curves (default true). \~ \param[in] prevCubes - \ru Габариты тел до изменений. \en Bounding boxes of solids before changes. \~ + \result \ru Возвращает результат операции. + \en Returns the result of the operation. \~ + \ingroup Mapping */ // --- -MATH_FUNC (void) GetVestiges ( const MbPlacement3D & place, - double znear, - const RPArray & lumps, - const MbProjectionsObjects & objects, - MbVEFVestiges & result, - const MbMapVisibilityMode & visMode, - VERSION version = Math::DefaultMathVersion(), - bool merge = true, - const std::vector * prevCubes = NULL ); +MATH_FUNC (MbResultType) GetVestiges ( const MbPlacement3D & place, + double znear, + const RPArray & lumps, + const MbProjectionsObjects & objects, + MbVEFVestiges & result, + const MbMapVisibilityMode & visMode, + VERSION version = Math::DefaultMathVersion(), + bool merge = true, + const std::vector * prevCubes = NULL ); //------------------------------------------------------------------------------ @@ -358,14 +361,17 @@ private: Destruction of the results is a responsibility of the function caller. \~ \param[in] version - \ru Версия построения. Последняя версия Math::DefaultMathVersion(). \en The version of construction. The last version Math::DefaultMathVersion(). -\ingroup Mapping + \result \ru Возвращает результат операции. + \en Returns the result of the operation. \~ + + \ingroup Mapping */ // --- -MATH_FUNC (void) GetVestiges ( const SArray & settings, - const RPArray & lumps, - const MbProjectionsObjects & objects, - PArray & results, - VERSION version = Math::DefaultMathVersion() ); +MATH_FUNC (MbResultType) GetVestiges ( const SArray & settings, + const RPArray & lumps, + const MbProjectionsObjects & objects, + PArray & results, + VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ /** \brief \ru Определение участков граничной кривой. diff --git a/C3d/Include/map_lump.h b/C3d/Include/map_lump.h index c295976..8290612 100644 --- a/C3d/Include/map_lump.h +++ b/C3d/Include/map_lump.h @@ -587,7 +587,7 @@ public: Free the unnecessary memory in arrays of points and names. \~ */ void AdjustMemory() { - #ifdef STANDARD_C11 + #ifdef C3D_STANDARD_CXX_11_PARTIAL points.shrink_to_fit(); names.shrink_to_fit(); #endif } @@ -877,7 +877,7 @@ public: Frees the unnecessary memory in arrays of points and names. \~ */ void AdjustMemory() { - #ifdef STANDARD_C11 + #ifdef C3D_STANDARD_CXX_11_PARTIAL curves.shrink_to_fit(); names.shrink_to_fit(); #endif } @@ -1140,9 +1140,9 @@ public: , willCut( false ) // конструктор по нескольким телам только в случае "не рассекать" { size_t count = _lumps.size(); - C3D_ASSERT( count > 0 ); + C3D_ASSERT( count > 0 && _lumps[0] != NULL ); - if ( count > 0 ) { + if ( count > 0 && _lumps[0] != NULL ) { from = _lumps[0]->GetMatrixFrom(); component = _lumps[0]->GetComponent(); identifier = _lumps[0]->GetIdentifier(); @@ -1154,7 +1154,8 @@ public: lumps = new c3d::LumpsSPtrVector(); for ( size_t i = 1; i < count; ++i ) { MbLump * lump = _lumps[i]; - lumps->push_back( c3d::LumpSPtr( lump ) ); + if ( lump != NULL ) + lumps->push_back( c3d::LumpSPtr(lump) ); } } } diff --git a/C3d/Include/map_vestige.h b/C3d/Include/map_vestige.h index 7e41dfe..bc4e949 100644 --- a/C3d/Include/map_vestige.h +++ b/C3d/Include/map_vestige.h @@ -609,14 +609,16 @@ protected: \en A name. \~ \param[in] isCenterLine - \ru Является ли кривая осевой линией или нет. \en Is curve is center line or not. \~ + \param[in] ownName - \ru Является ли otherName собственным именем объекта. + \en Is otherName own object name or not. \~ */ explicit - MbEdgeVestige( uint otherComp, size_t otherIdent, const MbName & otherName, bool isCenterLine ) + MbEdgeVestige( uint otherComp, size_t otherIdent, const MbName & otherName, bool isCenterLine, bool ownName = false ) : MbBaseVestige( otherComp, otherIdent, otherName ) , curveInfo ( ) , vesType ( (uint8)(isCenterLine ? vt_CenterLine : vt_SpaceCurve) ) , vesSubType ( vst_None ) - {} + { if ( ownName ) name.SetOwn( ownName ); } /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. MbEdgeVestige( const MbEdgeVestige & other, MbRegDuplicate * iReg ) : MbBaseVestige( other, iReg ) @@ -644,7 +646,7 @@ public: void SetSubType( SubType vt ) { vesSubType = (uint8)vt; } /// \ru Добавить MbEdgeVestige в массив. \en Add the MbEdgeVestige to an array. \~ - friend MbEdgeVestige * AddVestigeCurve( uint otherComp, size_t otherIdent, const MbName & otherName, RPArray & arr, bool isCenterLine ); + friend MbEdgeVestige * AddVestigeCurve( uint otherComp, size_t otherIdent, const MbName & otherName, RPArray & arr, bool isCenterLine, bool ownName ); private: bool operator == ( const MbEdgeVestige & ); // \ru Не реализован. \en Not implemented. @@ -670,6 +672,8 @@ IMPL_PERSISTENT_OPS( MbEdgeVestige ) \en Array of edges. \~ \param[in] isCenterLine - \ru Является ли ребро осевой линией или нет. \en Is curve is center line or not. \~ + \param[in] ownName - \ru Является ли otherName собственным именем объекта. + \en Is otherName own object name or not. \~ \ingroup Mapping */ // --- @@ -677,9 +681,10 @@ inline MbEdgeVestige * AddVestigeCurve( uint otherComp size_t otherIdent, const MbName & otherName, RPArray & arr, - bool isCenterLine ) + bool isCenterLine, + bool ownName ) { - MbEdgeVestige * vestige = new MbEdgeVestige( otherComp, otherIdent, otherName, isCenterLine ); + MbEdgeVestige * vestige = new MbEdgeVestige( otherComp, otherIdent, otherName, isCenterLine, ownName ); if ( vestige ) { arr.Add( vestige ); } @@ -977,6 +982,17 @@ public: pointVestiges.Flush(); curveVestiges.Flush(); } + /// \ru Очистить массивы следов. \en Clear arrays of vestiges. + void SetEmptyHard() + { + vertexVestiges.HardFlush(); + edgeVestiges.HardFlush(); + faceVestiges.HardFlush(); + annotateVestiges.HardFlush(); + symbolVestiges.HardFlush(); + pointVestiges.HardFlush(); + curveVestiges.HardFlush(); + } /// \ru Освободить неиспользуемую память. \en Adjust memory. void Adjust() { @@ -1184,7 +1200,7 @@ inline MbEdgeVestige * MbVEFVestiges::AddVestigeEdge( uint otherComp, size_t oth // // --- inline MbEdgeVestige * MbVEFVestiges::AddVestigeCurve( uint otherComp, size_t otherIdent, const MbName & otherName, bool isCenterLine ) { - return ::AddVestigeCurve( otherComp, otherIdent, otherName, curveVestiges, isCenterLine ); + return ::AddVestigeCurve( otherComp, otherIdent, otherName, curveVestiges, isCenterLine, false ); } //------------------------------------------------------------------------------ @@ -1195,7 +1211,7 @@ inline MbEdgeVestige * MbVEFVestiges::AddVestigeCurve( uint otherComp, size_t ot { MbEdgeVestige * ev = NULL; - ev = ::AddVestigeCurve( otherComp, otherIdent, otherName, curveVestiges, false ); + ev = ::AddVestigeCurve( otherComp, otherIdent, otherName, curveVestiges, false, false ); // BUG_93683 ev = ::AddVestigeEdge( otherComp, otherIdent, otherName, MbBaseVestige::vt_Edge, edgeVestiges ); if ( ev != NULL ) { diff --git a/C3d/Include/marker.h b/C3d/Include/marker.h index 24150b4..49b7d18 100644 --- a/C3d/Include/marker.h +++ b/C3d/Include/marker.h @@ -1,123 +1,123 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Маркер. - \en Marker. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MARKER_H -#define __MARKER_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Маркер со свойствами геометрического объекта. - \en Marker with properties of a geometric object. \~ - \par \ru Определение - Маркером называется тройка объектов: точка и пара ортонормированных векторов. - Например, в системе КОМПАС-3D маркером задается "присоединительная точка", - которая применяется в качестве геометрического коннектора для сопряжения и - позиционирования тел в пространстве.\n - \en Definition - The marker is a triple of objects: a point and a pair of orthonormalized vectors. - For example, in the COMPAS-3D system marker sets the "connecting point", - which is used as geometric connector for conjugation and - positioning of solids in space.\n \~ - - \details \ru Термин "Маркер" позаимствован из книги Г.Крамера, Geometric constraint solving in kinematics.\n - С помощью маркера можно задавать вспомогательные построения, передавать - геометрию кинематических соединений или сопряжений. Маркер всегда принадлежит - какому-то подпространству, например, ЛСК твердого тела.\n - Для маркера всегда выполняется требование; его вектора (в отличие от локальной - системы координат) всегда ортонормированы. Ось Z всегда нормирована, ось X всегда - ортогональна Z (может быть, что X = 0). Маркер может задавать любые геометрические - объекты, которые удобно задать точкой или векторами; это унифицированная форма записи - таких объектов, как точка, прямая, плоскость, ортонормированная правая СК и т.д. - При дополнении маркера радиусом он используется, как сжатая форма записи цилиндра, - окружности, сферы, тора и т.д. \n - \en The term "Marker" is taken from the book "Geometric constraint solving in kinematics" (G.Kramera ).\n - With the help of marker it is possible to set auxiliary constructions and to transmit - geometry of kinematic compounds or conjugations. The marker always belongs - to some subspace, for example, to LSC of solid. \n - For the marker the following requirement is always satisfied: its vectors (as opposed to the local - coordinate system) are always orthonormalized. Z-axis is always normalized, X-axis is always - orthogonal to Z (it could be that X = 0). Marker can set any geometric - objects which are easy to set by point or vectors, this is a unified form of writing - of objects as point, line, plane, right orthonormal CS etc. - When adding a radius to a marker it is used as a compressed form of writing of cylinder, - circle, sphere, torus etc. \n \~ - \sa #MtMarker, #MtUnifiedGeom, #MtMatingGeometry, #MtMatingGeom - \ingroup Legend -*/ -// --- -class MATH_CLASS MbMarker: public MbLegend -{ - MbCartPoint3D origin; ///< \ru Точка маркера. \en Marker point. - MbVector3D axisZ; ///< \ru Нормированный вектор оси OZ. \en Normalized vector of OZ-axis. - MbVector3D axisX; ///< \ru Ортонормированный вектор оси OX. \en Orthonormalized vector of OX-axis. - -public: - /// \ru Конструктор копирования. \en Copy constructor. - MbMarker( const MbMarker & ); - /// \ru Конструктор по точке и вектору. \en Constructor by a point and a vector. - MbMarker( const MbCartPoint3D &, const MbVector3D & ); - /// \ru Конструктор по точке и векторам. \en Constructor by a point and vectors. - MbMarker( const MbCartPoint3D &, const MbVector3D &, const MbVector3D & ); - /// \ru Деструктор. \en Destructor. - virtual ~MbMarker(); - -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 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. - 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. - - // \ru Свойства \en Properties - 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. - - /** \ru \name Функции маркера. - \en \name Functions of marker. - \{ */ - /// \ru Получить точку маркера. \en Get point of marker. - const MbCartPoint3D & GetOrigin() const { return origin; } - /// \ru Получить ось маркера. \en Get axis of marker. - const MbVector3D & GetAxisX() const { return axisX; } - /// \ru Получить вторую ось маркера. \en Get the second axis of marker. - const MbVector3D & GetAxisZ() const { return axisZ; } - /// \ru Задать нулевую ось X. \en Set the X-axis to null. - void SetNullX() { axisX.SetZero(); } - /// \ru Перевернуть ось Z. \en Invert the Z-axis. - MbMarker & InvertZ(); - - /** \} */ - -private: - MbMarker & operator = ( const MbMarker & ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMarker ) -}; - - -IMPL_PERSISTENT_OPS( MbMarker ) - - -#endif // __MARKER_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Маркер. + \en Marker. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MARKER_H +#define __MARKER_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Маркер со свойствами геометрического объекта. + \en Marker with properties of a geometric object. \~ + \par \ru Определение + Маркером называется тройка объектов: точка и пара ортонормированных векторов. + Например, в системе КОМПАС-3D маркером задается "присоединительная точка", + которая применяется в качестве геометрического коннектора для сопряжения и + позиционирования тел в пространстве.\n + \en Definition + The marker is a triple of objects: a point and a pair of orthonormalized vectors. + For example, in the COMPAS-3D system marker sets the "connecting point", + which is used as geometric connector for conjugation and + positioning of solids in space.\n \~ + + \details \ru Термин "Маркер" позаимствован из книги Г.Крамера, Geometric constraint solving in kinematics.\n + С помощью маркера можно задавать вспомогательные построения, передавать + геометрию кинематических соединений или сопряжений. Маркер всегда принадлежит + какому-то подпространству, например, ЛСК твердого тела.\n + Для маркера всегда выполняется требование; его вектора (в отличие от локальной + системы координат) всегда ортонормированы. Ось Z всегда нормирована, ось X всегда + ортогональна Z (может быть, что X = 0). Маркер может задавать любые геометрические + объекты, которые удобно задать точкой или векторами; это унифицированная форма записи + таких объектов, как точка, прямая, плоскость, ортонормированная правая СК и т.д. + При дополнении маркера радиусом он используется, как сжатая форма записи цилиндра, + окружности, сферы, тора и т.д. \n + \en The term "Marker" is taken from the book "Geometric constraint solving in kinematics" (G.Kramera ).\n + With the help of marker it is possible to set auxiliary constructions and to transmit + geometry of kinematic compounds or conjugations. The marker always belongs + to some subspace, for example, to LSC of solid. \n + For the marker the following requirement is always satisfied: its vectors (as opposed to the local + coordinate system) are always orthonormalized. Z-axis is always normalized, X-axis is always + orthogonal to Z (it could be that X = 0). Marker can set any geometric + objects which are easy to set by point or vectors, this is a unified form of writing + of objects as point, line, plane, right orthonormal CS etc. + When adding a radius to a marker it is used as a compressed form of writing of cylinder, + circle, sphere, torus etc. \n \~ + \sa #MtMarker, #MtUnifiedGeom, #MtMatingGeometry, #MtMatingGeom + \ingroup Legend +*/ +// --- +class MATH_CLASS MbMarker: public MbLegend +{ + MbCartPoint3D origin; ///< \ru Точка маркера. \en Marker point. + MbVector3D axisZ; ///< \ru Нормированный вектор оси OZ. \en Normalized vector of OZ-axis. + MbVector3D axisX; ///< \ru Ортонормированный вектор оси OX. \en Orthonormalized vector of OX-axis. + +public: + /// \ru Конструктор копирования. \en Copy constructor. + MbMarker( const MbMarker & ); + /// \ru Конструктор по точке и вектору. \en Constructor by a point and a vector. + MbMarker( const MbCartPoint3D &, const MbVector3D & ); + /// \ru Конструктор по точке и векторам. \en Constructor by a point and vectors. + MbMarker( const MbCartPoint3D &, const MbVector3D &, const MbVector3D & ); + /// \ru Деструктор. \en Destructor. + virtual ~MbMarker(); + +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 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. + 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. + + // \ru Свойства \en Properties + 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. + + /** \ru \name Функции маркера. + \en \name Functions of marker. + \{ */ + /// \ru Получить точку маркера. \en Get point of marker. + const MbCartPoint3D & GetOrigin() const { return origin; } + /// \ru Получить ось маркера. \en Get axis of marker. + const MbVector3D & GetAxisX() const { return axisX; } + /// \ru Получить вторую ось маркера. \en Get the second axis of marker. + const MbVector3D & GetAxisZ() const { return axisZ; } + /// \ru Задать нулевую ось X. \en Set the X-axis to null. + void SetNullX() { axisX.SetZero(); } + /// \ru Перевернуть ось Z. \en Invert the Z-axis. + MbMarker & InvertZ(); + + /** \} */ + +private: + MbMarker & operator = ( const MbMarker & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMarker ) +}; + + +IMPL_PERSISTENT_OPS( MbMarker ) + + +#endif // __MARKER_H diff --git a/C3d/Include/math_cfg.h b/C3d/Include/math_cfg.h index 26c5a32..861f61d 100644 --- a/C3d/Include/math_cfg.h +++ b/C3d/Include/math_cfg.h @@ -61,5 +61,13 @@ #endif //C3D_WINDOWS +/* + \ru Включение/выключение контроля выделения памяти под отладкой. + \en Switching on/off memory allocation control during the debugging process. +*/ +//#define __DEBUG_MEMORY_ALLOCATE_FREE_ // Overload operators new/delete and check memory +//#define __MEMSET_USED_FREE_HEAP_HEAR__ // Mark used memory +//#define __REALLOC_ARRAYS_STATISTIC_ // Collect statistics on arrays size changes + #endif // __MATH_CFG_H diff --git a/C3d/Include/math_define.h b/C3d/Include/math_define.h index 7c63110..e76fd8b 100644 --- a/C3d/Include/math_define.h +++ b/C3d/Include/math_define.h @@ -32,7 +32,6 @@ #endif // PRECONDITION #endif // C3D_WINDOWS -#include // \ru Внимание! Читаем внимательно! Если вытереть отсюда, то подключить везде, где есть функции из этого файла! \en Attention! Read carefully! If remove this from here, then it should be included anywhere where the functions from this file exist! #include #include #include @@ -82,12 +81,15 @@ typedef UintSet::iterator UintSetIt; typedef UintSet::const_iterator UintSetConstIt; typedef std::pair UintSetRet; +typedef std::pair IndicesPairsPair; ///< \ru Пара индексных пар. \en Pair of indices' pair. + + //------------------------------------------------------------------------------ // // --- template bool IsNullPointer( const ItemPtr * itemPtr ) { - return ((NULL == itemPtr) ? true : false); + return ((C3D_NULL_PTR == itemPtr) ? true : false); } //------------------------------------------------------------------------------ @@ -194,7 +196,7 @@ size_t BinarySearch( Elements & items, const Element & item ) //------------------------------------------------------------------------------ // \ru Синтаксис дружественной шаблонной функции шаблона \en Syntax of friendly template function of a template -#if !(defined (_MSC_VER)) || __BORLANDC__ +#if !(defined (_MSC_VER)) #define TEMPLATE_FRIEND friend // \ru по стандарту C++98 \en by the C++98 standard #define TEMPLATE_SUFFIX @@ -266,7 +268,7 @@ private: \ #define __WARN__ __FILE__ "("__DEFTOSTR__(__LINE__)") : warning: " #else // _MSC_VER -// For linux and borland +// For linux #define __TODO__ #define __WARN__ @@ -295,15 +297,18 @@ private: \ #define MATH_CLASS __declspec( dllexport ) #define MATH_FUNC(retType) __declspec( dllexport ) retType CALL_DECLARATION #define MATH_FUNC_EX __declspec( dllexport ) // \ru для KNOWN_OBJECTS_RW_REF_OPERATORS_EX и KNOWN_OBJECTS_RW_PTR_OPERATORS_EX \en for KNOWN_OBJECTS_RW_REF_OPERATORS_EX and KNOWN_OBJECTS_RW_PTR_OPERATORS_EX + #define MATH_SYMBOL __declspec( dllexport ) #else #define MATH_CLASS __declspec( dllimport ) #define MATH_FUNC(retType) __declspec( dllimport ) retType CALL_DECLARATION #define MATH_FUNC_EX __declspec( dllimport ) + #define MATH_SYMBOL __declspec( dllimport ) #endif #else // C3D_WINDOWS #define MATH_CLASS #define MATH_FUNC(retType) retType #define MATH_FUNC_EX + #define MATH_SYMBOL #endif // \ru Модуль геометрических ограничений. \en Geometric constraints module. @@ -329,12 +334,12 @@ namespace c3d // namespace C3D //------------------------------------------------------------------------------ /// \ru Максимальное количество элементов матрицы MxN. \en Maximum number of MxN matrix elements. //--- -const size_t MATRIX_MAX_COUNT = 1000000000; // 1e9 +const_expr size_t MATRIX_MAX_COUNT = 1000000000; // 1e9 //------------------------------------------------------------------------------ /// \ru Максимальный размер массива. \en Maximum size of array. //--- -const size_t ARRAY_MAX_COUNT = 1000000; // 1e6 +const_expr size_t ARRAY_MAX_COUNT = 1000000; // 1e6 //------------------------------------------------------------------------------ /** @@ -559,6 +564,38 @@ inline void GetCosSin( const double & tt, double & cosT, double & sinT ) inline void DummyAssert( bool ) { } + namespace older_stl_support + { + //------------------------------------------------------------------------------ + /** \brief \ru Суррогат "iterator erase( iterator pos )" для старых версий std:map и std::set. + \en "iterator erase( iterator pos )" surrogate for older versions of std:map and std:: set.. \~ + \details \ru Для унификации кода при поддержке версий std:map и std::set, + в которых не реализована iterator erase( iterator pos ). \n + \en To unify the code with support for STD:map and std::set versions + that do not implement iterator erase( iterator pos). \n \~ + \param[in] obj - \ru Контейнер из которого удаляется элемент. + \en Container that the item is being removed from. \~ + \param[in] pos - \ru Итератор на удаляемый элемент. + \en Iterator to the element to remove. \~ + \return \ru Итератор на элемент, следующий за удаленным. + \en Iterator following the removed element. \~ + \ingroup Base_Tools + */ + // --- + template inline typename T::iterator erase( T& obj, typename T::iterator pos ) + { + #if defined(__GNUC__) && ( C3D_GCC_VERSION < 40805 ) + typename T::iterator temp = pos; + pos++; + obj.erase( temp ); + return pos; + #else + return obj.erase( pos ); + #endif + } + } + + } // namespace C3D diff --git a/C3d/Include/math_doxigen.h b/C3d/Include/math_doxigen.h index 2162966..1845d77 100644 --- a/C3d/Include/math_doxigen.h +++ b/C3d/Include/math_doxigen.h @@ -1,421 +1,421 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Группы для документирования с помощью Doxygen. - \en Groups for documenting by Doxygen. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MATH_DOXIGEN_H -#define __MATH_DOXIGEN_H - - -//----------------------------------------------------------------------------- -// -// -// \ru Группы геометрического ядра \en Groups of the Geometric Kernel \~ -// -// -//----------------------------------------------------------------------------- - -/** - \ru \defgroup Geometric_Modelling C3D Modeler: Модуль геометрического моделирования - \en \defgroup Geometric_Modelling C3D Modeler: The Geometric Modelling Module - \~ \ingroup Geometric_Kernel -*/ - - -/** - \ru \defgroup Geometric_Constraints C3D Solver: Модуль геометрических ограничений - \en \defgroup Geometric_Constraints C3D Solver: The Geometric Constraints Module - \~ \ingroup Geometric_Kernel -*/ - - -/** - \ru \defgroup Data_Exchange C3D Converter: Модуль конвертеров - \en \defgroup Data_Exchange C3D Converter: The Converters Module - \~ \ingroup Geometric_Kernel -*/ - - -//----------------------------------------------------------------------------- -// -// \ru Подгруппа Geometric_Modelling - Модуль геометрического моделирования \en The Geometric Modelling Module \~ -// -//----------------------------------------------------------------------------- -/** - \ru \defgroup Geometric_Items Геометрические объекты - \en \defgroup Geometric_Items Geometric Objects - \~ \ingroup Geometric_Modelling -*/ -/** - \ru \defgroup Base_Items Объекты алгоритмов - \en \defgroup Base_Items Algorithm Objects - \~ \ingroup Geometric_Modelling -*/ -/** - \ru \defgroup Modelling_Functions Методы геометрических построений - \en \defgroup Modelling_Functions Geometric Construction Methods - \~ \ingroup Geometric_Modelling -*/ -/** - \ru \defgroup Geometric_Computation Методы геометрических вычислений - \en \defgroup Geometric_Computation Geometric Computations Methods - \~ \ingroup Geometric_Modelling -*/ -/** - \ru \defgroup Base_Tools Библиотека шаблонов и сериализации - \en \defgroup Base_Tools Templates and Serializations Library - \~ \ingroup Geometric_Modelling -*/ - - -//----------------------------------------------------------------------------------- -// \ru Подгруппа Geometric_Items - Геометрические объекты \en Geometric Objects \~ -//----------------------------------------------------------------------------------- -/** - \ru \defgroup Model_Items Объекты геометрической модели - \en \defgroup Model_Items Geometric Model Objects - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Topology_Items Топологические объекты - \en \defgroup Topology_Items Topological Objects - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Surfaces Поверхности - \en \defgroup Surfaces Surfaces - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Curves_3D Кривые - \en \defgroup Curves_3D Curves - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Point_3D Точка - \en \defgroup Point_3D Point - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Legend Вспомогательные объекты - \en \defgroup Legend Ancillary Items - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Curves_2D Двумерные кривые - \en \defgroup Curves_2D Two-Dimensional uv-Curves - \~ \ingroup Geometric_Items -*/ -/** - \ru \defgroup Region_2D Двумерные области - \en \defgroup Region_2D Two-Dimensional Regions - \~ \ingroup Geometric_Items -*/ - - -//----------------------------------------------------------------------------- -// \ru Подгруппа Base_Items - базовые объекты \en Base Objects \~ -//----------------------------------------------------------------------------- -/** - \ru \defgroup Mathematic_Base_3D Трёхмерные базовые объекты - \en \defgroup Mathematic_Base_3D Three-Dimensional Base Objects - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Mathematic_Base_2D Двумерные базовые объекты - \en \defgroup Mathematic_Base_2D Two-Dimensional Base Objects - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Model_Creators Строители - \en \defgroup Model_Creators Creators - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Model_Attributes Атрибуты - \en \defgroup Model_Attributes Attributes - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Functions Скалярные функции - \en \defgroup Functions Scalar Functions - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Build_Parameters Параметры операций - \en \defgroup Build_Parameters Operation Parameters - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Model_Properties Свойства - \en \defgroup Model_Properties Properties - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Data_Structures Структуры данных - \en \defgroup Data_Structures Data Structures - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Parser Разбор строки - \en \defgroup Parser Parser - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Names Имена - \en \defgroup Names Names - \~ \ingroup Base_Items -*/ -/** - \ru \defgroup Model Модель - \en \defgroup Model Model - \~ \ingroup Base_Items -*/ - - -//----------------------------------------------------------------------------------- -// \ru Подгруппа Modelling_Functions - Методы геометрических построений \en Methods of Geometric Constructions \~ -//----------------------------------------------------------------------------------- -/** - \ru \defgroup Solid_Modeling Построение тел - \en \defgroup Solid_Modeling Solid Modeling - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Shell_Modeling Построение оболочек - \en \defgroup Shell_Modeling Shell Modeling - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Sheet_Metal_Modeling Построения листовых тел - \en \defgroup Sheet_Metal_Modeling Sheet Metal Modeling - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Direct_Modeling Прямое редактирование тел - \en \defgroup Direct_Modeling Direct Solid Modeling - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Surface_Modeling Построение поверхностей - \en \defgroup Surface_Modeling Construction of Surfaces - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Curve3D_Modeling Построение кривых в трёхмерном пространстве - \en \defgroup Curve3D_Modeling Construction of Curves - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Curve_Modeling Построение кривых в двумерном пространстве - \en \defgroup Curve_Modeling Construction of uv-Curves in Two-Dimensional Space - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Point_Modeling Операции с точками - \en \defgroup Point_Modeling Operations with Points - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Base_Algorithms Базовые алгоритмы - \en \defgroup Base_Algorithms Base Algorithms - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Algorithms_3D Алгоритмы в трёхмерном пространстве - \en \defgroup Algorithms_3D Algorithms in Three-Dimensional Space - \~ \ingroup Modelling_Functions -*/ -/** - \ru \defgroup Algorithms_2D Алгоритмы в двумерном пространстве - \en \defgroup Algorithms_2D Algorithms in Two-Dimensional Space - \~ \ingroup Modelling_Functions -*/ - - -//---------------------------------------------------------------------------- -// \ru Подгруппа Geometric_Computation - Методы геометрических расчетов \en Geometric Computations Methods \~ -//---------------------------------------------------------------------------- -/** - \ru \defgroup Polygonal_Objects Полигональные объекты - \en \defgroup Polygonal_Objects Polygonal Objects - \~ \ingroup Geometric_Computation -*/ -/** - \ru \defgroup Triangulation Триангуляция - \en \defgroup Triangulation Triangulation - \~ \ingroup Geometric_Computation -*/ -/** - \ru \defgroup Mapping Построение плоских проекций - \en \defgroup Mapping Construction of Plane Projections - \~ \ingroup Geometric_Computation -*/ -/** - \ru \defgroup Inertia_Computation Вычисление инерционных характеристик - \en \defgroup Inertia_Computation Mass-Inertial Properties - \~ \ingroup Geometric_Computation -*/ -/** - \ru \defgroup Collision_Detection Определение столкновений - \en \defgroup Collision_Detection Collision Detection - \~ \ingroup Geometric_Computation -*/ -/** - \ru \defgroup Drawing Визуализация объектов - \en \defgroup Drawing Objects Visualization - \~ \ingroup Geometric_Computation -*/ - - -//----------------------------------------------------------------------------- -// \ru Подгруппа Base_Tools - Библиотека шаблонов и сериализации \en Library of Templates and Serializations \~ -//----------------------------------------------------------------------------- -/** - \ru \defgroup Base_Tools_Containers Контейнеры - \en \defgroup Base_Tools_Containers Containers - \~ \ingroup Base_Tools -*/ -/** - \ru \defgroup Base_Tools_SmartPointers Автоматические указатели - \en \defgroup Base_Tools_SmartPointers Smart Pointers - \~ \ingroup Base_Tools -*/ -/** - \ru \defgroup Base_Tools_String Работа со строками - \en \defgroup Base_Tools_String Work with Strings - \~ \ingroup Base_Tools -*/ -/** - \ru \defgroup Base_Tools_IO Работа с потоками - \en \defgroup Base_Tools_IO Work with Streams - \~ \ingroup Base_Tools -*/ - - -//----------------------------------------------------------------------------- -// -// \ru Подгруппа Geometric_Constraints - Модуль геометрических ограничений \en The Geometric Constraints Module \~ -// -//----------------------------------------------------------------------------- -/** - \ru \defgroup Mating Геометрические ограничения трёхмерных объектов - \en \defgroup Mating Geometric Constraint Solver in Three-Dimensional Space - \~ \ingroup Geometric_Constraints -*/ -/** - \ru \defgroup MathGC Геометрические ограничения двумерных объектов - \en \defgroup MathGC Geometric Constraint Solver in Two-Dimensional Space - \~ \ingroup Geometric_Constraints -*/ - -//----------------------------------------------------------------------------- -// \ru Подгруппа трехмерного геометрического решателя \en The subgroup of three-dimensional geometric constraint manager (GCM) -//----------------------------------------------------------------------------- -/** - \ru \defgroup GCM_3D_API Базовые функции и типы данных - \en \defgroup GCM_3D_API Basic functions and data types - \~ \ingroup Mating -*/ -/** - \ru \defgroup GCM_3D_ObjectAPI Объектный интерфейс - \en \defgroup GCM_3D_ObjectAPI Object-oriented interface - \~ \ingroup Mating -*/ -/** - \ru \defgroup GCM_3D_Routines Вспомогательные процедуры - \en \defgroup GCM_3D_Routines Auxiliary routines - \~ \ingroup Mating -*/ - -//----------------------------------------------------------------------------- -// \ru Подгруппа двумерного геометрического решателя \en The subgroup of two-dimensional geometric constraint engine (GCE) -//----------------------------------------------------------------------------- -/** - \ru \defgroup Constraints2D_API Интерфейс - \en \defgroup Constraints2D_API Solver Interface - \~ \ingroup MathGC -*/ - -//----------------------------------------------------------------------------------- -// -// \ru Подгруппа Data_Exchange - Модуль конвертеров \en The Converters Module \~ -// -//----------------------------------------------------------------------------------- -/** - \ru \defgroup Exchange_Interface Интерфейс конвертеров - \en \defgroup Exchange_Interface Converters Interface - \~ \ingroup Data_Exchange -*/ -/** - \internal - \ru \defgroup Exchange_Base Базовые объекты конвертеров - \en \defgroup Exchange_Base Converters Basic Objects - \~ \ingroup Data_Exchange - \endinternal -*/ -/** - \internal - \ru \defgroup Exchange_Util Вспомогательные объекты конвертеров - \en \defgroup Exchange_Util Converters Ancillary Facilities - \~ \ingroup Data_Exchange - \endinternal -*/ -/** - \internal - \ru \defgroup Exchange_Algorithms Алгоритмы конвертеров - \en \defgroup Exchange_Algorithms Converters Algorithms - \~ \ingroup Data_Exchange - \endinternal -*/ -/** - \ru \defgroup Exchange_Formats Поддерживаемые форматы данных - \en \defgroup Exchange_Formats Supported Data Formats - \~ \ingroup Data_Exchange -*/ - - -//----------------------------------------------------------------------------------- -// \ru Подгруппа Exchange_Formats - Поддерживаемые конвертером форматы данных \en Converters Supported Data Formats \~ -//----------------------------------------------------------------------------------- -/** - \ru \defgroup Parasolid_Exchange Parasolid конвертер - \en \defgroup Parasolid_Exchange Parasolid Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup ACIS_Exchange ACIS конвертер - \en \defgroup ACIS_Exchange ACIS Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup IGES_Exchange IGES конвертер - \en \defgroup IGES_Exchange IGES Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup STEP_Exchange STEP конвертер - \en \defgroup STEP_Exchange STEP Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup STL_Exchange STL конвертер - \en \defgroup STL_Exchange STL Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup VRML_Exchange VRML конвертер - \en \defgroup VRML_Exchange VRML Converter - \~ \ingroup Exchange_Formats -*/ -/** - \ru \defgroup DXF_Exchange DXF конвертер 3D - \en \defgroup DXF_Exchange DXF Converter for 3D - \~ \ingroup Exchange_Formats -*/ - - -#endif // __MATH_DOXIGEN_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Группы для документирования с помощью Doxygen. + \en Groups for documenting by Doxygen. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MATH_DOXIGEN_H +#define __MATH_DOXIGEN_H + + +//----------------------------------------------------------------------------- +// +// +// \ru Группы геометрического ядра \en Groups of the Geometric Kernel \~ +// +// +//----------------------------------------------------------------------------- + +/** + \ru \defgroup Geometric_Modelling C3D Modeler: Модуль геометрического моделирования + \en \defgroup Geometric_Modelling C3D Modeler: The Geometric Modelling Module + \~ \ingroup Geometric_Kernel +*/ + + +/** + \ru \defgroup Geometric_Constraints C3D Solver: Модуль геометрических ограничений + \en \defgroup Geometric_Constraints C3D Solver: The Geometric Constraints Module + \~ \ingroup Geometric_Kernel +*/ + + +/** + \ru \defgroup Data_Exchange C3D Converter: Модуль конвертеров + \en \defgroup Data_Exchange C3D Converter: The Converters Module + \~ \ingroup Geometric_Kernel +*/ + + +//----------------------------------------------------------------------------- +// +// \ru Подгруппа Geometric_Modelling - Модуль геометрического моделирования \en The Geometric Modelling Module \~ +// +//----------------------------------------------------------------------------- +/** + \ru \defgroup Geometric_Items Геометрические объекты + \en \defgroup Geometric_Items Geometric Objects + \~ \ingroup Geometric_Modelling +*/ +/** + \ru \defgroup Base_Items Объекты алгоритмов + \en \defgroup Base_Items Algorithm Objects + \~ \ingroup Geometric_Modelling +*/ +/** + \ru \defgroup Modelling_Functions Методы геометрических построений + \en \defgroup Modelling_Functions Geometric Construction Methods + \~ \ingroup Geometric_Modelling +*/ +/** + \ru \defgroup Geometric_Computation Методы геометрических вычислений + \en \defgroup Geometric_Computation Geometric Computations Methods + \~ \ingroup Geometric_Modelling +*/ +/** + \ru \defgroup Base_Tools Библиотека шаблонов и сериализации + \en \defgroup Base_Tools Templates and Serializations Library + \~ \ingroup Geometric_Modelling +*/ + + +//----------------------------------------------------------------------------------- +// \ru Подгруппа Geometric_Items - Геометрические объекты \en Geometric Objects \~ +//----------------------------------------------------------------------------------- +/** + \ru \defgroup Model_Items Объекты геометрической модели + \en \defgroup Model_Items Geometric Model Objects + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Topology_Items Топологические объекты + \en \defgroup Topology_Items Topological Objects + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Surfaces Поверхности + \en \defgroup Surfaces Surfaces + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Curves_3D Кривые + \en \defgroup Curves_3D Curves + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Point_3D Точка + \en \defgroup Point_3D Point + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Legend Вспомогательные объекты + \en \defgroup Legend Ancillary Items + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Curves_2D Двумерные кривые + \en \defgroup Curves_2D Two-Dimensional uv-Curves + \~ \ingroup Geometric_Items +*/ +/** + \ru \defgroup Region_2D Двумерные области + \en \defgroup Region_2D Two-Dimensional Regions + \~ \ingroup Geometric_Items +*/ + + +//----------------------------------------------------------------------------- +// \ru Подгруппа Base_Items - базовые объекты \en Base Objects \~ +//----------------------------------------------------------------------------- +/** + \ru \defgroup Mathematic_Base_3D Трёхмерные базовые объекты + \en \defgroup Mathematic_Base_3D Three-Dimensional Base Objects + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Mathematic_Base_2D Двумерные базовые объекты + \en \defgroup Mathematic_Base_2D Two-Dimensional Base Objects + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Model_Creators Строители + \en \defgroup Model_Creators Creators + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Model_Attributes Атрибуты + \en \defgroup Model_Attributes Attributes + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Functions Скалярные функции + \en \defgroup Functions Scalar Functions + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Build_Parameters Параметры операций + \en \defgroup Build_Parameters Operation Parameters + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Model_Properties Свойства + \en \defgroup Model_Properties Properties + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Data_Structures Структуры данных + \en \defgroup Data_Structures Data Structures + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Parser Разбор строки + \en \defgroup Parser Parser + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Names Имена + \en \defgroup Names Names + \~ \ingroup Base_Items +*/ +/** + \ru \defgroup Model Модель + \en \defgroup Model Model + \~ \ingroup Base_Items +*/ + + +//----------------------------------------------------------------------------------- +// \ru Подгруппа Modelling_Functions - Методы геометрических построений \en Methods of Geometric Constructions \~ +//----------------------------------------------------------------------------------- +/** + \ru \defgroup Solid_Modeling Построение тел + \en \defgroup Solid_Modeling Solid Modeling + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Shell_Modeling Построение оболочек + \en \defgroup Shell_Modeling Shell Modeling + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Sheet_Metal_Modeling Построения листовых тел + \en \defgroup Sheet_Metal_Modeling Sheet Metal Modeling + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Direct_Modeling Прямое редактирование тел + \en \defgroup Direct_Modeling Direct Solid Modeling + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Surface_Modeling Построение поверхностей + \en \defgroup Surface_Modeling Construction of Surfaces + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Curve3D_Modeling Построение кривых в трёхмерном пространстве + \en \defgroup Curve3D_Modeling Construction of Curves + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Curve_Modeling Построение кривых в двумерном пространстве + \en \defgroup Curve_Modeling Construction of uv-Curves in Two-Dimensional Space + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Point_Modeling Операции с точками + \en \defgroup Point_Modeling Operations with Points + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Base_Algorithms Базовые алгоритмы + \en \defgroup Base_Algorithms Base Algorithms + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Algorithms_3D Алгоритмы в трёхмерном пространстве + \en \defgroup Algorithms_3D Algorithms in Three-Dimensional Space + \~ \ingroup Modelling_Functions +*/ +/** + \ru \defgroup Algorithms_2D Алгоритмы в двумерном пространстве + \en \defgroup Algorithms_2D Algorithms in Two-Dimensional Space + \~ \ingroup Modelling_Functions +*/ + + +//---------------------------------------------------------------------------- +// \ru Подгруппа Geometric_Computation - Методы геометрических расчетов \en Geometric Computations Methods \~ +//---------------------------------------------------------------------------- +/** + \ru \defgroup Polygonal_Objects Полигональные объекты + \en \defgroup Polygonal_Objects Polygonal Objects + \~ \ingroup Geometric_Computation +*/ +/** + \ru \defgroup Triangulation Триангуляция + \en \defgroup Triangulation Triangulation + \~ \ingroup Geometric_Computation +*/ +/** + \ru \defgroup Mapping Построение плоских проекций + \en \defgroup Mapping Construction of Plane Projections + \~ \ingroup Geometric_Computation +*/ +/** + \ru \defgroup Inertia_Computation Вычисление инерционных характеристик + \en \defgroup Inertia_Computation Mass-Inertial Properties + \~ \ingroup Geometric_Computation +*/ +/** + \ru \defgroup Collision_Detection Определение столкновений + \en \defgroup Collision_Detection Collision Detection + \~ \ingroup Geometric_Computation +*/ +/** + \ru \defgroup Drawing Визуализация объектов + \en \defgroup Drawing Objects Visualization + \~ \ingroup Geometric_Computation +*/ + + +//----------------------------------------------------------------------------- +// \ru Подгруппа Base_Tools - Библиотека шаблонов и сериализации \en Library of Templates and Serializations \~ +//----------------------------------------------------------------------------- +/** + \ru \defgroup Base_Tools_Containers Контейнеры + \en \defgroup Base_Tools_Containers Containers + \~ \ingroup Base_Tools +*/ +/** + \ru \defgroup Base_Tools_SmartPointers Автоматические указатели + \en \defgroup Base_Tools_SmartPointers Smart Pointers + \~ \ingroup Base_Tools +*/ +/** + \ru \defgroup Base_Tools_String Работа со строками + \en \defgroup Base_Tools_String Work with Strings + \~ \ingroup Base_Tools +*/ +/** + \ru \defgroup Base_Tools_IO Работа с потоками + \en \defgroup Base_Tools_IO Work with Streams + \~ \ingroup Base_Tools +*/ + + +//----------------------------------------------------------------------------- +// +// \ru Подгруппа Geometric_Constraints - Модуль геометрических ограничений \en The Geometric Constraints Module \~ +// +//----------------------------------------------------------------------------- +/** + \ru \defgroup Mating Геометрические ограничения трёхмерных объектов + \en \defgroup Mating Geometric Constraint Solver in Three-Dimensional Space + \~ \ingroup Geometric_Constraints +*/ +/** + \ru \defgroup MathGC Геометрические ограничения двумерных объектов + \en \defgroup MathGC Geometric Constraint Solver in Two-Dimensional Space + \~ \ingroup Geometric_Constraints +*/ + +//----------------------------------------------------------------------------- +// \ru Подгруппа трехмерного геометрического решателя \en The subgroup of three-dimensional geometric constraint manager (GCM) +//----------------------------------------------------------------------------- +/** + \ru \defgroup GCM_3D_API Базовые функции и типы данных + \en \defgroup GCM_3D_API Basic functions and data types + \~ \ingroup Mating +*/ +/** + \ru \defgroup GCM_3D_ObjectAPI Объектный интерфейс + \en \defgroup GCM_3D_ObjectAPI Object-oriented interface + \~ \ingroup Mating +*/ +/** + \ru \defgroup GCM_3D_Routines Вспомогательные процедуры + \en \defgroup GCM_3D_Routines Auxiliary routines + \~ \ingroup Mating +*/ + +//----------------------------------------------------------------------------- +// \ru Подгруппа двумерного геометрического решателя \en The subgroup of two-dimensional geometric constraint engine (GCE) +//----------------------------------------------------------------------------- +/** + \ru \defgroup Constraints2D_API Интерфейс + \en \defgroup Constraints2D_API Solver Interface + \~ \ingroup MathGC +*/ + +//----------------------------------------------------------------------------------- +// +// \ru Подгруппа Data_Exchange - Модуль конвертеров \en The Converters Module \~ +// +//----------------------------------------------------------------------------------- +/** + \ru \defgroup Exchange_Interface Интерфейс конвертеров + \en \defgroup Exchange_Interface Converters Interface + \~ \ingroup Data_Exchange +*/ +/** + \internal + \ru \defgroup Exchange_Base Базовые объекты конвертеров + \en \defgroup Exchange_Base Converters Basic Objects + \~ \ingroup Data_Exchange + \endinternal +*/ +/** + \internal + \ru \defgroup Exchange_Util Вспомогательные объекты конвертеров + \en \defgroup Exchange_Util Converters Ancillary Facilities + \~ \ingroup Data_Exchange + \endinternal +*/ +/** + \internal + \ru \defgroup Exchange_Algorithms Алгоритмы конвертеров + \en \defgroup Exchange_Algorithms Converters Algorithms + \~ \ingroup Data_Exchange + \endinternal +*/ +/** + \ru \defgroup Exchange_Formats Поддерживаемые форматы данных + \en \defgroup Exchange_Formats Supported Data Formats + \~ \ingroup Data_Exchange +*/ + + +//----------------------------------------------------------------------------------- +// \ru Подгруппа Exchange_Formats - Поддерживаемые конвертером форматы данных \en Converters Supported Data Formats \~ +//----------------------------------------------------------------------------------- +/** + \ru \defgroup Parasolid_Exchange Parasolid конвертер + \en \defgroup Parasolid_Exchange Parasolid Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup ACIS_Exchange ACIS конвертер + \en \defgroup ACIS_Exchange ACIS Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup IGES_Exchange IGES конвертер + \en \defgroup IGES_Exchange IGES Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup STEP_Exchange STEP конвертер + \en \defgroup STEP_Exchange STEP Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup STL_Exchange STL конвертер + \en \defgroup STL_Exchange STL Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup VRML_Exchange VRML конвертер + \en \defgroup VRML_Exchange VRML Converter + \~ \ingroup Exchange_Formats +*/ +/** + \ru \defgroup DXF_Exchange DXF конвертер 3D + \en \defgroup DXF_Exchange DXF Converter for 3D + \~ \ingroup Exchange_Formats +*/ + + +#endif // __MATH_DOXIGEN_H diff --git a/C3d/Include/math_version.h b/C3d/Include/math_version.h index 9acb56a..b2d3c52 100644 --- a/C3d/Include/math_version.h +++ b/C3d/Include/math_version.h @@ -83,6 +83,8 @@ #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 C3D_2020_VERSION 0x13001004L ///< \ru Версия файла - C3D 2020. \en The file version - C3D 2020. \~ \ingroup Base_Tools //------------------------------------------------------------------------------ @@ -128,6 +130,7 @@ enum MbeWritableReleaseVersion wrv_MATH_18 = MATH_18_VERSION, ///< \ru Версия файла - 18.0. \en The file version - 18.0. 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_PrevRelease = wrv_MATH_18_SP1, ///< \ru Версия потока предпоследнего релиза. \en The previous release version. wrv_LastRelease = wrv_C3D_2019, ///< \ru Версия потока последнего релиза. \en The last release version. diff --git a/C3d/Include/mb_cart_point.h b/C3d/Include/mb_cart_point.h index ef9d07a..752ced9 100644 --- a/C3d/Include/mb_cart_point.h +++ b/C3d/Include/mb_cart_point.h @@ -15,6 +15,25 @@ class MATH_CLASS MbFloatPoint; +class MATH_CLASS MbCartPoint; + + +namespace c3d // namespace C3D +{ +typedef std::vector ParamPointsVector; ///< \ru Вектор точек. \en Points vector. +typedef std::vector ParamVectorsVector; ///< \ru Вектор векторов. \en Vectors vector. + +typedef std::pair ParamPointIndex; ///< \ru Пара точка-индекс. \en Pair point-index. +typedef std::pair Point2DIndex; ///< \ru Пара точка-индекс. \en Pair point-index. + +typedef std::pair IndexParamPoint; ///< \ru Пара индекс-точка. \en Pair index-point. +typedef std::pair IndexPoint2D; ///< \ru Пара индекс-точка. \en Pair index-point. + +typedef std::pair ParamPointsPair; ///< \ru Пара точка-точка. \en Pair point-point. + +typedef std::pair ParamPointVector; ///< \ru Пара точка-вектор. \en Pair point-vector. +typedef std::pair PointVector2D; ///< \ru Пара точка-вектор. \en Pair point-vector. +} //------------------------------------------------------------------------------ @@ -255,7 +274,7 @@ public : MbCartPoint operator - ( const MbDirection & d ) const; /// \ru Унарный минус. \en The unary minus. - MbCartPoint operator - (); + MbCartPoint operator - () const; /// \ru Умножить точку на число. \en Multiply a point by a number. MbCartPoint operator * ( double factor ) const; /// \ru Разделить точку на число. \en Divide a point by a number. @@ -299,7 +318,7 @@ public : \return \ru Искомое расстояние. \en The required distance. \~ */ - double DistanceToLineSeg( const MbCartPoint & p1, const MbCartPoint &p2 ) const; + double DistanceToLineSeg( const MbCartPoint & p1, const MbCartPoint & p2 ) const; /// \ru Длина вектора ( 0, p(x,y) ). \en The vector length ( 0, p(x,y) ). double Length() const; @@ -574,7 +593,7 @@ inline void MbCartPoint::operator /= ( double factor ) { //------------------------------------------------------------------------------ // \ru Унарный минус. \en The unary minus. // --- -inline MbCartPoint MbCartPoint::operator - () { +inline MbCartPoint MbCartPoint::operator - () const { return MbCartPoint ( - x, - y ); } diff --git a/C3d/Include/mb_cart_point3d.h b/C3d/Include/mb_cart_point3d.h index 680cbbb..b71dd12 100644 --- a/C3d/Include/mb_cart_point3d.h +++ b/C3d/Include/mb_cart_point3d.h @@ -11,14 +11,32 @@ #ifndef __MB_CART_POINT3D_H #define __MB_CART_POINT3D_H - #include class MATH_CLASS MbCartPoint; +class MATH_CLASS MbCartPoint3D; class MATH_CLASS MbFloatPoint3D; +namespace c3d // namespace C3D +{ +typedef std::vector SpacePointsVector; ///< \ru Вектор точек. \en Points vector. +typedef std::vector SpaceVectorsVector; ///< \ru Вектор векторов. \en Vectors vector. + +typedef std::pair SpacePointIndex; ///< \ru Пара точка-индекс. \en Pair point-index. +typedef std::pair Point3DIndex; ///< \ru Пара точка-индекс. \en Pair point-index. + +typedef std::pair IndexSpacePoint; ///< \ru Пара индекс-точка. \en Pair index-point. +typedef std::pair IndexPoint3D; ///< \ru Пара индекс-точка. \en Pair index-point. + +typedef std::pair SpacePointsPair; ///< \ru Пара точка-точка. \en Pair point-point. + +typedef std::pair SpacePointVector; ///< \ru Пара точка-вектор. \en Pair point-vector. +typedef std::pair PointVector3D; ///< \ru Пара точка-вектор. \en Pair point-vector. +} + + //------------------------------------------------------------------------------ /** \brief \ru Трехмерная точка. \en The three-dimensional point. \~ @@ -179,7 +197,7 @@ public : /// \ru Вычесть из точки точку. \en Subtract a point from the point. MbVector3D operator - ( const MbCartPoint3D & ) const; /// \ru Унарный минус. \en The unary minus. - MbCartPoint3D operator - (); + MbCartPoint3D operator - () const; /// \ru Вычислить точку как копию данной точки, преобразованную матрицей. \en Calculate the point as this copy transformed by the matrix. MbCartPoint3D operator * ( const MbMatrix3D & ) const; @@ -546,7 +564,7 @@ inline void MbCartPoint3D::Minimum( const MbCartPoint3D & p ) { //------------------------------------------------------------------------------ // \ru Унарный минус \en The unary minus // --- -inline MbCartPoint3D MbCartPoint3D::operator - () { +inline MbCartPoint3D MbCartPoint3D::operator - () const { return MbCartPoint3D( -x, -y, -z ); } diff --git a/C3d/Include/mb_class_traits.h b/C3d/Include/mb_class_traits.h index a3494dd..f2572c6 100644 --- a/C3d/Include/mb_class_traits.h +++ b/C3d/Include/mb_class_traits.h @@ -1,145 +1,223 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file \brief \ru Характеристики типов для математических классов ядра "Mb..." - \en Type traits of the math basic classes of the kernel "Mb..." \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __MB_CLASS_TRAITS_H -#define __MB_CLASS_TRAITS_H - -#include -#include -#include - - -class MATH_CLASS MbLineSegment; -class MATH_CLASS MbArc; -class MATH_CLASS MbNurbs; -class MATH_CLASS MbLine; -class MATH_CLASS MbPlaneInstance; -class MATH_CLASS MbSpaceInstance; -class MATH_CLASS MbAssembly; -class MATH_CLASS MbInstance; -class MbSolid; -class MATH_CLASS MbWireFrame; -class MATH_CLASS MbMesh; -class MATH_CLASS MbLineSegment3D; -class MATH_CLASS MbArc3D; -class MATH_CLASS MbFace; -class MATH_CLASS MbEdge; -class MATH_CLASS MbVertex; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Характеристики классов геометрического ядра C3D. - \en Class traits of C3D geometric kernel. - \attention \ru Экспериментальный класс. Пока приведены не все типы классов. - \en Experimental class. While not all listed types of classes. \~ -*/ -//--- -template -struct MbClassTraits -{ -private: - // \ru Идентификатор класса математического ядра. \en Identifier of class of the geometric kernel. - static const MbeSpaceType typeId = st_Undefined; -}; - -/* - 2D-curve sub-classes. -*/ -template<> -struct MbClassTraits { static const MbePlaneType typeId = pt_LineSegment; }; -template<> -struct MbClassTraits { static const MbePlaneType typeId = pt_Arc; }; -template<> -struct MbClassTraits { static const MbePlaneType typeId = pt_Nurbs; }; -template<> -struct MbClassTraits { static const MbePlaneType typeId = pt_Line; }; -/* - C3D model sub-classes. Inherited from MbItem. -*/ -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_PlaneInstance; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_SpaceInstance; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_Assembly; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_Instance; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_Solid; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_WireFrame; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_Mesh; }; -/* - 3D-curve sub-classes. -*/ -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_LineSegment3D; }; -template<> -struct MbClassTraits { static const MbeSpaceType typeId = st_Arc3D; }; - -/* - Topology sub-classes. -*/ -template<> -struct MbClassTraits { static const MbeTopologyType typeId = tt_Face; }; -template<> -struct MbClassTraits { static const MbeTopologyType typeId = tt_Edge; }; -template<> -struct MbClassTraits { static const MbeTopologyType typeId = tt_Vertex; }; - -//---------------------------------------------------------------------------------------- -// \ru Статическое приведение из типа к (разадресация типа) \en Static cast from type to -//--- -template struct Deref { private: typedef _Type Type; }; -template struct Deref { typedef _Type Type; }; -template struct Deref<_Type*> { typedef _Type Type; }; -template struct Deref<_Type&> { typedef _Type Type; }; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). - \en Dynamic type cast based on the function Derived::IsA(). -*/ -//--- -template< class DerivedPtr, class ParentType > -DerivedPtr isa_cast ( ParentType * obj ) -{ - if ( (obj != NULL) && obj->IsA() == MbClassTraits::Type>::typeId ) - { - return static_cast( obj ); - } - return static_cast( NULL ); -} - -//---------------------------------------------------------------------------------------- -// -//--- -template< class DerivedPtr, class ParentPtr > -DerivedPtr _IsaCast( ParentPtr * obj, const MbTopItem * tItem ) -{ - if ( (obj != tItem) && obj->RefType() == rt_TopItem ) - { - tItem = static_cast( obj ); - } - return isa_cast( tItem ); -} - -//---------------------------------------------------------------------------------------- -/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). - \en Dynamic type cast based on the function Derived::IsA(). -*/ -//--- -template< class DerivedPtr > -DerivedPtr isa_cast ( const MbRefItem * obj ) -{ - DerivedPtr resPtr = NULL; - return _IsaCast( obj, resPtr ); -} - -#endif // __MB_CLASS_TRAITS_H - +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file \brief \ru Характеристики типов для математических классов ядра "Mb..." + \en Type traits of the math basic classes of the kernel "Mb..." \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_CLASS_TRAITS_H +#define __MB_CLASS_TRAITS_H + +#include +#include +#include +#include +#include + +class MbLineSegment; +class MbArc; +class MbNurbs; +class MbLine; +class MbItem; +class MbPlaneInstance; +class MbSpaceInstance; +class MbAssembly; +class MbInstance; +class MbSolid; +class MbWireFrame; +class MbMesh; +class MbLineSegment3D; +class MbArc3D; +class MbFace; +class MbEdge; +class MbCurveEdge; +class MbVertex; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Характеристики классов геометрического ядра C3D. + \en Class traits of C3D geometric kernel. + \attention \ru Экспериментальный класс. Пока приведены не все типы классов. + \en Experimental class. While not all listed types of classes. \~ +*/ +//--- +template +struct MbClassTraits +{ +private: + // \ru Идентификатор класса математического ядра. \en Identifier of class of the geometric kernel. + static const MbeSpaceType typeId = st_Undefined; +}; + +//---------------------------------------------------------------------------------------- +// For instantiated math classes. +//--- +struct _IsInstant +{ + template + inline bool operator()( const ParentType * obj, const ClassEnum _typeId ) + { + return obj == NULL ? true : obj->IsA() == _typeId; + } +}; + +//---------------------------------------------------------------------------------------- +// For abstract family classes. +//--- +struct _IsFamily +{ + template + inline bool operator()( const ParentType * obj, const ClassEnum _typeId ) + { + return obj == NULL ? true : obj->Family() == _typeId; + } +}; + +/* + 2D-curve sub-classes. +*/ +template<> +struct MbClassTraits:_IsInstant { static const MbePlaneType typeId = pt_LineSegment; }; +template<> +struct MbClassTraits:_IsInstant { static const MbePlaneType typeId = pt_Arc; }; +template<> +struct MbClassTraits:_IsInstant { static const MbePlaneType typeId = pt_Nurbs; }; +template<> +struct MbClassTraits:_IsInstant { static const MbePlaneType typeId = pt_Line; }; + +/* + Declarations of abstract classes inherited from MbSpaceItem. +*/ +template<> +struct MbClassTraits:_IsFamily { static const MbeSpaceType typeId = st_Item; }; +template<> +struct MbClassTraits:_IsFamily { static const MbeSpaceType typeId = st_Curve3D; }; +template<> +struct MbClassTraits:_IsFamily { static const MbeSpaceType typeId = st_Surface; }; + +/* + C3D model sub-classes. Inherited from MbItem. +*/ +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_PlaneInstance; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_SpaceInstance; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_Assembly; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_Instance; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_Solid; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_WireFrame; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_Mesh; }; + +/* + 3D-curve sub-classes. +*/ +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_LineSegment3D; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeSpaceType typeId = st_Arc3D; }; + +/* + Topology sub-classes. +*/ +template<> +struct MbClassTraits:_IsInstant { static const MbeTopologyType typeId = tt_Face; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeTopologyType typeId = tt_Edge; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeTopologyType typeId = tt_CurveEdge; }; +template<> +struct MbClassTraits:_IsInstant { static const MbeTopologyType typeId = tt_Vertex; }; + +//---------------------------------------------------------------------------------------- +// \ru Статическое приведение из типа к (разадресация типа) \en Static cast from type to +//--- +template struct Deref { private: typedef _Type Type; }; +template struct Deref { typedef _Type Type; }; +template struct Deref<_Type*> { typedef _Type Type; }; +template struct Deref<_Type&> { typedef _Type Type; }; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). + \en Dynamic type cast based on the function Derived::IsA(). +*/ +//--- +template< class DerivedPtr, class ParentType > +inline DerivedPtr _IsaCast( ParentType * obj ) +{ + MbClassTraits::Type> isAClass; + if ( isAClass(obj, isAClass.typeId) ) + { + return static_cast( obj ); + } + return static_cast( NULL ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template< class DerivedPtr, class ParentPtr > +inline DerivedPtr _IsaCast( ParentPtr * obj, const MbSpaceItem * item ) +{ + if ( (obj != item) && obj->RefType() == rt_SpaceItem ) + { + item = static_cast( obj ); + } + return _IsaCast( item ); +} + +//---------------------------------------------------------------------------------------- +// +//--- +template< class DerivedPtr, class ParentPtr > +inline DerivedPtr _IsaCast( ParentPtr * obj, const MbTopItem * tItem ) +{ + if ( (obj != tItem) && obj->RefType() == rt_TopItem ) + { + tItem = static_cast( obj ); + } + return _IsaCast( tItem ); +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). + \en Dynamic type cast based on the function Derived::IsA(). +*/ +//--- +template< class DerivedPtr, class ParentType > +DerivedPtr isa_cast( ParentType * obj ) +{ + return _IsaCast( obj ); +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). + \en Dynamic type cast based on the function Derived::IsA(). +*/ +//--- +template< class DerivedPtr > +DerivedPtr isa_cast( const MbRefItem * obj ) +{ + DerivedPtr resPtr = NULL; + return _IsaCast( obj, resPtr ); +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Динамическое приведение типа, основанное на функции Derived::IsA(). + \en Dynamic type cast based on the function Derived::IsA(). +*/ +//--- +template< class DerivedPtr > +DerivedPtr isa_cast( MbRefItem * obj ) +{ + DerivedPtr resPtr = NULL; + return _IsaCast( obj, resPtr ); +} + +#endif // __MB_CLASS_TRAITS_H + // eof \ No newline at end of file diff --git a/C3d/Include/mb_cube.h b/C3d/Include/mb_cube.h index 8ea6017..401c367 100644 --- a/C3d/Include/mb_cube.h +++ b/C3d/Include/mb_cube.h @@ -16,10 +16,10 @@ #include -#define CUBE_CONTROL_POINTS_COUNT 26 ///< \ru Количество характерных точек куба. \en The number of control points of cube. -#define CUBE_VERTEX_COUNT 8 ///< \ru Количество вершин куба. \en The number of cube vertices. -#define CUBE_EDGES_COUNT 12 ///< \ru Количество рёбер куба. \en The number of cube edges. -#define CUBE_FACES_COUNT 6 ///< \ru Количество граней куба. \en The number of cube faces. +const_expr size_t CUBE_CONTROL_POINTS_COUNT = 26; ///< \ru Количество характерных точек куба. \en The number of control points of cube. +const_expr size_t CUBE_VERTEX_COUNT = 8; ///< \ru Количество вершин куба. \en The number of cube vertices. +const_expr size_t CUBE_EDGES_COUNT = 12; ///< \ru Количество рёбер куба. \en The number of cube edges. +const_expr size_t CUBE_FACES_COUNT = 6; ///< \ru Количество граней куба. \en The number of cube faces. class MATH_CLASS MbRect; @@ -425,6 +425,8 @@ public : double GetMin( size_t k ) const { return k ? (--k ? pmin.z : pmin.y) : pmin.x; } /// \ru Доступ к максимальной координате по индексу. \en Access to a coordinate by an index. double GetMax( size_t k ) const { return k ? (--k ? pmax.z : pmax.y) : pmax.x; } + /// \ru Дать длина по стороне. \en Get side length. + double GetSideLength( size_t k ) const { return k ? (--k ? ::fabs(GetLengthZ()) : ::fabs(GetLengthY())) : ::fabs(GetLengthX()); } /// \ru Дать себя. \en Give itself. const MbCube & GetCube() const { return *this; } diff --git a/C3d/Include/mb_data.h b/C3d/Include/mb_data.h index 0a98e72..0ca34ec 100644 --- a/C3d/Include/mb_data.h +++ b/C3d/Include/mb_data.h @@ -1,557 +1,597 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Данные. - \en Data. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MB_DATA_H -#define __MB_DATA_H - - -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные для вычисления шага. - \en Data for step calculation. \~ - \details \ru Данные для вычисления шага при триангуляции поверхностей и граней. \n - \en Data for step calculation during face triangulation. \n \~ - \ingroup Data_Structures -*/ -// --- -class MATH_CLASS MbStepData { - -private: - /** \brief \ru Способ вычисления приращения параметра при движении по объекту. - \en The method of calculation of parameter increment by the object. \~ - \details \ru Способ вычисления приращения параметра при движении по кривой или поверхности. - Для визуализации геометрической формы используется способ ist_SpaceStep. \n - Для операций построения используется способ ist_DeviationStep. \n - Для 3D принтеров используется способ ist_MetricStep и могут быть добавлены первые два. \n - Для привязки объектов к параметрам поверхности следует добавить способ ist_ParamStep, - Для определения столкновений элементов модели используется способ ist_CollisionStep, - Для вычисления инерционных характеристик используется способ ist_MipStep. - \en Methods of calculation of parameter increment by the object. \n \~ - Step by sag ist_SpaceStep is used for visualizations. - Step by deviation angle ist_DeviationStep is used for calculation. - Step by length ist_MetricStep is used for 3D printer (plus by sag and by deviation angle). \n - Special step ist_ParamStep is added for binding with surface parameters. - Special step ist_CollisionStep is used for collision detection of model elements. - Special step ist_MipStep is used for calculation of inertial characteristics. \~ - */ - uint8 stepType; - double sag; ///< \ru Максимально допустимый прогиб кривой или поверхности в соседних точках на расстоянии шага. \en The maximum permissible sag of the curve or surface at adjacent points away step. \~ - double angle; ///< \ru Максимально допустимое угловое отклонение касательных кривой или нормалей поверхности в соседних точках на расстоянии шага. \en The maximum angular deviation of the curve or surface normal in the neighboring points on the distance of a step. \~ - double length; ///< \ru Максимально допустимое расстояние между соседними точками на расстоянии шага. \en The maximum distance between points a step away. \~ - size_t maxCount; ///< \ru Максимальное количество ячеек в строке и ряду триангуляционной сетки (если 0, то не задано). \en Maximum count of cell in row and column for triangulation grid (if 0, then unlimited). \~ - -public: - - /// \ru Конструктор с заданным типом шага. \en Constructor by step type. - MbStepData( MbeStepType t, double s ); - /// \ru Пустой конструктор. \en Empty constructor. - MbStepData() - : stepType( ist_SpaceStep ) - , sag ( Math::visualSag ) - , angle ( Math::deviateSag ) - , length ( MAXIMON ) - , maxCount( 0 ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbStepData( const MbStepData & other ) - : stepType( other.stepType ) - , sag ( other.sag ) - , angle ( other.angle ) - , length ( other.length ) - , maxCount( other.maxCount ) - {} - /// \ru Деструктор. \en Destructor. - ~MbStepData() {} - -public: - /// \ru Установить способ вычисления шага. \en Set the method of calculation of parameter increment by the object. \~ - void SetStepType( MbeStepType t, bool add = true ) { if ( add ) { stepType |= t; } else { stepType = (uint8)t; } } - /// \ru Установить максимально допустимый прогиб на расстоянии шага. \en Set the maximum permissible sag at adjacent points away step. \~ - void SetSag ( double s ) { sag = s; } - /// \ru Установить максимально допустимое угловое отклонение в соседних точках. \en Set the maximum angular deviation in the neighboring points on the distance of a step. \~ - void SetAngle ( double a ) { angle = a; } - /// \ru Установить максимально допустимое расстояние между соседними точками на расстоянии шага. \en Set the maximum distance between points a step away. \~ - void SetLength ( double l ) { length = l; } - /// \ru Установить максимально допустимое количество ячеек в строке или ряду триангуляционной сетки. \en Set the maximum count of cell in row and column for triangulation grid. \~ - void SetMaxCount( size_t c ) { maxCount = c; } - - /// \ru Дать максимально допустимый прогиб на расстоянии шага. \en Get the maximum permissible sag at adjacent points away step. \~ - double GetSag () const { return sag; } - /// \ru Дать максимально допустимое угловое отклонение в соседних точках. \en Get the maximum angular deviation in the neighboring points on the distance of a step. \~ - double GetAngle () const { return angle; } - /// \ru Дать максимально допустимое расстояние между соседними точками на расстоянии шага. \en Get the maximum distance between points a step away. \~ - double GetLength () const { return length; } - /// \ru Дать максимально допустимое количество ячеек в строке или ряду триангуляционной сетки. \en Get the maximum count of cell in row and column for triangulation grid. \~ - size_t GetMaxCount() const { return maxCount; } - - /// \ru Указанный шаг задан. \en This step is set. - bool StepIs( MbeStepType sType ) const { return !!(stepType & sType); } - - /// \ru Задан шаг по максимальному прогибу. \en Step by maximum deflection defined. \~ - bool SagIncluded() const { return //!!(stepType & ist_ParamStep) || - !!(stepType & ist_SpaceStep) || - !!(stepType & ist_CollisionStep); } - /// \ru Задан шаг по угловому отклонению. \en Step by angular deviation defined. \~ - bool AngleIncluded() const { return !!(stepType & ist_DeviationStep) || - !!(stepType & ist_MipStep); } - /// \ru Задан шаг по максимальному расстоянию. \en Step by maximum distance defined. \~ - bool LengthIncluded() const { return !!(stepType & ist_MetricStep); } - - /// \ru Установить данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. - void Init( MbeStepType t, double s, double a, double l, size_t c = 0 ) - { - stepType = (uint8)t; - sag = s; - angle = a; - length = l; - maxCount = c; -} - - /// \ru Установить данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. - void InitStepBySag( double s ) - { - stepType = (uint8)ist_SpaceStep; - sag = ::fabs(s); - angle = Math::deviateSag; - length = MAXIMON; - maxCount = 0; - } - - /// \ru Функция копирования данных. \en Copy function of data. - void Init( const MbStepData & other ) - { - stepType = other.stepType; - sag = other.sag; - angle = other.angle; - length = other.length; - maxCount = other.maxCount; - } - - /// \ru Оператор присваивания. \en Assignment operator. - MbStepData & operator = ( const MbStepData & other ) - { - stepType = other.stepType; - sag = other.sag; - angle = other.angle; - length = other.length; - maxCount = other.maxCount; - return *this; - } - - /// \ru Сбросить данные для вычисления шага. \en Reset data for step calculation. - void Reset() - { - stepType = (uint8)ist_SpaceStep; - sag = Math::visualSag; - angle = Math::deviateSag; - length = MAXIMON; - maxCount = 0; - } - - /// \ru Функция сравнения. \en Equal function. - bool IsEqual( const MbStepData & other, double epsilon ) const; - /// \ru Вырожденный ли объект? \en Is empty? - bool IsEmpty( double epsilon ) const; - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbStepData, MATH_FUNC_EX ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные для построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \details \ru Дополнительные данные для построения полигонального объекта и триангуляции поверхностей и граней. \n - \en Way for polygonal object constructing or face triangulation. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbFormNote { - -private: - bool exact; ///< \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). - bool wire; ///< \ru Строить изолинии поверхностей. \en Construct isolines of surfaces. \~ - bool grid; ///< \ru Строить триангуляцию поверхностей. \en Construct triangulations of surfaces. \~ - bool seam; ///< \ru Дублировать точки триангуляции на швах (true) замкнутых поверхностей, не дублировать точки триангуляции на швах (false). \en Flag for not ignore the seam edges. \~ - bool quad; ///< \ru Строить четырёхугольники (true) при триангуляции поверхностей (по возможности). \en Build quadrangles (true) in triangulations of surfaces (if possible). \~ - -public: - - /// \ru Пустой конструктор. \en Empty constructor. - MbFormNote() - : exact( false ) - , wire( false ) - , grid( true ) - , seam( true ) - , quad( false ) - {} - /// \ru Конструктор с заданным типом шага. \en Constructor by step type. - MbFormNote( bool w, bool g, bool s = true, bool e = false, bool q = false ) - : exact( e ) - , wire( w ) - , grid( g ) - , seam( s ) - , quad( q ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbFormNote( const MbFormNote & other ) - : exact( other.exact ) - , wire( other.wire ) - , grid( other.grid ) - , seam( other.seam ) - , quad( other.quad ) - {} - /// \ru Деструктор. \en Destructor. - ~MbFormNote() {} - -public: - /// \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). - void SetExact( bool e ) { exact = e; } - /// \ru Установить флаг построения изолиний поверхностей. \en Set flag construction isolines of surfaces. \~ - void SetWire( bool w ) { wire = w; } - /// \ru Установить флаг cтроить триангуляцию поверхностей. \en Set flag constructing triangulations of surfaces. \~ - void SetGrid( bool g ) { grid = g; } - /// \ru Установить флаг шовных ребер. \en Set flag for seam edges. \~ - void SetSeam( bool s ) { seam = s; } - /// \ru Установить флаг cтроить четырёхугольники при триангуляции поверхностей (по возможности).. \en Set flag for build quadrangles in triangulations of surfaces (if possible). \~ - void SetQuad( bool q ) { quad = q; } - - /// \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). - bool DoExact() const { return exact; } - /// \ru Дать флаг построения изолиний поверхностей. \en Whether to construct isolines of surfaces? \~ - bool Wire() const { return wire;} - /// \ru Cтроить триангуляцию поверхностей? \en Whether to construct triangulations of surfaces? \~ - bool Grid() const { return grid; } - /// \ru Дублировать точки триангуляции на швах? \en Get flag for seam edges. \~ - bool Seam() const { return seam; } - /// \ru Строить четырёхугольники при триангуляции поверхностей (по возможности).? \en Whether to build quadrangles in triangulations of surfaces (if possible)? \~ - bool Quad() const { return quad; } - - /// \ru Установить Данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. - void Init( bool w, bool g, bool s, bool e = false, bool q = false ) { - exact = e; - wire = w; - grid = g; - seam = s; - quad = q; - } - - /// \ru Функция копирования данных. \en Copy function of data. - void Init( const MbFormNote & other ) { - exact = other.exact; - wire = other.wire; - grid = other.grid; - seam = other.seam; - quad = other.quad; - } - - /// \ru Оператор присваивания. \en Assignment operator. - MbFormNote & operator = ( const MbFormNote & other ) { - exact = other.exact; - wire = other.wire; - grid = other.grid; - seam = other.seam; - quad = other.quad; - return *this; - } - - /// \ru Функция сравнения. \en Equal function. - bool IsEqual( const MbFormNote & other ) const; - -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные для управления двумерными объектами. - \en The data for two-dimensional object control. \~ - \details \ru Данные содержат контрольные точки двумерных объектов. \n - \en The data consist of two-dimensional control points for object. \n \~ -\ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbControlData { - -private: - SArray total; ///< \ru Точки, перемещаемые вместе. \en Points conveyed along. \~ - SArray share; ///< \ru Точки, перемещаемые по отдельности. \en Points transported separately. \~ - mutable size_t totalIndex; ///< \ru Индекс текущей точки total. \en The index of current point total. \~ - mutable size_t shareIndex; ///< \ru Индекс текущей точки share. \en The index of current point share. \~ - -public: - /// \ru Пустой конструктор. \en Empty constructor. - MbControlData() : total( 0, 1 ), share(0, 1), totalIndex( 0 ), shareIndex(0) {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbControlData( const MbControlData & other ) - : total( other.total ) - , share( other.share ) - , totalIndex( other.totalIndex ) - , shareIndex( other.shareIndex ) - {} - /// \ru Деструктор. \en Destructor. - ~MbControlData() {} - -public: - /// \ru Зарезервировать память. \en Size reserve. \~ - void ReserveTotal( size_t c ) { total.Reserve( c ); } - /// \ru Зарезервировать память. \en Size reserve. \~ - void ReserveShare( size_t c ) { share.Reserve( c ); } - - /// \ru Добавить точку. \en Add a point conveyed along. \~ - void AddTotal( const MbCartPoint & p ) { total.push_back(p); } - /// \ru Добавить точки. \en Add points. \~ - template - void AddTotals( const PointsVector & points ) - { - size_t addCnt = points.size(); - if ( addCnt > 0 ) { - total.reserve( total.size() + addCnt ); - for ( size_t k = 0; k < addCnt; ++k ) - total.push_back( points[k] ); - } - } - /// \ru Добавить точку. \en Add a point. \~ - void AddShare( const MbCartPoint & p ) { share.push_back(p); } - /// \ru Добавить точки. \en Add points. \~ - template - void AddShares( const PointsVector & points ) - { - size_t addCnt = points.size(); - if ( addCnt > 0 ) { - share.reserve( share.size() + addCnt ); - for ( size_t k = 0; k < addCnt; ++k ) - share.push_back( points[k] ); - } - } - - /// \ru Выдать количество точек. \en Get points count conveyed along. \~ - size_t TotalCount() const { return total.Count(); } - /// \ru Выдать количество точек. \en Get points count. \~ - size_t ShareCount() const { return share.Count(); } - - /// \ru Обнулить индексы. \en Reset index. - void ResetIndex() const { totalIndex = 0; shareIndex = 0; } - - /// \ru Выдать очередную точку. \en Get current point for totalIndex++. - bool GetTotal( MbCartPoint & p ) const; - /// \ru Выдать очередную точку. \en Get current point for shareIndex++. - bool GetShare( MbCartPoint & p ) const; - /// \ru Выдать точку по индексу. \en Get point by index conveyed along. - bool GetTotal( size_t i, MbCartPoint & p ) const; - /// \ru Выдать точку по индексу. \en Get point by index. - bool GetShare( size_t i, MbCartPoint & p ) const; - /// \ru Выдать общее точек. \en Get all points count. \~ - size_t Count() const { return total.Count() + share.Count(); } - /// \ru Выдать точку по индексу. \en Get point by index conveyed along. - bool GetPoint( size_t i, MbCartPoint & p ) const; - /// \ru Установить точку по индексу. \en Set point by index conveyed along. - bool SetPoint( size_t i, MbCartPoint & p ); - /// \ru Выдать все точки. \en Get points. - SArray & SetTotalPoints() { return total; } - /// \ru Выдать все точки. \en Get points. - SArray & SetSharePoints() { return share; } - /// \ru Освободить память. \en Free memory. - void HardFlush() { total.HardFlush(); share.HardFlush(); totalIndex = 0; shareIndex = 0; } - - /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. - void Transform( const MbMatrix & matrix ); - /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. - void Move( const MbVector & to ); - /// \ru Повернуть вокруг точки. \en Rotate around a point. - void Rotate( const MbCartPoint & point, double angle ); - - /// \ru Дать точку по индексу. \en Set point by index. - MbCartPoint & operator []( size_t i ) const; - /// \ru Оператор присваивания. \en Assignment operator. - MbControlData & operator = ( const MbControlData & other ) - { - total = other.total; - share = other.share; - totalIndex = other.totalIndex; - shareIndex = other.shareIndex; - return *this; - } - /// \ru Вырожденный ли объект? \en Is empty? - bool IsEmpty() const { return ( total.Count() == 0 && share.Count() == 0 ); } -}; // MbControlData - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные для управления трехмерными объектами. - \en The data for three-dimensional object control. \~ - \details \ru Данные содержат контрольные точки трехмерных объектов. \n - \en The data consist of three-dimensional control points for object. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbControlData3D { - -private: - SArray total; ///< \ru Точки, перемещаемые вместе. \en Points conveyed along. \~ - SArray share; ///< \ru Точки, перемещаемые по отдельности. \en Points transported separately. \~ - mutable size_t totalIndex; ///< \ru Индекс текущей точки total. \en The index of current point total. \~ - mutable size_t shareIndex; ///< \ru Индекс текущей точки share. \en The index of current point share. \~ - -public: - /// \ru Пустой конструктор. \en Empty constructor. - MbControlData3D() : total( 0, 1 ), share(0, 1), totalIndex( 0 ), shareIndex(0) {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbControlData3D( const MbControlData3D & other ) - : total( other.total ) - , share( other.share ) - , totalIndex( other.totalIndex ) - , shareIndex( other.shareIndex ) - {} - /// \ru Деструктор. \en Destructor. - ~MbControlData3D() {} - -public: - /// \ru Зарезервировать память. \en Size reserve. \~ - void ReserveTotal( size_t c ) { total.Reserve( c ); } - /// \ru Зарезервировать память. \en Size reserve. \~ - void ReserveShare( size_t c ) { share.Reserve( c ); } - - /// \ru Добавить точку. \en Add a point conveyed along. \~ - void AddTotal( const MbCartPoint3D & p ) { total.Add(p); } - /// \ru Добавить точки. \en Add points. \~ - template - void AddTotals( const PointsVector & points ) - { - size_t addCnt = points.size(); - if ( addCnt > 0 ) { - total.reserve( total.size() + addCnt ); - for ( size_t k = 0; k < addCnt; ++k ) - total.push_back( points[k] ); - } - } - /// \ru Добавить точку. \en Add a point. \~ - void AddShare( const MbCartPoint3D & p ) { share.Add(p); } - /// \ru Добавить точки. \en Add points. \~ - template - void AddShares( const PointsVector & points ) - { - size_t addCnt = points.size(); - if ( addCnt > 0 ) { - share.reserve( share.size() + addCnt ); - for ( size_t k = 0; k < addCnt; ++k ) - share.push_back( points[k] ); - } - } - /// \ru Выдать количество точек. \en Get points count conveyed along. \~ - size_t TotalCount() const { return total.Count(); } - /// \ru Выдать количество точек. \en Get points count. \~ - size_t ShareCount() const { return share.Count(); } - - /// \ru Обнулить индексы. \en Reset index. - void ResetIndex() const { totalIndex = 0; shareIndex = 0; } - /// \ru Выдать очередную точку. \en Get current point for totalIndex++. - bool GetTotal( MbCartPoint3D & p ) const; - /// \ru Выдать очередную точку. \en Get current point for shareIndex++. - bool GetShare( MbCartPoint3D & p ) const; - /// \ru Выдать точку по индексу. \en Get point by index conveyed along. - bool GetTotal( size_t i, MbCartPoint3D & p ) const; - /// \ru Выдать точку по индексу. \en Get point by index. - bool GetShare( size_t i, MbCartPoint3D & p ) const; - /// \ru Выдать общее точек. \en Get all points count. \~ - size_t Count() const { return total.Count() + share.Count(); } - /// \ru Выдать точку по индексу. \en Get point by index conveyed along. - bool GetPoint( size_t i, MbCartPoint3D & p ) const; - /// \ru Установить точку по индексу. \en Set point by index conveyed along. - bool SetPoint( size_t i, MbCartPoint3D & p ); - /// \ru Выдать все точки. \en Get points. - SArray & SetTotalPoints() { return total; } - /// \ru Выдать все точки. \en Get points. - SArray & SetSharePoints() { return share; } - /// \ru Освободить память. \en Free memory. - void HardFlush() { total.HardFlush(); share.HardFlush(); totalIndex = 0; shareIndex = 0; } - - /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. - void Transform( const MbMatrix3D & matrix ); - /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. - void Move( const MbVector3D & to ); - /// \ru Повернуть вокруг оси. \en Rotate around an axis. - void Rotate( const MbAxis3D & axis, double angle ); - - /// \ru Дать точку по индексу. \en Set point by index. - MbCartPoint3D & operator []( size_t i ) const; - /// \ru Оператор присваивания. \en Assignment operator. - MbControlData3D & operator = ( const MbControlData3D & other ) - { - total = other.total; - share = other.share; - totalIndex = other.totalIndex; - shareIndex = other.shareIndex; - return *this; - } - /// \ru Вырожденный ли объект? \en Is empty? - bool IsEmpty() const { return ( total.Count() == 0 && share.Count() == 0 ); } -}; // MbControlData3D - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные управления построением гладких кривых на базе трехмерной ломаной. - \en The data for the construction of smooth curves based on a three-dimensional polyline. \~ - \details \ru Данные содержат параметры построения сплайнов с плавным изменением кривизны. \n - \en The data contains parameters for constructing splines with smooth curvature changes. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbFairCurveData { - -public: - int arrange; ///< \ru Перераспределение точек по контуру (0 - без перераспределения, 1 - с перераспределением). \en Redistribution of points (0 - without of distribution, 1 - with distribution) . \~ - int subdivision; ///< \ru Коэффициент уплотнения кривой (0 - без уплотнения, 1 - однократное уплотнение, 2 - двукратное уплотнение). \en Curve subdivision coefficient (0 - without subdivision, 1 - single subdivision, 2 - double subdivision). \~ - int accountCurvature; ///< \ru Учет кривизны в концевых точках (0 - не учитывать, 1 - в начальной точке, 2 - в конечной точке, 3 - учитывать оба конца). \en Accounting for curvature at end points (0 - do not take into account, 1 - at the starting point, 2 - at the ending point, 3 - take into account both ends). \~ - int accountInflexVector; ///< \ru Учет вектора в точке перегиба (0 - направление звена S-полигона, 1 - направление касательной). \en How to take into account the vector at the inflection point (0 - direction of segment of S-polygon, 1 - direction of tangent to curve). \~ - int approx; ///< \ru Метод аппроксимации (0 - B-сплайновая кривая по узловым точкам, 1 - изогеометрическая B-сплайновая кривая, 2 - изогеометрическая NURBzS кривая). \en Approx method (0 - B-spline curve on nodes, 1 - isogeometric B-spline curve, 2 - isogeometric NURBzS curve). \~ - int degreeBSpline; ///< \ru Степень B-сплайновой кривой m (3<=m<=10). \en The degree m (3<=m<=10) of B-Spline curve. \~ - int outFormat; ///< \ru Выходной формат сплайна (2 - S-полигон, 3 - GB-полигон). \en Output format of spline (2 - S-polygon, 3 - GB-polygon). \~ - int nSegments; ///< \ru Количество сегментов сплайна. \en Number of segments of spline. \~ - int numSegment; ///< \ru Номер сегмента. \en Number of segment. \~ - double tParam; ///< \ru Внутренний параметр точки сегмента сплайна. \en Point internal param on segment of spline. \~ - int warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ - int error; ///< \ru Ошибка о работе. \en The operation error. \~ - double clothoidRMin; ///< \ru Радиус кривизны на конце начального участка клотоиды. \en Curvature radius on end of initial part of Clothoid. \~ - double clothoidLMax; ///< \ru Максимальная длина начального участка клотоиды. \en Max length of initial part of Clothoid. \~ - int clothoidSegms; ///< \ru Количество сегментов аппроксимирующей клотоиду кривой. \en Number of segments of curve approximated the Clothoid. \~ - - -public: - /// \ru Пустой конструктор. \en Empty constructor. - MbFairCurveData() {} - - ~MbFairCurveData() {} - - /// \ru Оператор присваивания. \en Assignment operator. - MbFairCurveData & operator = ( const MbFairCurveData & other ) - { - arrange = other.arrange; - subdivision = other.subdivision; - accountCurvature = other.accountCurvature; - accountInflexVector = other.accountInflexVector; - approx = other.approx; - degreeBSpline = other.degreeBSpline; - outFormat = other.outFormat; - nSegments = other.nSegments; - numSegment = other.numSegment; - tParam = other.tParam;; - warning = other.warning; - error = other.error; - clothoidRMin = other.clothoidRMin; - clothoidLMax = other.clothoidLMax; - clothoidSegms = other.clothoidSegms; - return *this; - } -}; // MbFairCurveData - - -#endif // __MB_DATA_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Данные. + \en Data. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_DATA_H +#define __MB_DATA_H + + +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные для вычисления шага. + \en Data for step calculation. \~ + \details \ru Данные для вычисления шага при триангуляции поверхностей и граней. \n + \en Data for step calculation during face triangulation. \n \~ + \ingroup Data_Structures +*/ +// --- +class MATH_CLASS MbStepData { + +private: + /** \brief \ru Способ вычисления приращения параметра при движении по объекту. + \en The method of calculation of parameter increment by the object. \~ + \details \ru Способ вычисления приращения параметра при движении по кривой или поверхности. + Для визуализации геометрической формы используется способ ist_SpaceStep. \n + Для операций построения используется способ ist_DeviationStep. \n + Для 3D принтеров используется способ ist_MetricStep и могут быть добавлены первые два. \n + Для привязки объектов к параметрам поверхности следует добавить способ ist_ParamStep, + Для определения столкновений элементов модели используется способ ist_CollisionStep, + Для вычисления инерционных характеристик используется способ ist_MipStep. + \en Methods of calculation of parameter increment by the object. \n \~ + Step by sag ist_SpaceStep is used for visualizations. + Step by deviation angle ist_DeviationStep is used for calculation. + Step by length ist_MetricStep is used for 3D printer (plus by sag and by deviation angle). \n + Special step ist_ParamStep is added for binding with surface parameters. + Special step ist_CollisionStep is used for collision detection of model elements. + Special step ist_MipStep is used for calculation of inertial characteristics. \~ + */ + uint8 stepType; + double sag; ///< \ru Максимально допустимый прогиб кривой или поверхности в соседних точках на расстоянии шага. \en The maximum permissible sag of the curve or surface at adjacent points away step. \~ + double angle; ///< \ru Максимально допустимое угловое отклонение касательных кривой или нормалей поверхности в соседних точках на расстоянии шага. \en The maximum angular deviation of the curve or surface normal in the neighboring points on the distance of a step. \~ + double length; ///< \ru Максимально допустимое расстояние между соседними точками на расстоянии шага. \en The maximum distance between points a step away. \~ + size_t maxCount; ///< \ru Максимальное количество ячеек в строке и ряду триангуляционной сетки (если 0, то не задано). \en Maximum count of cell in row and column for triangulation grid (if 0, then unlimited). \~ + +public: + + /// \ru Конструктор с заданным типом шага. \en Constructor by step type. + MbStepData( MbeStepType t, double s ); + /// \ru Пустой конструктор. \en Empty constructor. + MbStepData() + : stepType( ist_SpaceStep ) + , sag ( Math::visualSag ) + , angle ( Math::deviateSag ) + , length ( MAXIMON ) + , maxCount( 0 ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbStepData( const MbStepData & other ) + : stepType( other.stepType ) + , sag ( other.sag ) + , angle ( other.angle ) + , length ( other.length ) + , maxCount( other.maxCount ) + {} + /// \ru Деструктор. \en Destructor. + ~MbStepData() {} + +public: + /// \ru Установить способ вычисления шага. \en Set the method of calculation of parameter increment by the object. \~ + void SetStepType( MbeStepType t, bool add = true ) { if ( add ) { stepType |= t; } else { stepType = (uint8)t; } } + /// \ru Установить максимально допустимый прогиб на расстоянии шага. \en Set the maximum permissible sag at adjacent points away step. \~ + void SetSag ( double s ) { sag = s; } + /// \ru Установить максимально допустимое угловое отклонение в соседних точках. \en Set the maximum angular deviation in the neighboring points on the distance of a step. \~ + void SetAngle ( double a ) { angle = a; } + /// \ru Установить максимально допустимое расстояние между соседними точками на расстоянии шага. \en Set the maximum distance between points a step away. \~ + void SetLength ( double l ) { length = l; } + /// \ru Установить максимально допустимое количество ячеек в строке или ряду триангуляционной сетки. \en Set the maximum count of cell in row and column for triangulation grid. \~ + void SetMaxCount( size_t c ) { maxCount = c; } + + /// \ru Дать максимально допустимый прогиб на расстоянии шага. \en Get the maximum permissible sag at adjacent points away step. \~ + double GetSag () const { return sag; } + /// \ru Дать максимально допустимое угловое отклонение в соседних точках. \en Get the maximum angular deviation in the neighboring points on the distance of a step. \~ + double GetAngle () const { return angle; } + /// \ru Дать максимально допустимое расстояние между соседними точками на расстоянии шага. \en Get the maximum distance between points a step away. \~ + double GetLength () const { return length; } + /// \ru Дать максимально допустимое количество ячеек в строке или ряду триангуляционной сетки. \en Get the maximum count of cell in row and column for triangulation grid. \~ + size_t GetMaxCount() const { return maxCount; } + + /// \ru Указанный шаг задан. \en This step is set. + bool StepIs( MbeStepType sType ) const { return !!(stepType & sType); } + + /// \ru Задан шаг по максимальному прогибу. \en Step by maximum deflection defined. \~ + bool SagIncluded() const { return //!!(stepType & ist_ParamStep) || + !!(stepType & ist_SpaceStep) || + !!(stepType & ist_CollisionStep); } + /// \ru Задан шаг по угловому отклонению. \en Step by angular deviation defined. \~ + bool AngleIncluded() const { return !!(stepType & ist_DeviationStep) || + !!(stepType & ist_MipStep); } + /// \ru Задан шаг по максимальному расстоянию. \en Step by maximum distance defined. \~ + bool LengthIncluded() const { return !!(stepType & ist_MetricStep); } + + /// \ru Установить данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. + void Init( MbeStepType t, double s, double a, double l, size_t c = 0 ) + { + stepType = (uint8)t; + sag = s; + angle = a; + length = l; + maxCount = c; +} + + /// \ru Установить данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. + void InitStepBySag( double s ) + { + stepType = (uint8)ist_SpaceStep; + sag = ::fabs(s); + angle = Math::deviateSag; + length = MAXIMON; + maxCount = 0; + } + + /// \ru Функция копирования данных. \en Copy function of data. + void Init( const MbStepData & other ) + { + stepType = other.stepType; + sag = other.sag; + angle = other.angle; + length = other.length; + maxCount = other.maxCount; + } + + /// \ru Оператор присваивания. \en Assignment operator. + MbStepData & operator = ( const MbStepData & other ) + { + stepType = other.stepType; + sag = other.sag; + angle = other.angle; + length = other.length; + maxCount = other.maxCount; + return *this; + } + + /// \ru Сбросить данные для вычисления шага. \en Reset data for step calculation. + void Reset() + { + stepType = (uint8)ist_SpaceStep; + sag = Math::visualSag; + angle = Math::deviateSag; + length = MAXIMON; + maxCount = 0; + } + + /// \ru Функция сравнения. \en Equal function. + bool IsEqual( const MbStepData & other, double epsilon ) const; + /// \ru Вырожденный ли объект? \en Is empty? + bool IsEmpty( double epsilon ) const; + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbStepData, MATH_FUNC_EX ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные для построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \details \ru Дополнительные данные для построения полигонального объекта и триангуляции поверхностей и граней. \n + \en Way for polygonal object constructing or face triangulation. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MATH_CLASS MbFormNote { + +private: + bool exact; ///< \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). + bool wire; ///< \ru Строить изолинии поверхностей. \en Construct isolines of surfaces. \~ + bool grid; ///< \ru Строить триангуляцию поверхностей. \en Construct triangulations of surfaces. \~ + bool seam; ///< \ru Дублировать точки триангуляции на швах (true) замкнутых поверхностей, не дублировать точки триангуляции на швах (false). \en Flag for not ignore the seam edges. \~ + bool quad; ///< \ru Строить четырёхугольники (true) при триангуляции поверхностей (по возможности). \en Build quadrangles (true) in triangulations of surfaces (if possible). \~ + bool fair; ///< \ru Удалить вырожденные треугольники (true). \en Degenerate triangles removing (if surface has pole). \~ + +public: + + /// \ru Пустой конструктор. \en Empty constructor. + MbFormNote() + : exact( false ) + , wire( false ) + , grid( true ) + , seam( true ) + , quad( false ) + , fair( false ) + {} + /// \ru Конструктор с заданным типом шага. \en Constructor by step type. + MbFormNote( bool w, bool g, bool s = true, bool e = false, bool q = false, bool f = false ) + : exact( e ) + , wire( w ) + , grid( g ) + , seam( s ) + , quad( q ) + , fair( f ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbFormNote( const MbFormNote & other ) + : exact( other.exact ) + , wire( other.wire ) + , grid( other.grid ) + , seam( other.seam ) + , quad( other.quad ) + , fair( other.fair ) + {} + /// \ru Деструктор. \en Destructor. + ~MbFormNote() {} + +public: + /// \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). + void SetExact( bool e ) { exact = e; } + /// \ru Установить флаг построения изолиний поверхностей. \en Set flag construction isolines of surfaces. \~ + void SetWire( bool w ) { wire = w; } + /// \ru Установить флаг cтроить триангуляцию поверхностей. \en Set flag constructing triangulations of surfaces. \~ + void SetGrid( bool g ) { grid = g; } + /// \ru Установить флаг шовных ребер. \en Set flag for seam edges. \~ + void SetSeam( bool s ) { seam = s; } + /// \ru Установить флаг cтроить четырёхугольники при триангуляции поверхностей (по возможности).. \en Set flag for build quadrangles in triangulations of surfaces (if possible). \~ + void SetQuad( bool q ) { quad = q; } + /// \ru Установить флаг удаления вырожденных треугольников. \en Set flag degenerate triangles removing. \~ + void SetFair( bool f ) { fair = f; } + + /// \ru Выполнить построение полигональных объектов на числах double (true) на числах float (false). \en Polygonal objects will created on double data (true) on float data (false). + bool DoExact() const { return exact; } + /// \ru Дать флаг построения изолиний поверхностей. \en Whether to construct isolines of surfaces? \~ + bool Wire() const { return wire;} + /// \ru Cтроить триангуляцию поверхностей? \en Whether to construct triangulations of surfaces? \~ + bool Grid() const { return grid; } + /// \ru Дублировать точки триангуляции на швах? \en Get flag for seam edges. \~ + bool Seam() const { return seam; } + /// \ru Строить четырёхугольники при триангуляции поверхностей (по возможности).? \en Whether to build quadrangles in triangulations of surfaces (if possible)? \~ + bool Quad() const { return quad; } + /// \ru Удалить вырожденные треугольники? \en Get flag for degenerate triangles removing. \~ + bool Fair() const { return fair; } + + /// \ru Установить Данные для вычисления шага при триангуляции. \en Set data for step calculation during triangulation. + void Init( bool w, bool g, bool s, bool e = false, bool q = false, bool f = false ) { + exact = e; + wire = w; + grid = g; + seam = s; + quad = q; + fair = f; + } + + /// \ru Функция копирования данных. \en Copy function of data. + void Init( const MbFormNote & other ) { + exact = other.exact; + wire = other.wire; + grid = other.grid; + seam = other.seam; + quad = other.quad; + fair = other.fair; + } + + /// \ru Оператор присваивания. \en Assignment operator. + MbFormNote & operator = ( const MbFormNote & other ) { + exact = other.exact; + wire = other.wire; + grid = other.grid; + seam = other.seam; + quad = other.quad; + fair = other.fair; + return *this; + } + + /// \ru Функция сравнения. \en Equal function. + bool IsEqual( const MbFormNote & other ) const; + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные для управления двумерными объектами. + \en The data for two-dimensional object control. \~ + \details \ru Данные содержат контрольные точки двумерных объектов. \n + \en The data consist of two-dimensional control points for object. \n \~ +\ingroup Data_Structures +*/ +// --- +struct MATH_CLASS MbControlData { + +private: + SArray total; ///< \ru Точки, перемещаемые вместе. \en Points conveyed along. \~ + SArray share; ///< \ru Точки, перемещаемые по отдельности. \en Points transported separately. \~ + mutable size_t totalIndex; ///< \ru Индекс текущей точки total. \en The index of current point total. \~ + mutable size_t shareIndex; ///< \ru Индекс текущей точки share. \en The index of current point share. \~ + +public: + /// \ru Пустой конструктор. \en Empty constructor. + MbControlData() : total( 0, 1 ), share(0, 1), totalIndex( 0 ), shareIndex(0) {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbControlData( const MbControlData & other ) + : total( other.total ) + , share( other.share ) + , totalIndex( other.totalIndex ) + , shareIndex( other.shareIndex ) + {} + /// \ru Деструктор. \en Destructor. + ~MbControlData() {} + +public: + /// \ru Зарезервировать память. \en Size reserve. \~ + void ReserveTotal( size_t c ) { total.Reserve( c ); } + /// \ru Зарезервировать память. \en Size reserve. \~ + void ReserveShare( size_t c ) { share.Reserve( c ); } + + /// \ru Добавить точку. \en Add a point conveyed along. \~ + void AddTotal( const MbCartPoint & p ) { total.push_back(p); } + /// \ru Добавить точки. \en Add points. \~ + template + void AddTotals( const PointsVector & points ) + { + size_t addCnt = points.size(); + if ( addCnt > 0 ) { + total.reserve( total.size() + addCnt ); + for ( size_t k = 0; k < addCnt; ++k ) + total.push_back( points[k] ); + } + } + /// \ru Добавить точку. \en Add a point. \~ + void AddShare( const MbCartPoint & p ) { share.push_back(p); } + /// \ru Добавить точки. \en Add points. \~ + template + void AddShares( const PointsVector & points ) + { + size_t addCnt = points.size(); + if ( addCnt > 0 ) { + share.reserve( share.size() + addCnt ); + for ( size_t k = 0; k < addCnt; ++k ) + share.push_back( points[k] ); + } + } + + /// \ru Выдать количество точек. \en Get points count conveyed along. \~ + size_t TotalCount() const { return total.Count(); } + /// \ru Выдать количество точек. \en Get points count. \~ + size_t ShareCount() const { return share.Count(); } + + /// \ru Обнулить индексы. \en Reset index. + void ResetIndex() const { totalIndex = 0; shareIndex = 0; } + + /// \ru Выдать очередную точку. \en Get current point for totalIndex++. + bool GetTotal( MbCartPoint & p ) const; + /// \ru Выдать очередную точку. \en Get current point for shareIndex++. + bool GetShare( MbCartPoint & p ) const; + /// \ru Выдать точку по индексу. \en Get point by index conveyed along. + bool GetTotal( size_t i, MbCartPoint & p ) const; + /// \ru Выдать точку по индексу. \en Get point by index. + bool GetShare( size_t i, MbCartPoint & p ) const; + /// \ru Выдать общее точек. \en Get all points count. \~ + size_t Count() const { return total.Count() + share.Count(); } + /// \ru Выдать точку по индексу. \en Get point by index conveyed along. + bool GetPoint( size_t i, MbCartPoint & p ) const; + /// \ru Установить точку по индексу. \en Set point by index conveyed along. + bool SetPoint( size_t i, MbCartPoint & p ); + /// \ru Выдать все точки. \en Get points. + SArray & SetTotalPoints() { return total; } + /// \ru Выдать все точки. \en Get points. + SArray & SetSharePoints() { return share; } + /// \ru Освободить память. \en Free memory. + void HardFlush() { total.HardFlush(); share.HardFlush(); totalIndex = 0; shareIndex = 0; } + + /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. + void Transform( const MbMatrix & matrix ); + /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. + void Move( const MbVector & to ); + /// \ru Повернуть вокруг точки. \en Rotate around a point. + void Rotate( const MbCartPoint & point, double angle ); + + /// \ru Дать точку по индексу. \en Set point by index. + MbCartPoint & operator []( size_t i ) const; + /// \ru Оператор присваивания. \en Assignment operator. + MbControlData & operator = ( const MbControlData & other ) + { + total = other.total; + share = other.share; + totalIndex = other.totalIndex; + shareIndex = other.shareIndex; + return *this; + } + /// \ru Вырожденный ли объект? \en Is empty? + bool IsEmpty() const { return ( total.Count() == 0 && share.Count() == 0 ); } +}; // MbControlData + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные для управления трехмерными объектами. + \en The data for three-dimensional object control. \~ + \details \ru Данные содержат контрольные точки трехмерных объектов. \n + \en The data consist of three-dimensional control points for object. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MATH_CLASS MbControlData3D { + +private: + SArray total; ///< \ru Точки, перемещаемые вместе. \en Points conveyed along. \~ + SArray share; ///< \ru Точки, перемещаемые по отдельности. \en Points transported separately. \~ + mutable size_t totalIndex; ///< \ru Индекс текущей точки total. \en The index of current point total. \~ + mutable size_t shareIndex; ///< \ru Индекс текущей точки share. \en The index of current point share. \~ + +public: + /// \ru Пустой конструктор. \en Empty constructor. + MbControlData3D() : total( 0, 1 ), share(0, 1), totalIndex( 0 ), shareIndex(0) {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbControlData3D( const MbControlData3D & other ) + : total( other.total ) + , share( other.share ) + , totalIndex( other.totalIndex ) + , shareIndex( other.shareIndex ) + {} + /// \ru Деструктор. \en Destructor. + ~MbControlData3D() {} + +public: + /// \ru Зарезервировать память. \en Size reserve. \~ + void ReserveTotal( size_t c ) { total.Reserve( c ); } + /// \ru Зарезервировать память. \en Size reserve. \~ + void ReserveShare( size_t c ) { share.Reserve( c ); } + + /// \ru Добавить точку. \en Add a point conveyed along. \~ + void AddTotal( const MbCartPoint3D & p ) { total.Add(p); } + /// \ru Добавить точки. \en Add points. \~ + template + void AddTotals( const PointsVector & points ) + { + size_t addCnt = points.size(); + if ( addCnt > 0 ) { + total.reserve( total.size() + addCnt ); + for ( size_t k = 0; k < addCnt; ++k ) + total.push_back( points[k] ); + } + } + /// \ru Добавить точку. \en Add a point. \~ + void AddShare( const MbCartPoint3D & p ) { share.Add(p); } + /// \ru Добавить точки. \en Add points. \~ + template + void AddShares( const PointsVector & points ) + { + size_t addCnt = points.size(); + if ( addCnt > 0 ) { + share.reserve( share.size() + addCnt ); + for ( size_t k = 0; k < addCnt; ++k ) + share.push_back( points[k] ); + } + } + /// \ru Выдать количество точек. \en Get points count conveyed along. \~ + size_t TotalCount() const { return total.Count(); } + /// \ru Выдать количество точек. \en Get points count. \~ + size_t ShareCount() const { return share.Count(); } + + /// \ru Обнулить индексы. \en Reset index. + void ResetIndex() const { totalIndex = 0; shareIndex = 0; } + /// \ru Выдать очередную точку. \en Get current point for totalIndex++. + bool GetTotal( MbCartPoint3D & p ) const; + /// \ru Выдать очередную точку. \en Get current point for shareIndex++. + bool GetShare( MbCartPoint3D & p ) const; + /// \ru Выдать точку по индексу. \en Get point by index conveyed along. + bool GetTotal( size_t i, MbCartPoint3D & p ) const; + /// \ru Выдать точку по индексу. \en Get point by index. + bool GetShare( size_t i, MbCartPoint3D & p ) const; + /// \ru Выдать общее точек. \en Get all points count. \~ + size_t Count() const { return total.Count() + share.Count(); } + /// \ru Выдать точку по индексу. \en Get point by index conveyed along. + bool GetPoint( size_t i, MbCartPoint3D & p ) const; + /// \ru Установить точку по индексу. \en Set point by index conveyed along. + bool SetPoint( size_t i, MbCartPoint3D & p ); + /// \ru Выдать все точки. \en Get points. + SArray & SetTotalPoints() { return total; } + /// \ru Выдать все точки. \en Get points. + SArray & SetSharePoints() { return share; } + /// \ru Освободить память. \en Free memory. + void HardFlush() { total.HardFlush(); share.HardFlush(); totalIndex = 0; shareIndex = 0; } + + /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. + void Transform( const MbMatrix3D & matrix ); + /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. + void Move( const MbVector3D & to ); + /// \ru Повернуть вокруг оси. \en Rotate around an axis. + void Rotate( const MbAxis3D & axis, double angle ); + + /// \ru Дать точку по индексу. \en Set point by index. + MbCartPoint3D & operator []( size_t i ) const; + /// \ru Оператор присваивания. \en Assignment operator. + MbControlData3D & operator = ( const MbControlData3D & other ) + { + total = other.total; + share = other.share; + totalIndex = other.totalIndex; + shareIndex = other.shareIndex; + return *this; + } + /// \ru Вырожденный ли объект? \en Is empty? + bool IsEmpty() const { return ( total.Count() == 0 && share.Count() == 0 ); } +}; // MbControlData3D + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные управления построением гладких кривых на базе трехмерной ломаной. + \en The data for the construction of smooth curves based on a three-dimensional polyline. \~ + \details \ru Данные содержат параметры построения сплайнов с плавным изменением кривизны. \n + \en The data contains parameters for constructing splines with smooth curvature changes. \n \~ + \ingroup Data_Structures +*/ +// --- +//#define C3D_DEBUG_FAIR_CURVES ///< \ru Для отладочной печати данных гладких кривых. \en For debugging printing of smooth curve data. +struct MATH_CLASS MbFairCurveData { + +public: + bool closed; ///< \ru Признак замкнутости кривой. \en Sign of closed curve \~ + bool fairing; ///< \ru Сглаживание (0 - без сглаживания, 1 - со сглаживанием). \en Smoothing of curve: 0 - disable, 1 - enable. \~ + bool arrange; ///< \ru Перераспределение точек по контуру (false - без перераспределения, true - с перераспределением). \en Redistribution of points (false - without of distribution, true - with distribution) . \~ + MbeFairSubdivision subdivision; ///< \ru Коэффициент уплотнения кривой. \en Curve subdivision coefficient . \~ + MbeFairCurvature accountCurvature; ///< \ru Учет кривизны в концевых точках. \en Accounting for curvature at end points. \~ + MbeFairVector accountInflexVector; ///< \ru Учет вектора в точке перегиба (0 - направление звена S-полигона, 1 - направление касательной). \en How to take into account the vector at the inflection point (0 - direction of segment of S-polygon, 1 - direction of tangent to curve). \~ + MbeFixPntTng fixPntTng; ///< \ru Фиксировать точки на касательных / касательные в точках. \en Fix the points on tangents / the tangents on points. + MbeFairApprox approx; ///< \ru Метод аппроксимации. \en Approx method. \~ + int create; ///< \ru Исходные ГО: 1 - опорная ломаная, 2 - касательная ломаная. \en Initial GD: 1 - base polyline, 2 - tangent polyline. \~ + size_t degreeBSpline; ///< \ru Степень B-сплайновой кривой m (3<=m<=10). \en The degree m (3<=m<=10) of B-Spline curve. \~ + MbeFairSplineFormat initFormat; ///< \ru Исходный формат сплайна (1 - открытый S-полигон, 2 - закрытый S-полигон, 3 - GB-полигон). \en Output format of spline (1 - foat S-polygon, 2 - clamped S-polygon, 3 - GB-polygon). \~ + MbeFairSplineFormat outFormat; ///< \ru Выходной формат сплайна (2 - S-полигон, 3 - GB-полигон). \en Output format of spline (2 - S-polygon, 3 - GB-polygon). \~ + size_t nSegments; ///< \ru Количество сегментов сплайна. \en Number of segments of spline. \~ + size_t numSegment; ///< \ru Номер сегмента. \en Number of segment. \~ + double tParam; ///< \ru Внутренний параметр точки сегмента сплайна. \en Point internal param on segment of spline. \~ + double clothoidRMin; ///< \ru Радиус кривизны на конце начального участка клотоиды. \en Curvature radius on end of initial part of Clothoid. \~ + double clothoidLMax; ///< \ru Максимальная длина начального участка клотоиды. \en Max length of initial part of Clothoid. \~ + size_t clothoidSegms; ///< \ru Количество сегментов аппроксимирующей клотоиду кривой. \en Number of segments of curve approximated the Clothoid. \~ + MbeFairWarning warning; ///< \ru Предупреждение о работе. \en The operation warning. \~ + MbResultType error; ///< \ru Ошибка о работе. \en The operation error. \~ + SArray arrayFixPntTngSign; ///< \ru Признаки учета касательных на точках / точек на касательных. \en Signs of points on tangents / tangents on points. + size_t numberOfIterationsBSpl; ///< \ru Количество итераций построения B-сплайна (заданное и фактическое). \en The number of iterations for building the B-spline (given and actual). + size_t numberOfIterationsVCurve; ///< \ru Количество итераций построения V-кривой (заданное и фактическое). \en The number of iterations for building the V-curve (given and actual). + double realAccuracyBSpl; ///< \ru Точность построения B-сплайна (заданная и фактическая). \en The accuracy of creating the B-spline (given and actual). + double realAccuracyVCurve; ///< \ru Точность построения V-кривой (заданная и фактическая). \en The accuracy of creating the V-curve (given and actual). +#ifdef C3D_DEBUG_FAIR_CURVES + /*DEBUG*/ FILE *prt; +#endif + +public: + /// \ru Пустой конструктор. \en Empty constructor. + MbFairCurveData() : + closed( false ), fairing( false ), arrange( false ), subdivision( fairSubdiv_Single ), + accountCurvature( fairCur_No ), accountInflexVector( fairVector_SegmentDir ), + fixPntTng( fixPntTng_NotFix ), + approx( fairApprox_KnotsSpline ), create(1), degreeBSpline( 8 ), + 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), +#endif + realAccuracyBSpl( METRIC_ACCURACY ), realAccuracyVCurve( METRIC_EPSILON ) {} + + ~MbFairCurveData() {} + + /// \ru Оператор присваивания. \en Assignment operator. + MbFairCurveData & operator = ( const MbFairCurveData & other ) + { + closed = other.closed; + fairing = other.fairing; + arrange = other.arrange; + subdivision = other.subdivision; + accountCurvature = other.accountCurvature; + accountInflexVector = other.accountInflexVector; + approx = other.approx; + create = other.create; + degreeBSpline = other.degreeBSpline; + outFormat = other.outFormat; + nSegments = other.nSegments; + numSegment = other.numSegment; + tParam = other.tParam;; + warning = other.warning; + error = other.error; + clothoidRMin = other.clothoidRMin; + clothoidLMax = other.clothoidLMax; + clothoidSegms = other.clothoidSegms; + return *this; + } +}; // MbFairCurveData + + +#endif // __MB_DATA_H diff --git a/C3d/Include/mb_enum.h b/C3d/Include/mb_enum.h index eb3cc67..b754335 100644 --- a/C3d/Include/mb_enum.h +++ b/C3d/Include/mb_enum.h @@ -135,7 +135,7 @@ enum MbeSplineParamType { \ingroup Data_Structures */ // --- -enum MbeNurbsCurveForm { +enum MbeNurbsCurveForm { ncf_Unspecified = 0, ///< \ru Неопределенная форма. \en Undefined form ncf_PolylineForm, ///< \ru Ломаная. \en Polyline. ncf_CircularArc, ///< \ru Дуга окружности. \en Circle arc. @@ -145,6 +145,7 @@ enum MbeNurbsCurveForm { ncf_BezierForm, ///< \ru Сплайн Безье. \en Bezier spline. ncf_HermitForm, ///< \ru Сплайн Эрмита. \en Hermite spline. ncf_SurfacePoleForm, ///< \ru Сплайн в полюсе поверхности. \en Spline in the pole of surface. + ncf_FairCurveForm, ///< \ru Плавная кривая. \en Fair curve. }; @@ -167,6 +168,21 @@ enum MbeMatingType { }; +//------------------------------------------------------------------------------ +/** \brief \ru Тип сопряжения по кривой заплатки. + \en The conjugation type by patch curve. \~ + \details \ru Тип сопряжения по кривой заплатки. + \en The conjugation type by patch curve. \~ + \ingroup Data_Structures +*/ +//--- +enum MbePatchMatingType { + pmt_None = 0, ///< \ru Без сопряжений. \en Without conjugations. + pmt_Tangent = 1, ///< \ru Сопряжение по касательной. \en Tangential conjugation + pmt_SmoothG2 = 2, ///< \ru Гладкое сопряжение по первой производной касательной (по кривизне). \en The smooth conjugation by the first derivative of the tangent (the curvature). +}; + + //------------------------------------------------------------------------------ /** \brief \ru Тип сопряжения по ребрам. \en The type of conjugation by edges. \~ @@ -402,9 +418,9 @@ enum MbeConnectingType { //------------------------------------------------------------------------------ -/** \brief \ru Cпособы передачи данных при копировании оболочек. +/** \brief \ru Способы передачи данных при копировании оболочек. \en Methods of transferring data while copying shells. \~ - \details \ru Cпособы передачи данных при копировании оболочек в операциях над телами. \n + \details \ru Способы передачи данных при копировании оболочек в операциях над телами. \n Любая операция, и удачная, и ошибочная, безвозвратно модифицирует вершины, рёбра и грани оболочек операндов. \n Для сохранения неизменной исходной оболочки операнда применяется полное или частичное копирование данных. \n Используются четыре способа передачи данных в операцию. \n @@ -642,5 +658,129 @@ enum MbeProgBarId_PointsSurface pbarId_PointsSurface_End, }; +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Коэффициент уплотнения кривой. + \en Construction of smooth curves based on a three-dimensional polyline. Curve subdivision coefficient. \~ + \ingroup Data_Structures +*/ +//--- +enum MbeFairSubdivision +{ + fairSubdiv_No = 0, ///< \ru Без уплотнения. \en Without subdivision. + fairSubdiv_Single = 1, ///< \ru Однократное уплотнение. \en Single subdivision. + fairSubdiv_Double = 2 ///< \ru Двукратное уплотнение. \en Double subdivision. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Учет кривизны в концевых точках. + \en Construction of smooth curves based on a three-dimensional polyline. Accounting for curvature at end points. \~ + \ingroup Data_Structures +*/ +//--- +enum MbeFairCurvature +{ + fairCur_No = 0, ///< \ru Не учитывать. \en Do not take into accoun. + fairCur_Start = 1, ///< \ru В начальной точке. \en At the starting point. + fairCur_End = 2, ///< \ru В конечной точке. \en At the ending point. + fairCur_Both = 3, ///< \ru Учитывать оба конца. \en Take into account both ends. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Метод аппроксимации. + \en Construction of smooth curves based on a three-dimensional polyline. Approx method. \~ + \ingroup Data_Structures +*/ +//--- +enum MbeFairApprox +{ + fairApprox_KnotsSpline = 0, ///< \ru B-сплайновая кривая по узловым точкам. \en B-spline curve on nodes. + fairApprox_IsoSpline = 1, ///< \ru Изогеометрическая B-сплайновая кривая. \en Isogeometric B-spline curve. + fairApprox_IsoNurbs = 2, ///< \ru Изогеометрическая NURBzS кривая. \en Isogeometric NURBzS curve. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Учет вектора в точке перегиба. + \en Construction of smooth curves based on a three-dimensional polyline. Taking into account vector at inflection point. \~ +*/ +//--- +enum MbeFairVector +{ + fairVector_SegmentDir = 0, ///< \ru Направление звена S-полигона. \en Direction of segment of S-polygon. + fairVector_Tangent = 1, ///< \ru Направление касательной. \en Direction of tangent to curve. +}; +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Учет касательной в заданной точке / точки на касательной. +\en Construction of smooth curves based on a three-dimensional polyline. Taking into account tangent on point / point on tangent. \~ +*/ +//--- +enum MbeFixPntTng +{ + fixPntTng_NotFix = 0, ///< \ru Не фиксировать точки на касательных / касательные в точках. \en Do not fix the points on tangents / the tangents on points. + fixPntTng_Fix = 1, ///< \ru Фиксировать точки на касательных / касательные в точках. \en Fix the points on tangents / the tangents on points. +}; +//------------------------------------------------------------------------------ +/** \brief \ru Управление построением гладких кривых на базе трехмерной ломаной. Формат сплайна. + \en Construction of smooth curves based on a three-dimensional polyline. Spline Format. \~ + \ingroup Data_Structures +*/ +// --- +enum MbeFairSplineFormat +{ + fairFormat_Open = 1, ///< \ru Открытый S-полигон. \en Open S-polygon. + fairFormat_Close = 2, ///< \ru Закрытый S-полигон. \en Close S-polygon. + fairFormat_GB = 3 ///< \ru GB-полигон. \en GB-polygon. +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Предупреждения построения плавной кривой. \en Warnings of fair curve creation. \~ + \ingroup Data_Structures +*/ +// --- +enum MbeFairWarning +{ + fwarn_Success = 0, ///< \ru Нормальная работа. \en Normal work. + fwarn_IncorrectFirstTang = 1, ///< \ru Некорректное направление первой касательной. Игнорируется. \en Incorrect direction of first tangent. Ignored. + fwarn_StraightFirstSite = 2, ///< \ru Прямолинейный первый участок. Первый касательный вектор игнорируется. \en Straighten start site. First tangent ignored. + fwarn_IncorrectPolylines = 3, ///< \ru Некорректные формы ломаных / направления касательных. \en Incorrect polylines / tangent directions. + fwarn_IncorrectFixPntTng = 4, ///< \ru Некорректное направление / положение фиксированной касательной / точки. Игнорируется. \en Incorrect direction / position of a fixed tangent / point. Ignored. + fwarn_BadAccuracyFixPntTng = 5, ///< \ru Погрешность направления / положения фиксированной касательной / точки превышает заданную точность. \en The error of the direction / position of the fixed tangent / point exceeds the specified accuracy. + fwarn_BadStructureFixPntTng = 6, ///< \ru Положения фиксированных касательных не согласованы со стркуктурой кривой. Игнорируются. \en The positions of the fixed tangents are not consistent with the structure of the curve. Are ignored. + fwarn_BadPositionFixPntTng = 7, ///< \ru Положения фиксированных касательных не согласованы по интервалу. Игнорируются. \en The positions of fixed tangents are not matched by interval. Are ignored. + fwarn_CriticalConfig = 8, ///< \ru Критическая конфигурация для B-сплайновой аппроксимации. \en Critical configuration for B-Spline approximation. + fwarn_CantSetCurvature = 9, ///< \ru Конфигурация ломаной не позволяет установить кривизну с заданным значением. \en Configuration of polyline does not allow setting curvature value. + fwarn_AccuracyCritical = 10, ///< \ru Точность на прямолинейных / критических участках. \en Accuracy of approximation rectilinear / critical sites. + fwarn_AccuracyStraight = 11, ///< \ru Точность на прямолинейных участках. \en Accuracy of approximation on straight sites. + fwarn_BadAccuracy = 13, ///< \ru Критический участок. Погрешность превышает заданную точность. \en The Critical site. The error is more than set accuracy. + fwarn_BadInflection = 15, ///< \ru Неуместный перегиб. \en Unexpected inflection. + fwarn_CurvatureOutOfRange = 16, ///< \ru Значение кривизны вне диапазона допустимых значений. \en Curvatute out of range. + fwarn_SawtoothPolyline = 17 ///< \ru Пилообразная ломаная. \en Sawtooth polyline. +}; + + +//------------------------------------------------------------------------------ +/// \ru Форма поверхности заметания переменного сечения. \en The swept surface cross-section shape. \~ +// --- +enum MbeSectionShape { + cs_Round = 0, ///< \ru Дуга окружности в сечении. \en The section is circle or arc. + cs_Linea = 1, ///< \ru Отрезок прямой в сечении. \en The section is line segment. + cs_Conic = 2, ///< \ru Кривая второго порядка в сечении. \en The section is conic curve. + cs_Cubic = 3, ///< \ru Кубическая кривая в сечении. \en The section is cubic curve. + cs_Shape = 4, ///< \ru Сплайн определяет форму сечения. \en The section is spline. +}; // MbeSectionShape + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность кривой пересечения, отвечающая существующей грани. + \en Surface of the intersection curve corresponding to the existent face. \~ + \ingroup Data_Structures +*/ +// --- +enum MbeIntCurSurface +{ + ics_First = 0, ///<\ru Первая поверхность. \en First surface. \~ + ics_Second = 1, ///<\ru Вторая поверхность. \en Second surface. \~ + ics_Both = 2, ///<\ru Обе поверхности. \en Both surfaces. \~ +}; + #endif // __MB_ENUM_H diff --git a/C3d/Include/mb_homogeneous.h b/C3d/Include/mb_homogeneous.h index 54a14c9..a07fbc1 100644 --- a/C3d/Include/mb_homogeneous.h +++ b/C3d/Include/mb_homogeneous.h @@ -437,7 +437,7 @@ inline void MbHomogeneous::operator /= ( double factor ) { // \ru Умножение на число \en The multiplication by a number // --- inline MbHomogeneous MbHomogeneous::operator * ( double factor ) const { - return MbHomogeneous( x * factor, y * factor, w * factor ); + return MbHomogeneous( x * factor, y * factor, w * factor ); } diff --git a/C3d/Include/mb_matrix.h b/C3d/Include/mb_matrix.h index f84773d..6426e9b 100644 --- a/C3d/Include/mb_matrix.h +++ b/C3d/Include/mb_matrix.h @@ -15,7 +15,7 @@ #include -#define MATRIX_DIM_2D 3 +#define MATRIX_DIM_2D 3 class MATH_CLASS MbPlacement; diff --git a/C3d/Include/mb_matrix3d.h b/C3d/Include/mb_matrix3d.h index 7c0c6ab..b33ea87 100644 --- a/C3d/Include/mb_matrix3d.h +++ b/C3d/Include/mb_matrix3d.h @@ -16,10 +16,10 @@ #include -#define MATRIX_DIM_3D 4 // \ru Размер матрицы \en A matrix size -#define AXIS_0X 0 // \ru Ось 0X \en 0X-axis -#define AXIS_0Y 1 // \ru Ось 0Y \en 0Y-axis -#define AXIS_0Z 2 // \ru Ось 0Z \en 0Z-axis +const_expr size_t MATRIX_DIM_3D = 4; // \ru Размер матрицы \en A matrix size +const_expr size_t AXIS_0X = 0; // \ru Ось 0X \en 0X-axis +const_expr size_t AXIS_0Y = 1; // \ru Ось 0Y \en 0Y-axis +const_expr size_t AXIS_0Z = 2; // \ru Ось 0Z \en 0Z-axis class MATH_CLASS MbMatrix; @@ -524,13 +524,18 @@ public: \{ */ /// \ru Транспонировать матрицу. \en Transpose a matrix. - void Adj(); + void Adj(); /// \ru Вычислить алгебраическое дополнение. \en Calculate the algebraic adjunct. - double Delta( size_t line, size_t column, size_t dim ) const; + double Delta( size_t line, size_t column, size_t dim ) const; /// \ru Вычислить определитель матрицы. \en Calculate the determinant of a matrix. - double Det( size_t dim ) const; - /// \ru Вычислить обратную матрицу. \en Calculate inverse matrix. - void Div( MbMatrix3D & ) const; + double Det( size_t dim ) const; + /** + \brief \ru Вычислить обратную матрицу. + \en Calculate inverse matrix. + \return \ru Функция вернет аргумент, принятый по ссылке, с результатом вычисления обратной матрицы. + \en The function returns the argument passed by reference with the result of calculating the inverse matrix. \~ + */ + MbMatrix3D & Div( MbMatrix3D & ) const; /** \} */ @@ -598,7 +603,7 @@ public: private: /// \ru Удалить мусор в данных \en Remove trash from data. - void RemoveInaccuracies(); + //void RemoveInaccuracies(); /// \ru Выставить флаги. \en Set flags. uint8 ResetFlag() const; // Оценить флаги, если оценки не было diff --git a/C3d/Include/mb_matrixnn.h b/C3d/Include/mb_matrixnn.h index 3c89139..b88d6a3 100644 --- a/C3d/Include/mb_matrixnn.h +++ b/C3d/Include/mb_matrixnn.h @@ -158,7 +158,7 @@ MbeNewtonResult TypedGaussEquation ( MatrixNN & a, Type * b, double epsilon, Pro } if ( l != k ) { - // (!) Рекомендуется использовать MatrixNN::SwapLines(k,l) + // (!) Рекомендуется использовать MatrixNN::SwapLines(k,l) for ( j = k; j < count; j++ ) { tmp = a(k, j); @@ -269,14 +269,14 @@ MbeNewtonResult TypedTridiagonalSolve ( const size_t n, ArrayDouble & a, ArrayDo if ( ::fabs ( a[0] ) < epsZero ) return nr_Special; // \ru Прогонка не работает \en Sweep does not work // \ru Прямой ход прогонки \en Forward step of sweep - b[0] /= - a[0]; - r[0] /= a[0]; + b[0] /= - a[0]; + r[0] /= a[0]; for ( size_t i = 1; i < n; ++i ) { double dom = a[i] + b[i - 1] * c[i - 1]; if ( ::fabs ( dom ) < epsZero ) return nr_Special; // \ru Прогонка не работает \en Sweep does not work if ( i < n - 1 ) // \ru Размерность b равна n-1, поэтому не можем вычислять b[n-1], да и не нужно оно. \en B dimension is equal to n-1, therefore we can not calculate b [n-1], and it isn't necessary. - b[i] /= - dom; + b[i] /= - dom; r[i] = ( r[i] - r[i - 1] * c[i - 1] ) / dom; } // \ru Обратный ход \en Backward substitution diff --git a/C3d/Include/mb_nurbs_function.h b/C3d/Include/mb_nurbs_function.h index 082d9d3..5651beb 100644 --- a/C3d/Include/mb_nurbs_function.h +++ b/C3d/Include/mb_nurbs_function.h @@ -1,2316 +1,2344 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Модуль геометрических построений. - \en The module of geometric constructions. \~ - \details \ru Базовые алгоритмы Nurbs кривых и поверхностей. - \en The base algorithms for NURBS curves and surfaces. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MB_NURBS_FUNCTION_H -#define __MB_NURBS_FUNCTION_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class MATH_CLASS MbContour; -class MATH_CLASS MbContour3D; -class MATH_CLASS MbNurbs; -class MATH_CLASS MbNurbs3D; - - -//------------------------------------------------------------------------------ -/** \brief \ru Флаг, определяющий построение сплайна, проходящего через точки. - \en Flag defining creation of spline passing through points. \~ - \details \ru Флаг, определяющий построение сплайна, проходящего через точки. Связан с версией. \n - \en Flag defining creation of spline passing through points. Related to the version. \n \~ - \ingroup Data_Structures -*/ -// --- -enum MbeSplineCreateType { - sct_Version0 = 0, ///< \ru Используется в версиях < V13 (центростремительная параметризация). \en Used in versions < V13 (centripetal parameterization). - sct_Version1 = 1, ///< \ru Используется в версии V13 (параметризация по длине хорды). \en Used in version V13 (parameterization by chord length). - sct_Version2 = 2, ///< \ru Используется в версии V13+. \en Used in version V13+. -}; - - -//------------------------------------------------------------------------------- -/** \brief \ru Дополнительная информация для преобразования кривой или поверхности в Nurbs. - \en Additional information for transformation of a curve or surface to NURBS. \~ - \details \ru Дополнительная информация для преобразования кривой или поверхности в Nurbs. \n - \en Additional information for transformation of a curve or surface to NURBS. \n \~ - \ingroup Data_Structures -*/ -// --- -class MbCurveIntoNurbsInfo { -private: - double tbeg; ///< \ru Параметр начала участка кривой. \en A parameter of the curve piece start. - double tend; ///< \ru Параметр конца участка кривой. \en A parameter of the curve piece end. - int sense; ///< \ru Направление сплайн-кривой. \en Direction of spline-curve. - bool matchParams; ///< \ru Сохранять ли при преобразовании однозначное соответствие параметрических областей. \en Whether to save correspondence of parametric regions while transforming or not. - bool extendRange; ///< \ru Строится ли преобразование на продолжении для незамкнутой подложки. \en Whether transformation is constructed on the extension for a non-closed substrate. - VERSION version; ///< \ru Версия исполнения. \en The version of execution. -private: - MbCurveIntoNurbsInfo(); -public: - /// \ru Конструктор. \en Constructor. - template - MbCurveIntoNurbsInfo( const Curve & c, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) - : tbeg ( c.GetTMin() ) - , tend ( c.GetTMax() ) - , sense ( 1 ) - , matchParams( match ) - , extendRange( ext ) - , version ( ver ) - {} - /// \ru Конструктор. \en Constructor. - MbCurveIntoNurbsInfo( double t1, double t2, int s, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) - : tbeg ( t1 ) - , tend ( t2 ) - , sense ( s ) - , matchParams( match ) - , extendRange( ext ) - , version ( ver ) - {} - /// \ru Конструктор. \en Constructor. - MbCurveIntoNurbsInfo( const MbCurveIntoNurbsInfo & other, double t1, double t2, int s ) - : tbeg ( t1 ) - , tend ( t2 ) - , sense ( s ) - , matchParams( other.matchParams ) - , extendRange( other.extendRange ) - , version ( other.version ) - {} - /// \ru Функция присвоения. \en Assignment function. - void Assign( const MbCurveIntoNurbsInfo & other ) - { - tbeg = other.tbeg; - tend = other.tend; - sense = other.sense; - matchParams = other.matchParams; - extendRange = other.extendRange; - version = other.version; - } - /// \ru Функция инициализации. \en The initialization function. - bool Init( double t1, double t2, int s ) - { - tbeg = t1; - tend = t2; - sense = s; - C3D_ASSERT( ((sense == 1) || (sense == -1)) ); - return ((sense == 1) || (sense == -1)); - } - /// \ru Функция инициализации. \en The initialization function. - bool Init( double t1, double t2, int s, bool match, bool ext ) { - matchParams = match; - extendRange = ext; - return Init( t1, t2, s ); - } - -public: - /// \ru Получить параметр начала участка кривой. \en Get the parameter of the start curve region. - double GetTBeg() const { return tbeg; } - /// \ru Получить параметр конца участка кривой. \en Get the parameter of the end curve region. - double GetTEnd() const { return tend; } - /// \ru Получить направление сплайн-кривой. \en Get the direction of spline-curve. - int GetSense() const { return sense; } - /// \ru Сохранять ли при преобразовании однозначное соответствие параметрических областей. \en Whether to save correspondence of parametric regions by transformation or not. - bool MatchParams() const { return matchParams; } - /// \ru Строится ли преобразование на продолжении для незамкнутой подложки. \en Whether transformation is constructed on the extension for a non-closed substrate or not. - bool ExtendRange() const { return extendRange; } - /// \ru Получить версию исполнения. \en Get the version of execution. - VERSION GetMathVersion() const { return version; } - -OBVIOUS_PRIVATE_COPY( MbCurveIntoNurbsInfo ) -}; - - -//------------------------------------------------------------------------------- -/** \brief \ru Параметры построения NURBS копии объекта. - \en Parameters for the construction of a NURBS copy of the object. \~ - \details \ru Параметры построения NURBS копии объекта. \n - \en Parameters for the construction of a NURBS copy of the object. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MbNurbsParameters { -public: - size_t degree; ///< \ru Порядок NURBS копии. \en Order of NURBS copy. - size_t pointsCount; ///< \ru Количество контрольных точек (при 0 параметр игнорируется). \en The number of control points (if there is no control points, parameter is ignored). - MbRect1D region; ///< \ru Область объекта, подлежащая копированию: [0 1] соответствует [tMin tMax] объекта. \en Region of the object to be copied: [0, 1] corresponds to [tMin tMax] object. - SArray knots; ///< \ru Узловой вектор. \en Knot vector. - mutable bool useApprox; ///< \ru Не пытаться построить точную поверхность. \en Don't try to create the exact surface. - -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - MbNurbsParameters() - : degree ( c3d::NURBS_DEGREE ) - , pointsCount( 0 ) - , region ( 0.0, 1.0 ) - , knots ( 0, 1 ) - , useApprox ( true ) - {} - /// \ru Конструктор по параметрам (без узлов) построения NURBS. \en The constructor of NURBS by parameters (without knots). - MbNurbsParameters( size_t d, size_t c, double zmin, double zmax, bool approx ) - : degree ( d ) - , pointsCount( c ) - , region ( zmin, zmax ) - , knots ( 0, 1 ) - , useApprox ( approx ) - { - C3D_ASSERT( d > 1 && d < SYS_MAX_UINT16 ); - degree = std_max( d, (size_t)2 ); - degree = std_min( d, (size_t)SYS_MAX_UINT16 ); - } - /// \ru Конструктор по полному набору параметров построения NURBS. \en The constructor of NURBS by a complete set of parameters. - MbNurbsParameters( size_t d, size_t c, double zmin, double zmax, bool approx, const SArray & aKnots ) - : degree ( d ) - , pointsCount( c ) - , region ( zmin, zmax ) - , knots ( aKnots ) - , useApprox ( approx ) - { - C3D_ASSERT( d > 1 && d < SYS_MAX_UINT16 ); - degree = std_max( d, (size_t)2 ); - degree = std_min( d, (size_t)SYS_MAX_UINT16 ); - } - /// \ru Конструктор копирования. \en The copy constructor. - MbNurbsParameters( const MbNurbsParameters & other ) - : degree ( other.degree ) - , pointsCount( other.pointsCount ) - , region ( other.region ) - , knots ( other.knots ) - , useApprox ( other.useApprox ) - {} - /// \ru Деструктор. \en Destructor. - ~MbNurbsParameters() {} - - /// \ru Инициализировать по другим параметрам построения NURBS копии объекта. \en Initialize by another parameters. - void Init( const MbNurbsParameters & other ) { - degree = other.degree; - pointsCount = other.pointsCount; - region = other.region; - knots = other.knots; - useApprox = other.useApprox; - } - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbNurbsParameters & other, double accuracy ) const; - /// \ru Оператор присваивания. \en The assignment operator. - MbNurbsParameters & operator = ( const MbNurbsParameters & other ) { - degree = other.degree; - pointsCount = other.pointsCount; - region = other.region; - knots = other.knots; - useApprox = other.useApprox; - return (*this); - } - -public: - size_t GetDegree() const { return degree; } - size_t GetPointsCount() const { return pointsCount; } - const MbRect1D & GetRegion() const { return region; } - const SArray & GetKnots() const { return knots; } - bool UseApprox() const { return useApprox; } - -KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsParameters ) // \ru Для работы со ссылками и объектами класса \en For working with references and objects of the class -}; // MbNurbsParameters - - -//------------------------------------------------------------------------------- -/** \brief \ru Параметры узловой точки сплайновой копии объекта. - \en Parameters of knot point of the object spline copy. \~ - \details \ru Параметры узловой точки сплайновой копии объекта. \n - \en Parameters of knot point of the object spline copy. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MbNurbsPointInfo { -public: - MbCartPoint3D point; ///< \ru Узловая точка сплайновой поверхности. \en A knot point of a spline surface. - bool visible; ///< \ru Флаг видимости точки. \en A point visibility flag. - int8 poleLocation; ///< \ru Расположение полюса в параметрической области. \en The location of a pole in the parametric region. -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - MbNurbsPointInfo() - : point ( ) - , visible ( true ) - , poleLocation ( (uint8)pln_None ) - {} - /// \ru Конструктор по точке и флагу видимости. \en The constructor by a point and visibility flag. - MbNurbsPointInfo( MbCartPoint3D aPount, bool aVisible, MbePoleLocation aPoleLocation ) - : point ( aPount ) - , visible ( aVisible ) - , poleLocation ( (uint8)aPoleLocation ) - {} - /// \ru Конструктор копирования. \en The copy constructor. - MbNurbsPointInfo( const MbNurbsPointInfo & other ) - : point ( other.point ) - , visible ( other.visible ) - , poleLocation ( (uint8)other.poleLocation ) - {} - /// \ru Деструктор. \en Destructor. - ~MbNurbsPointInfo() {} - - /// \ru Инициализировать по точке и флагу видимости. \en Initialize by a point and visibility flag. - void Init( const MbNurbsPointInfo & other ) - { - point = other.point; - visible = other.visible; - poleLocation = other.poleLocation; - } - /// \ru Оператор присваивания. \en The assignment operator. - MbNurbsPointInfo & operator = ( const MbNurbsPointInfo & other ) - { - point = other.point; - visible = other.visible; - poleLocation = other.poleLocation; - return (*this); - } - /// \ru Определить, является ли точка полюсом. \en Define whether the point is a pole. - MbePoleLocation GetPoleLocation() { return (MbePoleLocation)poleLocation; } - - // \ru Закомментировала строчку ниже, поскольку объект служит только для передачи дополнительной информации об узлах сплайна \en Commented out the line below, because the object is used only to pass additional information about spline knots - // \ru В процессе прямого моделирования. Не пишется и не читается. \en In the direct modeling. Not written and not read. - // \ru KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsPointInfo ) // для работы со ссылками и объектами класса \en KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsPointInfo ) // for working with references and objects of the class -}; //MbNurbsPointInfo - - -//------------------------------------------------------------------------------ -/** \brief \ru Дать меру расстояния. - \en Get a measure of the distance. \~ - \details \ru Дать меру расстояния. - \en Get a measure of the distance. \~ - \param[in] p1, p2 - \ru Точки между которыми ищется расстояние. - \en Points between which the distance is computed. \~ - \param[in] spType - \ru Тип параметризации сплайновых объектов. - \en The parametrization type of spline objects. \~ - \return \ru Расстояние. - \en Distance. \~ - \ingroup Base_Algorithms -*/ -// --- -template -double GetParamDistance( const Type & p1, const Type & p2, MbeSplineParamType spType ) -{ - switch ( spType ) { - case spt_Unstated : - case spt_EquallySpaced : - return 1.0; - case spt_ChordLength : - return p1.DistanceToPoint( p2 ); - case spt_Centripetal: - return ::sqrt( p1.DistanceToPoint( p2 ) ); - } - - return 1.0; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \details \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] pcnt - \ru Число точек. - \en Number of points. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -inline bool IsValidNurbsParams( ptrdiff_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. - // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. - - return ( (degree > 1) && (pcnt >= (closed ? 3 : (size_t)degree)) ); -} - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \details \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] pcnt - \ru Число точек. - \en Number of points. \~ - \param[in] wcnt - \ru Число весов. - \en Number of weights. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -inline bool IsValidNurbsParams( ptrdiff_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. - // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. - // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. - - bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && (wcnt == pcnt); - return res; -} - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \details \ru Проверить параметры инициализации nurbs-объекта. - \en Check initialization parameters of a nurbs-object. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] pcnt - \ru Число точек. - \en Number of points. \~ - \param[in] wcnt - \ru Число весов. - \en Number of weights. \~ - \param[in] kcnt - \ru Число узлов. - \en Number of knots. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -inline bool IsValidNurbsParams( ptrdiff_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. - // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. - // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. - // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. - - bool res = ::IsValidNurbsParams( degree, closed, pcnt, wcnt ) && - ( kcnt == ((size_t)degree + pcnt + (closed ? ((size_t)degree - 1) : 0)) ); - return res; -} - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры инициализации nurbs-кривой. - \en Check initialization parameters of a nurbs-curve. \~ - \details \ru Проверить параметры инициализации nurbs-кривой. - \en Check initialization parameters of a nurbs-curve. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] pcnt - \ru Число точек. - \en Number of points. \~ - \param[in] knots - \ru Узловой вектор. - \en Knots vector. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -template -bool IsValidNurbsParamsExt( ptrdiff_t degree, bool closed, size_t pcnt, - const KnotsVector & knots ) -{ - // \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. - // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. - // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. - // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. - - bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && - ( knots.size() == ((size_t)degree + pcnt + (closed ? ((size_t)degree - 1) : 0)) ); - - if ( res ) { - if ( !c3d::IsMonotonic( knots, true, true ) ) - res = false; // SD#7118498 - } - - return res; -} - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить параметры инициализации nurbs-кривой. - \en Check initialization parameters of a nurbs-curve. \~ - \details \ru Проверить параметры инициализации nurbs-кривой. - \en Check initialization parameters of a nurbs-curve. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] pnts - \ru Точки. - \en Points vector. \~ - \param[in] wts - \ru Веса точек. - \en Weights vector. \~ - \param[in] knots - \ru Узловой вектор. - \en Knots vector. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -template -bool IsValidNurbsParamsExt( ptrdiff_t degree, bool closed, const PointVector & pnts, - const DoubleVector * wts, - const DoubleVector * knots = 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. - // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. - // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. - // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. - - size_t pcnt = pnts.size(); - - bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && - ( (wts == NULL) || (wts->size() == pcnt) ) && - ( (knots == NULL) || (knots->size() == ((size_t)degree + pcnt + (closed ? ((size_t)degree - 1) : 0))) ); - - if ( res && (knots != NULL) ) { - if ( !c3d::IsMonotonic( *knots, true, true ) ) - res = false; // SD#7118498 - } - - return res; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить узловой вектор nurbs-объекта. - \en Check knots vector of a nurbs-object. \~ - \details \ru Проверить узловой вектор nurbs-объекта. - \en Check knots vector of a nurbs-object. \~ - \param[in] knots - \ru Узловой вектор. - \en Knots vector. \~ - \return \ru true, если параметры согласованы. - \en Returns true if parameters are consistent. \~ - \ingroup Base_Algorithms -*/ -// --- -template -bool IsValidNurbsKnots( const KnotsVector & knots, double eps = EXTENT_EPSILON ) -{ - // \ru 1 . Количество узлов должно быть не менее 4 \en 1 . The number of knots must be at least 4 - // \ru 2 . Последовательность узлов должна быть неубывающей \en 2 . Sequence of nodes must be nondecreasing - // \ru 3 . Первый и последний узлы должны быть различны \en 3 . The first and the last nodes must be different - - size_t cnt = knots.size(); - if ( cnt < 4 ) - return false; - - eps = ::fabs(eps); - if ( ::fabs(knots[cnt-1] - knots[0]) < eps ) - return false; - - for ( size_t i = 0; i < (cnt - 1); i++ ) { - if ( knots[i+1] < knots[i] - eps ) - return false; - } - - return true; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Определение индекса узла left для первой ненулевой функции. - \en Definition of "left" knot index for the first non-zero function. \~ - \details \ru Определение индекса узла left для первой ненулевой функции (knots[mid] <= t < knots[mid + 1]). - \en Definition of "left" knot index for the first non-zero function (knots[mid] <= t < knots[mid + 1]). \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] knots - \ru Множество узлов. - \en Knots. \~ - \param[in, out] t - \ru Значение параметра. - \en A parameter value. \~ - \return \ru Индекс узла. - \en A knot index. \~ - \ingroup Base_Algorithms -*/ -// --- -template -ptrdiff_t KnotIndex( ptrdiff_t degree, const KnotsVector & knots, double & t ) -{ - ptrdiff_t low = ( (ptrdiff_t)degree - 1 ); - ptrdiff_t high = ( (ptrdiff_t)knots.size() - (ptrdiff_t)degree ); - ptrdiff_t mid = low; - - if ( t <= knots[low] ) { - t = knots[low]; - ptrdiff_t countKnt = knots.size(); - ptrdiff_t lowP = low; - lowP++; - // \ru Исправление ошибки BUG_21185 while ( (lowP < countKnt) && (t == knots[lowP]) ) { \en Bugfix BUG_21185 while ( (lowP < countKnt) && (t == knots[lowP]) ) { - while ( (lowP < countKnt - degree) && (t == knots[lowP]) ) { //-V550 - low = lowP; - lowP++; - } - mid = low; - } - else if ( t >= knots[high] ) { - t = knots[high]; - // BUG_82980 while ( (high > 0) && (knots[high] == t) ) { - while ( (high > degree - 1) && (knots[high] == t) ) { - high--; - } - mid = high; - } - else if ( c3d::ArFind( knots, t, mid ) ) { - while ( knots[mid] == t ) { - mid++; - } - mid--; - } - return mid; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить узловой вектор (равномерная параметризация). - \en Define knot vector (uniform parameterization). \~ - \details \ru Определить узловой вектор (равномерная параметризация). - \en Define knot vector (uniform parameterization). \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] uppPointsIndex - \ru Индекс последней точки. - \en Last point index. \~ - \param[in] knots - \ru Узловой вектор. - \en Knots vector. \~ - \ingroup Base_Algorithms -*/ -// --- -template -ptrdiff_t DefineKnotsVector( ptrdiff_t degree, bool closed, ptrdiff_t uppPointsIndex, - KnotsVector & knots ) -{ - if ( (degree < 2) || (uppPointsIndex < 1) ) { - knots.clear(); - return -1; - } - - ptrdiff_t pointsCount = uppPointsIndex + 1; - ptrdiff_t power = degree - 1; - - ptrdiff_t knotsCount = degree + pointsCount + (closed ? power : 0); - knots.clear(); - knots.reserve( knotsCount ); - - ptrdiff_t i = 0; - - if ( closed ) { // замкнутый В-сплайн - double knot = 0.0; - for ( i = 0; i < knotsCount; i++ ) { - knot = (double)(i - power); - knots.push_back( knot ); - } - } - else { - double knot = 0.0; - for ( i = 0; i < degree; i++ ) - knots.push_back( knot ); - - ptrdiff_t cnt = pointsCount - degree; - for ( i = 0; i < cnt; i++ ) { - knot += 1.0; - knots.push_back( knot ); - } - - knot += 1.0; - for ( i = 0; i < degree; i++ ) - knots.push_back( knot ); - } - - return (knotsCount - 1); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить узловой вектор. - \en Define knot vector. \~ - \details \ru Определить узловой вектор. - \en Define knot vector. \~ - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in] count - \ru Количество точек. - \en Number of points. \~ - \param[in] params - \ru Параметры точек (для замкнутого count+1). - \en Points parameters (for closed spline - "count"+1). \~ - \param[out] knots - \ru Узловой вектор. - \en Knots vector. \~ - \return \ru true, если набор параметров сформирован. - \en Returns true if result is success. \~ - \ingroup Base_Algorithms -*/ -// --- -MATH_FUNC (bool) DefineKnotsVector( ptrdiff_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 - - -//------------------------------------------------------------------------------ -/** \brief \ru Определить параметрическое распределение точек. - \en Define parametric distribution of points. \~ - \details \ru Определить параметрическое распределение точек. - \en Define parametric distribution of points. \~ - \param[in] points - \ru Массив точек. - \en Points vector. \~ - \param[in] spType - \ru Тип параметризации сплайновых объектов. - \en The parameterization type of spline objects. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[out] params - \ru Параметрическое распределение точек. - \en Parametric distribution of points. \~ - \return \ru true, если набор параметров сформирован. - \en Returns true if result is success. \~ - \ingroup Base_Algorithms -*/ -// --- -template -bool DefineThroughPointsParams( const Points & points, MbeSplineParamType spType, bool closed, - Params & params ) -{ - bool res = false; - - ptrdiff_t count = (ptrdiff_t)points.size(); - - if ( count > (closed ? 2 : 1) ) { - double param = 0.0; - ptrdiff_t extCount = closed ? (count + 1) : count; - params.clear(); - params.resize( extCount, param ); - - double paramSum = 0.0; - for ( ptrdiff_t j = 1; j < extCount; j++ ) { - ptrdiff_t jp = (j - 1 + count) % count; - ptrdiff_t jc = j % count; - param = ::GetParamDistance( points[jp], points[jc], spType ); - params[j] = ( params[j-1] + param ); - paramSum += param; - } - - if ( paramSum > METRIC_PRECISION ) { - for ( ptrdiff_t j = 0; j < extCount; j++ ) { - params[j] /= paramSum; - params[j] *= (double)(extCount-1); - } - res = true; - } - else if ( spType != spt_EquallySpaced ) { - C3D_ASSERT_UNCONDITIONAL( false ); - paramSum = 0.0; - for ( ptrdiff_t j = 1; j < extCount; j++ ) { - ptrdiff_t jp = (j - 1 + count) % count; - ptrdiff_t jc = j % count; - param = ::GetParamDistance( points[jp], points[jc], spt_EquallySpaced ); - params[j] = ( params[j-1] + param ); - paramSum += param; - } - if ( paramSum > METRIC_PRECISION ) { - for ( ptrdiff_t j = 0; j < extCount; j++ ) { - params[j] /= paramSum; - params[j] *= (double)(extCount-1); - } - res = true; - } - } - } - - return res; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычисление B - базиса (degree - порядок B-сплайна, p = (degree - 1) - степень полинома(B-сплайна)). - \en The calculation of B - basis ("degree" - order of B-spline, p = (degree - 1) - the degree of the polynomial (B-spline)). \~ - \details \ru Вычисление B - базиса (degree - порядок B-сплайна, p = (degree - 1) - степень полинома(B-сплайна)). - Для ускорения используется рабочий вектор lr = { left[p+1], right[p+1] } ). - \en The calculation of B - basis ("degree" - order of B-spline, p = (degree - 1) - the degree of the polynomial (B-spline)). - To speed up vector lr = { left[p+1], right[p+1] } is used. \~ - \param[in] i - \ru Индекс в массиве узлов, получаемый с помощью функции KnotIndex(). - \en Index of knots vector obtained by the function KnotIndex(). \~ - \param[in] t - \ru Параметр. - \en Parameter. \~ - \param[in] p - \ru p = degree - 1, где degree - порядок B-сплайна. - \en p = degree - 1, where degree is B-spline degree. \~ - \param[in] knots - \ru Узловой вектор. - \en Knots vector. \~ - \param[out] nsplines - \ru Массив размерности degree, заполняется значениями сплайна в поля 0..degree-2; nsplines[degree-1] = 0. - \en Array of B-spline values. \~ - \param[in,out] lrVect - \ru Массив размерности 2*(p+1) = 2*degree, содержимое игнорируется и будет перезаписано. Нужен для ускорения работы функции. В результате работы в нем останется мусор.. - \en Temporary working vector with dimension 2*(p+1) = 2*degree. \~ - \ingroup Base_Algorithms -*/ -// --- -template -MATH_FUNC (bool) BasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const Knots & knots, DoubleVector & nsplines, - DoubleVector & lrVect ); - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить базисный сплайн по параметру t и узловому вектору. - \en Calculate basic spline by "t" parameter and knots vector. \~ - \details \ru Вычислить базисный сплайн по параметру t и узловому вектору. - \en Calculate basic spline by "t" parameter and knots vector. \~ - \ingroup Base_Algorithms -*/ -// --- -template -MATH_FUNC (bool) CalcBsplvb( const DoubleVector & knots, double t, ptrdiff_t left, ptrdiff_t degree, - DoubleVector & biatx, DoubleVector & lrVect ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). - \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ - \details \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). - \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ - \ingroup Base_Algorithms -*/ -// --- -void AllBasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const SArray & knots, double ** ndu, - double * left, double * right, bool newPatch = true ); - -//------------------------------------------------------------------------------ -/** \brief \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). - \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ - \details \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). - \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ - \ingroup Base_Algorithms -*/ -// --- -void AllBasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const SArray & knots, double * ndu, size_t degree, - double * left, double * right, bool newPatch = true ); - -//------------------------------------------------------------------------------ -/// \ru Вычислить значения базисного сплайна и его производных. \en Calculate values and derivatives of basic spline. -/** - \param[in] t - \ru Параметр на кривой. - \en Curve parameter. \~ - \param[in] left - \ru Номер узла первого ненулевого сплайна. - \en Knot number of the first nonzero spline. \~ - \param[in] n - \ru Порядок вычисляемых производных. - \en Order of calculated derivatives. \~ - \param[out] values - \ru Двумерный массив значений. - \en 2D-Array filled by spline values. \~ - \ingroup Base_Algorithms -*/ -//--- -bool CalcDBsplvb( const SArray & knots, ptrdiff_t degree, double t, ptrdiff_t left, ptrdiff_t n, Array2 & values ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить все разностные формы кривой. - \en Calculate all difference forms of curve. \~ - \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). - \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ - \ingroup Base_Algorithms -*/ -// --- -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) ); - - ptrdiff_t r = ( r2 - r1 ); - ptrdiff_t degree = ( p + 1 ); - ptrdiff_t i, k, icount; - NurbsVector & PK0 = PK[0]; - - if ( PW != NULL ) { - for ( i = 0; i <= r; i++ ) - PK0.Set( i, *PW, (r1 + i) ); - } - else { - if ( !PK0.UseWeights() && ( r1 + r ) < pointCount ) { - for ( i = 0; i <= r; i++ ) { - PK0[i] = P[r1 + i]; - } - } - else { - for ( i = 0; i <= r; i++ ) { - k = ( ( r1 + i ) % pointCount ); - PK0.Init( i, P[k], W[k] ); - } - } - } - - for ( k = 1; k <= d; k++ ) { - NurbsVector & PKMin = PK[k - 1]; - NurbsVector & PKPls = PK[k]; - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = (r - k); i <= icount; i++ ) { - r1i = ( r1 + i ); - C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - PKPls.Dec( i, PKMin, i, PKMin, (i + 1), (tmp / (U[r1i + degree] - U[r1i + k])) ); - } - } -} - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить все разностные формы кривой. - \en Calculate all difference forms of curve. \~ - \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). - \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ - \ingroup Base_Algorithms -*/ -// --- -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) ); - - ptrdiff_t r = ( r2 - r1 ); - ptrdiff_t degree = ( p + 1 ); - ptrdiff_t i, k, icount; - NurbsVector & PK0 = PK[0]; - - if ( PW != NULL ) { - for ( i = 0; i <= r; i++ ) - PK0.Set( i, *PW, (r1 + i) ); - } - else { - if ( !PK0.UseWeights() && ( r1 + r ) < pointCount ) { - for ( i = 0; i <= r; i++ ) { - PK0[i] = P[r1 + i]; - } - } - else { - for ( i = 0; i <= r; i++ ) { - k = ( ( r1 + i ) % pointCount ); - PK0.Init( i, P[k], w ); - } - } - } - - for ( k = 1; k <= d; k++ ) { - NurbsVector & PKMin = PK[k - 1]; - NurbsVector & PKPls = PK[k]; - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = (r - k); i <= icount; i++ ) { - r1i = ( r1 + i ); - C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - PKPls.Dec( i, PKMin, i, PKMin, (i + 1), (tmp / (U[r1i + degree] - U[r1i + k])) ); - } - } -} - -//------------------------------------------------------------------------------ - /** \brief \ru Вычислить все разностные формы кривой. - \en Calculate all difference forms of curve. \~ - \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). - \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ - \ingroup Base_Algorithms -*/ -// --- -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 ) ); - - 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; - - if ( PW != NULL ) { - if ( !useWeight ) { - for ( i = 0; i <= r; i++ ) - DT0[i].Init( (*PW)[r1 + i] ); - } - else { - for ( i = 0; i <= r; i++ ) { - DT0[i].Init( (*PW)[r1 + i] ); - WT0[i] = PW->w( r1 + i ); - } - } - } - else { - if ( !useWeight && ( r1 + r ) < pointCount ) { - for ( i = 0; i <= r; i++ ) { - DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); - } - } - else { - for ( i = 0; i <= r; i++ ) { - k = ( ( r1 + i ) % pointCount ); - DT0[i].Init( P[k], W[k] ); - if ( useWeight ) - WT0[i] = W[k]; - } - } - } - - double * WTMin = NULL; - double * WTPls = NULL; - for ( k = 1; k <= d; k++ ) { - DoubleTriple * DTMin = DT[k - 1]; - DoubleTriple * DTPls = DT[k]; - if ( useWeight ) { - WTMin = WT[k - 1]; - WTPls = WT[k]; - } - - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = ( r - k ); i <= icount; i++ ) { - r1i = ( r1 + i ); - double tmp2 = U[r1i + degree] - U[r1i + k]; - C3D_ASSERT( ( ::fabs( tmp2 ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - DTPls[i].Dec( DTMin[i], DTMin[i + 1], tmp / (tmp2) ); - if ( useWeight ) - WTPls[i] = ( WTMin[i + 1] - WTMin[i] ) * ( tmp / (tmp2) ); - } - } -} - -//------------------------------------------------------------------------------ - /** \brief \ru Вычислить все разностные формы кривой. - \en Calculate all difference forms of curve. \~ - \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). - \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ - \ingroup Base_Algorithms -*/ -// --- -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 ) ); - - 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; - - if ( PW != NULL ) { - if ( !useWeight ) { - for ( i = 0; i <= r; i++ ) - DT0[i].Init( (*PW)[r1 + i] ); - } - else { - for ( i = 0; i <= r; i++ ) { - DT0[i].Init( (*PW)[r1 + i] ); - WT0[i] = PW->w( r1 + i ); - } - - } - } - else { - if ( !useWeight && ( r1 + r ) < pointCount ) { - for ( i = 0; i <= r; i++ ) { - DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); - } - } - else { - for ( i = 0; i <= r; i++ ) { - k = ( ( r1 + i ) % pointCount ); - DT0[i].Init( P[k], w ); - if( useWeight ) - WT0[i] = w; - } - } - } - - double * WTMin = NULL; - double * WTPls = NULL; - for ( k = 1; k <= d; k++ ) { - DoubleTriple * DTMin = DT[k - 1]; - DoubleTriple * DTPls = DT[k]; - if ( useWeight ) { - WTMin = WT[k - 1]; - WTPls = WT[k]; - } - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = ( r - k ); i <= icount; i++ ) { - r1i = ( r1 + i ); - double tmp2 = U[r1i + degree] - U[r1i + k]; - C3D_ASSERT( ( ::fabs( tmp2 ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - DTPls[i].Dec( DTMin[i], DTMin[i + 1], tmp / (tmp2) ); - if ( useWeight ) - WTPls[i] = ( WTMin[i + 1] - WTMin[i] ) * ( tmp / ( tmp2 ) ); - } - } -} - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить все разностные формы кривой. - \en Calculate all difference forms of curve. \~ - \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). - \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ - \ingroup Base_Algorithms -*/ -// --- -template -void CurveDeriveCpts( ptrdiff_t p, const double * U, const Point * P, const double * W, size_t pointCount, - ptrdiff_t r1, ptrdiff_t r2, - Homogeneous * H0, Homogeneous * H1, Homogeneous * H2, Homogeneous * H3 ) -{ - ptrdiff_t r = ( r2 - r1 ); - ptrdiff_t degree = ( p + 1 ); - ptrdiff_t i, k, icount; - - for ( i = 0; i <= r; i++ ) { - k = ( (r1 + i) % pointCount ); - if ( W != NULL ) - H0[i].Init( P[k], W[k] ); - else - H0[i].Init( P[k], 1.0 ); - } - k = 1; - { - Homogeneous * PKMin = H0; - Homogeneous * PKPls = H1; - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = (r - k); i <= icount; i++ ) { - r1i = ( r1 + i ); - C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); - } - } - k = 2; - { - Homogeneous * PKMin = H1; - Homogeneous * PKPls = H2; - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = (r - k); i <= icount; i++ ) { - r1i = ( r1 + i ); - C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); - } - } - k = 3; - { - Homogeneous * PKMin = H2; - Homogeneous * PKPls = H3; - double tmp = (double)( degree - k ); - ptrdiff_t r1i = r1; - for ( i = 0, icount = (r - k); i <= icount; i++ ) { - r1i = ( r1 + i ); - C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure - PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Cвертка по Энш. \en Einstein's convolution product. -// --- -void EiSum( const double * pk, double ** nd, size_t jcount, double & sum ); - - -//------------------------------------------------------------------------------ -// \ru Cвертка по Энш. \en Einstein's convolution product. -// --- -void EiSum( const MbHomogeneous * pk, double * nd, size_t degree, size_t jcount, MbHomogeneous & sum ); - - -//------------------------------------------------------------------------------ -// \ru Cвертка по Энш. \en Einstein's convolution product. -// --- -void EiSum( const MbHomogeneous3D * pk, double * nd, size_t degree, size_t jcount, MbHomogeneous3D & sum ); - - -//------------------------------------------------------------------------------ -/// \ru Загнать параметр t в параметрическую область кривой. \en Reduce "t" to parameter in the parametric domain of the curve. -/** - \param[in] tMin, tMax - \ru Параметры, задающие параметрическую область кривой. - \en Parameters which define the parametric region of the curve. \~ - \param[in] closed - \ru Признак замкнутости кривой. - \en An attribute of curve closedness. \~ - \param[in, out] t - \ru Исходный параметр. - \en Initial parameter. \~ - \ingroup Base_Algorithms -*/ -// --- -inline void CheckParam( const double & tMin, const double & tMax, bool closed, double & t ) -{ - if ( (t < tMin) || (t > tMax) ) { - if ( closed ) { // \ru Сплайн кривая замкнута \en Spline curve is closed - double period = tMax - tMin; - t -= ::floor( (t - tMin) / period ) * period; - } - else if ( t < tMin ) - t = tMin; - else if ( t > tMax ) - t = tMax; - } -} - - -//------------------------------------------------------------------------------ -/// \ru Рассчитать ненулевые сплайны при данном параметре. \en Calculate non-zero splines with a given parameter. -/** - \param[in] degree - \ru Порядок B-сплайна. - \en B-spline degree. \~ - \param[in] knots - \ru Множество узлов. - \en Knots. \~ - \param[in] closed - \ru Признак замкнутости. - \en A closedness attribute. \~ - \param[in, out] t - \ru Параметр - \en A parameter \~ - \param[out] nsplines - \ru Множество размерности degree, заполняется значениями сплайна. - \en Array (dimension is "degree") is filled by spline values. \~ - \param[out] lrVect - \ru Вспомогательный массив (содержит мусор). - \en An assisting array (contains garbage). \~ - \return \ru Номер первого ненулевого B-сплайна. - \en The number of the first non-zero B-spline. \~ - \ingroup Base_Algorithms -*/ -// --- -template -ptrdiff_t CalculateSplines( ptrdiff_t degree, - const KnotsVector & knots, - bool closed, - double & t, - DoubleVector1 & nsplines, - DoubleVector2 & lrVect ) -{ - ptrdiff_t begInd = -1; // \ru Возвращаемое значение = номер первого ненулевого B-сплайна \en The return value = the number of the first non-zero B-spline. - - if ( (degree > 1) && ((ptrdiff_t)knots.size() > (ptrdiff_t)degree) ) { - ptrdiff_t power = degree-1; - ptrdiff_t lastKnotInd = (ptrdiff_t)knots.size() - 1; - - // \ru Загнать параметр t в параметрическую область кривой \en Reduce "t" to a parameter in the parametric domain of the curve - ::CheckParam( knots[power], knots[lastKnotInd - (ptrdiff_t)power], closed, t ); - - ptrdiff_t tspan = ::KnotIndex( degree, knots, t ); - begInd = tspan - (ptrdiff_t)power; - if ( begInd >= 0 && begInd <= lastKnotInd - (ptrdiff_t)power ) - ::BasisFuns( tspan, t, power, knots, nsplines, lrVect ); - else { - begInd = SYS_MAX_T; // \ru Ошибка \en Error - for ( size_t i = 0; i < (size_t)degree; i++ ) - nsplines[i] = 0.0; - } - - C3D_ASSERT( (size_t)begInd != SYS_MAX_T ); - } - - return begInd; -} - - -//------------------------------------------------------------------------------ -// \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, - ptrdiff_t degree, bool closed, const DoubleVector & knots, - PointVector & pointList ) -{ - MbeNewtonResult res = nr_Failure; - - ptrdiff_t pointsCount = (ptrdiff_t)points.size(); - C3D_ASSERT( points.size() > 1 ); - - if ( pointsCount > 1 && degree > 1 && knots.size() > 1 ) { - // \ru Инициализация опорных точек \en Initialization of support points - if ( &pointList != &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 ) ) { - pointList.erase( pointList.begin() + uppIndex ); - pointsCount = (ptrdiff_t)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 ) ) { - MatrixNN & matrix = *matrixPtr; - - std::vector bSplines; // \ru Ненулевые B-сплайны \en Non-zero B-splines - bSplines.resize( degree ); - - std::vector lrVect; - - for ( ptrdiff_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 + (size_t)degree; k < pointsCount; k++ ) - matrix( i, k ) = 0.0; - } - - 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 = ::TypedGaussEquation( matrix, &pointList[0], epsilon ); - } - } - - return res; -} - - -//------------------------------------------------------------------------------ -// \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, - ptrdiff_t degree, bool closed, const DoubleVector & knots, - PointsVector & pointList ); - - -//------------------------------------------------------------------------------ -// \ru Установить касательность сплайна к вектору \en Set tangency of spline to vector -//--- -template -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 res = false; - - if ( !nurbs.IsClosed() && nurbs.GetPointListCount() > 2 && nurbs.GetDegree() > 2 ) { - bool needRebuild = false; - - TypedVector normTang( tang ); - double tangLen = tang.Length(); - if ( tangLen > LENGTH_EPSILON ) - normTang /= tangLen; - - SArray points ( 0, 1 ); - SArray weights( 0, 1 ); - SArray knots ( 0, 1 ); - nurbs.GetPointList( points ); - nurbs.GetWeights( weights ); - nurbs.GetKnots( knots ); - ptrdiff_t degree = nurbs.GetDegree(); - bool closed = false; - - // \ru Дополнительная точка, которая обеспечивает визуальную касательность \en Additional point which provides a visual tangency - TypedPoint point, add( points[begin ? 0 : points.MaxIndex()] ); - TypedVector curTang, curVect; - double dist = 0.0; - //double dKnots = 0.0; - - double part = modify ? 1.0 : 0.5; // \ru Параметрическая доля \en Parametric part - double pointKnot = 0.0; // \ru Узел точки, обеспечивающий сопряжение \en Point knot which provides a conjugation - double pointWeight = 1.0; // \ru Вес точки \en A point weight - - if ( begin ) { // \ru Стыковка производится в начале \en Connection is performed in the beginning - nurbs._Tangent( nurbs.GetTMin(), curTang ); - if ( !curTang.Colinear(tang) || - curTang * tang < -ANGLE_EPSILON ) // BUG_55564 - { // \ru Если еще не установлено сопряжение \en If conjugation is not set - curVect.Set( points[1], 1.0, points[0], -1.0 ); - - if ( isC1 || !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { - // BUG_53978 if ( !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { - pointKnot = modify ? knots[(size_t)degree] : - knots[(size_t)degree] * part + knots[0] * ( 1.0 - part ); - - pointWeight = modify ? weights[1] : weights[0]; - - dist = points[0].DistanceToPoint( points[1] ) * part; // \ru Длина производной \en Derivative length - - if ( isC1 ) - add.Add( tang, (pointKnot - knots[0]) / (double)(degree - 1) * weights[0] / pointWeight ); - else - add.Add( normTang, dist / (double)(degree - 1) * weights[0] / pointWeight ); - - if ( modify ) - points[1] = add; - else { - points.AddAt( add, 1 ); - weights.AddAt( pointWeight, 1 ); - knots.AddAt( pointKnot, (size_t)degree ); - } - } - else { - // \ru BUG_50080 dist = (normTang * curVect); // МСГ К12 решено не учитывать знак производной \en BUG_50080 dist = (normTang * curVect); // МСГ К12 ignore the sign of the derivative - dist = ::fabs(normTang * curVect); - points[1] = points[0] + normTang * dist; - } - needRebuild = true; - } - - res = true; - } - else { // \ru Стыковка производится в конце \en Connection is performed at the end - nurbs._Tangent( nurbs.GetTMax(), curTang ); - if ( !curTang.Colinear(tang) || - curTang * tang < -ANGLE_EPSILON ) // BUG_55564) - { // \ru Если еще не установлено сопряжение \en If conjugation is not set - ptrdiff_t shear = points.MaxIndex(); - curVect.Set( points[shear], 1.0, points[shear - 1], -1.0 ); - - if ( isC1 || !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { - // BUG_53978 if ( !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { - pointKnot = modify ? knots[shear] : - knots[shear] * ( 1.0 - part ) + knots[shear + (size_t)degree] * part; - - pointWeight = modify ? weights[shear - 1] : weights[shear]; - - dist = points[shear].DistanceToPoint( points[shear - 1] ) * part; // \ru Длина производной \en Derivative length - - if ( isC1 ) - add.Add( tang, -(knots[shear + degree] - pointKnot) / (double)(degree - 1) * weights[shear] / pointWeight ); - else { - // BUG_49940 add.Add( tang, -dist / (degree - 1) * weights[shear] / pointWeight ); - add.Add( normTang, -dist / (double)(degree - 1) * weights[shear] / pointWeight ); - } - - if ( modify ) - points[shear - 1] = add; - else { - points.AddAt( add, shear ); - weights.AddAt( pointWeight, shear ); - knots.AddAt( pointKnot, shear + 1 ); - } - } - else { - // \ru BUG_50080 dist = (normTang * curVect); // МСГ К12 решено не учитывать знак производной \en BUG_50080 dist = (normTang * curVect); // МСГ К12 ignore the sign of the derivative - dist = ::fabs(normTang * curVect); - points[shear - 1] = points[shear] - normTang * dist; - } - needRebuild = true; - } - - res = true; - } - - if ( res && needRebuild ) - nurbs.Init( degree, closed, points, weights, knots, ncf_Unspecified ); -/*#if defined(C3D_DEBUG) - if ( res ){ // \ru Отладка \en Debugging - TypedVector vect; - if ( begin ) nurbs._FirstDer( nurbs.GetTMin(), vect ); - else nurbs._FirstDer( nurbs.GetTMax(), vect ); - double vectLen = vect.Length(); - C3D_ASSERT( tang.Colinear( vect ) && tang * vect > ANGLE_EPSILON ); - C3D_ASSERT( !isC1 || ::fabs(tangLen - vectLen) < METRIC_EPSILON ); - } -#endif -*/ - } - - return res; -} - - -//------------------------------------------------------------------------------ -// \ru Установить касательные на краях \en Set tangents at the ends -// --- -template -bool SetLimitFirstDerivatives( const Curve & curve, bool setBeg, bool setEnd, Nurbs & nurbs, bool setLen ) -{ // BUG_59596 - bool changed = false; - - if ( setBeg ) { - Vector fd; - curve._FirstDer( curve.GetTMin(), fd ); - if ( ::AttachNurbsG1( nurbs, fd, true, false, setLen ) ) - changed = true; - } - if ( setEnd ) { - Vector fd; - curve._FirstDer( curve.GetTMax(), fd ); - if ( ::AttachNurbsG1( nurbs, fd, false, false, setLen ) ) - changed = true; - } - - return changed; -} - - -//------------------------------------------------------------------------------ -// \ru Установить точки так, чтобы совпала касательная и главная нормаль \en Set points such that tangent and principal normal are coincident -//--- -template -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 res = false; - - if ( !nurbs.IsClosed() && nurbs.GetPointListCount() > 3 && nurbs.GetDegree() > 3 && - ::AttachNurbsG1( nurbs, tang, begin, modify, false ) ) // \ru Стыкуем сначала по касательной \en Join by a tangent at first - { - bool needRebuild = false; // \ru Нужно ли перестраивать кривую \en Whether to rebuild the curve - - TypedVector normTang( tang ); - double tangLen = tang.Length(); - if ( tangLen > LENGTH_EPSILON ) - normTang /= tangLen; - - SArray points ( 0, 1 ); - SArray weights( 0, 1 ); - SArray knots ( 0, 1 ); - nurbs.GetPointList( points ); - nurbs.GetWeights( weights ); - nurbs.GetKnots( knots ); - ptrdiff_t degree = nurbs.GetDegree(); - bool closed = nurbs.IsClosed(); - - double eps = Math::metricEpsilon; - - //double dKnots = 0.0; - ptrdiff_t degm = degree - 1; - double curCurv = 0.0; - double curvature = tangDiff.Length(); - - TypedVector curNormal; // \ru Текущая нормаль в стыке \en Current normal at the joint - TypedVector firstDer; // \ru Первая производная сплайна в точке \en The first spline derivative at the point - TypedVector secndDer; // \ru Старая производная сплайна в точке \en The old spline derivative at the point - TypedVector secDer( tangDiff ); // \ru Вторая производная, с которой фактически устанавливается равенство \en The second derivative which the equality is set with - - TypedPoint add; // \ru Точка, обеспечивающая равенство вторых производных \en Point which provides the equality of second derivatives - TypedPoint wp0, wp1; // \ru Взвешенные точки \en Weighted points - - double part = modify ? 1.0 : 0.5; // \ru Параметрическая доля \en Parametric part - double pointKnot = 0.0; // \ru Узел точки, обеспечивающий сопряжение \en Point knot which provides a conjugation - double pointWeight = 1.0; // \ru Вес точки \en A point weight - - double weightDiff1 = 0.0, weightDiff2 = 0.0; // \ru Первая и вторая производная весов \en The first and the second derivative of weights - if ( begin ) { // \ru Стыковка производится в начале \en Connection is performed at the start - nurbs._Normal( nurbs.GetTMin(), curNormal ); - curCurv = nurbs.Curvature( nurbs.GetTMin() ); - - pointKnot = modify ? knots[(size_t)degree + 1] : - knots[(size_t)degree + 1] * part + knots[degree] *( 1.0 - part ); - pointWeight = modify ? weights[2] : weights[0] ; - weightDiff1 = (double)degm * ( weights[1] - weights[0] ) / ( knots[degree] - knots[1] ); - weightDiff2 = ( (double)degm - 1 ) * (double)degm / ( knots[degree] - knots[2] ) * - ( (pointWeight - weights[1]) / (pointKnot - knots[2]) - - (weights[1] - weights[0]) / (knots[degree] - knots[1]) ); - - if ( !(curNormal.Colinear(tangDiff) && - ::fabs(curCurv - curvature) < eps) ) // \ru Еще нет необходимой гладкости стыка \en The required smoothness of a joint is not provided yet - { - nurbs._FirstDer( nurbs.GetTMin(), firstDer ); - secDer *= firstDer * firstDer; - nurbs._SecondDer( nurbs.GetTMin(), secndDer ); - secDer += normTang * ( part * normTang * secndDer ); // \ru Сохранение старой проекции \en Saving of the old projection - - wp0 += points[0] * weights[0]; - wp1 += points[1] * weights[1]; - - // \ru Обрабатываем вторую производную \en Process the second derivative - secDer *= weights[0]; - secDer.Add( points[0], weightDiff2, firstDer, 2.0 * weightDiff1 ); - - double dK = pointKnot - knots[2]; - double dK1 = 1.0 / dK + 1.0 / ( knots[(size_t)degree] - knots[1] ); - - add.Set( wp0, 1.0, wp1 - wp0, dK1 * dK ); - add.Add( secDer, (knots[(size_t)degree] - knots[2]) * dK / ((double)degm * (double)(degm - 1)) ); - add /= pointWeight; - - if ( modify ) - points[2] = add; - else { - knots.AddAt( pointKnot, (size_t)degree + 1 ); - points.AddAt( add, 2 ); - weights.AddAt( pointWeight, 2 ); - } - needRebuild = true; - } - - res = true; - } - else { // \ru Стыковка производится в конце \en Connection is performed at the end - nurbs._Normal( nurbs.GetTMax(), curNormal ); - curCurv = nurbs.Curvature( nurbs.GetTMax() ); - - ptrdiff_t shear = points.MaxIndex(); - - pointKnot = modify ? knots[shear - 1] : - knots[shear] * ( 1.0 - part ) + knots[shear - 1] * part ; - - pointWeight = modify ? weights[shear - 2] : weights[shear]; - - weightDiff1 = (double)degm * ( weights[shear] - weights[shear - 1] ) / - ( knots[shear + (size_t)degree] - knots[shear] ); - weightDiff2 = (double)(degm - 1) * (double)degm / ( knots[shear + (size_t)degm] - knots[shear] ) * - ( (weights[shear] - weights[shear - 1]) / (knots[shear + (size_t)degree] - knots[shear]) - - (weights[shear - 1] - pointWeight ) / (knots[shear + (size_t)degree - 1] - pointKnot ) ); - - if ( !(curNormal.Colinear(tangDiff) && - ::fabs(curCurv - curvature) < eps) ) // \ru Еще нет необходимой гладкости стыка \en The required smoothness of a joint is not provided yet - { - nurbs. _FirstDer( nurbs.GetTMax(), firstDer ); - secDer *= firstDer * firstDer; - nurbs._SecondDer( nurbs.GetTMax(), secndDer ); - secDer += normTang * ( part * normTang * secndDer ); // \ru Сохранение старой проекции \en Saving of the old projection - - wp0 += points[shear] * weights[shear]; - wp1 += points[shear - 1] * weights[shear - 1]; - - // \ru Обрабатываем вторую производную \en Process the second derivative - secDer *= weights[shear]; - secDer.Add( points[shear], weightDiff2, firstDer, 2.0 * weightDiff1 ); - - double dK = knots[shear + (size_t)degm] - pointKnot; - double dK1 = 1.0 / ( knots[shear + (size_t)degm] - knots[shear] ) + - 1.0 / ( knots[shear + (size_t)degm] - pointKnot ); - - add.Set( wp0, 1.0, wp1 - wp0, dK1 * dK ); - add.Add( secDer, (knots[shear + (size_t)degm] - knots[shear]) * dK / ((double)degm * (double)(degm - 1)) ); - add /= pointWeight; - - if ( modify ) - points[shear - 2] = add; - else { - knots.AddAt( pointKnot, shear ); - points.AddAt( add, shear - 1 ); - weights.AddAt( pointWeight, shear - 1 ); - } - needRebuild = true; - } - - res = true; - } - - // \ru Сохраняем вычисленные производные \en Save the calculated derivatives - if ( res ) { - if ( wDiff1 != NULL ) - *wDiff1 = weightDiff1; - if ( wDiff2 != NULL && res ) - *wDiff2 = weightDiff2; - } - - if ( res && needRebuild ) - nurbs.Init( degree, closed, points, weights, knots, ncf_Unspecified ); - } - -/*#if defined(C3D_DEBUG) - if ( res ) { // \ru Отладка \en Debugging - double t = begin ? nurbs.GetTMin() : nurbs.GetTMax(); - - MbVector3D vect; - nurbs._Tangent( t, vect ); - C3D_ASSERT( vect.Colinear( tang ) ); - - MbVector3D normal; - nurbs._Normal( t, normal ); - C3D_ASSERT( normal.Colinear(tangDiff) ); - - double curvature = tangDiff.Length(); - double curCurvature = nurbs.Curvature( t ); - C3D_ASSERT( ::fabs(curCurvature - curvature) < Math::metricAccuracy ); - } -#endif -*/ - - return res; -} - - -//------------------------------------------------------------------------------ -// \ru Создать замкнутый NURBS, проходящий через точки с заданными параметрами. \en Calculate closed NURBS by points which it passes through and points parameters. -//--- -template -bool CreateClosedNURBS4( Nurbs & nurbs, const SArray & initPoints, const SArray & initParams ) -{ - bool bRes = ( (initParams.Count() > 3) && (initParams.Count() == initPoints.Count() + 1) ); - - if ( bRes ) { - nurbs.Refresh(); // должен стоять первым, т.к. освобождается выделенная память - - const ptrdiff_t degree = 4; // степень В-сплайна //-V112 - const bool closed = true; // признак замкнутости - const MbeNurbsCurveForm form = ncf_Unspecified; // форма B - сплайна - - // скопировать массив характеристических точек - SArray points( initPoints ); - - // установить единичные веса - SArray weights( points.Count(), 1 ); - { - const double weight0 = 1.0; - weights.Fill( points.Count(), weight0 ); - } - - const ptrdiff_t degm = degree - 1; - - // заполнить массив параметров (на концах используем условие "отсутствия узла"), обеспечивающий замыкание - SArray knots ( (initParams.MaxIndex() + 2 * degree - 1), 1 ); - { - ptrdiff_t uppKnotsIndex = (ptrdiff_t)initParams.Count() - 1; - ptrdiff_t i = 0; // индекс - - // вставляем начальные узлы 0.. degree - 2 - for ( i = 0; i < degm; i++ ) { - ptrdiff_t startIndex = uppKnotsIndex - degm; - knots.Add( initParams[0] - initParams[uppKnotsIndex] + initParams[startIndex + i] ); - } - - knots += initParams; - - // вставляем конечные узлы - const double tmax = initParams[initParams.MaxIndex()]; - ptrdiff_t i0 = degm; - for ( i = i0; i < i0 + degm; i++ ) - knots.Add( tmax + knots[i + 1] - knots[i0] ); - - uppKnotsIndex = knots.MaxIndex(); - } - - points.Adjust(); - weights.Adjust(); - knots.Adjust(); - - const ptrdiff_t pointsCnt = initPoints.Count(); - const ptrdiff_t uppIndex = pointsCnt - 1; - // для приведения матрицы к матрице с диагональным преобладанием необходимо - // последнее уравнение исключать первым - // далее решаем систему уравнений методом Гаусса без выбора ведущего элемента - SArray biatx( degree, 1 ); // не нулевые B - сплайны - SArray d ( pointsCnt ); // массив диагоналей - SArray ar ( pointsCnt ); // массив правых частей - SArray n ( pointsCnt ); // последний столбец в результирующей матрице - - SArray lrVect; - lrVect.resize( 2*degree ); - - ar.Add( initPoints[initPoints.MaxIndex()] ); - ar += initPoints; - ar.RemoveInd( ar.MaxIndex() ); - - ptrdiff_t lastIndex = initParams.MaxIndex() - 1; - ptrdiff_t lastKnot = knots.Count() - degree - 1; - - // первое уравнение - ::CalcBsplvb( knots, initParams[lastIndex], lastKnot, degree, biatx, lrVect ); - - double norm = 1 / biatx[1]; - double normLast = 1.0; - - ar[0] *= norm; - - d.Add( biatx[2] * norm ); - n.Add( biatx[0] * norm ); - - // последнее уравнение - ::CalcBsplvb( knots, initParams[lastIndex - 1], lastKnot - 1, degree, biatx, lrVect ); - norm = 1.0 / biatx[2]; - // в последнем уравнении, соответственно, внедиагональный и диагональный элемент - double a = biatx[0] * norm; - double b = biatx[1] * norm; - - ar[lastIndex] *= norm; - Point & sn = ar[lastIndex]; - - // прямой ход - ptrdiff_t crLeft = degm; - ptrdiff_t i = 1, im = 0, ip = 1; - for ( ; i < lastIndex - 1; i++, im++, crLeft++ ) { - ::CalcBsplvb( knots, initParams[i - 1], crLeft, degree, biatx, lrVect ); - - norm = 1 / ( biatx[1] - d[im] * biatx[0] ); - - ar[i] = ( ar[i] - ar[im] * biatx[0] ) * norm; - d [i] = biatx[2] * norm; - // исключаем из последнего уравнения ведущую 1 и меняем последний столбец - normLast = -1.0 / d[im]; - - a *= normLast; - b = ( b - n[im] ) * normLast; - - sn = ( sn - ar[im] ) * normLast; - - n.Add( -norm * biatx[0] * n[im] ); - } - - // исключаем из 2-х последних уравнений 3-е с конца - ::CalcBsplvb( knots, initParams[i - 1], crLeft, degree, biatx, lrVect ); - - norm = 1.0 / ( biatx[1] - d[im] * biatx[0] ); - d [lastIndex - 1] = ( biatx[2] - n[im] * biatx[0] ) * norm; - ar[lastIndex - 1] = ( ar[lastIndex - 1] - ar[im] * biatx[0] ) * norm; - - normLast = 1.0 / ( a - d[im] ); - b = ( b - n[im] ) * normLast; - a = 1.0; - sn = ( sn - ar[im] ) * normLast; - - // исключаем из последнего предпоследнее - im++; - points[uppIndex] = ( sn - ar[im] ) / ( b - d[im] ); - - ptrdiff_t prevLast = uppIndex - 1; - points[prevLast] = ar[lastIndex - 1] - points[uppIndex] * d[prevLast]; - - // обратный ход - for ( i = prevLast - 1, ip = prevLast; i >= 0; i--, ip-- ) { - points[i] = ar[i] - points[ip] * d[i] - - points[uppIndex] * n[i]; - } - - bRes = nurbs.Init( degree, closed, points, weights, knots, form ); - C3D_ASSERT( bRes ); - } - - return bRes; -} - - -//------------------------------------------------------------------------------ -// \ru Получить массив параметров по точкам \en Get an array of parameters given the points -// --- -template -bool CreateSplineParameters( const PointsVector & points, MbeSplineParamType spType, bool cls, - DoubleVector & params ) -{ - bool isDone = false; - params.clear(); - isDone = ::DefineThroughPointsParams( points, spType, cls, params ); - - // \ru Нормализация \en Normalization - if ( isDone ) - c3d::SetLimitParam( params, 0.0, (double)((ptrdiff_t)points.size() - 1 + (cls ? 1 : 0)) ); - - return isDone; - -} - - -//------------------------------------------------------------------------------ -// \ru Выбрать точки на кривой для аппроксимации замкнутой nurbs \en Select points on the curve for approximation of closed nurbs -// --- -template -size_t DefineApproxPointsClosed( const Curve & curve, size_t pCount, double pmin, double pmax, ptrdiff_t degree, SArray & points, const KnotsVector & aKnots, const SArray & pCounts ) -{ - size_t pCountActual = pCount; - if ( pCount < 1 ) - return 0; - - points.clear(); - size_t stepCount = 0; - double factor = 1.0 / ( (double)pCount ); - const double epsilon = curve.GetTRegion( METRIC_REGION ); - const double angle = Math::deviateSag; - - size_t segmCount = curve.GetSegmentsCount(); - - SArray segmPointsCnt( segmCount, 2 ); - SArray tList, restList; - - double tmin, tmax; - ptrdiff_t first_Segm = curve.FindSegment( pmin, tmin ); - ptrdiff_t last_Segm = curve.FindSegment( pmax, tmax ); - ptrdiff_t i = 0; - - size_t freePntsCount = pCount; - - // \ru Найдем количество точек для каждого сегмента. \en Find the number of points for each segment. - size_t totalCount = 0; - for ( i = 0; i < pCounts.size(); ++i ) - totalCount += pCounts[i]; - if ( totalCount < 1 ) - totalCount = 1; - - for ( i = 0; i < pCounts.size(); i++ ){ - double part = ((double)pCounts[i]) / ((double)totalCount); - size_t segmPCnt = (size_t)(pCount * part); //-V113 - if ( i == last_Segm ) - segmPCnt = freePntsCount; - else { - segmPCnt = std_max( segmPCnt, (size_t)1); - segmPCnt = std_min( segmPCnt, freePntsCount ); - } - segmPointsCnt.push_back( segmPCnt ); - freePntsCount -= segmPCnt; - } - - Point p; - double plusT = 0.0; - for ( i = first_Segm; i <= last_Segm; i++ ) { - tList.clear(); - double smin, smax; - smin = curve.GetSegment(i)->GetTMin(); - smax = curve.GetSegment(i)->GetTMax(); - - if ( first_Segm == last_Segm ) { - plusT = pmin + smin - tmin; - smin = tmin; - smax = tmax; - } - else if ( i == first_Segm ){ - plusT = pmin + smin - tmin; - smin = tmin; - } - else if ( i == last_Segm ) { - smax = tmax; - } - double t = smin; - size_t tempCount = segmPointsCnt[i - first_Segm]; - factor = 1.0 / ( (double)tempCount ); - stepCount = 0; - while ( t < (smax - epsilon) ) { - double step = curve.GetSegment(i)->DeviationStep( t, angle ); - if ( (t + step) >= (smax - epsilon) ) - step = smax - t; - - for ( size_t k = 0; k < tempCount; k++ ) - tList.push_back( plusT + t + (step * factor * (double)k) ); - t += step; - stepCount++; - } - tList.push_back(plusT + smax); - plusT += smax; - - for ( size_t j = 0; j < tempCount; j++ ) { - t = tList[j * stepCount]; - curve._PointOn( t, p ); - points.push_back( p ); - restList.push_back( t ); - } - } - - restList.push_back( pmax ); - - // \ru Если задан узловой вектор, надо проверить, что между любыми 2 узлами есть хотя бы одна точка. \en If the knot vector is given, then it is necessary to check that there is at least one point between any two knots. - // \ru Если нет, то добавим точек, сохранив все уже набранные \en If not, then add the points and save old points - if ( aKnots.size() > 0 ) { - SArray pParams( 0, 1 ); - ::CreateSplineParameters( points, spt_ChordLength, true, pParams ); - c3d::SetLimitParam( pParams, aKnots[degree - 1], aKnots[aKnots.size() - degree] ); - double t1, t2; - bool bRes = false; - while ( !bRes ) { - bRes = true; - for ( i = degree - 1; i < aKnots.MaxIndex() - degree + 1 && bRes; i++ ) { - t1 = aKnots[i]; - t2 = aKnots[i + 1]; - if ( ::fabs(t2 - t1) > NULL_EPSILON ) { - size_t il = 0, ir = pParams.MaxIndex(); - size_t itemp = 0; - size_t ires1 = 0; - size_t ires2 = 0; - // \ru Левая граница \en The left boundary - bool goOn = true; - while ( goOn ) { - if ( ::fabs(pParams[il] - t1) < NULL_EPSILON ){ - ires1 = il; - goOn = false; - break; - } - else if ( ::fabs(pParams[ir] - t1) < NULL_EPSILON ) { - ires1 = ir; - goOn = false; - break; - } - else { - itemp = ( il + ir ) / 2; - if ( ::fabs(pParams[itemp] - t1) < NULL_EPSILON ) { - ires1 = itemp; - goOn = false; - break; - } - if ( pParams[itemp] < t1 ) - il = itemp; - else if ( pParams[itemp] > t1 ) - ir = itemp; - if ( ir - il < 2) { - ires1 = il; - goOn = false; - break; - } - } - } - // \ru Правая граница \en The right boundary - il = ires1; - ir = pParams.MaxIndex(); - goOn = true; - while ( goOn ) { - if ( ::fabs(pParams[il] - t2) < NULL_EPSILON ){ - ires2 = il; - goOn = false; - break; - } - else if ( ::fabs(pParams[ir] - t2) < NULL_EPSILON ) { - ires2 = ir; - goOn = false; - break; - } - else { - itemp = ( il + ir ) / 2; - if ( ::fabs(pParams[itemp] - t2) < NULL_EPSILON ) { - ires2 = itemp; - goOn = false; - break; - } - if ( pParams[itemp] < t2 ) - il = itemp; - else if ( pParams[itemp] > t2 ) - ir = itemp; - if ( ir - il < 2) { - ires2 = ir; - goOn = false; - break; - } - } - } - if ( ires2 - ires1 < 2 ) { - bRes = false; - // \ru Вставим среднюю точку между ires1 и ires2 и пересчитаем параметры \en Insert mid-point between ires1 and ires2 and recalculate parameters - double t = 0.5 * (restList[ ires1 ] + restList[ ires2 ]); - restList.AddAt( t, ires1 + 1 ); - - curve._PointOn( t, p ); - points.AddAt( p, ires1 + 1); - - pParams.clear(); - ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); - c3d::SetLimitParam( pParams, aKnots[degree - 1], aKnots[aKnots.size() - degree] ); - pCountActual++; - } - } - } - } - } - - return pCountActual; -} - - -//------------------------------------------------------------------------------ -// \ru Выбрать точки на кривой для аппроксимации незамкнутой nurbs \en Select points on the curve for approximation of non-closed nurbs -// --- -template -size_t DefineApproxPointsOpen( const Curve & curve, size_t pCount, double pmin, double pmax, SArray & points, const KnotsVector & aKnots, const SArray & pCounts ) -{ - size_t pCountActual = pCount; - if ( pCount < 1 ) - return 0; - - points.clear(); - size_t stepCount = 0; - double factor = 1.0 / ( (double)(pCount - 1) ); - const double epsilon = curve.GetTRegion( METRIC_REGION ); - const double angle = Math::deviateSag; - - size_t segmCount = curve.GetSegmentsCount(); - if ( pCounts.size() != segmCount ) - return 0; - - SArray tList, restList; - SArray segmPointsCnt( segmCount, 2 ); - - double tpmin = pmin; - double tpmax = pmax; - - double tmin, tmax; - ptrdiff_t first_Segm = curve.FindSegment( tpmin, tmin ); - ptrdiff_t last_Segm = curve.FindSegment( tpmax, tmax ); - ptrdiff_t i; - - size_t freePntsCount = pCount - 1; - - // \ru Найдем количество точек для каждого сегмента. \en Find the number of points for each segment. - size_t totalCount = 0; - for ( i = 0; i < pCounts.size(); ++i ) - totalCount += pCounts[i]; - if ( totalCount == 0 ) - totalCount = 1; - - for ( i = 0; i < pCounts.size(); i++ ){ - double part = ((double)pCounts[i]) / ((double)totalCount); - size_t segmPCnt = (size_t)(pCount * part); //-V113 - if ( i == last_Segm ) - segmPCnt = freePntsCount; - else { - segmPCnt = std_max( segmPCnt, (size_t)1); - segmPCnt = std_min( segmPCnt, freePntsCount ); - } - segmPointsCnt.push_back( segmPCnt ); - freePntsCount -= segmPCnt; - } - - Point p; - double plusT = 0.0; - for ( i = first_Segm; i <= last_Segm; i++ ) { - tList.clear(); - - double smin = curve.GetSegment(i)->GetTMin(); - double smax = curve.GetSegment(i)->GetTMax(); - - if ( first_Segm == last_Segm ) { - plusT = tpmin + smin - tmin; - smin = tmin; - if (pmin < tpmin - PARAM_EPSILON ) - smin += pmin - tpmin; - smax = tmax; - if (pmax > tpmax + PARAM_EPSILON ) - smax += pmax - tpmax; - } - else if ( i == first_Segm ){ - plusT = tpmin + smin - tmin; - smin = tmin; - if (pmin < tpmin - PARAM_EPSILON ) - smin += pmin - tpmin; - } - else if ( i == last_Segm ) { - smax = tmax; - if (pmax > tpmax + PARAM_EPSILON ) - smax += pmax - tpmax; - } - double t = smin; - size_t tempCount = segmPointsCnt[i - first_Segm]; - factor = 1.0 / ( (double)tempCount ); - stepCount = 0; - while ( t < (smax - epsilon) ) { - double step = curve.GetSegment(i)->DeviationStep( t, angle ); - if ( (t + step) >= (smax - epsilon) ) - step = smax - t; - - for ( size_t j = 0; j < tempCount; j++ ) - tList.push_back( plusT + t + (step * factor * (double)j) ); - t += step; - stepCount++; - } - tList.push_back(plusT + smax); - plusT += smax; - - for ( size_t k = 0; k < tempCount; k++ ) { - t = tList[k * stepCount]; - curve._PointOn ( t, p ); - points.push_back( p ); - restList.push_back( t ); - } - } - - double t = pmax; - curve._PointOn ( t, p ); - points.push_back( p ); - restList.push_back( t ); - - // \ru Если задан узловой вектор, надо проверить, что между любыми 2 узлами есть хотя бы одна точка. \en If the knot vector is given, then it is necessary to check that there is at least one point between any two knots. - // \ru Если нет, то добавим точек, сохранив все уже набранные \en If not, then add the points and save old points - if ( aKnots.size() > 0 ) { - SArray pParams( 0, 1 ); - ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); - c3d::SetLimitParam( pParams, aKnots.front(), aKnots.back() ); - - double t1, t2; - bool bRes = false; - while ( !bRes ) { - bRes = true; - for ( i = 0; i < aKnots.MaxIndex() && bRes; i++ ) { - t1 = aKnots[i]; - t2 = aKnots[i + 1]; - if ( ::fabs(t2 - t1) > NULL_EPSILON ) { - size_t il = 0, ir = pParams.MaxIndex(); - size_t itemp = 0; - size_t ires1 = 0; - size_t ires2 = 0; - // \ru Левая граница \en The left boundary - bool goOn = true; - while ( goOn ) { - if ( ::fabs(pParams[il] - t1) < NULL_EPSILON ){ - ires1 = il; - goOn = false; - break; - } - else if ( ::fabs(pParams[ir] - t1) < NULL_EPSILON ) { - ires1 = ir; - goOn = false; - break; - } - else { - itemp = ( il + ir ) / 2; - if ( ::fabs(pParams[itemp] - t1) < NULL_EPSILON ) { - ires1 = itemp; - goOn = false; - break; - } - if ( pParams[itemp] < t1 ) - il = itemp; - else if ( pParams[itemp] > t1 ) - ir = itemp; - if ( ir - il < 2) { - ires1 = il; - goOn = false; - break; - } - } - } - // \ru Правая граница \en The right boundary - il = ires1; - ir = pParams.MaxIndex(); - goOn = true; - while ( goOn ) { - if ( ::fabs(pParams[il] - t2) < NULL_EPSILON ){ - ires2 = il; - goOn = false; - break; - } - else if ( ::fabs(pParams[ir] - t2) < NULL_EPSILON ) { - ires2 = ir; - goOn = false; - break; - } - else { - itemp = ( il + ir ) / 2; - if ( ::fabs(pParams[itemp] - t2) < NULL_EPSILON ) { - ires2 = itemp; - goOn = false; - break; - } - if ( pParams[itemp] < t2 ) - il = itemp; - else if ( pParams[itemp] > t2 ) - ir = itemp; - if ( ir - il < 2) { - ires2 = ir; - goOn = false; - break; - } - } - } - if ( ires2 - ires1 < 2 ) { - bRes = false; - // \ru Вставим среднюю точку между ires1 и ires2 и пересчитаем параметры \en Insert mid-point between ires1 and ires2 and recalculate parameters - t = 0.5 * (restList[ ires1 ] + restList[ ires2 ]); - restList.AddAt( t, ires1 + 1 ); - - curve._PointOn( t, p ); - points.AddAt( p, ires1 + 1 ); - - pParams.clear(); - ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); - c3d::SetLimitParam( pParams, aKnots.front(), aKnots.back() ); - pCountActual++; - } - } - } - } - } - return pCountActual; -} - - -//------------------------------------------------------------------------------ -// \ru Построение незамкнутого сплайна, аппроксимирующего набор точек, с помощью метода наименьших квадратов \en Construction of non-closed spline which approximates a set of points by the method of least squares -/*\ru aDegree - порядок сплайна, - pCount - количество узлов, - aPoints - набор точек для аппроксимации, - aKnots - предустановленный узловой вектор - \en ADegree - spline order, - pCount - count of knots, - aPoints - point set for approximation, - aKnots - predefined knots vector \~ -*/ -//--- -template -MATH_FUNC (bool) CreateNurbsLSMClosed( SPtr & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline - const ptrdiff_t degree, - const ptrdiff_t pCount, - const PointsVector & aPoints, - const DoubleVector & aKnots, - const DoubleVector * aParams = NULL ); - -//------------------------------------------------------------------------------ -// \ru Построение незамкнутого сплайна, аппроксимирующего набор точек, с помощью метода наименьших квадратов \en Construction of non-closed spline which approximates a set of points by the method of least squares -// \ru Для построения замкнутого сплайна, надо затем использовать Unclamped( true ) \en Use Unclamped (true) for the construction of a closed spline -/*\ru aDegree - порядок сплайна, - pCount - количество узлов, - aPoints - набор точек для аппроксимации, - aKnots - предустановленный узловой вектор - \en ADegree - spline degree, - pCount - count of knots, - aPoints - point set for approximation, - aKnots - predefined knot vector \~ -*/ -//--- -template -MATH_FUNC (bool) CreateNurbsLSM( SPtr & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline - const ptrdiff_t degree, - const ptrdiff_t pCount, - const PointsVector & aPoints, - const DoubleVector & aKnots, - const DoubleVector * aParams = NULL ); - -//------------------------------------------------------------------------------- -// -// --- -template -Nurbs * CreateLineOutRgn( const Curve & curve, double tn1, double tn2, double t1, double t2, - const MbCurveIntoNurbsInfo & nci ) -{ - Nurbs * nurbs = NULL; - - if ( !curve.IsClosed() && nci.ExtendRange() && ((tn2 - tn1) > Math::paramEpsilon) ) { - SArray points ( 2, 1 ); - SArray weights( 2, 1 ); - SArray knots ( 4, 1 ); //-V112 - - curve._PointOn( t1, *(points.Add()) ); - curve._PointOn( t2, *(points.Add()) ); - - weights.Add( 1.0 ); - weights.Add( 1.0 ); - - knots.Add( tn1 ); - knots.Add( tn1 ); - knots.Add( tn2 ); - knots.Add( tn2 ); - - nurbs = Nurbs::Create( 2, false, points, weights, knots, ncf_Unspecified ); - } - - return nurbs; -} - - -//------------------------------------------------------------------------------ -// \ru Преобразовать контур в нурбс \en Transform contour to NURBS -// --- -MbNurbs * ContourToNurbs( const MbContour & cntr, double t1, double t2, int sense, const MbCurveIntoNurbsInfo & nci, bool reparamByLength ); - -//------------------------------------------------------------------------------ -// \ru Преобразовать контур в нурбс \en Transform contour to NURBS -// --- -MbNurbs3D * ContourToNurbs( const MbContour3D & cntr, double t1, double t2, int sense, const MbCurveIntoNurbsInfo & nci, bool reparamByLength ); - - -#endif // __MB_NURBS_FUNCTION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Модуль геометрических построений. + \en The module of geometric constructions. \~ + \details \ru Базовые алгоритмы Nurbs кривых и поверхностей. + \en The base algorithms for NURBS curves and surfaces. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_NURBS_FUNCTION_H +#define __MB_NURBS_FUNCTION_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class MATH_CLASS MbContour; +class MATH_CLASS MbContour3D; +class MATH_CLASS MbNurbs; +class MATH_CLASS MbNurbs3D; + + +//------------------------------------------------------------------------------ +/** \brief \ru Флаг, определяющий построение сплайна, проходящего через точки. + \en Flag defining creation of spline passing through points. \~ + \details \ru Флаг, определяющий построение сплайна, проходящего через точки. Связан с версией. \n + \en Flag defining creation of spline passing through points. Related to the version. \n \~ + \ingroup Data_Structures +*/ +// --- +enum MbeSplineCreateType { + sct_Version0 = 0, ///< \ru Используется в версиях < V13 (центростремительная параметризация). \en Used in versions < V13 (centripetal parameterization). + sct_Version1 = 1, ///< \ru Используется в версии V13 (параметризация по длине хорды). \en Used in version V13 (parameterization by chord length). + sct_Version2 = 2, ///< \ru Используется в версии V13+. \en Used in version V13+. +}; + + +//------------------------------------------------------------------------------- +/** \brief \ru Дополнительная информация для преобразования кривой или поверхности в Nurbs. + \en Additional information for transformation of a curve or surface to NURBS. \~ + \details \ru Дополнительная информация для преобразования кривой или поверхности в Nurbs. \n + \en Additional information for transformation of a curve or surface to NURBS. \n \~ + \ingroup Data_Structures +*/ +// --- +class MbCurveIntoNurbsInfo { +private: + double tbeg; ///< \ru Параметр начала участка кривой. \en A parameter of the curve piece start. + double tend; ///< \ru Параметр конца участка кривой. \en A parameter of the curve piece end. + int sense; ///< \ru Направление сплайн-кривой. \en Direction of spline-curve. + bool matchParams; ///< \ru Сохранять ли при преобразовании однозначное соответствие параметрических областей. \en Whether to save correspondence of parametric regions while transforming or not. + bool extendRange; ///< \ru Строится ли преобразование на продолжении для незамкнутой подложки. \en Whether transformation is constructed on the extension for a non-closed substrate. + VERSION version; ///< \ru Версия исполнения. \en The version of execution. +private: + MbCurveIntoNurbsInfo(); +public: + /// \ru Конструктор. \en Constructor. + template + MbCurveIntoNurbsInfo( const Curve & c, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) + : tbeg ( c.GetTMin() ) + , tend ( c.GetTMax() ) + , sense ( 1 ) + , matchParams( match ) + , extendRange( ext ) + , version ( ver ) + {} + /// \ru Конструктор. \en Constructor. + MbCurveIntoNurbsInfo( double t1, double t2, int s, bool match, bool ext, VERSION ver = Math::DefaultMathVersion() ) + : tbeg ( t1 ) + , tend ( t2 ) + , sense ( s ) + , matchParams( match ) + , extendRange( ext ) + , version ( ver ) + {} + /// \ru Конструктор. \en Constructor. + MbCurveIntoNurbsInfo( const MbCurveIntoNurbsInfo & other, double t1, double t2, int s ) + : tbeg ( t1 ) + , tend ( t2 ) + , sense ( s ) + , matchParams( other.matchParams ) + , extendRange( other.extendRange ) + , version ( other.version ) + {} + /// \ru Функция присвоения. \en Assignment function. + void Assign( const MbCurveIntoNurbsInfo & other ) + { + tbeg = other.tbeg; + tend = other.tend; + sense = other.sense; + matchParams = other.matchParams; + extendRange = other.extendRange; + version = other.version; + } + /// \ru Функция инициализации. \en The initialization function. + bool Init( double t1, double t2, int s ) + { + tbeg = t1; + tend = t2; + sense = s; + C3D_ASSERT( ((sense == 1) || (sense == -1)) ); + return ((sense == 1) || (sense == -1)); + } + /// \ru Функция инициализации. \en The initialization function. + bool Init( double t1, double t2, int s, bool match, bool ext ) { + matchParams = match; + extendRange = ext; + return Init( t1, t2, s ); + } + +public: + /// \ru Получить параметр начала участка кривой. \en Get the parameter of the start curve region. + double GetTBeg() const { return tbeg; } + /// \ru Получить параметр конца участка кривой. \en Get the parameter of the end curve region. + double GetTEnd() const { return tend; } + /// \ru Получить направление сплайн-кривой. \en Get the direction of spline-curve. + int GetSense() const { return sense; } + /// \ru Сохранять ли при преобразовании однозначное соответствие параметрических областей. \en Whether to save correspondence of parametric regions by transformation or not. + bool MatchParams() const { return matchParams; } + /// \ru Строится ли преобразование на продолжении для незамкнутой подложки. \en Whether transformation is constructed on the extension for a non-closed substrate or not. + bool ExtendRange() const { return extendRange; } + /// \ru Получить версию исполнения. \en Get the version of execution. + VERSION GetMathVersion() const { return version; } + +OBVIOUS_PRIVATE_COPY( MbCurveIntoNurbsInfo ) +}; + + +//------------------------------------------------------------------------------- +/** \brief \ru Параметры построения NURBS копии объекта. + \en Parameters for the construction of a NURBS copy of the object. \~ + \details \ru Параметры построения NURBS копии объекта. \n + \en Parameters for the construction of a NURBS copy of the object. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MbNurbsParameters { +public: + size_t degree; ///< \ru Порядок NURBS копии. \en Order of NURBS copy. + size_t pointsCount; ///< \ru Количество контрольных точек (при 0 параметр игнорируется). \en The number of control points (if there is no control points, parameter is ignored). + MbRect1D region; ///< \ru Область объекта, подлежащая копированию: [0 1] соответствует [tMin tMax] объекта. \en Region of the object to be copied: [0, 1] corresponds to [tMin tMax] object. + SArray knots; ///< \ru Узловой вектор. \en Knot vector. + mutable bool useApprox; ///< \ru Не пытаться построить точную поверхность. \en Don't try to create the exact surface. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbNurbsParameters() + : degree ( c3d::NURBS_DEGREE ) + , pointsCount( 0 ) + , region ( 0.0, 1.0 ) + , knots ( 0, 1 ) + , useApprox ( true ) + {} + /// \ru Конструктор по параметрам (без узлов) построения NURBS. \en The constructor of NURBS by parameters (without knots). + MbNurbsParameters( size_t d, size_t c, double zmin, double zmax, bool approx ) + : degree ( d ) + , pointsCount( c ) + , region ( zmin, zmax ) + , knots ( 0, 1 ) + , useApprox ( approx ) + { + C3D_ASSERT( d > 1 && d < SYS_MAX_UINT16 ); + degree = std_max( d, (size_t)2 ); + degree = std_min( d, (size_t)SYS_MAX_UINT16 ); + } + /// \ru Конструктор по полному набору параметров построения NURBS. \en The constructor of NURBS by a complete set of parameters. + MbNurbsParameters( size_t d, size_t c, double zmin, double zmax, bool approx, const SArray & aKnots ) + : degree ( d ) + , pointsCount( c ) + , region ( zmin, zmax ) + , knots ( aKnots ) + , useApprox ( approx ) + { + C3D_ASSERT( d > 1 && d < SYS_MAX_UINT16 ); + degree = std_max( d, (size_t)2 ); + degree = std_min( d, (size_t)SYS_MAX_UINT16 ); + } + /// \ru Конструктор копирования. \en The copy constructor. + MbNurbsParameters( const MbNurbsParameters & other ) + : degree ( other.degree ) + , pointsCount( other.pointsCount ) + , region ( other.region ) + , knots ( other.knots ) + , useApprox ( other.useApprox ) + {} + /// \ru Деструктор. \en Destructor. + ~MbNurbsParameters() {} + + /// \ru Инициализировать по другим параметрам построения NURBS копии объекта. \en Initialize by another parameters. + void Init( const MbNurbsParameters & other ) { + degree = other.degree; + pointsCount = other.pointsCount; + region = other.region; + knots = other.knots; + useApprox = other.useApprox; + } + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbNurbsParameters & other, double accuracy ) const; + /// \ru Оператор присваивания. \en The assignment operator. + MbNurbsParameters & operator = ( const MbNurbsParameters & other ) { + degree = other.degree; + pointsCount = other.pointsCount; + region = other.region; + knots = other.knots; + useApprox = other.useApprox; + return (*this); + } + +public: + size_t GetDegree() const { return degree; } + size_t GetPointsCount() const { return pointsCount; } + const MbRect1D & GetRegion() const { return region; } + const SArray & GetKnots() const { return knots; } + bool UseApprox() const { return useApprox; } + + void SetDegree( size_t c ) { if ( c > 1 ) degree = c; } + void SetPointsCount( size_t c ) { if ( c > 1 ) pointsCount = c; } + SArray & SetKnots() { return knots; } + void SetKnots( SArray & c ) { knots = c; } + void SetKnots( std::vector & c ) { knots = c; } + void SetApprox( bool c ) { useApprox = c; } + +KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsParameters ) // \ru Для работы со ссылками и объектами класса \en For working with references and objects of the class +}; // MbNurbsParameters + + +//------------------------------------------------------------------------------- +/** \brief \ru Параметры узловой точки сплайновой копии объекта. + \en Parameters of knot point of the object spline copy. \~ + \details \ru Параметры узловой точки сплайновой копии объекта. \n + \en Parameters of knot point of the object spline copy. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MbNurbsPointInfo { +public: + MbCartPoint3D point; ///< \ru Узловая точка сплайновой поверхности. \en A knot point of a spline surface. + bool visible; ///< \ru Флаг видимости точки. \en A point visibility flag. + int8 poleLocation; ///< \ru Расположение полюса в параметрической области. \en The location of a pole in the parametric region. +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbNurbsPointInfo() + : point ( ) + , visible ( true ) + , poleLocation ( (uint8)pln_None ) + {} + /// \ru Конструктор по точке и флагу видимости. \en The constructor by a point and visibility flag. + MbNurbsPointInfo( MbCartPoint3D aPount, bool aVisible, MbePoleLocation aPoleLocation ) + : point ( aPount ) + , visible ( aVisible ) + , poleLocation ( (uint8)aPoleLocation ) + {} + /// \ru Конструктор копирования. \en The copy constructor. + MbNurbsPointInfo( const MbNurbsPointInfo & other ) + : point ( other.point ) + , visible ( other.visible ) + , poleLocation ( (uint8)other.poleLocation ) + {} + /// \ru Деструктор. \en Destructor. + ~MbNurbsPointInfo() {} + + /// \ru Инициализировать по точке и флагу видимости. \en Initialize by a point and visibility flag. + void Init( const MbNurbsPointInfo & other ) + { + point = other.point; + visible = other.visible; + poleLocation = other.poleLocation; + } + /// \ru Оператор присваивания. \en The assignment operator. + MbNurbsPointInfo & operator = ( const MbNurbsPointInfo & other ) + { + point = other.point; + visible = other.visible; + poleLocation = other.poleLocation; + return (*this); + } + /// \ru Определить, является ли точка полюсом. \en Define whether the point is a pole. + MbePoleLocation GetPoleLocation() { return (MbePoleLocation)poleLocation; } + + // \ru Закомментировала строчку ниже, поскольку объект служит только для передачи дополнительной информации об узлах сплайна \en Commented out the line below, because the object is used only to pass additional information about spline knots + // \ru В процессе прямого моделирования. Не пишется и не читается. \en In the direct modeling. Not written and not read. + // \ru KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsPointInfo ) // для работы со ссылками и объектами класса \en KNOWN_OBJECTS_RW_REF_OPERATORS( MbNurbsPointInfo ) // for working with references and objects of the class +}; //MbNurbsPointInfo + + +//------------------------------------------------------------------------------ +/** \brief \ru Дать меру расстояния. + \en Get a measure of the distance. \~ + \details \ru Дать меру расстояния. + \en Get a measure of the distance. \~ + \param[in] p1, p2 - \ru Точки между которыми ищется расстояние. + \en Points between which the distance is computed. \~ + \param[in] spType - \ru Тип параметризации сплайновых объектов. + \en The parametrization type of spline objects. \~ + \return \ru Расстояние. + \en Distance. \~ + \ingroup Base_Algorithms +*/ +// --- +template +double GetParamDistance( const Type & p1, const Type & p2, MbeSplineParamType spType ) +{ + switch ( spType ) { + case spt_Unstated : + case spt_EquallySpaced : + return 1.0; + case spt_ChordLength : + return p1.DistanceToPoint( p2 ); + case spt_Centripetal: + return ::sqrt( p1.DistanceToPoint( p2 ) ); + } + + return 1.0; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \details \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] pcnt - \ru Число точек. + \en Number of points. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +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. + // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. + + return ( (degree > 1) && (pcnt >= (closed ? 3 : degree)) ); +} + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \details \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] pcnt - \ru Число точек. + \en Number of points. \~ + \param[in] wcnt - \ru Число весов. + \en Number of weights. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +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. + // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. + // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. + + bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && (wcnt == pcnt); + return res; +} + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \details \ru Проверить параметры инициализации nurbs-объекта. + \en Check initialization parameters of a nurbs-object. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] pcnt - \ru Число точек. + \en Number of points. \~ + \param[in] wcnt - \ru Число весов. + \en Number of weights. \~ + \param[in] kcnt - \ru Число узлов. + \en Number of knots. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +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. + // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. + // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. + // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. + + bool res = ::IsValidNurbsParams( degree, closed, pcnt, wcnt ) && + ( kcnt == (degree + pcnt + (closed ? (degree - 1) : 0)) ); + return res; +} + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры инициализации nurbs-кривой. + \en Check initialization parameters of a nurbs-curve. \~ + \details \ru Проверить параметры инициализации nurbs-кривой. + \en Check initialization parameters of a nurbs-curve. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] pcnt - \ru Число точек. + \en Number of points. \~ + \param[in] knots - \ru Узловой вектор. + \en Knots vector. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +template +bool IsValidNurbsParamsExt( size_t degree, bool closed, size_t pcnt, + const KnotsVector & knots ) +{ + // \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. + // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. + // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. + // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. + + bool res = ::IsValidNurbsParams( degree, closed, pcnt ) && + ( knots.size() == (degree + pcnt + (closed ? (degree - 1) : 0)) ); + + if ( res ) { + if ( !c3d::IsMonotonic(knots, true, true) ) + res = false; // SD#7118498 + } + + return res; +} + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить параметры инициализации nurbs-кривой. + \en Check initialization parameters of a nurbs-curve. \~ + \details \ru Проверить параметры инициализации nurbs-кривой. + \en Check initialization parameters of a nurbs-curve. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] pnts - \ru Точки. + \en Points vector. \~ + \param[in] wts - \ru Веса точек. + \en Weights vector. \~ + \param[in] knots - \ru Узловой вектор. + \en Knots vector. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +template +bool IsValidNurbsParamsExt( size_t degree, bool closed, const PointVector & pnts, + const DoubleVector * wts, + const DoubleVector * knots = 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. + // \ru 2б. Для замкнутой кривой должно быть как минимум 3 различных точки. \en 2b. Closed curve must have at least 3 different points. + // \ru 3. Количество точек и количество весов должны быть согласованы. \en 3. Number of points and number of weights must be equal. + // \ru 4. Количество узлов должно быть согласовано по остальным параметрам. \en 4. Number of knots must be consistent with the other parameters. + + 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))) ); + + if ( res && (knots != NULL) ) { + if ( !c3d::IsMonotonic(*knots, true, true) ) + res = false; // SD#7118498 + } + + return res; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить узловой вектор nurbs-объекта. + \en Check knots vector of a nurbs-object. \~ + \details \ru Проверить узловой вектор nurbs-объекта. + \en Check knots vector of a nurbs-object. \~ + \param[in] knots - \ru Узловой вектор. + \en Knots vector. \~ + \return \ru true, если параметры согласованы. + \en Returns true if parameters are consistent. \~ + \ingroup Base_Algorithms +*/ +// --- +template +bool IsValidNurbsKnots( const KnotsVector & knots, double eps = EXTENT_EPSILON ) +{ + // \ru 1 . Количество узлов должно быть не менее 4 \en 1 . The number of knots must be at least 4 + // \ru 2 . Последовательность узлов должна быть неубывающей \en 2 . Sequence of nodes must be nondecreasing + // \ru 3 . Первый и последний узлы должны быть различны \en 3 . The first and the last nodes must be different + + size_t cnt = knots.size(); + if ( cnt < 4 ) + return false; + + eps = ::fabs(eps); + if ( ::fabs(knots[cnt-1] - knots[0]) < eps ) + return false; + + for ( size_t i = 0; i < (cnt - 1); i++ ) { + if ( knots[i+1] < knots[i] - eps ) + return false; + } + + return true; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Определение индекса узла left для первой ненулевой функции. + \en Definition of "left" knot index for the first non-zero function. \~ + \details \ru Определение индекса узла left для первой ненулевой функции (knots[mid] <= t < knots[mid + 1]). + \en Definition of "left" knot index for the first non-zero function (knots[mid] <= t < knots[mid + 1]). \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] knots - \ru Множество узлов. + \en Knots. \~ + \param[in, out] t - \ru Значение параметра. + \en A parameter value. \~ + \return \ru Индекс узла. + \en A knot index. \~ + \ingroup Base_Algorithms +*/ +// --- +template +ptrdiff_t KnotIndex( size_t degree, const KnotsVector & knots, double & t ) +{ + size_t low = degree - 1; + size_t high = knots.size() - degree; + ptrdiff_t mid = low; + + if ( t <= knots[low] ) { + t = knots[low]; + size_t countKnt = knots.size(); + size_t lowP = low; + lowP++; + // \ru Исправление ошибки BUG_21185 while ( (lowP < countKnt) && (t == knots[lowP]) ) { \en Bugfix BUG_21185 while ( (lowP < countKnt) && (t == knots[lowP]) ) { + while ( (lowP + degree < countKnt) && (t == knots[lowP]) ) { //-V550 + low = lowP; + lowP++; + } + mid = low; + } + else if ( t >= knots[high] ) { + t = knots[high]; + // BUG_82980 while ( (high > 0) && (knots[high] == t) ) { + while ( (high + 1 > degree) && (knots[high] == t) ) { + high--; + } + mid = high; + } + else if ( c3d::ArFind(knots, t, mid) ) { + while ( knots[mid] == t ) { + mid++; + } + mid--; + } + return mid; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить узловой вектор (равномерная параметризация). + \en Define knot vector (uniform parameterization). \~ + \details \ru Определить узловой вектор (равномерная параметризация). + \en Define knot vector (uniform parameterization). \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] uppPointsIndex - \ru Индекс последней точки. + \en Last point index. \~ + \param[in] knots - \ru Узловой вектор. + \en Knots vector. \~ + \ingroup Base_Algorithms +*/ +// --- +template +ptrdiff_t DefineKnotsVector( ptrdiff_t degree, bool closed, ptrdiff_t uppPointsIndex, + KnotsVector & knots ) +{ + if ( (degree < 2) || (uppPointsIndex < 1) ) { + knots.clear(); + return -1; + } + + ptrdiff_t pointsCount = uppPointsIndex + 1; + ptrdiff_t power = degree - 1; + + ptrdiff_t knotsCount = degree + pointsCount + (closed ? power : 0); + knots.clear(); + knots.reserve( knotsCount ); + + ptrdiff_t i = 0; + + if ( closed ) { // замкнутый В-сплайн + double knot = 0.0; + for ( i = 0; i < knotsCount; i++ ) { + knot = (double)(i - power); + knots.push_back( knot ); + } + } + else { + double knot = 0.0; + for ( i = 0; i < degree; i++ ) + knots.push_back( knot ); + + ptrdiff_t cnt = pointsCount - degree; + for ( i = 0; i < cnt; i++ ) { + knot += 1.0; + knots.push_back( knot ); + } + + knot += 1.0; + for ( i = 0; i < degree; i++ ) + knots.push_back( knot ); + } + + return (knotsCount - 1); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить узловой вектор. + \en Define knot vector. \~ + \details \ru Определить узловой вектор. + \en Define knot vector. \~ + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in] count - \ru Количество точек. + \en Number of points. \~ + \param[in] params - \ru Параметры точек (для замкнутого count+1). + \en Points parameters (for closed spline - "count"+1). \~ + \param[out] knots - \ru Узловой вектор. + \en Knots vector. \~ + \return \ru true, если набор параметров сформирован. + \en Returns true if result is success. \~ + \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 + + +//------------------------------------------------------------------------------ +/** \brief \ru Определить параметрическое распределение точек. + \en Define parametric distribution of points. \~ + \details \ru Определить параметрическое распределение точек. + \en Define parametric distribution of points. \~ + \param[in] points - \ru Массив точек. + \en Points vector. \~ + \param[in] spType - \ru Тип параметризации сплайновых объектов. + \en The parameterization type of spline objects. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[out] params - \ru Параметрическое распределение точек. + \en Parametric distribution of points. \~ + \return \ru true, если набор параметров сформирован. + \en Returns true if result is success. \~ + \ingroup Base_Algorithms +*/ +// --- +template +bool DefineThroughPointsParams( const PointsVector & points, MbeSplineParamType spType, bool closed, + ParamsVector & params ) +{ + bool res = false; + + ptrdiff_t count = (ptrdiff_t)points.size(); + + if ( count > (closed ? 2 : 1) ) { + double param = 0.0; + ptrdiff_t extCount = closed ? (count + 1) : count; + params.clear(); + params.resize( extCount, param ); + + double paramSum = 0.0; + for ( ptrdiff_t j = 1; j < extCount; j++ ) { + ptrdiff_t jp = (j - 1 + count) % count; + ptrdiff_t jc = j % count; + param = ::GetParamDistance( points[jp], points[jc], spType ); + params[j] = ( params[j-1] + param ); + paramSum += param; + } + + if ( paramSum > METRIC_PRECISION ) { + for ( ptrdiff_t j = 0; j < extCount; j++ ) { + params[j] /= paramSum; + params[j] *= (double)(extCount-1); + } + res = true; + } + else if ( spType != spt_EquallySpaced ) { + C3D_ASSERT_UNCONDITIONAL( false ); + paramSum = 0.0; + for ( ptrdiff_t j = 1; j < extCount; j++ ) { + ptrdiff_t jp = (j - 1 + count) % count; + ptrdiff_t jc = j % count; + param = ::GetParamDistance( points[jp], points[jc], spt_EquallySpaced ); + params[j] = ( params[j-1] + param ); + paramSum += param; + } + if ( paramSum > METRIC_PRECISION ) { + for ( ptrdiff_t j = 0; j < extCount; j++ ) { + params[j] /= paramSum; + params[j] *= (double)(extCount-1); + } + res = true; + } + } + } + + return res; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычисление B - базиса (degree - порядок B-сплайна, p = (degree - 1) - степень полинома(B-сплайна)). + \en The calculation of B - basis ("degree" - order of B-spline, p = (degree - 1) - the degree of the polynomial (B-spline)). \~ + \details \ru Вычисление B - базиса (degree - порядок B-сплайна, p = (degree - 1) - степень полинома(B-сплайна)). + Для ускорения используется рабочий вектор lr = { left[p+1], right[p+1] } ). + \en The calculation of B - basis ("degree" - order of B-spline, p = (degree - 1) - the degree of the polynomial (B-spline)). + To speed up vector lr = { left[p+1], right[p+1] } is used. \~ + \param[in] i - \ru Индекс в массиве узлов, получаемый с помощью функции KnotIndex(). + \en Index of knots vector obtained by the function KnotIndex(). \~ + \param[in] t - \ru Параметр. + \en Parameter. \~ + \param[in] p - \ru p = degree - 1, где degree - порядок B-сплайна. + \en p = degree - 1, where degree is B-spline degree. \~ + \param[in] knots - \ru Узловой вектор. + \en Knots vector. \~ + \param[out] nsplines - \ru Массив размерности degree, заполняется значениями сплайна в поля 0..degree-2; nsplines[degree-1] = 0. + \en Array of B-spline values. \~ + \param[in,out] lrVect - \ru Массив размерности 2*(p+1) = 2*degree, содержимое игнорируется и будет перезаписано. Нужен для ускорения работы функции. В результате работы в нем останется мусор.. + \en Temporary working vector with dimension 2*(p+1) = 2*degree. \~ + \ingroup Base_Algorithms +*/ +// --- +template +MATH_FUNC (bool) BasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const KnotsVector & knots, DoubleVector & nsplines, + DoubleVector & lrVect ); + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить базисный сплайн по параметру t и узловому вектору. + \en Calculate basic spline by "t" parameter and knots vector. \~ + \details \ru Вычислить базисный сплайн по параметру t и узловому вектору. + \en Calculate basic spline by "t" parameter and knots vector. \~ + \ingroup Base_Algorithms +*/ +// --- +template +MATH_FUNC (bool) CalcBsplvb( const DoubleVector & knots, double t, ptrdiff_t left, ptrdiff_t degree, + DoubleVector & biatx, DoubleVector & lrVect ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). + \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ + \details \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). + \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ + \ingroup Base_Algorithms +*/ +// --- +void AllBasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const SArray & knots, double ** ndu, + double * left, double * right, bool newPatch = true ); + +//------------------------------------------------------------------------------ +/** \brief \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). + \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ + \details \ru Вычисление B - базиса ( с использованием рабочих указателей классов nurbs кривых и поверхностей ). + \en Calculation of B - basis (using working pointers to nurbs curves and surfaces). \~ + \ingroup Base_Algorithms +*/ +// --- +void AllBasisFuns( ptrdiff_t i, double t, ptrdiff_t p, const SArray & knots, double * ndu, size_t degree, + double * left, double * right, bool newPatch = true ); + +//------------------------------------------------------------------------------ +/// \ru Вычислить значения базисного сплайна и его производных. \en Calculate values and derivatives of basic spline. +/** + \param[in] t - \ru Параметр на кривой. + \en Curve parameter. \~ + \param[in] left - \ru Номер узла первого ненулевого сплайна. + \en Knot number of the first nonzero spline. \~ + \param[in] n - \ru Порядок вычисляемых производных. + \en Order of calculated derivatives. \~ + \param[out] values - \ru Двумерный массив значений. + \en 2D-Array filled by spline values. \~ + \ingroup Base_Algorithms +*/ +//--- +bool CalcDBsplvb( const SArray & knots, size_t degree, double t, ptrdiff_t left, size_t n, Array2 & values ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить все разностные формы кривой. + \en Calculate all difference forms of curve. \~ + \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). + \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ + \ingroup Base_Algorithms +*/ +// --- +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) ); + + ptrdiff_t r = ( r2 - r1 ); + ptrdiff_t degree = ( p + 1 ); + ptrdiff_t i, k, icount; + NurbsVector & PK0 = PK[0]; + + if ( PW != NULL ) { + for ( i = 0; i <= r; i++ ) + PK0.Set( i, *PW, (r1 + i) ); + } + else { + if ( !PK0.UseWeights() && ( r1 + r ) < pointCount ) { + for ( i = 0; i <= r; i++ ) { + PK0[i] = P[r1 + i]; + } + } + else { + for ( i = 0; i <= r; i++ ) { + k = ( ( r1 + i ) % pointCount ); + PK0.Init( i, P[k], W[k] ); + } + } + } + + for ( k = 1; k <= d; k++ ) { + NurbsVector & PKMin = PK[k - 1]; + NurbsVector & PKPls = PK[k]; + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = (r - k); i <= icount; i++ ) { + r1i = ( r1 + i ); + C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + PKPls.Dec( i, PKMin, i, PKMin, (i + 1), (tmp / (U[r1i + degree] - U[r1i + k])) ); + } + } +} + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить все разностные формы кривой. + \en Calculate all difference forms of curve. \~ + \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). + \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ + \ingroup Base_Algorithms +*/ +// --- +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) ); + + ptrdiff_t r = ( r2 - r1 ); + ptrdiff_t degree = ( p + 1 ); + ptrdiff_t i, k, icount; + NurbsVector & PK0 = PK[0]; + + if ( PW != NULL ) { + for ( i = 0; i <= r; i++ ) + PK0.Set( i, *PW, (r1 + i) ); + } + else { + if ( !PK0.UseWeights() && ( r1 + r ) < pointCount ) { + for ( i = 0; i <= r; i++ ) { + PK0[i] = P[r1 + i]; + } + } + else { + for ( i = 0; i <= r; i++ ) { + k = ( ( r1 + i ) % pointCount ); + PK0.Init( i, P[k], w ); + } + } + } + + for ( k = 1; k <= d; k++ ) { + NurbsVector & PKMin = PK[k - 1]; + NurbsVector & PKPls = PK[k]; + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = (r - k); i <= icount; i++ ) { + r1i = ( r1 + i ); + C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + PKPls.Dec( i, PKMin, i, PKMin, (i + 1), (tmp / (U[r1i + degree] - U[r1i + k])) ); + } + } +} + +//------------------------------------------------------------------------------ + /** \brief \ru Вычислить все разностные формы кривой. + \en Calculate all difference forms of curve. \~ + \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). + \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ + \ingroup Base_Algorithms +*/ +// --- +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 ) ); + + 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; + + if ( PW != NULL ) { + if ( !useWeight ) { + for ( i = 0; i <= r; i++ ) + DT0[i].Init( (*PW)[r1 + i] ); + } + else { + for ( i = 0; i <= r; i++ ) { + DT0[i].Init( (*PW)[r1 + i] ); + WT0[i] = PW->w( r1 + i ); + } + } + } + else { + if ( !useWeight && ( r1 + r ) < (ptrdiff_t)pointCount ) { + for ( i = 0; i <= r; i++ ) { + DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); + } + } + else { + for ( i = 0; i <= r; i++ ) { + k = ( ( r1 + i ) % pointCount ); + DT0[i].Init( P[k], W[k] ); + if ( useWeight ) + WT0[i] = W[k]; + } + } + } + + double * WTMin = NULL; + double * WTPls = NULL; + for ( k = 1; k <= d; k++ ) { + DoubleTriple * DTMin = DT[k - 1]; + DoubleTriple * DTPls = DT[k]; + if ( useWeight ) { + WTMin = WT[k - 1]; + WTPls = WT[k]; + } + + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = ( r - k ); i <= icount; i++ ) { + r1i = ( r1 + i ); + double tmp2 = U[r1i + degree] - U[r1i + k]; + C3D_ASSERT( ( ::fabs( tmp2 ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + DTPls[i].Dec( DTMin[i], DTMin[i + 1], tmp / (tmp2) ); + if ( useWeight ) + WTPls[i] = ( WTMin[i + 1] - WTMin[i] ) * ( tmp / (tmp2) ); + } + } +} + +//------------------------------------------------------------------------------ + /** \brief \ru Вычислить все разностные формы кривой. + \en Calculate all difference forms of curve. \~ + \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). + \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ + \ingroup Base_Algorithms +*/ +// --- +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 ) ); + + 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; + + if ( PW != NULL ) { + if ( !useWeight ) { + for ( i = 0; i <= r; i++ ) + DT0[i].Init( (*PW)[r1 + i] ); + } + else { + for ( i = 0; i <= r; i++ ) { + DT0[i].Init( (*PW)[r1 + i] ); + WT0[i] = PW->w( r1 + i ); + } + + } + } + else { + if ( !useWeight && ( r1 + r ) < (ptrdiff_t)pointCount ) { + for ( i = 0; i <= r; i++ ) { + DT0[i].Init( P[r1 + i].x, P[r1 + i].y, P[r1 + i].z ); + } + } + else { + for ( i = 0; i <= r; i++ ) { + k = ( ( r1 + i ) % pointCount ); + DT0[i].Init( P[k], w ); + if( useWeight ) + WT0[i] = w; + } + } + } + + double * WTMin = NULL; + double * WTPls = NULL; + for ( k = 1; k <= d; k++ ) { + DoubleTriple * DTMin = DT[k - 1]; + DoubleTriple * DTPls = DT[k]; + if ( useWeight ) { + WTMin = WT[k - 1]; + WTPls = WT[k]; + } + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = ( r - k ); i <= icount; i++ ) { + r1i = ( r1 + i ); + double tmp2 = U[r1i + degree] - U[r1i + k]; + C3D_ASSERT( ( ::fabs( tmp2 ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + DTPls[i].Dec( DTMin[i], DTMin[i + 1], tmp / (tmp2) ); + if ( useWeight ) + WTPls[i] = ( WTMin[i + 1] - WTMin[i] ) * ( tmp / ( tmp2 ) ); + } + } +} + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить все разностные формы кривой. + \en Calculate all difference forms of curve. \~ + \details \ru Вычислить все (или опционально некоторые) разностные формы кривой (характеристические производные). + \en Calculate all (or some, optionally) difference forms of curve (characteristic derivatives). \~ + \ingroup Base_Algorithms +*/ +// --- +template +void CurveDeriveCpts( ptrdiff_t p, const double * U, const Point * P, const double * W, size_t pointCount, + ptrdiff_t r1, ptrdiff_t r2, + Homogeneous * H0, Homogeneous * H1, Homogeneous * H2, Homogeneous * H3 ) +{ + ptrdiff_t r = ( r2 - r1 ); + ptrdiff_t degree = ( p + 1 ); + ptrdiff_t i, k, icount; + + for ( i = 0; i <= r; i++ ) { + k = ( (r1 + i) % pointCount ); + if ( W != NULL ) + H0[i].Init( P[k], W[k] ); + else + H0[i].Init( P[k], 1.0 ); + } + k = 1; + { + Homogeneous * PKMin = H0; + Homogeneous * PKPls = H1; + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = (r - k); i <= icount; i++ ) { + r1i = ( r1 + i ); + C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); + } + } + k = 2; + { + Homogeneous * PKMin = H1; + Homogeneous * PKPls = H2; + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = (r - k); i <= icount; i++ ) { + r1i = ( r1 + i ); + C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); + } + } + k = 3; + { + Homogeneous * PKMin = H2; + Homogeneous * PKPls = H3; + double tmp = (double)( degree - k ); + ptrdiff_t r1i = r1; + for ( i = 0, icount = (r - k); i <= icount; i++ ) { + r1i = ( r1 + i ); + C3D_ASSERT( ( ::fabs( U[r1i + degree] - U[r1i + k] ) > DOUBLE_EPSILON ) ); // \ru Проверка на сбой \en Check of failure + PKPls[i].Dec( PKMin[i], PKMin[i + 1], (tmp / (U[r1i + degree] - U[r1i + k])) ); + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Cвертка по Энш. \en Einstein's convolution product. +// --- +void EiSum( const double * pk, double ** nd, size_t jcount, double & sum ); + + +//------------------------------------------------------------------------------ +// \ru Cвертка по Энш. \en Einstein's convolution product. +// --- +void EiSum( const MbHomogeneous * pk, double * nd, size_t degree, size_t jcount, MbHomogeneous & sum ); + + +//------------------------------------------------------------------------------ +// \ru Cвертка по Энш. \en Einstein's convolution product. +// --- +void EiSum( const MbHomogeneous3D * pk, double * nd, size_t degree, size_t jcount, MbHomogeneous3D & sum ); + + +//------------------------------------------------------------------------------ +/// \ru Загнать параметр t в параметрическую область кривой. \en Reduce "t" to parameter in the parametric domain of the curve. +/** + \param[in] tMin, tMax - \ru Параметры, задающие параметрическую область кривой. + \en Parameters which define the parametric region of the curve. \~ + \param[in] closed - \ru Признак замкнутости кривой. + \en An attribute of curve closedness. \~ + \param[in, out] t - \ru Исходный параметр. + \en Initial parameter. \~ + \ingroup Base_Algorithms +*/ +// --- +inline void CheckParam( const double & tMin, const double & tMax, bool closed, double & t ) +{ + if ( (t < tMin) || (t > tMax) ) { + if ( closed ) { // \ru Сплайн кривая замкнута \en Spline curve is closed + double period = tMax - tMin; + t -= ::floor( (t - tMin) / period ) * period; + } + else if ( t < tMin ) + t = tMin; + else if ( t > tMax ) + t = tMax; + } +} + + +//------------------------------------------------------------------------------ +/// \ru Рассчитать ненулевые сплайны при данном параметре. \en Calculate non-zero splines with a given parameter. +/** + \param[in] degree - \ru Порядок B-сплайна. + \en B-spline degree. \~ + \param[in] knots - \ru Множество узлов. + \en Knots. \~ + \param[in] closed - \ru Признак замкнутости. + \en A closedness attribute. \~ + \param[in, out] t - \ru Параметр + \en A parameter \~ + \param[out] nsplines - \ru Множество размерности degree, заполняется значениями сплайна. + \en Array (dimension is "degree") is filled by spline values. \~ + \param[out] lrVect - \ru Вспомогательный массив (содержит мусор). + \en An assisting array (contains garbage). \~ + \return \ru Номер первого ненулевого B-сплайна. + \en The number of the first non-zero B-spline. \~ + \ingroup Base_Algorithms +*/ +// --- +template +ptrdiff_t CalculateSplines( size_t degree, + const KnotsVector & knots, + bool closed, + double & t, + DoubleVector1 & nsplines, + DoubleVector2 & lrVect ) +{ + ptrdiff_t begInd = -1; // \ru Возвращаемое значение = номер первого ненулевого B-сплайна. \en The return value = the number of the first non-zero B-spline. + + if ( (degree > 1) && (knots.size() > degree) ) { + size_t power = degree - 1; + size_t lastKnotInd = knots.size() - 1; + + // \ru Загнать параметр t в параметрическую область кривой. \en Reduce "t" to a parameter in the parametric domain of the curve + ::CheckParam( knots[power], knots[lastKnotInd - power], closed, t ); + + ptrdiff_t tspan = ::KnotIndex( degree, knots, t ); + begInd = tspan - (ptrdiff_t)power; + if ( begInd >= 0 && begInd + power <= lastKnotInd ) + ::BasisFuns( tspan, t, power, knots, nsplines, lrVect ); + else { + begInd = SYS_MAX_T; // \ru Ошибка. \en Error + for ( size_t i = 0; i < degree; i++ ) + nsplines[i] = 0.0; + } + + C3D_ASSERT( (size_t)begInd != SYS_MAX_T ); + } + + return begInd; +} + + +//------------------------------------------------------------------------------ +// \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 ) +{ + MbeNewtonResult res = nr_Failure; + + size_t pointsCount = points.size(); + C3D_ASSERT( points.size() > 1 ); + + if ( pointsCount > 1 && degree > 1 && knots.size() > 1 ) { + // \ru Инициализация опорных точек. \en Initialization of support points. + if ( &pointList != &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 ) ) { + 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) ) { + MatrixNN & matrix = *matrixPtr; + + std::vector bSplines; // \ru Ненулевые B-сплайны \en Non-zero B-splines + bSplines.resize( degree ); + + std::vector lrVect; + + 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++ ) + matrix( i, k ) = 0.0; + } + + 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 = ::TypedGaussEquation( matrix, &pointList[0], epsilon ); + } + } + + return res; +} + + +//------------------------------------------------------------------------------ +// \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 ); + + +//------------------------------------------------------------------------------ +// \ru Установить касательность сплайна к вектору \en Set tangency of spline to vector +//--- +template +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 res = false; + + if ( !nurbs.IsClosed() && nurbs.GetPointListCount() > 2 && nurbs.GetDegree() > 2 ) { + bool needRebuild = false; + + TypedVector normTang( tang ); + double tangLen = tang.Length(); + if ( tangLen > LENGTH_EPSILON ) + normTang /= tangLen; + + SArray points ( 0, 1 ); + SArray weights( 0, 1 ); + SArray knots ( 0, 1 ); + nurbs.GetPointList( points ); + nurbs.GetWeights( weights ); + nurbs.GetKnots( knots ); + ptrdiff_t degree = nurbs.GetDegree(); + bool closed = false; + + // \ru Дополнительная точка, которая обеспечивает визуальную касательность \en Additional point which provides a visual tangency + TypedPoint point, add( points[begin ? 0 : points.MaxIndex()] ); + TypedVector curTang, curVect; + double dist = 0.0; + //double dKnots = 0.0; + + double part = modify ? 1.0 : 0.5; // \ru Параметрическая доля \en Parametric part + double pointKnot = 0.0; // \ru Узел точки, обеспечивающий сопряжение \en Point knot which provides a conjugation + double pointWeight = 1.0; // \ru Вес точки \en A point weight + + if ( begin ) { // \ru Стыковка производится в начале \en Connection is performed in the beginning + nurbs._Tangent( nurbs.GetTMin(), curTang ); + if ( !curTang.Colinear(tang) || + curTang * tang < -ANGLE_EPSILON ) // BUG_55564 + { // \ru Если еще не установлено сопряжение \en If conjugation is not set + curVect.Set( points[1], 1.0, points[0], -1.0 ); + + if ( isC1 || !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { + // BUG_53978 if ( !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { + pointKnot = modify ? knots[(size_t)degree] : + knots[(size_t)degree] * part + knots[0] * ( 1.0 - part ); + + pointWeight = modify ? weights[1] : weights[0]; + + dist = points[0].DistanceToPoint( points[1] ) * part; // \ru Длина производной \en Derivative length + + if ( isC1 ) + add.Add( tang, (pointKnot - knots[0]) / (double)(degree - 1) * weights[0] / pointWeight ); + else + add.Add( normTang, dist / (double)(degree - 1) * weights[0] / pointWeight ); + + if ( modify ) + points[1] = add; + else { + points.AddAt( add, 1 ); + weights.AddAt( pointWeight, 1 ); + knots.AddAt( pointKnot, (size_t)degree ); + } + } + else { + // \ru BUG_50080 dist = (normTang * curVect); // МСГ К12 решено не учитывать знак производной \en BUG_50080 dist = (normTang * curVect); // МСГ К12 ignore the sign of the derivative + dist = ::fabs(normTang * curVect); + points[1] = points[0] + normTang * dist; + } + needRebuild = true; + } + + res = true; + } + else { // \ru Стыковка производится в конце \en Connection is performed at the end + nurbs._Tangent( nurbs.GetTMax(), curTang ); + if ( !curTang.Colinear(tang) || + curTang * tang < -ANGLE_EPSILON ) // BUG_55564) + { // \ru Если еще не установлено сопряжение \en If conjugation is not set + ptrdiff_t shear = points.MaxIndex(); + curVect.Set( points[shear], 1.0, points[shear - 1], -1.0 ); + + if ( isC1 || !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { + // BUG_53978 if ( !modify || tang.Orthogonal( curTang, Math::metricNear ) ) { + pointKnot = modify ? knots[shear] : + knots[shear] * ( 1.0 - part ) + knots[shear + (size_t)degree] * part; + + pointWeight = modify ? weights[shear - 1] : weights[shear]; + + dist = points[shear].DistanceToPoint( points[shear - 1] ) * part; // \ru Длина производной \en Derivative length + + if ( isC1 ) + add.Add( tang, -(knots[shear + degree] - pointKnot) / (double)(degree - 1) * weights[shear] / pointWeight ); + else { + // BUG_49940 add.Add( tang, -dist / (degree - 1) * weights[shear] / pointWeight ); + add.Add( normTang, -dist / (double)(degree - 1) * weights[shear] / pointWeight ); + } + + if ( modify ) + points[shear - 1] = add; + else { + points.AddAt( add, shear ); + weights.AddAt( pointWeight, shear ); + knots.AddAt( pointKnot, shear + 1 ); + } + } + else { + // \ru BUG_50080 dist = (normTang * curVect); // МСГ К12 решено не учитывать знак производной \en BUG_50080 dist = (normTang * curVect); // МСГ К12 ignore the sign of the derivative + dist = ::fabs(normTang * curVect); + points[shear - 1] = points[shear] - normTang * dist; + } + needRebuild = true; + } + + res = true; + } + + if ( res && needRebuild ) + nurbs.Init( degree, closed, points, weights, knots, ncf_Unspecified ); +/*#if defined(C3D_DEBUG) + if ( res ){ // \ru Отладка \en Debugging + TypedVector vect; + if ( begin ) nurbs._FirstDer( nurbs.GetTMin(), vect ); + else nurbs._FirstDer( nurbs.GetTMax(), vect ); + double vectLen = vect.Length(); + C3D_ASSERT( tang.Colinear( vect ) && tang * vect > ANGLE_EPSILON ); + C3D_ASSERT( !isC1 || ::fabs(tangLen - vectLen) < METRIC_EPSILON ); + } +#endif +*/ + } + + return res; +} + + +//------------------------------------------------------------------------------ +// \ru Установить касательные на краях \en Set tangents at the ends +// --- +template +bool SetLimitFirstDerivatives( const Curve & curve, bool setBeg, bool setEnd, Nurbs & nurbs, bool setLen ) +{ // BUG_59596 + bool changed = false; + + if ( setBeg ) { + Vector fd; + curve._FirstDer( curve.GetTMin(), fd ); + if ( ::AttachNurbsG1( nurbs, fd, true, false, setLen ) ) + changed = true; + } + if ( setEnd ) { + Vector fd; + curve._FirstDer( curve.GetTMax(), fd ); + if ( ::AttachNurbsG1( nurbs, fd, false, false, setLen ) ) + changed = true; + } + + return changed; +} + + +//------------------------------------------------------------------------------ +// \ru Установить точки так, чтобы совпала касательная и главная нормаль \en Set points such that tangent and principal normal are coincident +//--- +template +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 res = false; + + if ( !nurbs.IsClosed() && nurbs.GetPointListCount() > 3 && nurbs.GetDegree() > 3 && + ::AttachNurbsG1( nurbs, tang, begin, modify, false ) ) // \ru Стыкуем сначала по касательной \en Join by a tangent at first + { + bool needRebuild = false; // \ru Нужно ли перестраивать кривую \en Whether to rebuild the curve + + TypedVector normTang( tang ); + double tangLen = tang.Length(); + if ( tangLen > LENGTH_EPSILON ) + normTang /= tangLen; + + SArray points ( 0, 1 ); + SArray weights( 0, 1 ); + SArray knots ( 0, 1 ); + nurbs.GetPointList( points ); + nurbs.GetWeights( weights ); + nurbs.GetKnots( knots ); + ptrdiff_t degree = nurbs.GetDegree(); + bool closed = nurbs.IsClosed(); + + double eps = Math::metricEpsilon; + + //double dKnots = 0.0; + ptrdiff_t degm = degree - 1; + double curCurv = 0.0; + double curvature = tangDiff.Length(); + + TypedVector curNormal; // \ru Текущая нормаль в стыке \en Current normal at the joint + TypedVector firstDer; // \ru Первая производная сплайна в точке \en The first spline derivative at the point + TypedVector secndDer; // \ru Старая производная сплайна в точке \en The old spline derivative at the point + TypedVector secDer( tangDiff ); // \ru Вторая производная, с которой фактически устанавливается равенство \en The second derivative which the equality is set with + + TypedPoint add; // \ru Точка, обеспечивающая равенство вторых производных \en Point which provides the equality of second derivatives + TypedPoint wp0, wp1; // \ru Взвешенные точки \en Weighted points + + double part = modify ? 1.0 : 0.5; // \ru Параметрическая доля \en Parametric part + double pointKnot = 0.0; // \ru Узел точки, обеспечивающий сопряжение \en Point knot which provides a conjugation + double pointWeight = 1.0; // \ru Вес точки \en A point weight + + double weightDiff1 = 0.0, weightDiff2 = 0.0; // \ru Первая и вторая производная весов \en The first and the second derivative of weights + if ( begin ) { // \ru Стыковка производится в начале \en Connection is performed at the start + nurbs._Normal( nurbs.GetTMin(), curNormal ); + curCurv = nurbs.Curvature( nurbs.GetTMin() ); + + pointKnot = modify ? knots[(size_t)degree + 1] : + knots[(size_t)degree + 1] * part + knots[degree] *( 1.0 - part ); + pointWeight = modify ? weights[2] : weights[0] ; + weightDiff1 = (double)degm * ( weights[1] - weights[0] ) / ( knots[degree] - knots[1] ); + weightDiff2 = ( (double)degm - 1 ) * (double)degm / ( knots[degree] - knots[2] ) * + ( (pointWeight - weights[1]) / (pointKnot - knots[2]) - + (weights[1] - weights[0]) / (knots[degree] - knots[1]) ); + + if ( !(curNormal.Colinear(tangDiff) && + ::fabs(curCurv - curvature) < eps) ) // \ru Еще нет необходимой гладкости стыка \en The required smoothness of a joint is not provided yet + { + nurbs._FirstDer( nurbs.GetTMin(), firstDer ); + secDer *= firstDer * firstDer; + nurbs._SecondDer( nurbs.GetTMin(), secndDer ); + secDer += normTang * ( part * normTang * secndDer ); // \ru Сохранение старой проекции \en Saving of the old projection + + wp0 += points[0] * weights[0]; + wp1 += points[1] * weights[1]; + + // \ru Обрабатываем вторую производную \en Process the second derivative + secDer *= weights[0]; + secDer.Add( points[0], weightDiff2, firstDer, 2.0 * weightDiff1 ); + + double dK = pointKnot - knots[2]; + double dK1 = 1.0 / dK + 1.0 / ( knots[(size_t)degree] - knots[1] ); + + add.Set( wp0, 1.0, wp1 - wp0, dK1 * dK ); + add.Add( secDer, (knots[(size_t)degree] - knots[2]) * dK / ((double)degm * (double)(degm - 1)) ); + add /= pointWeight; + + if ( modify ) + points[2] = add; + else { + knots.AddAt( pointKnot, (size_t)degree + 1 ); + points.AddAt( add, 2 ); + weights.AddAt( pointWeight, 2 ); + } + needRebuild = true; + } + + res = true; + } + else { // \ru Стыковка производится в конце \en Connection is performed at the end + nurbs._Normal( nurbs.GetTMax(), curNormal ); + curCurv = nurbs.Curvature( nurbs.GetTMax() ); + + ptrdiff_t shear = points.MaxIndex(); + + pointKnot = modify ? knots[shear - 1] : + knots[shear] * ( 1.0 - part ) + knots[shear - 1] * part ; + + pointWeight = modify ? weights[shear - 2] : weights[shear]; + + weightDiff1 = (double)degm * ( weights[shear] - weights[shear - 1] ) / + ( knots[shear + (size_t)degree] - knots[shear] ); + weightDiff2 = (double)(degm - 1) * (double)degm / ( knots[shear + (size_t)degm] - knots[shear] ) * + ( (weights[shear] - weights[shear - 1]) / (knots[shear + (size_t)degree] - knots[shear]) - + (weights[shear - 1] - pointWeight ) / (knots[shear + (size_t)degree - 1] - pointKnot ) ); + + if ( !(curNormal.Colinear(tangDiff) && + ::fabs(curCurv - curvature) < eps) ) // \ru Еще нет необходимой гладкости стыка \en The required smoothness of a joint is not provided yet + { + nurbs. _FirstDer( nurbs.GetTMax(), firstDer ); + secDer *= firstDer * firstDer; + nurbs._SecondDer( nurbs.GetTMax(), secndDer ); + secDer += normTang * ( part * normTang * secndDer ); // \ru Сохранение старой проекции \en Saving of the old projection + + wp0 += points[shear] * weights[shear]; + wp1 += points[shear - 1] * weights[shear - 1]; + + // \ru Обрабатываем вторую производную \en Process the second derivative + secDer *= weights[shear]; + secDer.Add( points[shear], weightDiff2, firstDer, 2.0 * weightDiff1 ); + + double dK = knots[shear + (size_t)degm] - pointKnot; + double dK1 = 1.0 / ( knots[shear + (size_t)degm] - knots[shear] ) + + 1.0 / ( knots[shear + (size_t)degm] - pointKnot ); + + add.Set( wp0, 1.0, wp1 - wp0, dK1 * dK ); + add.Add( secDer, (knots[shear + (size_t)degm] - knots[shear]) * dK / ((double)degm * (double)(degm - 1)) ); + add /= pointWeight; + + if ( modify ) + points[shear - 2] = add; + else { + knots.AddAt( pointKnot, shear ); + points.AddAt( add, shear - 1 ); + weights.AddAt( pointWeight, shear - 1 ); + } + needRebuild = true; + } + + res = true; + } + + // \ru Сохраняем вычисленные производные \en Save the calculated derivatives + if ( res ) { + if ( wDiff1 != NULL ) + *wDiff1 = weightDiff1; + if ( wDiff2 != NULL && res ) + *wDiff2 = weightDiff2; + } + + if ( res && needRebuild ) + nurbs.Init( degree, closed, points, weights, knots, ncf_Unspecified ); + } + +/*#if defined(C3D_DEBUG) + if ( res ) { // \ru Отладка \en Debugging + double t = begin ? nurbs.GetTMin() : nurbs.GetTMax(); + + MbVector3D vect; + nurbs._Tangent( t, vect ); + C3D_ASSERT( vect.Colinear( tang ) ); + + MbVector3D normal; + nurbs._Normal( t, normal ); + C3D_ASSERT( normal.Colinear(tangDiff) ); + + double curvature = tangDiff.Length(); + double curCurvature = nurbs.Curvature( t ); + C3D_ASSERT( ::fabs(curCurvature - curvature) < Math::metricAccuracy ); + } +#endif +*/ + + return res; +} + + +//------------------------------------------------------------------------------ +// \ru Создать замкнутый NURBS, проходящий через точки с заданными параметрами. \en Calculate closed NURBS by points which it passes through and points parameters. +//--- +template +bool CreateClosedNURBS4( Nurbs & nurbs, const SArray & initPoints, const SArray & initParams ) +{ + bool bRes = ( (initParams.Count() > 3) && (initParams.Count() == initPoints.Count() + 1) ); + + if ( bRes ) { + nurbs.Refresh(); // должен стоять первым, т.к. освобождается выделенная память + + const ptrdiff_t degree = 4; // степень В-сплайна //-V112 + const bool closed = true; // признак замкнутости + const MbeNurbsCurveForm form = ncf_Unspecified; // форма B - сплайна + + // скопировать массив характеристических точек + SArray points( initPoints ); + + // установить единичные веса + SArray weights( points.Count(), 1 ); + { + const double weight0 = 1.0; + weights.Fill( points.Count(), weight0 ); + } + + const ptrdiff_t degm = degree - 1; + + // заполнить массив параметров (на концах используем условие "отсутствия узла"), обеспечивающий замыкание + SArray knots ( (initParams.MaxIndex() + 2 * degree - 1), 1 ); + { + ptrdiff_t uppKnotsIndex = (ptrdiff_t)initParams.Count() - 1; + ptrdiff_t i = 0; // индекс + + // вставляем начальные узлы 0.. degree - 2 + for ( i = 0; i < degm; i++ ) { + ptrdiff_t startIndex = uppKnotsIndex - degm; + knots.Add( initParams[0] - initParams[uppKnotsIndex] + initParams[startIndex + i] ); + } + + knots += initParams; + + // вставляем конечные узлы + const double tmax = initParams[initParams.MaxIndex()]; + ptrdiff_t i0 = degm; + for ( i = i0; i < i0 + degm; i++ ) + knots.Add( tmax + knots[i + 1] - knots[i0] ); + + uppKnotsIndex = knots.MaxIndex(); + } + + points.Adjust(); + weights.Adjust(); + knots.Adjust(); + + const ptrdiff_t pointsCnt = initPoints.Count(); + const ptrdiff_t uppIndex = pointsCnt - 1; + // для приведения матрицы к матрице с диагональным преобладанием необходимо + // последнее уравнение исключать первым + // далее решаем систему уравнений методом Гаусса без выбора ведущего элемента + SArray biatx( degree, 1 ); // не нулевые B - сплайны + SArray d ( pointsCnt ); // массив диагоналей + SArray ar ( pointsCnt ); // массив правых частей + SArray n ( pointsCnt ); // последний столбец в результирующей матрице + + SArray lrVect; + lrVect.resize( 2*degree ); + + ar.Add( initPoints[initPoints.MaxIndex()] ); + ar += initPoints; + ar.RemoveInd( ar.MaxIndex() ); + + ptrdiff_t lastIndex = initParams.MaxIndex() - 1; + ptrdiff_t lastKnot = knots.Count() - degree - 1; + + // первое уравнение + ::CalcBsplvb( knots, initParams[lastIndex], lastKnot, degree, biatx, lrVect ); + + double norm = 1 / biatx[1]; + double normLast = 1.0; + + ar[0] *= norm; + + d.Add( biatx[2] * norm ); + n.Add( biatx[0] * norm ); + + // последнее уравнение + ::CalcBsplvb( knots, initParams[lastIndex - 1], lastKnot - 1, degree, biatx, lrVect ); + norm = 1.0 / biatx[2]; + // в последнем уравнении, соответственно, внедиагональный и диагональный элемент + double a = biatx[0] * norm; + double b = biatx[1] * norm; + + ar[lastIndex] *= norm; + Point & sn = ar[lastIndex]; + + // прямой ход + ptrdiff_t crLeft = degm; + ptrdiff_t i = 1, im = 0, ip = 1; + for ( ; i < lastIndex - 1; i++, im++, crLeft++ ) { + ::CalcBsplvb( knots, initParams[i - 1], crLeft, degree, biatx, lrVect ); + + norm = 1 / ( biatx[1] - d[im] * biatx[0] ); + + ar[i] = ( ar[i] - ar[im] * biatx[0] ) * norm; + d [i] = biatx[2] * norm; + // исключаем из последнего уравнения ведущую 1 и меняем последний столбец + normLast = -1.0 / d[im]; + + a *= normLast; + b = ( b - n[im] ) * normLast; + + sn = ( sn - ar[im] ) * normLast; + + n.Add( -norm * biatx[0] * n[im] ); + } + + // исключаем из 2-х последних уравнений 3-е с конца + ::CalcBsplvb( knots, initParams[i - 1], crLeft, degree, biatx, lrVect ); + + norm = 1.0 / ( biatx[1] - d[im] * biatx[0] ); + d [lastIndex - 1] = ( biatx[2] - n[im] * biatx[0] ) * norm; + ar[lastIndex - 1] = ( ar[lastIndex - 1] - ar[im] * biatx[0] ) * norm; + + normLast = 1.0 / ( a - d[im] ); + b = ( b - n[im] ) * normLast; + a = 1.0; + sn = ( sn - ar[im] ) * normLast; + + // исключаем из последнего предпоследнее + im++; + points[uppIndex] = ( sn - ar[im] ) / ( b - d[im] ); + + ptrdiff_t prevLast = uppIndex - 1; + points[prevLast] = ar[lastIndex - 1] - points[uppIndex] * d[prevLast]; + + // обратный ход + for ( i = prevLast - 1, ip = prevLast; i >= 0; i--, ip-- ) { + points[i] = ar[i] - points[ip] * d[i] + - points[uppIndex] * n[i]; + } + + bRes = nurbs.Init( degree, closed, points, weights, knots, form ); + C3D_ASSERT( bRes ); + } + + return bRes; +} + + +//------------------------------------------------------------------------------ +// \ru Получить массив параметров по точкам \en Get an array of parameters given the points +// --- +template +bool CreateSplineParameters( const PointsVector & points, MbeSplineParamType spType, bool cls, + DoubleVector & params ) +{ + bool isDone = false; + params.clear(); + isDone = ::DefineThroughPointsParams( points, spType, cls, params ); + + // \ru Нормализация \en Normalization + if ( isDone ) + c3d::SetLimitParam( params, 0.0, (double)((ptrdiff_t)points.size() - 1 + (cls ? 1 : 0)) ); + + return isDone; + +} + + +//------------------------------------------------------------------------------ +// \ru Выбрать точки на кривой для аппроксимации замкнутой nurbs \en Select points on the curve for approximation of closed nurbs +// --- +template +size_t DefineApproxPointsClosed( const Curve & curve, size_t pCount, double pmin, double pmax, ptrdiff_t degree, SArray & points, const KnotsVector & aKnots, const SArray & pCounts ) +{ + size_t pCountActual = pCount; + if ( pCount < 1 ) + return 0; + + points.clear(); + size_t stepCount = 0; + double factor = 1.0 / ( (double)pCount ); + const double epsilon = curve.GetTRegion( METRIC_REGION ); + const double angle = Math::deviateSag; + + size_t segmCount = curve.GetSegmentsCount(); + + SArray segmPointsCnt( segmCount, 2 ); + SArray tList, restList; + + double tmin, tmax; + ptrdiff_t first_Segm = curve.FindSegment( pmin, tmin ); + ptrdiff_t last_Segm = curve.FindSegment( pmax, tmax ); + ptrdiff_t i = 0; + + size_t freePntsCount = pCount, j = 0; + + // \ru Найдем количество точек для каждого сегмента. \en Find the number of points for each segment. + size_t totalCount = 0; + for ( j = 0; j < pCounts.size(); ++j ) + totalCount += pCounts[j]; + if ( totalCount < 1 ) + totalCount = 1; + + for ( j = 0; j < pCounts.size(); j++ ){ + double part = ((double)pCounts[j]) / ((double)totalCount); + size_t segmPCnt = (size_t)(pCount * part); //-V113 + if ( j == (size_t)last_Segm ) + segmPCnt = freePntsCount; + else { + segmPCnt = std_max( segmPCnt, (size_t)1); + segmPCnt = std_min( segmPCnt, freePntsCount ); + } + segmPointsCnt.push_back( segmPCnt ); + freePntsCount -= segmPCnt; + } + + Point p; + double plusT = 0.0; + for ( i = first_Segm; i <= last_Segm; i++ ) { + tList.clear(); + double smin, smax; + smin = curve.GetSegment(i)->GetTMin(); + smax = curve.GetSegment(i)->GetTMax(); + + if ( first_Segm == last_Segm ) { + plusT = pmin + smin - tmin; + smin = tmin; + smax = tmax; + } + else if ( i == first_Segm ){ + plusT = pmin + smin - tmin; + smin = tmin; + } + else if ( i == last_Segm ) { + smax = tmax; + } + double t = smin; + size_t tempCount = segmPointsCnt[i - first_Segm]; + factor = 1.0 / ( (double)tempCount ); + stepCount = 0; + while ( t < (smax - epsilon) ) { + double step = curve.GetSegment(i)->DeviationStep( t, angle ); + if ( (t + step) >= (smax - epsilon) ) + step = smax - t; + + for ( size_t k = 0; k < tempCount; k++ ) + tList.push_back( plusT + t + (step * factor * (double)k) ); + t += step; + stepCount++; + } + tList.push_back(plusT + smax); + plusT += smax; + + for ( j = 0; j < tempCount; j++ ) { + t = tList[j * stepCount]; + curve._PointOn( t, p ); + points.push_back( p ); + restList.push_back( t ); + } + } + + restList.push_back( pmax ); + + // \ru Если задан узловой вектор, надо проверить, что между любыми 2 узлами есть хотя бы одна точка. \en If the knot vector is given, then it is necessary to check that there is at least one point between any two knots. + // \ru Если нет, то добавим точек, сохранив все уже набранные \en If not, then add the points and save old points + if ( aKnots.size() > 0 ) { + SArray pParams( 0, 1 ); + ::CreateSplineParameters( points, spt_ChordLength, true, pParams ); + c3d::SetLimitParam( pParams, aKnots[degree - 1], aKnots[aKnots.size() - degree] ); + double t1, t2; + bool bRes = false; + while ( !bRes ) { + bRes = true; + for ( i = degree - 1; i < aKnots.MaxIndex() - degree + 1 && bRes; i++ ) { + t1 = aKnots[i]; + t2 = aKnots[i + 1]; + if ( ::fabs(t2 - t1) > NULL_EPSILON ) { + size_t il = 0, ir = pParams.MaxIndex(); + size_t itemp = 0; + size_t ires1 = 0; + size_t ires2 = 0; + // \ru Левая граница \en The left boundary + bool goOn = true; + while ( goOn ) { + if ( ::fabs(pParams[il] - t1) < NULL_EPSILON ){ + ires1 = il; + goOn = false; + break; + } + else if ( ::fabs(pParams[ir] - t1) < NULL_EPSILON ) { + ires1 = ir; + goOn = false; + break; + } + else { + itemp = ( il + ir ) / 2; + if ( ::fabs(pParams[itemp] - t1) < NULL_EPSILON ) { + ires1 = itemp; + goOn = false; + break; + } + if ( pParams[itemp] < t1 ) + il = itemp; + else if ( pParams[itemp] > t1 ) + ir = itemp; + if ( ir - il < 2) { + ires1 = il; + goOn = false; + break; + } + } + } + // \ru Правая граница \en The right boundary + il = ires1; + ir = pParams.MaxIndex(); + goOn = true; + while ( goOn ) { + if ( ::fabs(pParams[il] - t2) < NULL_EPSILON ){ + ires2 = il; + goOn = false; + break; + } + else if ( ::fabs(pParams[ir] - t2) < NULL_EPSILON ) { + ires2 = ir; + goOn = false; + break; + } + else { + itemp = ( il + ir ) / 2; + if ( ::fabs(pParams[itemp] - t2) < NULL_EPSILON ) { + ires2 = itemp; + goOn = false; + break; + } + if ( pParams[itemp] < t2 ) + il = itemp; + else if ( pParams[itemp] > t2 ) + ir = itemp; + if ( ir - il < 2) { + ires2 = ir; + goOn = false; + break; + } + } + } + if ( ires2 - ires1 < 2 ) { + bRes = false; + // \ru Вставим среднюю точку между ires1 и ires2 и пересчитаем параметры \en Insert mid-point between ires1 and ires2 and recalculate parameters + double t = 0.5 * (restList[ ires1 ] + restList[ ires2 ]); + restList.AddAt( t, ires1 + 1 ); + + curve._PointOn( t, p ); + points.AddAt( p, ires1 + 1); + + pParams.clear(); + ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); + c3d::SetLimitParam( pParams, aKnots[degree - 1], aKnots[aKnots.size() - degree] ); + pCountActual++; + } + } + } + } + } + + return pCountActual; +} + + +//------------------------------------------------------------------------------ +// \ru Выбрать точки на кривой для аппроксимации незамкнутой nurbs \en Select points on the curve for approximation of non-closed nurbs +// --- +template +size_t DefineApproxPointsOpen( const Curve & curve, size_t pCount, double pmin, double pmax, SArray & points, const KnotsVector & aKnots, const SArray & pCounts ) +{ + size_t pCountActual = pCount; + if ( pCount < 1 ) + return 0; + + points.clear(); + size_t stepCount = 0; + double factor = 1.0 / ( (double)(pCount - 1) ); + const double epsilon = curve.GetTRegion( METRIC_REGION ); + const double angle = Math::deviateSag; + + size_t segmCount = curve.GetSegmentsCount(); + if ( pCounts.size() != segmCount ) + return 0; + + SArray tList, restList; + SArray segmPointsCnt( segmCount, 2 ); + + double tpmin = pmin; + double tpmax = pmax; + + double tmin, tmax; + ptrdiff_t first_Segm = curve.FindSegment( tpmin, tmin ); + ptrdiff_t last_Segm = curve.FindSegment( tpmax, tmax ); + ptrdiff_t i; + + size_t freePntsCount = pCount - 1, j = 0; + + // \ru Найдем количество точек для каждого сегмента. \en Find the number of points for each segment. + size_t totalCount = 0; + for ( j = 0; j < pCounts.size(); ++j ) + totalCount += pCounts[j]; + if ( totalCount == 0 ) + totalCount = 1; + + for ( j = 0; j < pCounts.size(); j++ ){ + double part = ((double)pCounts[j]) / ((double)totalCount); + size_t segmPCnt = (size_t)(pCount * part); //-V113 + if ( j == (size_t)last_Segm ) + segmPCnt = freePntsCount; + else { + segmPCnt = std_max( segmPCnt, (size_t)1); + segmPCnt = std_min( segmPCnt, freePntsCount ); + } + segmPointsCnt.push_back( segmPCnt ); + freePntsCount -= segmPCnt; + } + + Point p; + double plusT = 0.0; + for ( i = first_Segm; i <= last_Segm; i++ ) { + tList.clear(); + + double smin = curve.GetSegment(i)->GetTMin(); + double smax = curve.GetSegment(i)->GetTMax(); + + if ( first_Segm == last_Segm ) { + plusT = tpmin + smin - tmin; + smin = tmin; + if (pmin < tpmin - PARAM_EPSILON ) + smin += pmin - tpmin; + smax = tmax; + if (pmax > tpmax + PARAM_EPSILON ) + smax += pmax - tpmax; + } + else if ( i == first_Segm ){ + plusT = tpmin + smin - tmin; + smin = tmin; + if (pmin < tpmin - PARAM_EPSILON ) + smin += pmin - tpmin; + } + else if ( i == last_Segm ) { + smax = tmax; + if (pmax > tpmax + PARAM_EPSILON ) + smax += pmax - tpmax; + } + double t = smin; + size_t tempCount = segmPointsCnt[i - first_Segm]; + factor = 1.0 / ( (double)tempCount ); + stepCount = 0; + while ( t < (smax - epsilon) ) { + double step = curve.GetSegment(i)->DeviationStep( t, angle ); + if ( (t + step) >= (smax - epsilon) ) + step = smax - t; + + for ( j = 0; j < tempCount; j++ ) + tList.push_back( plusT + t + (step * factor * (double)j) ); + t += step; + stepCount++; + } + tList.push_back(plusT + smax); + plusT += smax; + + for ( size_t k = 0; k < tempCount; k++ ) { + t = tList[k * stepCount]; + curve._PointOn ( t, p ); + points.push_back( p ); + restList.push_back( t ); + } + } + + double t = pmax; + curve._PointOn ( t, p ); + points.push_back( p ); + restList.push_back( t ); + + // \ru Если задан узловой вектор, надо проверить, что между любыми 2 узлами есть хотя бы одна точка. \en If the knot vector is given, then it is necessary to check that there is at least one point between any two knots. + // \ru Если нет, то добавим точек, сохранив все уже набранные \en If not, then add the points and save old points + if ( aKnots.size() > 0 ) { + SArray pParams( 0, 1 ); + ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); + c3d::SetLimitParam( pParams, aKnots.front(), aKnots.back() ); + + double t1, t2; + bool bRes = false; + while ( !bRes ) { + bRes = true; + for ( i = 0; i < aKnots.MaxIndex() && bRes; i++ ) { + t1 = aKnots[i]; + t2 = aKnots[i + 1]; + if ( ::fabs(t2 - t1) > NULL_EPSILON ) { + size_t il = 0, ir = pParams.MaxIndex(); + size_t itemp = 0; + size_t ires1 = 0; + size_t ires2 = 0; + // \ru Левая граница \en The left boundary + bool goOn = true; + while ( goOn ) { + if ( ::fabs(pParams[il] - t1) < NULL_EPSILON ){ + ires1 = il; + goOn = false; + break; + } + else if ( ::fabs(pParams[ir] - t1) < NULL_EPSILON ) { + ires1 = ir; + goOn = false; + break; + } + else { + itemp = ( il + ir ) / 2; + if ( ::fabs(pParams[itemp] - t1) < NULL_EPSILON ) { + ires1 = itemp; + goOn = false; + break; + } + if ( pParams[itemp] < t1 ) + il = itemp; + else if ( pParams[itemp] > t1 ) + ir = itemp; + if ( ir - il < 2) { + ires1 = il; + goOn = false; + break; + } + } + } + // \ru Правая граница \en The right boundary + il = ires1; + ir = pParams.MaxIndex(); + goOn = true; + while ( goOn ) { + if ( ::fabs(pParams[il] - t2) < NULL_EPSILON ){ + ires2 = il; + goOn = false; + break; + } + else if ( ::fabs(pParams[ir] - t2) < NULL_EPSILON ) { + ires2 = ir; + goOn = false; + break; + } + else { + itemp = ( il + ir ) / 2; + if ( ::fabs(pParams[itemp] - t2) < NULL_EPSILON ) { + ires2 = itemp; + goOn = false; + break; + } + if ( pParams[itemp] < t2 ) + il = itemp; + else if ( pParams[itemp] > t2 ) + ir = itemp; + if ( ir - il < 2) { + ires2 = ir; + goOn = false; + break; + } + } + } + if ( ires2 - ires1 < 2 ) { + bRes = false; + // \ru Вставим среднюю точку между ires1 и ires2 и пересчитаем параметры \en Insert mid-point between ires1 and ires2 and recalculate parameters + t = 0.5 * (restList[ ires1 ] + restList[ ires2 ]); + restList.AddAt( t, ires1 + 1 ); + + curve._PointOn( t, p ); + points.AddAt( p, ires1 + 1 ); + + pParams.clear(); + ::CreateSplineParameters( points, spt_ChordLength, false, pParams ); + c3d::SetLimitParam( pParams, aKnots.front(), aKnots.back() ); + pCountActual++; + } + } + } + } + } + return pCountActual; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Построение замкнутого сплайна. + \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 Модифицируемый сплайн. + \en Modifiable spline. \~ + \param[in] aDegree - \ru Порядок сплайна. + \en The spline order. \~ + \param[in] pCount - \ru Количество точек. + \en Count of points. \~ + \param[in] aPoints - \ru Набор точек для аппроксимации. + \en Point set for approximation. \~ + \param[in] aKnots - \ru Предустановленный узловой вектор. + \en The predefined knots vector. \~ + \param[in] aParams - \ru Параметры для набора точек. + \en The parameters for point set. \~ + \result \ru Возвращает true при успешном построении, в противном случае - false. + \en Returns true if success, false - on other case. \~ + \ingroup Curve_Modeling +*/ +// --- +template +MATH_FUNC (bool) CreateNurbsLSMClosed( SPtr & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline + const ptrdiff_t degree, + const ptrdiff_t pCount, + const PointsVector & aPoints, + const DoubleVector & aKnots, + const DoubleVector * aParams = NULL ); + + +//------------------------------------------------------------------------------ +/** \brief \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 Модифицируемый сплайн. + \en Modifiable spline. \~ + \param[in] aDegree - \ru Порядок сплайна. + \en The spline order. \~ + \param[in] pCount - \ru Количество точек. + \en Count of points. \~ + \param[in] aPoints - \ru Набор точек для аппроксимации. + \en Point set for approximation. \~ + \param[in] aKnots - \ru Предустановленный узловой вектор. + \en The predefined knots vector. \~ + \param[in] aParams - \ru Параметры для набора точек. + \en The parameters for point set. \~ + \result \ru Возвращает true при успешном построении, в противном случае - false. + \en Returns true if success, false - on other case. \~ + \ingroup Curve_Modeling +*/ +// --- +template +MATH_FUNC (bool) CreateNurbsLSM( SPtr & nurbs, // \ru Модифицируемый сплайн \en Modifiable spline + const ptrdiff_t degree, + const ptrdiff_t pCount, + const PointsVector & aPoints, + const DoubleVector & aKnots, + const DoubleVector * aParams = NULL ); + + +//------------------------------------------------------------------------------- +/// \ru Построение приямолинейногло сплайна. \en Construction of line segment spline. \~ +// --- +template +Nurbs * CreateLineOutRgn( const Curve & curve, double tn1, double tn2, double t1, double t2, + const MbCurveIntoNurbsInfo & nci ) +{ + Nurbs * nurbs = NULL; + + if ( !curve.IsClosed() && nci.ExtendRange() && ((tn2 - tn1) > Math::paramEpsilon) ) { + SArray points ( 2, 1 ); + SArray weights( 2, 1 ); + SArray knots ( 4, 1 ); //-V112 + + curve._PointOn( t1, *(points.Add()) ); + curve._PointOn( t2, *(points.Add()) ); + + weights.Add( 1.0 ); + weights.Add( 1.0 ); + + knots.Add( tn1 ); + knots.Add( tn1 ); + knots.Add( tn2 ); + knots.Add( tn2 ); + + nurbs = Nurbs::Create( 2, false, points, weights, knots, ncf_Unspecified ); + } + + return nurbs; +} + + +//------------------------------------------------------------------------------ +// \ru Преобразовать контур в нурбс \en Transform contour to NURBS +// --- +MbNurbs * ContourToNurbs( const MbContour & cntr, double t1, double t2, int sense, const MbCurveIntoNurbsInfo & nci, bool reparamByLength ); + +//------------------------------------------------------------------------------ +// \ru Преобразовать контур в нурбс \en Transform contour to NURBS +// --- +MbNurbs3D * ContourToNurbs( const MbContour3D & cntr, double t1, double t2, int sense, const MbCurveIntoNurbsInfo & nci, bool reparamByLength ); + + +#endif // __MB_NURBS_FUNCTION_H diff --git a/C3d/Include/mb_operation_result.h b/C3d/Include/mb_operation_result.h index c7d946b..d9282b3 100644 --- a/C3d/Include/mb_operation_result.h +++ b/C3d/Include/mb_operation_result.h @@ -154,7 +154,7 @@ enum MbResultType { rt_ProcessIsStopped, ///< \ru Процесс остановлен. \en Process is stopped. rt_ContourSweptError, ///< \ru Контур невозможно использовать для заданного перемещения. \en Contour cannot be used for given movement. rt_SomeContourError, ///< \ru Один из контуров невозможно использовать для заданного построения. \en Contour cannot be used for given construction. - rt_SplitWireNotAllFaces, ///< \ru Линии разъема созданы не на всех выбранных гранях. \en Parting lines created not on all selected faces. + rt_SplitWireNotAllFaces, ///< \ru Линии разъема (ребра пересечения) созданы не на всех выбранных гранях или не доходят до границ граней. \en Parting lines (cross edges) created not on all selected faces or do not reach the boundaries of the faces. rt_GeneratrixColinearGuide, ///< \ru В некоторых точках образующая параллельна направляющей. \en Generatrix parallel to the giude at some points. rt_NotEnoughMemory, ///< \ru Недостаточно памяти. \en Not enough memory. rt_BorderColinearCurve, ///< \ru Направление боковой границы параллельно касательной на конце образующей кривой. \en Direction of lateral border is parallel to a tangent at the end of a guide curve. @@ -178,53 +178,63 @@ enum MbResultType { rt_FullFilletError, ///< \ru Ошибка при создании скругления грани. \en Error at creating full fillet. // \ru Ошибки построения плавных сплайнов. \en Build failure of fair splines. - rt_IncorrectSettings, ///< 0 \ru Некорректные объект / параметры. \en Incorrect object / parameters. rt_IncorrectData, ///< 1 \ru Некорректные данные. \en Incorrect data. rt_IncorrectPolylines, ///< 2 \ru Некорректные формы ломаных / направления касательных. \en Incorrect polylines / tangent directions. - rt_Incorrectstructure, ///< 3 \ru Некорректная структура ломаной с прямолинейными участками. \en Incorrect structure of 3d poly with straight sites. + rt_IncorrectStructure, ///< 3 \ru Некорректная структура ломаной с прямолинейными участками. \en Incorrect structure of 3d poly with straight sites. rt_TooFewPoints, ///< 4 \ru Слишком мало точек. \en Too few points. - rt_CoincidencePoints, ///< 5 \ru Совпадение точек. \en Coincidence of points. - rt_TooAcuteAngle, ///< 6 \ru Слишком острый угол между сегментами ломаной. \en Too acute angle between segments of polyline. - rt_ReturnMotion, ///< 7 \ru Обратный ход сегмента. \en Return motion of segment. + rt_CoincidentPoints, ///< 5 \ru Совпадение точек. \en Coincidence of points. + rt_TooSharpAngle, ///< 6 \ru Слишком острый угол между сегментами ломаной. \en Too acute angle between segments of polyline. + rt_ReverseMotion, ///< 7 \ru Обратный ход сегмента. \en Return motion of segment. rt_SharpTorsion, ///< 8 \ru Резкое кручение ломаной. \en Sharp torsion of spatial polyline. rt_IncorrectFirstDirection, ///< 9 \ru Некорректное направление касательной в начальной точке. \en Incorrect direction of first tangent vector. rt_IncorrectLastDirection, ///< 10 \ru Некорректное направление касательной в конечной точке. \en Incorrect direction of last tangent vector. rt_FirstTangentVector, ///< 11 \ru Первая касательная задана к прямолинейному участку. \en First tangent vector is set to a rectilinear site of a polyline. rt_LastTangentVector, ///< 12 \ru Последняя касательная задана к прямолинейному участку. \en Last tangent vector is set to a rectilinear site of a polyline. - rt_TangentVectorsSuitable, ///< 13 \ru Касательные векторы не корректны для локально-выпуклого участка. \en Tangent vectors are not suitable to convex shape of curve. - rt_IncorrectStructure, ///< 14 \ru Некорректная структура исходной кривой Безье. \en Incorrect structure of the initial Bezier curve. + rt_TangentVectorsUnsuitable, ///< 13 \ru Касательные векторы не корректны для локально-выпуклого участка. \en Tangent vectors are not suitable to convex shape of curve. + rt_IncorrectBezier, ///< 14 \ru Некорректная структура исходной кривой Безье. \en Incorrect structure of the initial Bezier curve. rt_NoIntersection, ///< 15 \ru Нет пересечения касательных. Некорректная структура ломаной. \en No intersection of tangents. Incorrect structure of polyline. rt_CriticalConfiguration, ///< 16 \ru Критическая конфигурация для B-сплайновой аппроксимации. \en Critical configuration for B-Spline approximation. rt_IncorrectInitialData, ///< 17 \ru Некорректные исходные данные. \en Incorrect initial data. - rt_CommandNotImplemented, ///< 18 \ru Данная команда не реализована. \en This command is not implemented. - rt_InsufficientMemory, ///< 19 \ru Недостаточно памятию \en Insufficient memory. + rt_NotImplemented, ///< 18 \ru Данная команда не реализована. \en This command is not implemented. + rt_InsufficientMemory, ///< 19 \ru Недостаточно памяти. \en Insufficient memory. rt_IncorrectFirstTangent, ///< 20 \ru Некорректное направление первой касательной. \en Incorrect direction of first tangent. rt_IncorrectLastTangent, ///< 21 \ru Некорректное направление последней касательной. \en Incorrect direction of last tangent. rt_StraightenLastSite, ///< 22 \ru Конечный прямолинейный участок. Касательный вектор не нужен. \en Straighten last site. Last tangent Ignored. rt_IncorrectPolylineStructure, ///< 23 \ru Некорректная структура ломаной с прямолинейными участками. \en Incorrect structure of polyline with straight sites. - rt_ncorrectDataStructure, ///< 24 \ru Некорректная структура данных в модели. \en Incorrect data structure in the model. + rt_IncorrectDataStructure, ///< 24 \ru Некорректная структура данных в модели. \en Incorrect data structure in the model. rt_ObjectIsNotPolyline, ///< 25 \ru Объект - не пространственная ломаная. \en Object is not a 3D polyline. rt_MissingKnots, ///< 26 \ru Отсутствует вектор узлов. \en Missing knots vector. rt_ClosedSpline, ///< 27 \ru Замкнутый сплайн во внешнем файле. \en Closed spline in an external file. rt_ObjectNotSelected, ///< 28 \ru Не выбран нужный объект. \en Object is not selected. - rt_InputFile, ///< 29 \ru Входной файл. \en Input file. - rt_ExternalMemory, ///< 30 \ru Внешняя память. \en External memory. + rt_Reserved1, ///< 29 \ru Зарезервировано. \en Reserved. + rt_Reserved2, ///< 30 \ru Зарезервировано. \en Reserved. rt_TooFewStartPoints, ///< 31 \ru Слишком мало точек на выпуклом участке начального участка. \en Too few points on convex start site of curve. rt_BanClosedConfiguration, ///< 32 \ru Запрет на замкнутую конфигурацию при количестве точек < 5. \en A ban on a closed configuration when the number of points < 5. rt_IncorrectDeterminant, ///< 33 \ru Некорректная структура исходного геометрического определителя. \en Incorrect structure of the initial geometric determinant. rt_DimensionsPointsArrays, ///< 34 \ru Размеры массивов точек. \en Dimensions of points arrays. rt_TangentsNotIntersect, ///< 35 \ru Касательные не пересекаются. \en Tangents do not intersect. - rt_PointsCoincide, ///< 36 \ru Точки совпадают. \en Points coincide. + rt_PointsCoincided, ///< 36 \ru Точки совпадают. \en Points coincide. rt_FewPointsForClosed, ///< 37 \ru Мало точек для замкнутой ломаной. \en Few points for a closed polyline. rt_TooFewPointsOnSite, ///< 38 \ru Слишком мало точек на выпуклом участке. \en Too few points on convex end site of curve. rt_PointsOnLine, ///< 39 \ru Точки на прямой. \en Points on the straight line. rt_TooManyApexes, ///< 40 \ru Слишком много точек. \en Too many points. rt_SiteNotConvex, ///< 41 \ru Трехсегментный участок не выпуклый. \en Three-linked site is not convex. - rt_CurvatuteRange, ///< 42 \ru Кривизна за пределами допустимого диапазона. \en Curvatute out of range. - rt_ObjectIsNotHermiteGD, ///< 43 \ru Объект не ГО Эрмита. \en The object is not Hermite GD. - rt_ObjectIsNotNURBS, ///< 44 \ru Объект не NURBzS. \en The object is not NURBzS. + rt_CurvatureRange, ///< 42 \ru Кривизна за пределами допустимого диапазона. \en Curvatute out of range. + rt_ObjectNotHermiteGD, ///< 43 \ru Объект не ГО Эрмита. \en The object is not Hermite GD. + rt_ObjectNotNURBS, ///< 44 \ru Объект не NURBzS. \en The object is not NURBzS. rt_DerivativeContinuityErr, ///< 45 \ru Ошибка обеспечения непрерывности производной. \en Error ensuring derivative continuity. + rt_NotEnoughBuildData, ///< 46 \ru Недостаточно данных для построения. \en Not enough data to build. + rt_InternalError, ///< 47 \ru Неизвестная ошибка. \en Unknown error. + rt_DerivativeGap = 198, ///< \ru Отсутствует непрерывность производной кривой по параметру. \en There is no continuity of the curve derivatives. + rt_DerivativeGapU, ///< \ru Отсутствует непрерывность производной поверхности по первому параметру. \en There is no continuity of the surface derivatives on first parameter. + rt_DerivativeGapV, ///< \ru Отсутствует непрерывность производной поверхности по второму параметру. \en There is no continuity of the surface derivatives on second parameter. + + rt_ContourGapError, ///< \ru В контуре есть разрывы между сегментами. \en There are gaps between the segments in the contour. + rt_ContourSegmentsOverlapError, ///< \ru В контуре есть наложения сегментов. \en There are segment overlays in the contour. + rt_ContourSegmentsNoTangentJoint,///< \en В контуре есть сегменты с не гладкой стыковкой. \ru In the contour there are segments with a non - smooth connection. + + rt_ExtensionOutOfRange, ///< \ru Удлинение не может быть ограничено заданной поверхностью. \en Extension cannot be limited given surface. // \ru !!! СТРОКИ ВСТАВЛЯТЬ СТРОГО ПЕРЕД ЭТОЙ СТРОКОЙ !!!! \en !!! INSERT LINES STRICTLY BEFORE THIS LINE !!!! rt_ErrorTotal // \ru НИЖЕ НЕ ДОБАВЛЯТЬ! \en DON'T ADD BELOW! }; diff --git a/C3d/Include/mb_placement.h b/C3d/Include/mb_placement.h index 8ae54a8..7e0858f 100644 --- a/C3d/Include/mb_placement.h +++ b/C3d/Include/mb_placement.h @@ -98,15 +98,15 @@ public : public: // \ru Функции инициализации \en Initialization functions. /// \ru Сделать совпадающей с мировой СК. \en Make coincident with global coordinate system. - void Init(); + void Init(); /// \ru Инициализировать по заданной ЛСК. \en Initialize by given local coordinate system. - void Init( const MbPlacement & init ); + void Init( const MbPlacement & init ); /// \ru Инициализировать по точке и вектору направления. \en Initialize by a point and direction vector. - void Init( const MbCartPoint & initOrigin, const MbDirection & initDir, bool l = false ); + void Init( const MbCartPoint & initOrigin, const MbDirection & initDir, bool l = false ); /// \ru Инициализировать по точке и углу. \en Initialize by a point and an angle. - void Init( const MbCartPoint & initOrigin, double angle, bool l = false ); + void Init( const MbCartPoint & initOrigin, double angle, bool l = false ); /// \ru Инициализировать по точке и двум векторам. \en Initialize by a point and two vectors. - void Init( const MbCartPoint &, const MbVector &, const MbVector & ); + void Init( const MbCartPoint &, const MbVector &, const MbVector & ); public: // \ru Функции доступа к данным. \en Getters and Setters. @@ -117,11 +117,11 @@ public: // \ru Функции доступа к данным. \en Getters and Se /// \ru Дать ось Y. \en Get the Y-axis. const MbVector & GetAxisY() const { return axisY; } /// \ru Дать начало ЛСК. \en Get the origin of local coordinate system. - void GetOrigin( MbCartPoint & pc ) const { pc = origin; } + void GetOrigin( MbCartPoint & pc ) const { pc = origin; } /// \ru Перевести точку и первые три производные из локальной в глобальную систему координат. \en Transform a point and the first three derivatives from a local coordinate system to the global coordinate system. - void GetPointAndDerivesFrom( MbCartPoint & point, MbVector & firstDer, - MbVector & secondDer, MbVector & thirdDer, - MbeLocalSystemType type = ls_CartesSystem ) const; + void GetPointAndDerivesFrom( MbCartPoint & point, MbVector & firstDer, + MbVector & secondDer, MbVector & thirdDer, + MbeLocalSystemType type = ls_CartesSystem ) const; // \ru Установить новое значение \en Set the new value /// \ru Дать начало ЛСК. \en Get the origin of local coordinate system. @@ -131,119 +131,119 @@ public: // \ru Функции доступа к данным. \en Getters and Se /// \ru Дать ось Y. \en Get the Y-axis. MbVector & SetAxisY() { flag = MB_UNSET; return axisY; } /// \ru Задать начало ЛСК. \en Set the origin of local coordinate system. - void SetOrigin( const MbCartPoint & p ); + void SetOrigin( const MbCartPoint & p ); /// \ru Задать ось X. \en Set the X-axis. - void SetAxisX ( const MbDirection & v ); + void SetAxisX ( const MbDirection & v ); /// \ru Задать ось Y. \en Set the Y-axis. - void SetAxisY ( const MbDirection & v ); + void SetAxisY ( const MbDirection & v ); /// \ru Задать ось X. \en Set the X-axis. - void SetAxisX ( const MbVector & v ); + void SetAxisX ( const MbVector & v ); /// \ru Задать ось Y. \en Set the Y-axis. - void SetAxisY ( const MbVector & v ); + void SetAxisY ( const MbVector & v ); /// \ru Дать матрицу преобразования в локальную СК: r=R*into (обратная матрица). \en Get the matrix of transformation to the local coordinate system: r=R*into (inverse matrix). - void GetMatrixInto( MbMatrix & m ) const; + void GetMatrixInto( MbMatrix & m ) const; /// \ru Дать матрицу преобразования из локальной СК: R=r*from (прямая матрица). \en Get the matrix of transformation from the local coordinate system: R=r*from (direct matrix). - void GetMatrixFrom( MbMatrix & m ) const; + void GetMatrixFrom( MbMatrix & m ) const; public: // \ru Функции доступа к данным. \en Getters and Setters. /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. - void Move( const MbVector & ); + void Move( const MbVector & ); /// \ru Сдвинуть на заданные приращения. \en Translate by given increments. - void Move( double dx, double dy ); + void Move( double dx, double dy ); /// \ru Повернуть вокруг точки на угол. \en Rotate at angle around a point. - void Rotate( const MbCartPoint & pnt, double angle ); + void Rotate( const MbCartPoint & pnt, double angle ); /// \ru Повернуть вокруг точки на угол, заданный вектором направления. \en Rotate around a point at the angle given by direction vector. - void Rotate( const MbCartPoint & pnt, const MbDirection & angle ); + void Rotate( const MbCartPoint & pnt, const MbDirection & angle ); /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. - void Transform( const MbMatrix & matr ); + void Transform( const MbMatrix & matr ); /// \ru Рассчитать СК по начальной и конечной точкам. \en Calculate the coordinate system by the start point and the end point. - void Calculate( const MbCartPoint & from, const MbCartPoint & to ); + void Calculate( const MbCartPoint & from, const MbCartPoint & to ); /// \ru Пересчитать СК по измененным внутренним данным. \en Recalculate the coordinate system by changed internal data. - void Reset(); + void Reset(); ///< \ru Масштабировать ЛСК. \en Scale the local coordinate system. - void Scale( double sx, double sy, double &lx, double &ly ); + void Scale( double sx, double sy, double &lx, double &ly ); /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbPlacement & other, double accuracy ) const; + bool IsSame( const MbPlacement & other, double accuracy ) const; /// \ru Инвертировать ось 0X. \en Invert the 0X-axis. - void InvertAxisX(); + void InvertAxisX(); /// \ru Инвертировать ось 0Y. \en Invert the 0Y-axis. - void InvertAxisY(); + void InvertAxisY(); /// \ru Проверить на равенство. \en Check for equality. - bool operator == ( const MbPlacement & ) const; + bool operator == ( const MbPlacement & ) const; /// \ru Проверить на неравенство. \en Check for inequality. - bool operator != ( const MbPlacement & ) const; + bool operator != ( const MbPlacement & ) const; /// \ru Присвоить другую систему координат. \en Assign another coordinate system. - void operator = ( const MbPlacement & ); + void operator = ( const MbPlacement & ); /// \ru Умножить на локальную систему (как перемножение матриц): P = this * p. \en Multiply by a local coordinate system: P = this * p (as of matrix multiplication). MbPlacement operator * ( const MbPlacement & p ) const; /// \ru Перевести точку из глобальной в локальную систему координат. \en Transform point from the global coordinate system to a local coordinate system. - void TransformInto( MbCartPoint & ) const; + void TransformInto( MbCartPoint & ) const; /// \ru Перевести точку из локальной в глобальную систему координат. \en Transform point from a local coordinate system to the global coordinate system. - void TransformFrom( MbCartPoint & ) const; + void TransformFrom( MbCartPoint & ) const; /// \ru Перевести вектор из глобальной в локальную систему координат. \en Transform a vector from the global coordinate system to a local coordinate system. - void TransformInto( MbVector & ) const; + void TransformInto( MbVector & ) const; /// \ru Перевести вектор из локальной в глобальную систему координат. \en Transform a vector from a local coordinate system to the global coordinate system. - void TransformFrom( MbVector & ) const; + void TransformFrom( MbVector & ) const; /// \ru Нормализовать. \en Normalize. - void Normalize() { Reset(); } + void Normalize() { Reset(); } public: // \ru Функции получения свойств. \en Properties. /// \ru Свойство совпадения с мировой системой координат. \en Property of coincidence with global coordinate system. - bool IsSingle () const { return (MB_IDENTITY == CheckFlag()); } + bool IsSingle () const { return (MB_IDENTITY == CheckFlag()); } /// \ru Проверить, присутствует ли сдвиг системы координат относительно глобальной. \en Check if a coordinate system is translated relative to the global coordinate system. - bool IsTranslation() const { return !!(CheckFlag() & MB_TRANSLATION); } + bool IsTranslation() const { return !!(CheckFlag() & MB_TRANSLATION); } /// \ru Проверить, присутствует ли поворот системы координат относительно глобальной. \en Check if the coordinate system is rotated relative to the global coordinate system. - bool IsRotation () const { return !!(CheckFlag() & MB_ROTATION); } + bool IsRotation () const { return !!(CheckFlag() & MB_ROTATION); } /// \ru Выдать признак лево-ориентированного плейсмента. \en Get attribute of left placement. - bool IsLeft () const { return !!(CheckFlag() & MB_LEFT); } + bool IsLeft () const { return !!(CheckFlag() & MB_LEFT); } /// \ru Проверить, является ли СК ортогональной, но ненормированной. \en Check if a coordinate system is orthogonal, but not normalized. - bool IsOrt () const { return !!(CheckFlag() & MB_ORTOGONAL); } + bool IsOrt () const { return !!(CheckFlag() & MB_ORTOGONAL); } /// \ru Проверить признак ортогональности СК. \en Check orthogonality of a coordinate system. - bool IsOrthogonal () const { CheckFlag(); return ( !(flag & MB_AFFINE) || !!(flag & MB_ORTOGONAL) ); } + bool IsOrthogonal () const { CheckFlag(); return ( !(flag & MB_AFFINE) || !!(flag & MB_ORTOGONAL) ); } /// \ru Проверить, является ли СК аффинной (если нет - то она ортонормированная). \en Check if a coordinate system is affine (otherwise it is orthonormalized). - bool IsAffine () const { return !!(CheckFlag() & MB_AFFINE); } + bool IsAffine () const { return !!(CheckFlag() & MB_AFFINE); } /// \ru Проверить признак ортонормированности СК. \en Check if a coordinate system is orthonormalized. - bool IsNormal () const { return !IsAffine(); } + bool IsNormal () const { return !IsAffine(); } /// \ru Проверить, что битовые флаги не установлены. \en Check whether bit flags are not set. - bool IsUnSet () const { return !!( flag & MB_UNSET ); } + bool IsUnSet () const { return !!( flag & MB_UNSET ); } /// \ru Вычислить и вернуть признак лево-ориентированного плейсмента. \en Calculate and return attribute of left placement. - bool CheckLeft(); + bool CheckLeft(); /// \ru Проверить ортогональность. \en Check orthogonality. - bool IsCardinalPoint( double eps = Math::AngleEps ) const; + bool IsCardinalPoint( double eps = Math::AngleEps ) const; /// \ru Проверить параллелен оси 0X или 0Y. \en Check if parallel to 0X-axis or 0Y-axis - bool IsCardinalStrict( double eps ) const; + bool IsCardinalStrict( double eps ) const; /// \ru Являются ли оси СК совпадающими со стандартной (правой ортонормированной СК). \en Check if axes of coordinate system are coincident to a standard one (right orthonormalized coordinate system). - bool IsTranslationStandard() const; + bool IsTranslationStandard() const; /// \ru Проверить, является ли СК ортогональной с равными по длине осями X,Y (круг остается кругом). \en Check if a coordinate system is orthogonal with axes X and Y of equal length (circle moves to circle). - bool IsCircular() const; + bool IsCircular() const; /// \ru Проверить, является ли СК ортогональной с равными по длине осями X,Y (круг остается кругом). \en Check if a coordinate system is orthogonal with axes X and Y of equal length (circle moves to circle). - bool IsCircular( double & lxy ) const; + bool IsCircular( double & lxy ) const; /// \ru Проверить, является ли СК ортогональной с равными по длине осями X,Y (круг остается кругом). \en Check if a coordinate system is orthogonal with axes X and Y of equal length (circle moves to circle). - bool IsIsotropic() const { return IsCircular(); } + bool IsIsotropic() const { return IsCircular(); } /// \ru Проверить, является ли СК ортогональной с равными по длине осями X,Y (круг остается кругом). \en Check if a coordinate system is orthogonal with axes X and Y of equal length (circle moves to circle). - bool IsIsotropic( double & lxy ) const { return IsCircular( lxy ); } + bool IsIsotropic( double & lxy ) const { return IsCircular( lxy ); } /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & properties ); + void GetProperties( MbProperties & properties ); /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties & properties ); + void SetProperties( const MbProperties & properties ); private: /// \ru Выставить флаги. \en Set flags. - uint8 ResetFlag() const; + uint8 ResetFlag() const; // Оценить флаги, если оценки не было - uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag; } + uint8 CheckFlag() const { return IsUnSet() ? ResetFlag() : flag; } // Проверить флаг смещения. - void CheckOrigin() const { ::CheckOrigin( *this, flag, true ); } + void CheckOrigin() const { ::CheckOrigin( *this, flag, true ); } // \ru Проверить флаг вращения. \en Check rotation flag. - void CheckRotation() const { ::CheckRotation( *this, flag, true ); } + void CheckRotation() const { ::CheckRotation( *this, flag, true ); } KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPlacement, MATH_FUNC_EX ) DECLARE_NEW_DELETE_CLASS( MbPlacement ) diff --git a/C3d/Include/mb_placement3d.h b/C3d/Include/mb_placement3d.h index 9798737..83c40d0 100644 --- a/C3d/Include/mb_placement3d.h +++ b/C3d/Include/mb_placement3d.h @@ -395,9 +395,13 @@ public: /** \} void Invert( MbMatrix * = NULL ); /// \ru Найти ближайшую точку пересечения с линией. \en Find the nearest point of intersection with line. - bool LineIntersectionPoint( const MbCartPoint3D & pc, const MbVector3D & axis, MbCartPoint3D & p, double & d ) const; + bool LineIntersectionPoint( const MbCartPoint3D & pc, const MbVector3D & axis, MbCartPoint3D & p, double & d, double eps = ANGLE_EPSILON ) const; /// \ru Получить точку и направление линии пересечения плоскостей. \en Get the point and direction of planes intersection line. - bool PlanesIntersection ( const MbPlacement3D & place, MbCartPoint3D & p, MbVector3D & axis ) const; + bool PlanesIntersection ( const MbPlacement3D & place, MbCartPoint3D & p, MbVector3D & axis, double eps = ANGLE_EPSILON ) const; + /// \ru Нахождение точки пересечения плоскости XY и кривой. \en Intersection plane XY with a curve. + MbeNewtonResult CurveIntersectNewton( const MbCurve3D & curve, bool ext, double funcEpsilon, size_t iterLimit, + double & u, double & v, double & t ) const; + /// \ru Преобразовать 2D-точки в другую 2D-точку. \en Transform 2D-point to another 2D-point. void TransformPoint ( const MbMatrix3D &, MbCartPoint & ) const; diff --git a/C3d/Include/mb_point_mating.h b/C3d/Include/mb_point_mating.h index e5181cb..2790997 100644 --- a/C3d/Include/mb_point_mating.h +++ b/C3d/Include/mb_point_mating.h @@ -1,719 +1,713 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Модуль геометрических построений. Сопряжение в точке - \en Geometric constructions module. Conjugation at point. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef __MB_POINT_MATING_H -#define __MB_POINT_MATING_H - - -#include -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -/// \ru Параметры сопряжения в точке \en Parameters of conjugation at point -//--- -template -class MbPntMatingData { -private: // \ru данные \en data -//OV_x64 The structure's size can be decreased via changing the fields' order. The size can be reduced from 56 to 40 bytes. -//OV_x64 MbeMatingType type; ///< \ru тип сопряжения \en conjugation type -//OV_x64 Vector * tangent; ///< \ru направляющий касательный вектор \en guide tangent vector -//OV_x64 Vector * tangentDer1; ///< \ru первая производная касательного вектора \en first derivative of tangent vector -//OV_x64 Vector * tangentDer2; ///< \ru вторая производная касательного вектора \en second derivative of tangent vector -//OV_x64 bool movePnts; ///< \ru двигать исходные точки или добавлять \en move or add source points -//OV_x64 SArray * changedPnts; ///< \ru индексы измененных точек \en indices of changed points -//OV_x64 bool attach; ///< \ru данные служат для стыковки сплайна с кривой \en data for spline and curve connection - - Vector * tangent; ///< \ru Направляющий касательный вектор. \en Guide tangent vector. - Vector * tangentDer1; ///< \ru Первая производная касательного вектора. \en First derivative of tangent vector. - Vector * tangentDer2; ///< \ru Вторая производная касательного вектора. \en Second derivative of tangent vector. - SArray * changedPnts; ///< \ru Индексы измененных точек. \en Indices of changed points. - MbeMatingType type; ///< \ru Тип сопряжения. \en Conjugation type. - bool movePnts; ///< \ru Двигать исходные точки или добавлять. \en Move or add source points. - bool attach; ///< \ru Данные служат для стыковки сплайна с кривой. \en Data for a spline and a curve connection. - -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 ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbPntMatingData( const MbPntMatingData & ); - /// \ru Деструктор. \en Destructor. - ~MbPntMatingData(); - -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 ); - - /// \ru Инициализировать по другому объекту параметров сопряжения в точке. \en Initialize by another parameters object of conjugation at point. - bool Init( const MbPntMatingData & ); - -public: - // \ru доступ к данным \en access to data - /// \ru Дать тип сопряжения. \en Get conjugation type. - MbeMatingType GetType() const { return type; } - /// \ru Дать направляющий касательный вектор. \en Get guide tangent vector. - const Vector * GetTangent() const { return tangent; } - /// \ru Дать первую производную касательного вектора. \en Get the first derivative of tangent vector. - const Vector * GetTangentDer1() const { return tangentDer1; } - /// \ru Дать вторую производную касательного вектора. \en Get the second derivative of tangent vector. - const Vector * GetTangentDer2() const { return tangentDer2; } - /// \ru Выдать признак совпадения направлений касательных в точке сопряжения. \en Get attribute of tangent directions coincidence at conjugation point. - bool IsAttach() const { return attach; } - /// \ru Выдать признак возможности передвижения исходных точек. \en Get attribute of source points movability. - bool CanMovePoints() const { return movePnts; } - /// \ru Вернуть массив изменных точек. \en Get array of changed points. - const SArray * GetChangedPoints() const { return changedPnts; } - /// \ru Вернуть массив изменных точек. \en Get array of changed points. - SArray *& SetChangedPoints() { return changedPnts; } - - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbPntMatingData &, double accuracy ) const; - /// \ru Сделать первичную проверку корректности параметров. \en Initial check of parameters correctness. - bool IsValid() const; - /// \ru Уcтановить параметры сопряжения. \en Set conjugation parameters. - void SetVector( ptrdiff_t i, const Vector & vect ); - /// \ru Нормализовать касательную в случае стыковки. \en Normalize tangent in case of connection. - void NormalizeAttachTangent(); - /// \ru Дать фактическую степень гладкости визуального перехода. \en Get the actual smoothness degree of visual transition. - ptrdiff_t GetSmoothDegree() const; - - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & ); - /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties & ); - -private: // \ru не реализовано \en not implemented - void operator = ( const MbPntMatingData & ); -}; - - -//------------------------------------------------------------------------------ -// \ru конструктор \en constructor -//--- -template -MbPntMatingData::MbPntMatingData() - : tangent ( NULL ) - , tangentDer1 ( NULL ) - , tangentDer2 ( NULL ) - , changedPnts ( NULL ) - , type ( trt_Position ) - , movePnts ( false ) - , attach ( false ) -{ -} - - -//------------------------------------------------------------------------------ -// \ru конструктор \en constructor -//--- -template -MbPntMatingData::MbPntMatingData( const MbeMatingType nType, - const Vector * nTang, - const Vector * nTangDer1, - const Vector * nTangDer2, - SArray *& nChangedPnts, - bool nMovePnts, - bool nAttach ) - : type ( nType ) - , tangent ( (nTang != NULL) ? new Vector( *nTang ) : NULL ) - , tangentDer1 ( (nTangDer1 != NULL) ? new Vector( *nTangDer1 ) : NULL ) - , tangentDer2 ( (nTangDer2 != NULL) ? new Vector( *nTangDer2 ) : NULL ) - , movePnts ( nMovePnts ) - , changedPnts ( nChangedPnts ) - , attach ( nAttach ) -{ - if ( type <= trt_Position ) { // BUG_52162 - ::DeleteMatItem( tangent ); - ::DeleteMatItem( tangentDer1 ); - ::DeleteMatItem( tangentDer2 ); - } -} - - -//------------------------------------------------------------------------------ -// \ru конструктор копирования \en copy constructor -//--- -template -MbPntMatingData::MbPntMatingData( const MbPntMatingData & d ) - : type ( d.type ) - , tangent ( (d.tangent != NULL) ? new Vector( *d.tangent ) : NULL ) - , tangentDer1 ( (d.tangentDer1 != NULL) ? new Vector( *d.tangentDer1 ) : NULL ) - , tangentDer2 ( (d.tangentDer2 != NULL) ? new Vector( *d.tangentDer2 ) : NULL ) - , movePnts ( d.movePnts ) - , changedPnts ( d.changedPnts ) - , attach ( d.attach ) -{ -} - - -//------------------------------------------------------------------------------ -// \ru деструктор \en destructor -//--- -template -MbPntMatingData ::~MbPntMatingData() -{ - ::DeleteMatItem( tangent ); - ::DeleteMatItem( tangentDer1 ); - ::DeleteMatItem( tangentDer2 ); -} - - -//------------------------------------------------------------------------------ -// \ru инициализация данных \en data initialization -//--- -template -void MbPntMatingData::Init( const MbeMatingType nType, - const Vector * nTang, - const Vector * nTangDer1, - const Vector * nTangDer2, - SArray *& nChangedPnts, - bool nMovePnts, - bool nAttach ) -{ - type = nType; - - if ( tangent != NULL && nTang != NULL ) // \ru касательный вектор \en tangent vector - tangent->Init( *nTang ); - else if ( nTang != NULL ) - tangent = new Vector( *nTang ); - else if ( tangent != NULL ) - ::DeleteMatItem( tangent ); - - if ( tangentDer1 != NULL && nTangDer1 != NULL ) // \ru первая производная касательного вектора \en first derivative of tangent vector - tangentDer1->Init( *nTangDer1 ); - else if ( nTangDer1 != NULL ) - tangentDer1 = new Vector( *nTangDer1 ); - else if ( tangentDer1 != NULL ) - ::DeleteMatItem( tangentDer1 ); - - if ( tangentDer2 != NULL && nTangDer2 != NULL ) // \ru вторая производная касательного вектора \en second derivative of tangent vector - tangentDer2->Init( *nTangDer2 ); - else if ( nTangDer2 != NULL ) - tangentDer2 = new Vector( *nTangDer2 ); - else if ( tangentDer2 != NULL ) - ::DeleteMatItem( tangentDer2 ); - - if ( type <= trt_Position ) { // BUG_52162 - ::DeleteMatItem( tangent ); - ::DeleteMatItem( tangentDer1 ); - ::DeleteMatItem( tangentDer2 ); - } - - if ( changedPnts != NULL ) - changedPnts->Flush(); - - movePnts = nMovePnts; - changedPnts = nChangedPnts; - attach = nAttach; -} - - -//------------------------------------------------------------------------------ -// \ru инициализация данных \en data initialization -//--- -template -bool MbPntMatingData::Init( const MbPntMatingData & d ) -{ - C3D_ASSERT( changedPnts == NULL ); - - if ( this != &d ) { - SArray * dummyInds = NULL; - Init( d.type, d.tangent, d.tangentDer1, d.tangentDer2, dummyInds, d.movePnts, d.attach ); - return true; - } - return false; -} - - -//------------------------------------------------------------------------------ -// \ru Являются ли объекты равными? \en Determine whether an object is equal? -//--- -template -bool MbPntMatingData::IsSame( const MbPntMatingData & other, double accuracy ) const -{ - bool isSame = false; - - if ( c3d::EqualVectors( *tangent, *other.tangent, accuracy ) && - c3d::EqualVectors( *tangentDer1, *other.tangentDer1, accuracy ) && - c3d::EqualVectors( *tangentDer2, *other.tangentDer2, accuracy ) && - *changedPnts == *other.changedPnts && - type == other.type && - movePnts == other.movePnts && - attach == other.attach ) - isSame = true; - - return isSame; -} - - -//------------------------------------------------------------------------------ -// \ru первичная проверка корректности параметров \en initial check of parameters correctness -//--- -template -bool MbPntMatingData::IsValid() const -{ - bool isValid = true; - - if ( type >= trt_Position ) { - double lenEps = LENGTH_EPSILON; - bool isTang = (tangent != NULL); - bool isTangDer1 = (tangentDer1 != NULL); - bool isTangDer2 = (tangentDer2 != NULL); - bool isTangLen = (isTang && tangent->Length() > lenEps); - - switch( type ) { - case trt_Tangent: - isValid = isTangLen; - break; - case trt_Normal: - // \ru под нормалью понимается как касательное сопряжение с тем, что названо нормалью, \en normal is considered to be either a tangent conjugation with what is called normal - // \ru так и управление только главной нормалью \en or only principal normal management - isValid = !attach && (isTangLen || (isTangDer1 && tangentDer1->Length() > lenEps)); - break; - case trt_SmoothG2 : - isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 )); - break; - case trt_SmoothG3: - isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 )) && isTangDer2; - break; - default: break; - } - } - - return isValid; -} - - -//------------------------------------------------------------------------------ -// \ru фактическая степень гладкости визуального перехода \en actual smoothness degree of visual transition -//--- -template -ptrdiff_t MbPntMatingData::GetSmoothDegree() const -{ - ptrdiff_t res = 0; - switch ( type ) { - case trt_Tangent : - res = 1; - break; - case trt_Normal : - if ( tangentDer1 != NULL ) res = 2; - else if ( tangent != NULL ) res = 1; - break; - case trt_SmoothG2: - res = 2; - break; - case trt_SmoothG3: - res = 3; - break; - default: break; - } - return res; -} - - -//------------------------------------------------------------------------------ -// \ru уcтановка параметров сопряжения \en set conjugation parameters -//--- -template -void MbPntMatingData::SetVector( ptrdiff_t i, const Vector & vect ) -{ - switch ( i ) { - case 0 : { - if ( tangent != NULL ) tangent->Init( vect ); - else tangent = new Vector( vect ); - break; - } - case 1 : { - if ( tangentDer1 != NULL ) tangentDer1->Init( vect ); - else tangentDer1 = new Vector( vect ); - break; - } - case 2 : { - if ( tangentDer2 != NULL ) tangentDer2->Init( vect ); - else tangentDer2 = new Vector( vect ); - break; - } - } -} - - -//------------------------------------------------------------------------------ -// \ru нормализовать касательную в случае стыковки \en normalize tangent in case of connection -//--- -template -void MbPntMatingData::NormalizeAttachTangent() -{ - if ( attach && tangent != NULL ) { - double tangLen = tangent->Length(); - if ( tangLen > LENGTH_EPSILON ) - (*tangent) /= tangLen; - } -} - - -//------------------------------------------------------------------------------ -// \ru выдать свойства объекта \en get properties of object -// --- -template -void MbPntMatingData::GetProperties( MbProperties & properties ) -{ -/* - properties.SetName( IDS_PROP_0900 ); - - TCHAR * typeName = new TCHAR[256]; - - switch ( type ) { - case trt_None : _sntprintf( typeName, IDS_PROP_0902 ); break; - case trt_Position : _sntprintf( typeName, IDS_PROP_0903 ); break; - case trt_Tangent : _sntprintf( typeName, IDS_PROP_0904 ); break; - case trt_Normal : _sntprintf( typeName, IDS_PROP_0905 ); break; - case trt_SmoothG2 : _sntprintf( typeName, IDS_PROP_0906 ); break; - case trt_SmoothG3 : _sntprintf( typeName, IDS_PROP_0907 ); break; - default : _sntprintf( typeName, IDS_ITEM_0902 ); break; - } - - properties.Add( new StringProperty( IDS_PROP_0901, typeName, false ) ); -*/ - if ( tangent != NULL ) - properties.Add( new MathItemProperty( IDS_PROP_0908, tangent, true ) ); - if ( tangentDer1 != NULL ) - properties.Add( new MathItemProperty( IDS_PROP_0909, tangentDer1, true ) ); - if ( tangentDer2 != NULL ) - properties.Add( new MathItemProperty( IDS_PROP_0910, tangentDer2, true ) ); - - properties.Add( new BoolProperty( IDS_PROP_0911, movePnts, false ) ); - properties.Add( new BoolProperty( IDS_PROP_0912, attach, false ) ); -} - - -//------------------------------------------------------------------------------ -// \ru выдать свойства объекта \en get properties of object -// --- -template -void MbPntMatingData::SetProperties( const MbProperties & /*properties*/ ) -{ -} - - -//------------------------------------------------------------------------------ -// \ru определено ли сопряжение \en whether conjugation is defined -//--- -template -bool IsMatingDefined( const MbPntMatingData * data ) -{ - bool isDefined = false; - - if ( data != NULL && data->IsValid() ) { - if ( data->GetType() > trt_Position ) // \ru по позиции и так выполнится, поэтому считаем не заданным \en would be held at position, so assumed as undefined - isDefined = true; - } - - return isDefined; -} - - -//------------------------------------------------------------------------------ -// \ru определены ли сопряжение \en whether conjugation is defined -//--- -template -bool IsAnyMatingDefined( const RPArray< MbPntMatingData > & data ) -{ - bool isDefined = false; - - if ( data.Count() > 0 ) { - for ( size_t k = 0, cnt = data.Count(); k < cnt; k++ ) { - if ( ::IsMatingDefined( data[k] ) ) { - isDefined = true; - break; - } - } - } - - return isDefined; -} - - -//------------------------------------------------------------------------------ -// \ru копировать сопряжения \en copy conjugations -//--- -template -bool CopyMating( const RPArray< MbPntMatingData > & src, RPArray< MbPntMatingData > & dst ) -{ - bool isDone = false; - - if ( src.Count() > 0 && dst.Count() < 1 ) { - isDone = true; - for ( size_t k = 0, cnt = src.Count(); k < cnt && isDone; k++ ) { - MbPntMatingData * copyItem = NULL; - if ( src[k] != NULL ) { - copyItem = new MbPntMatingData(); - isDone = copyItem->Init( *src[k] ); - } - dst.Add( copyItem ); - } - if ( !isDone ) - ::DeleteMatItems( dst ); - } - - return isDone; -} - - -//------------------------------------------------------------------------------ -// \ru Являются ли объекты равными? \en Determine whether an object is equal? -//--- -template -bool IsSame( const RPArray< MbPntMatingData > & data, const RPArray< MbPntMatingData > & other, double accuracy ) -{ - bool isSame = false; - - if ( data.Count() == other.Count() ) { - isSame = true; - for ( size_t k = 0, cnt = data.Count(); k < cnt; k++ ) - if ( !data[k]->IsSame( *other[k], accuracy ) ) { - isSame = false; - break; - } - } - - return isSame; -} - - -//------------------------------------------------------------------------------ -// \ru трансформировать сопряжения \en transform conjugations -//--- -template -void TransformMating( const RPArray< MbPntMatingData > & data, const Matrix & matr ) -{ - Vector vect; - for ( size_t k = 0, kcnt = data.Count(); k < kcnt; k++ ) { - MbPntMatingData * dataItem = data[k]; - - if ( dataItem != NULL ) { - if ( dataItem->GetTangent() != NULL ) { - vect = *dataItem->GetTangent(); - vect.Transform( matr ); - dataItem->SetVector( 0, vect ); - } - if ( dataItem->GetTangentDer1() != NULL ) { - vect = *dataItem->GetTangentDer1(); - vect.Transform( matr ); - dataItem->SetVector( 1, vect ); - } - if ( dataItem->GetTangentDer2() != NULL ) { - vect = *dataItem->GetTangentDer2(); - vect.Transform( matr ); - dataItem->SetVector( 2, vect ); - } - } - } -} - - -//------------------------------------------------------------------------------ -// \ru вращать сопряжения \en rotate conjugations -//--- -template -void RotateMating( const RPArray< MbPntMatingData > & data, const Axis & axis, double angle ) -{ - Vector vect; - for ( size_t i = 0; i < data.Count(); i++ ) { - MbPntMatingData * dataItem = data[i]; - - if ( dataItem->GetTangent() != NULL ){ - vect = *dataItem->GetTangent(); - vect.Rotate( axis, angle ); - dataItem->SetVector( 0, vect ); - } - if ( dataItem->GetTangentDer1() != NULL ){ - vect = *dataItem->GetTangentDer1(); - vect.Rotate( axis, angle ); - dataItem->SetVector( 1, vect ); - } - if ( dataItem->GetTangentDer2() != NULL ){ - vect = *dataItem->GetTangentDer2(); - vect.Rotate( axis, angle ); - dataItem->SetVector( 2, vect ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru запись массива данных сопряжений \en conjugation data array writing -//--- -template -void WriteMating( writer & out, const RPArray< MbPntMatingData > & data ) -{ - if ( out.good() ) { - size_t cnt = data.Count(); - WriteCOUNT( out, cnt ); - for ( size_t k = 0; k < cnt && out.good(); k++ ) { - const MbPntMatingData * item = data[k]; - // \ru наличие сопряжения \en presence of conjugation - bool isItem = (item != NULL); - out << isItem; - - if ( isItem && item->GetChangedPoints() != 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 ); - } - - if ( isItem && out.good() ) { - // \ru тип сопряжения \en conjugation type - uint32 type = (uint32)item->GetType(); - out << type; - // \ru касательный вектор \en tangent vector - isItem = (item->GetTangent() != NULL); - out << isItem; - if ( isItem ) - out << (*item->GetTangent()); - // \ru первая производная касательного вектора \en first derivative of tangent vector - isItem = (item->GetTangentDer1() != NULL); - out << isItem; - if ( isItem ) - out << (*item->GetTangentDer1()); - // \ru вторая производная касательного вектора \en second derivative of tangent vector - isItem = (item->GetTangentDer2() != NULL); - out << isItem; - if ( isItem ) - out << (*item->GetTangentDer2()); - - out << (bool)item->CanMovePoints(); - out << (bool)item->IsAttach(); - } - } - } -} - - -//------------------------------------------------------------------------------ -// \ru чтение массива данных сопряжений \en conjugation data array reading -//--- -template -void ReadMating( reader & in, RPArray< MbPntMatingData > & data ) -{ - if ( in.good() ) { - ::DeleteMatItems( data ); - size_t cnt = ReadCOUNT( in ); - - if ( cnt > 0 ) { - data.Reserve( cnt ); - SArray * dummyInds = NULL; - - for ( size_t k = 0; k < cnt && in.good(); k++ ) { - // \ru наличие сопряжения \en presence of conjugation - bool isItem = false; - in >> isItem; - - if ( isItem ) { - // \ru тип сопряжения \en conjugation type - uint32 type = trt_None; - in >> type; - - MbVector3D * v1 = NULL; - MbVector3D * v2 = NULL; - MbVector3D * v3 = NULL; - - // \ru касательный вектор \en tangent vector - in >> isItem; - if ( isItem ) { - v1 = new Vector; - in >> *v1; - } - // \ru первая производная касательного вектора \en first derivative of tangent vector - in >> isItem; - if ( isItem ) { - v2 = new Vector; - in >> *v2; - } - // \ru вторая производная касательного вектора \en second derivative of tangent vector - in >> isItem; - if ( isItem ) { - v3 = new Vector; - in >> *v3; - } - - bool movePnts = false; - in >> movePnts; - bool attach = false; - in >> attach; - - MbPntMatingData * item = new MbPntMatingData(); - item->Init( (MbeMatingType)type, v1, v2, v3, dummyInds, movePnts, attach ); - data.Add( item ); - - ::DeleteMatItem( v1 ); - ::DeleteMatItem( v2 ); - ::DeleteMatItem( v3 ); - } - else { - data.Add( NULL ); - } - } - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Функция копирования. \en Copy function. -//--- -template -void CopyPntMatingData( const MbPntMatingData & srcData, MbPntMatingData & dstData ) -{ - MbeMatingType type = srcData.GetType(); - bool movePnts = srcData.CanMovePoints(); - bool attach = srcData.IsAttach(); - SArray * changedPnts = const_cast *>( srcData.GetChangedPoints() ); - - size_t dim = std_min( SrcVector::GetDimension(), DstVector::GetDimension() ); - - DstVector * tangent = NULL; - DstVector * tangentDer1 = NULL; - DstVector * tangentDer2 = NULL; - - if ( srcData.GetTangent() != NULL ) { - tangent = new DstVector; - for ( size_t k = 0; k < dim; k++ ) - (*tangent)[k] = (*srcData.GetTangent())[k]; - } - if ( srcData.GetTangentDer1() != NULL ) { - tangentDer1 = new DstVector; - for ( size_t k = 0; k < dim; k++ ) - (*tangentDer1)[k] = (*srcData.GetTangentDer1())[k]; - } - if ( srcData.GetTangentDer2() != NULL ) { - tangentDer2 = new DstVector; - for ( size_t k = 0; k < dim; k++ ) - (*tangentDer2)[k] = (*srcData.GetTangentDer2())[k]; - } - - dstData.Init( type, tangent, tangentDer1, tangentDer2, changedPnts, movePnts, attach ); - - ::DeleteMatItem( tangent ); - ::DeleteMatItem( tangentDer1 ); - ::DeleteMatItem( tangentDer2 ); -} - - -#endif +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Модуль геометрических построений. Сопряжение в точке + \en Geometric constructions module. Conjugation at point. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + + +#ifndef __MB_POINT_MATING_H +#define __MB_POINT_MATING_H + + +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/// \ru Параметры сопряжения в точке \en Parameters of conjugation at point +//--- +template +class MbPntMatingData { +private: // \ru данные \en data + Vector * tangent; ///< \ru Направляющий касательный вектор. \en Guide tangent vector. + Vector * tangentDer1; ///< \ru Первая производная касательного вектора. \en First derivative of tangent vector. + Vector * tangentDer2; ///< \ru Вторая производная касательного вектора. \en Second derivative of tangent vector. + SArray * changedPnts; ///< \ru Индексы измененных точек. \en Indices of changed points. + MbeMatingType type; ///< \ru Тип сопряжения. \en Conjugation type. + bool movePnts; ///< \ru Двигать исходные точки или добавлять. \en Move or add source points. + bool attach; ///< \ru Данные служат для стыковки сплайна с кривой. \en Data for a spline and a curve connection. + +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 ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbPntMatingData( const MbPntMatingData & ); + /// \ru Деструктор. \en Destructor. + ~MbPntMatingData(); + +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 ); + + /// \ru Инициализировать по другому объекту параметров сопряжения в точке. \en Initialize by another parameters object of conjugation at point. + bool Init( const MbPntMatingData & ); + +public: + // \ru доступ к данным \en access to data + /// \ru Дать тип сопряжения. \en Get conjugation type. + MbeMatingType GetType() const { return type; } + /// \ru Дать направляющий касательный вектор. \en Get guide tangent vector. + const Vector * GetTangent() const { return tangent; } + /// \ru Дать первую производную касательного вектора. \en Get the first derivative of tangent vector. + const Vector * GetTangentDer1() const { return tangentDer1; } + /// \ru Дать вторую производную касательного вектора. \en Get the second derivative of tangent vector. + const Vector * GetTangentDer2() const { return tangentDer2; } + /// \ru Выдать признак совпадения направлений касательных в точке сопряжения. \en Get attribute of tangent directions coincidence at conjugation point. + bool IsAttach() const { return attach; } + /// \ru Выдать признак возможности передвижения исходных точек. \en Get attribute of source points movability. + bool CanMovePoints() const { return movePnts; } + /// \ru Вернуть массив изменных точек. \en Get array of changed points. + const SArray * GetChangedPoints() const { return changedPnts; } + /// \ru Вернуть массив изменных точек. \en Get array of changed points. + SArray *& SetChangedPoints() { return changedPnts; } + + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbPntMatingData &, double accuracy ) const; + /// \ru Сделать первичную проверку корректности параметров. \en Initial check of parameters correctness. + bool IsValid() const; + /// \ru Уcтановить параметры сопряжения. \en Set conjugation parameters. + void SetVector( ptrdiff_t i, const Vector & vect ); + /// \ru Нормализовать касательную в случае стыковки. \en Normalize tangent in case of connection. + void NormalizeAttachTangent(); + /// \ru Дать фактическую степень гладкости визуального перехода. \en Get the actual smoothness degree of visual transition. + size_t GetSmoothDegree() const; + + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties & ); + /// \ru Записать свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties & ); + +private: // \ru не реализовано \en not implemented + void operator = ( const MbPntMatingData & ); +}; + + +//------------------------------------------------------------------------------ +// \ru конструктор \en constructor +//--- +template +MbPntMatingData::MbPntMatingData() + : tangent ( C3D_NULL_PTR ) + , tangentDer1 ( C3D_NULL_PTR ) + , tangentDer2 ( C3D_NULL_PTR ) + , changedPnts ( C3D_NULL_PTR ) + , type ( trt_Position ) + , movePnts ( false ) + , attach ( false ) +{ +} + + +//------------------------------------------------------------------------------ +// \ru конструктор \en constructor +//--- +template +MbPntMatingData::MbPntMatingData( const MbeMatingType nType, + const Vector * nTang, + const Vector * nTangDer1, + const Vector * nTangDer2, + 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 ) +{ + if ( type <= trt_Position ) { // BUG_52162 + ::DeleteMatItem( tangent ); + ::DeleteMatItem( tangentDer1 ); + ::DeleteMatItem( tangentDer2 ); + } +} + + +//------------------------------------------------------------------------------ +// \ru конструктор копирования \en copy constructor +//--- +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 ) +{ +} + + +//------------------------------------------------------------------------------ +// \ru деструктор \en destructor +//--- +template +MbPntMatingData ::~MbPntMatingData() +{ + ::DeleteMatItem( tangent ); + ::DeleteMatItem( tangentDer1 ); + ::DeleteMatItem( tangentDer2 ); +} + + +//------------------------------------------------------------------------------ +// \ru инициализация данных \en data initialization +//--- +template +void MbPntMatingData::Init( const MbeMatingType nType, + const Vector * nTang, + const Vector * nTangDer1, + const Vector * nTangDer2, + SArray *& nChangedPnts, + bool nMovePnts, + bool nAttach ) +{ + type = nType; + + if ( tangent != C3D_NULL_PTR && nTang != C3D_NULL_PTR ) // \ru касательный вектор \en tangent vector + tangent->Init( *nTang ); + else if ( nTang != C3D_NULL_PTR ) + tangent = new Vector( *nTang ); + else if ( tangent != C3D_NULL_PTR ) + ::DeleteMatItem( tangent ); + + if ( tangentDer1 != C3D_NULL_PTR && nTangDer1 != C3D_NULL_PTR ) // \ru первая производная касательного вектора \en first derivative of tangent vector + tangentDer1->Init( *nTangDer1 ); + else if ( nTangDer1 != C3D_NULL_PTR ) + tangentDer1 = new Vector( *nTangDer1 ); + else if ( tangentDer1 != C3D_NULL_PTR ) + ::DeleteMatItem( tangentDer1 ); + + if ( tangentDer2 != C3D_NULL_PTR && nTangDer2 != C3D_NULL_PTR ) // \ru вторая производная касательного вектора \en second derivative of tangent vector + tangentDer2->Init( *nTangDer2 ); + else if ( nTangDer2 != C3D_NULL_PTR ) + tangentDer2 = new Vector( *nTangDer2 ); + else if ( tangentDer2 != C3D_NULL_PTR ) + ::DeleteMatItem( tangentDer2 ); + + if ( type <= trt_Position ) { // BUG_52162 + ::DeleteMatItem( tangent ); + ::DeleteMatItem( tangentDer1 ); + ::DeleteMatItem( tangentDer2 ); + } + + if ( changedPnts != C3D_NULL_PTR ) + changedPnts->clear(); + + movePnts = nMovePnts; + changedPnts = nChangedPnts; + attach = nAttach; +} + + +//------------------------------------------------------------------------------ +// \ru инициализация данных \en data initialization +//--- +template +bool MbPntMatingData::Init( const MbPntMatingData & d ) +{ + C3D_ASSERT( changedPnts == C3D_NULL_PTR ); + + if ( this != &d ) { + SArray * dummyInds = C3D_NULL_PTR; + Init( d.type, d.tangent, d.tangentDer1, d.tangentDer2, dummyInds, d.movePnts, d.attach ); + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +// \ru Являются ли объекты равными? \en Determine whether an object is equal? +//--- +template +bool MbPntMatingData::IsSame( const MbPntMatingData & other, double accuracy ) const +{ + bool isSame = false; + + if ( c3d::EqualVectors( *tangent, *other.tangent, accuracy ) && + c3d::EqualVectors( *tangentDer1, *other.tangentDer1, accuracy ) && + c3d::EqualVectors( *tangentDer2, *other.tangentDer2, accuracy ) && + *changedPnts == *other.changedPnts && + type == other.type && + movePnts == other.movePnts && + attach == other.attach ) + isSame = true; + + return isSame; +} + + +//------------------------------------------------------------------------------ +// \ru Первичная проверка корректности параметров. \en initial check of parameters correctness +//--- +template +bool MbPntMatingData::IsValid() const +{ + bool isValid = true; + + 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 isTangLen = (isTang && tangent->Length() > lenEps); + + switch( type ) { + case trt_Position : + isValid = true; + break; + case trt_Tangent: + isValid = isTangLen; + break; + case trt_Normal: + // \ru под нормалью понимается как касательное сопряжение с тем, что названо нормалью, \en normal is considered to be either a tangent conjugation with what is called normal + // \ru так и управление только главной нормалью \en or only principal normal management + isValid = !attach && (isTangLen || (isTangDer1 && tangentDer1->Length() > lenEps)); + break; + case trt_SmoothG2 : + isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 )); + break; + case trt_SmoothG3: + isValid = isTangLen && (isTangDer1 && tangent->Orthogonal( *tangentDer1 )) && isTangDer2; + break; + default: break; + } + } + + return isValid; +} + + +//------------------------------------------------------------------------------ +// \ru Фактическая степень гладкости визуального перехода. \en Actual smoothness degree of visual transition. +//--- +template +size_t MbPntMatingData::GetSmoothDegree() const +{ + size_t res = 0; + switch ( type ) { + case trt_Tangent : + res = 1; + break; + case trt_Normal : + if ( tangentDer1 != C3D_NULL_PTR ) res = 2; + else if ( tangent != C3D_NULL_PTR ) res = 1; + break; + case trt_SmoothG2: + res = 2; + break; + case trt_SmoothG3: + res = 3; + break; + default: break; + } + return res; +} + + +//------------------------------------------------------------------------------ +// \ru Уcтановка параметров сопряжения. \en set conjugation parameters +//--- +template +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 ); + break; + } + case 1 : { + if ( tangentDer1 != C3D_NULL_PTR ) tangentDer1->Init( vect ); + else tangentDer1 = new Vector( vect ); + break; + } + case 2 : { + if ( tangentDer2 != C3D_NULL_PTR ) tangentDer2->Init( vect ); + else tangentDer2 = new Vector( vect ); + break; + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Нормализовать касательную в случае стыковки. \en normalize tangent in case of connection +//--- +template +void MbPntMatingData::NormalizeAttachTangent() +{ + if ( attach && tangent != C3D_NULL_PTR ) { + double tangLen = tangent->Length(); + if ( tangLen > LENGTH_EPSILON ) + (*tangent) /= tangLen; + } +} + + +//------------------------------------------------------------------------------ +// \ru выдать свойства объекта \en get properties of object +// --- +template +void MbPntMatingData::GetProperties( MbProperties & properties ) +{ +/* + properties.SetName( IDS_PROP_0900 ); + + TCHAR * typeName = new TCHAR[256]; + + switch ( type ) { + case trt_None : _sntprintf( typeName, IDS_PROP_0902 ); break; + case trt_Position : _sntprintf( typeName, IDS_PROP_0903 ); break; + case trt_Tangent : _sntprintf( typeName, IDS_PROP_0904 ); break; + case trt_Normal : _sntprintf( typeName, IDS_PROP_0905 ); break; + case trt_SmoothG2 : _sntprintf( typeName, IDS_PROP_0906 ); break; + case trt_SmoothG3 : _sntprintf( typeName, IDS_PROP_0907 ); break; + default : _sntprintf( typeName, IDS_ITEM_0902 ); break; + } + + properties.Add( new StringProperty( IDS_PROP_0901, typeName, false ) ); +*/ + if ( tangent != C3D_NULL_PTR ) + properties.Add( new MathItemProperty( IDS_PROP_0908, tangent, true ) ); + if ( tangentDer1 != C3D_NULL_PTR ) + properties.Add( new MathItemProperty( IDS_PROP_0909, tangentDer1, true ) ); + if ( tangentDer2 != C3D_NULL_PTR ) + properties.Add( new MathItemProperty( IDS_PROP_0910, tangentDer2, true ) ); + + properties.Add( new BoolProperty( IDS_PROP_0911, movePnts, false ) ); + properties.Add( new BoolProperty( IDS_PROP_0912, attach, false ) ); +} + + +//------------------------------------------------------------------------------ +// \ru выдать свойства объекта \en get properties of object +// --- +template +void MbPntMatingData::SetProperties( const MbProperties & /*properties*/ ) +{ +} + + +//------------------------------------------------------------------------------ +// \ru определено ли сопряжение \en whether conjugation is defined +//--- +template +bool IsMatingDefined( const MbPntMatingData * data ) +{ + bool isDefined = false; + + if ( data != C3D_NULL_PTR && data->IsValid() ) { + if ( data->GetType() > trt_Position ) // \ru по позиции и так выполнится, поэтому считаем не заданным \en would be held at position, so assumed as undefined + isDefined = true; + } + + return isDefined; +} + + +//------------------------------------------------------------------------------ +// \ru определены ли сопряжение \en whether conjugation is defined +//--- +template +bool IsAnyMatingDefined( const RPArray< MbPntMatingData > & data ) +{ + bool isDefined = false; + + if ( !data.empty() ) { + for ( size_t k = 0, cnt = data.size(); k < cnt; ++k ) { + if ( ::IsMatingDefined( data[k] ) ) { + isDefined = true; + break; + } + } + } + + return isDefined; +} + + +//------------------------------------------------------------------------------ +// \ru копировать сопряжения \en copy conjugations +//--- +template +bool CopyMating( const RPArray< MbPntMatingData > & src, RPArray< MbPntMatingData > & 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 ) { + copyItem = new MbPntMatingData(); + isDone = copyItem->Init( *src[k] ); + } + dst.Add( copyItem ); + } + if ( !isDone ) + ::DeleteMatItems( dst ); + } + + return isDone; +} + + +//------------------------------------------------------------------------------ +// \ru Являются ли объекты равными? \en Determine whether an object is equal? +//--- +template +bool IsSame( const RPArray< MbPntMatingData > & data, const RPArray< MbPntMatingData > & other, double accuracy ) +{ + bool isSame = false; + + if ( data.size() == other.size() ) { + isSame = true; + for ( size_t k = 0, cnt = data.size(); k < cnt; ++k ) + if ( !data[k]->IsSame( *other[k], accuracy ) ) { + isSame = false; + break; + } + } + + return isSame; +} + + +//------------------------------------------------------------------------------ +// \ru трансформировать сопряжения \en transform conjugations +//--- +template +void TransformMating( const RPArray< MbPntMatingData > & data, const Matrix & matr ) +{ + Vector vect; + for ( size_t k = 0, kcnt = data.size(); k < kcnt; ++k ) { + MbPntMatingData * dataItem = data[k]; + + if ( dataItem != C3D_NULL_PTR ) { + if ( dataItem->GetTangent() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangent(); + vect.Transform( matr ); + dataItem->SetVector( 0, vect ); + } + if ( dataItem->GetTangentDer1() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangentDer1(); + vect.Transform( matr ); + dataItem->SetVector( 1, vect ); + } + if ( dataItem->GetTangentDer2() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangentDer2(); + vect.Transform( matr ); + dataItem->SetVector( 2, vect ); + } + } + } +} + + +//------------------------------------------------------------------------------ +// \ru вращать сопряжения \en rotate conjugations +//--- +template +void RotateMating( const RPArray< MbPntMatingData > & data, const Axis & axis, double angle ) +{ + Vector vect; + for ( size_t i = 0; i < data.size(); ++i ) { + MbPntMatingData * dataItem = data[i]; + + if ( dataItem->GetTangent() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangent(); + vect.Rotate( axis, angle ); + dataItem->SetVector( 0, vect ); + } + if ( dataItem->GetTangentDer1() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangentDer1(); + vect.Rotate( axis, angle ); + dataItem->SetVector( 1, vect ); + } + if ( dataItem->GetTangentDer2() != C3D_NULL_PTR ) { + vect = *dataItem->GetTangentDer2(); + vect.Rotate( axis, angle ); + dataItem->SetVector( 2, vect ); + } + } +} + + +//------------------------------------------------------------------------------ +// \ru запись массива данных сопряжений \en conjugation data array writing +//--- +template +void WriteMating( writer & out, const RPArray< MbPntMatingData > & data ) +{ + if ( out.good() ) { + size_t cnt = data.size(); + WriteCOUNT( out, cnt ); + for ( size_t k = 0; k < cnt && out.good(); k++ ) { + const MbPntMatingData * item = data[k]; + // \ru наличие сопряжения \en presence of conjugation + bool isItem = (item != NULL); + out << isItem; + + if ( isItem && item->GetChangedPoints() != C3D_NULL_PTR ) { + 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 ); + } + + if ( isItem && out.good() ) { + // \ru тип сопряжения \en conjugation type + uint32 type = (uint32)item->GetType(); + out << type; + // \ru касательный вектор \en tangent vector + isItem = (item->GetTangent() != C3D_NULL_PTR); + out << isItem; + if ( isItem ) + out << (*item->GetTangent()); + // \ru первая производная касательного вектора \en first derivative of tangent vector + isItem = (item->GetTangentDer1() != C3D_NULL_PTR); + out << isItem; + if ( isItem ) + out << (*item->GetTangentDer1()); + // \ru вторая производная касательного вектора \en second derivative of tangent vector + isItem = (item->GetTangentDer2() != C3D_NULL_PTR); + out << isItem; + if ( isItem ) + out << (*item->GetTangentDer2()); + + out << (bool)item->CanMovePoints(); + out << (bool)item->IsAttach(); + } + } + } +} + + +//------------------------------------------------------------------------------ +// \ru чтение массива данных сопряжений \en conjugation data array reading +//--- +template +void ReadMating( reader & in, RPArray< MbPntMatingData > & data ) +{ + if ( in.good() ) { + ::DeleteMatItems( data ); + size_t cnt = ReadCOUNT( in ); + + if ( cnt > 0 ) { + data.Reserve( cnt ); + SArray * dummyInds = C3D_NULL_PTR; + + for ( size_t k = 0; k < cnt && in.good(); k++ ) { + // \ru наличие сопряжения \en presence of conjugation + bool isItem = false; + in >> isItem; + + if ( isItem ) { + // \ru тип сопряжения \en conjugation type + uint32 type = trt_None; + in >> type; + + MbVector3D * v1 = C3D_NULL_PTR; + MbVector3D * v2 = C3D_NULL_PTR; + MbVector3D * v3 = C3D_NULL_PTR; + + // \ru касательный вектор \en tangent vector + in >> isItem; + if ( isItem ) { + v1 = new Vector; + in >> *v1; + } + // \ru первая производная касательного вектора \en first derivative of tangent vector + in >> isItem; + if ( isItem ) { + v2 = new Vector; + in >> *v2; + } + // \ru вторая производная касательного вектора \en second derivative of tangent vector + in >> isItem; + if ( isItem ) { + v3 = new Vector; + in >> *v3; + } + + bool movePnts = false; + in >> movePnts; + bool attach = false; + in >> attach; + + MbPntMatingData * item = new MbPntMatingData(); + item->Init( (MbeMatingType)type, v1, v2, v3, dummyInds, movePnts, attach ); + data.Add( item ); + + ::DeleteMatItem( v1 ); + ::DeleteMatItem( v2 ); + ::DeleteMatItem( v3 ); + } + else { + data.Add( NULL ); + } + } + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Функция копирования. \en Copy function. +//--- +template +void CopyPntMatingData( const MbPntMatingData & srcData, MbPntMatingData & dstData ) +{ + MbeMatingType type = srcData.GetType(); + bool movePnts = srcData.CanMovePoints(); + bool attach = srcData.IsAttach(); + SArray * changedPnts = const_cast *>( srcData.GetChangedPoints() ); + + size_t dim = std_min( SrcVector::GetDimension(), DstVector::GetDimension() ); + + DstVector * tangent = C3D_NULL_PTR; + DstVector * tangentDer1 = C3D_NULL_PTR; + DstVector * tangentDer2 = C3D_NULL_PTR; + + if ( srcData.GetTangent() != C3D_NULL_PTR ) { + tangent = new DstVector; + for ( size_t k = 0; k < dim; k++ ) + (*tangent)[k] = (*srcData.GetTangent())[k]; + } + if ( srcData.GetTangentDer1() != C3D_NULL_PTR ) { + tangentDer1 = new DstVector; + for ( size_t k = 0; k < dim; k++ ) + (*tangentDer1)[k] = (*srcData.GetTangentDer1())[k]; + } + if ( srcData.GetTangentDer2() != C3D_NULL_PTR ) { + tangentDer2 = new DstVector; + for ( size_t k = 0; k < dim; k++ ) + (*tangentDer2)[k] = (*srcData.GetTangentDer2())[k]; + } + + dstData.Init( type, tangent, tangentDer1, tangentDer2, changedPnts, movePnts, attach ); + + ::DeleteMatItem( tangent ); + ::DeleteMatItem( tangentDer1 ); + ::DeleteMatItem( tangentDer2 ); +} + + +#endif diff --git a/C3d/Include/mb_property.h b/C3d/Include/mb_property.h index 7889f83..4e226a4 100644 --- a/C3d/Include/mb_property.h +++ b/C3d/Include/mb_property.h @@ -1,881 +1,881 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Свойства математических объектов. - \en Properties of mathematical objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MB_PROPERTY_H -#define __MB_PROPERTY_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#define GET_PROPERTY_VALUE( v ) _GetPropertyValue( &(v), sizeof(v) ) - - -class MbAttribute; -class MbCurve; -class MbCurve3D; -class MbMultiline; -class MbMatrix3D; -class MbFloatPoint; -class MbFloatPoint3D; -class MbFloatVector3D; -class MbTriangle; -class MbQuadrangle; -class MbElement; -class MbApex3D; -class MbPolygon3D; -class MbGrid; -class MbNamedAttributeContainer; -class MbPlacement3D; -class MbMarker; -class MbSurface; -class MbPoint3D; -class MbPointFrame; -class MbWireFrame; -class MbSolid; -class MbInstance; -class MbAssembly; -class MbConstraintSystem; -class MbMesh; -class MbItem; -class MbSpaceInstance; -class MbPlaneInstance; -class MbAssistingItem; -class MbCollection; -class MbModel; -class MbRegion; -class MbDirection; -class MbPlacement; -class MbMatrix; -class MbMultiline; -class MbRegion; -class MbSymbol; -class MbThread; -class MbFunction; -class MbVertex; -class MbEdge; -class MbCurveEdge; -class MbOrientedEdge; -class MbLoop; -class MbFace; -class MbFaceShell; -class MbName; -class MbCreator; -class MbAttributeContainer; -class MbAttributeAction; -class MbTransactions; -template -class MbPntMatingData; -class MbProperties; - - -//---------------------------------------------------------------------------------------- - /** \brief \ru Типы свойств. - \en Types of properties. \~ - \details \ru Типы свойств. \n - Свойства дают доступ к внутренним данным объектов. - \en Types of properties. \n - Properties give access to internal data of objects. \~ - \ingroup Geometric_Items - */ -// --- -enum PrePropType -{ - pt_UndefinedProp, ///< \ru Свойство неизвестного типа данных. \en Property of unknown datatype. \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 - - // \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 - - // \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 - - // \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 - - // \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 - - // \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_LastPropType, ///< \ru Последний тип свойства, все остальные добавлять перед ним. \en Last type of property, any other ones must be added before. -}; - - -//----------------------------------------------------------------------------- -/// \ru Структура соответствия типа объекта и типа свойства. \en Object type and property type correspondence structure. -//--- -template -struct PropType { static const PrePropType propId = pt_UndefinedProp; }; - - -//----------------------------------------------------------------------------- -// \ru Специализация шаблона PropType - организует таблицу соответствий \en PropType template specialization - organizes lookup table -//--- -template<> struct PropType { static const PrePropType propId = pt_CartPointProp; }; -template<> struct PropType { static const PrePropType propId = pt_VectorProp; }; -template<> struct PropType { static const PrePropType propId = pt_DirectionProp; }; -template<> struct PropType { static const PrePropType propId = pt_PlacementProp; }; -template<> struct PropType { static const PrePropType propId = pt_MatrixProp; }; -template<> struct PropType { static const PrePropType propId = pt_CurveProp; }; -template<> struct PropType { static const PrePropType propId = pt_MultilineProp; }; -template<> struct PropType { static const PrePropType propId = pt_RegionProp; }; -template<> struct PropType { static const PrePropType propId = pt_SymbolProp; }; -template<> struct PropType { static const PrePropType propId = pt_ThreadProp; }; -template<> struct PropType { static const PrePropType propId = pt_CartPoint3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_Vector3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_Placement3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_Matrix3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_FloatPointProp; }; -template<> struct PropType { static const PrePropType propId = pt_FloatPoint3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_FloatVector3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_TriangleProp; }; -template<> struct PropType { static const PrePropType propId = pt_QuadrangleProp; }; -template<> struct PropType { static const PrePropType propId = pt_ElementProp; }; -template<> struct PropType { static const PrePropType propId = pt_Apex3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_Polygon3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_GridProp; }; -template<> struct PropType { static const PrePropType propId = pt_MarkerProp; }; -template<> struct PropType { static const PrePropType propId = pt_Curve3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_SurfaceProp; }; -template<> struct PropType { static const PrePropType propId = pt_Point3DProp; }; -template<> struct PropType { static const PrePropType propId = pt_PointFrameProp; }; -template<> struct PropType { static const PrePropType propId = pt_WireFrameProp; }; -template<> struct PropType { static const PrePropType propId = pt_SolidProp; }; -template<> struct PropType { static const PrePropType propId = pt_InstanceProp; }; -template<> struct PropType { static const PrePropType propId = pt_AssemblyProp; }; -template<> struct PropType { static const PrePropType propId = pt_ConstraintSystem; }; -template<> struct PropType { static const PrePropType propId = pt_MeshProp; }; -template<> struct PropType { static const PrePropType propId = pt_ItemProp; }; -template<> struct PropType { static const PrePropType propId = pt_SpaceInstanceProp; }; -template<> struct PropType { static const PrePropType propId = pt_PlaneInstanceProp; }; -template<> struct PropType { static const PrePropType propId = pt_AssistingItemProp; }; -template<> struct PropType { static const PrePropType propId = pt_CollectionProp; }; -template<> struct PropType { static const PrePropType propId = pt_ModelProp; }; -template<> struct PropType { static const PrePropType propId = pt_FunctionProp; }; -template<> struct PropType { static const PrePropType propId = pt_VertexProp; }; -template<> struct PropType { static const PrePropType propId = pt_EdgeProp; }; -template<> struct PropType { static const PrePropType propId = pt_CurveEdgeProp; }; -template<> struct PropType { static const PrePropType propId = pt_OrientedEdgeProp; }; -template<> struct PropType { static const PrePropType propId = pt_LoopProp; }; -template<> struct PropType { static const PrePropType propId = pt_FaceProp; }; -template<> struct PropType { static const PrePropType propId = pt_FaceShellProp; }; -template<> struct PropType { static const PrePropType propId = pt_NameProp; }; -template<> struct PropType { static const PrePropType propId = pt_CreatorProp; }; -template<> struct PropType { static const PrePropType propId = pt_AttributeContainerProp; }; -template<> struct PropType { static const PrePropType propId = pt_AttributeProp; }; -template<> struct PropType { static const PrePropType propId = pt_AttributeActionProp; }; -template<> struct PropType { static const PrePropType propId = pt_TransactionsProp; }; -template<> struct PropType { static const PrePropType propId = pt_NamedAttributeContainerProp; }; -template<> struct PropType > { static const PrePropType propId = pt_PntMatingProp; }; -template<> struct PropType > { static const PrePropType propId = pt_Pnt3DMatingProp; }; - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойство. - \en Property. \~ - \details \ru Свойство является базовым классом для доступа к внутренним данным объектов. - Наследники свойства содержать внутренние данные объектов или их копии. - Свойства предназначены для просмотра и модификации внутренних данных объектов. - \en Property is the base class for access to internal data of objects. - Inheritors of property may contain internal data of objects or its copies. - Properties are intended for reading and changing internal data of objects. \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS MbProperty -{ -private: - MbePrompt prompt; ///< \ru Номер подсказки. \en Number of hint string. - bool changeable; ///< \ru Признак редактируемости. \en Attribute of editability. - -public: - /// \ru Конструктор. \en Constructor. - 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 Выдать значение свойства. \en Get value of the property. - virtual void _GetPropertyValue( void * v, size_t size ) const = 0; - /// \ru Установить новое значение свойства. \en Set the new value of the property. - virtual void SetPropertyValue( TCHAR * v ) = 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). - virtual void SetProperties( const MbProperties & ) {} - /// \ru Выдать подсказку. \en Get a hint. - virtual size_t GetPrompt() const { return prompt; } - /// \ru Выдать подсказку. \en Get a hint. - MbePrompt & SetPrompt() { return prompt; } - /// \ru Можно ли изменять данные. \en Is it possible to change data. - bool IsChangeable() const { return changeable; } - -OBVIOUS_PRIVATE_COPY( MbProperty ) -}; // MbProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru bool свойство. - \en Bool property. \~ - \details \ru bool свойство предназначено для просмотра и модификации данных типа bool.\n - \en Bool property is intended for reading and changing data of boolean type.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS BoolProperty : public MbProperty { -public : - bool value; ///< \ru Значение. \en Value. - - /// \ru Конструктор. \en Constructor. - BoolProperty( MbePrompt name, bool initValue, bool change = true ) - : MbProperty( name, change ) - , value( initValue ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~BoolProperty(); - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( BoolProperty ) -}; // BoolProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru int свойство. - \en Int property. \~ - \details \ru int свойство предназначено для просмотра и модификации данных типа int.\n - \en Int property is intended for reading and changing data of integer type.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS IntProperty : public MbProperty { -public : - int64 value; ///< \ru Значение. \en Value. - - /// \ru Конструктор. \en Constructor. - IntProperty( MbePrompt name, int64 initValue, bool change = true ) - : MbProperty( name, change ) - , value( (int64)initValue ) - {} - - /// \ru Деструктор. \en Destructor. - virtual ~IntProperty(); - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( IntProperty ) -}; // IntProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru uint свойство. - \en Uint property. \~ - \details \ru uint свойство предназначено для просмотра и модификации данных типа uint64.\n - \en Uint property is intended for reading and changing data of uint64 type.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS UIntProperty : public MbProperty { -public : - uint64 value; ///< \ru Значение. \en Value. - - /// \ru Конструктор. \en Constructor. - UIntProperty( MbePrompt name, size_t initValue, bool change = true ) - : MbProperty( name, change ) - , value( (uint64)initValue ) - {} - - /// \ru Деструктор. \en Destructor. - virtual ~UIntProperty(); - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( UIntProperty ) -}; // UIntProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru double свойство. - \en Double property. \~ - \details \ru double свойство предназначено для просмотра и модификации данных типа double.\n - \en Double property is intended for reading and changing data of double type.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS DoubleProperty : public MbProperty { -public : - double value; ///< \ru Значение. \en Value. - - /// \ru Конструктор. \en Constructor. - DoubleProperty( MbePrompt name, double initValue, bool change = true ) - : MbProperty( name, change ) - , value( initValue ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~DoubleProperty(); - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( DoubleProperty ) -}; // DoubleProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru double свойство с номером. - \en Double property with number. \~ - \details \ru double свойство с номером предназначено для просмотра и модификации данных типа double, имеющих порядковый номер.\n - \en Double property with number is intended for reading and changing data of double type which have number.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS NDoubleProperty : public MbProperty { -public : - double value; ///< \ru Значение. \en Value. - uint32 number; ///< \ru Номер. \en Number. - - /// \ru Конструктор. \en Constructor. - NDoubleProperty( MbePrompt name, double initValue, bool change = true, uint32 n = 0 ) - : MbProperty( name, change ) - , value( initValue ) - , number( n ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~NDoubleProperty(); - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( NDoubleProperty ) -}; // NDoubleProperty - - -//---------------------------------------------------------------------------------------- -/** \brief \ru string свойство. - \en String property. \~ - \details \ru string свойство предназначено для просмотра и модификации данных типа TCHAR *.\n - \en String property is intended for reading and changing TCHAR * like data.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS StringProperty : public MbProperty -{ - TCHAR * value; ///< \ru Значение. \en Value. - -public: - /// \ru Конструктор. \en Constructor. - 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. - 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; } - -OBVIOUS_PRIVATE_COPY(StringProperty) -}; // StringProperty - - -typedef StringProperty CharProperty; - - -//------------------------------------------------------------------------------ -/** \brief \ru Version свойство. - \en Version property. \~ - \details \ru Version свойство предназначено для просмотра и модификации данных типа VERSION.\n - \en Version property is intended for reading and changing VERSION like data.\n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS VersionProperty : public MbProperty { -public : - VERSION value; ///< \ru Значение. \en Value. - - /// \ru Конструктор. \en Constructor. - VersionProperty( MbePrompt name, VERSION initValue, bool change = true ) - : MbProperty( name, change ) - , value( initValue ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~VersionProperty() {} - - 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. - virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. - -OBVIOUS_PRIVATE_COPY( VersionProperty ) -}; // IntProperty - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать строковое значение данного свойства для данного его поля. - \en Get string value of given property for its given field. \~ - \details \ru Функция определена для случая "по умолчанию", для конкретных типов FieldType, - следует перегрузить для статического сопоставления типов компилятором.\n - \en In "default" case function is defined for explicit types FieldType, - it should be overloaded for static mapping of types by compiler.\n \~ - \ingroup Model_Properties -*/ -//--- -template -inline void GetCharValue( const PropType *, const FieldType *, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( v != NULL ); - if ( v != NULL ) { - if ( n == 0 ) { - v[0] = _T(' '); - v[1] = _T('\0'); - } - else - _sntprintf( v, 64, _T("%d\t"), n ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства двумерной точки. - \en Get properties of two-dimensional point. \~ - \details \ru Выдать свойства двумерной точки MbCartPoint.\n - \en Get properties of two-dimensional point MbCartPoint.\n \~ - \ingroup Model_Properties -*/ -//--- -template -inline void GetCharValue( const PropType *, const MbCartPoint * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { - if ( n == 0 ) - _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); - else - _sntprintf( v, 64, _T("%d %.3f\t%.3f"), n, value->x, value->y ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства двумерного вектора. - \en Get properties of two-dimensional vector. \~ - \details \ru Выдать свойства двумерного вектора MbVector.\n - \en Get properties of two-dimensional vector MbVector.\n \~ - \ingroup Model_Properties -*/ -// --- -template -inline void GetCharValue( const PropType *, const MbVector * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { - if ( n == 0 ) - _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); - else - _sntprintf( v, 64, _T("%d %.3f\t%.3f"), n, value->x, value->y ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства двумерного нормированного вектора. - \en Get properties of two-dimensional normalized vector. \~ - \details \ru Выдать свойства двумерного нормированного вектора MbDirection.\n - \en Get properties of two-dimensional normalized vector MbDirection.\n \~ - \ingroup Model_Properties -*/ -// --- -template -inline void GetCharValue( const PropType *, const MbDirection * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { - double angle(0.0); - if ( value->ax==0 && value->ay==0 ) - angle = 0.0; - else - angle = 180 / M_PI * atan2( value->ay, value->ax ); - if ( n == 0 ) - _sntprintf( v, 64, _T("%.3f\t"), angle ); - else - _sntprintf( v, 64, _T("%d %.3f\t"), n, angle ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства трёхмерной точки. - \en Get properties of three-dimensional point. \~ - \details \ru Выдать свойства трёхмерной точки MbCartPoint3D.\n - \en Get properties of three-dimensional point MbCartPoint3D.\n \~ - \ingroup Model_Properties -*/ -// --- -template -inline void GetCharValue( const PropType *, const MbCartPoint3D * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { - if ( n == 0 ) - _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); - else - _sntprintf( v, 64, _T("%d %.3f\t%.3f\t%.3f"), n, value->x, value->y, value->z ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства трёхмерного вектора. - \en Get properties of three-dimensional vector. \~ - \details \ru Выдать свойства трёхмерного вектора MbVector3D.\n - \en Get properties of three-dimensional vector MbVector3D.\n \~ - \ingroup Model_Properties -*/ -// --- -template -inline void GetCharValue( const PropType *, const MbVector3D * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( value != NULL && v != NULL ); - if ( value != NULL && v != NULL ) { - if ( n == 0 ) - _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); - else - _sntprintf( v, 64, _T("%d %.3f\t%.3f\t%.3f"), n, value->x, value->y, value->z ); - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Выдать свойства имени объекта. - \en Get properties of object name. \~ - \details \ru Выдать свойства имени объекта MbName.\n - \en Get properties of object name MbName.\n \~ - \ingroup Model_Properties -*/ -// --- -template -inline void GetCharValue( const PropType *, const MbName * value, uint32 n, TCHAR * v ) -{ - C3D_ASSERT( v != NULL ); - if ( v != NULL ) { - if ( value != NULL ) { - c3d::string_t str; - value->ToString( str ); - - if ( n !=0 ) { - _sntprintf( v, 64, _T("%d "), n ); - _tcscat( v, str.c_str() ); - } - else { - _tcscpy( v, str.c_str() ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойство объекта. - \en The property of the object. \~ - \details \ru Обертка, реализующая свойство объекта с настройкой владения ним.\n - \en Wrapper that implements property of an object with its ownership setting.\n \~ - \ingroup Model_Properties -*/ -// --- -template -class MathItemProperty : public MbProperty { -public : - Type * value; ///< \ru Объект. \en Object. - uint32 number; ///< \ru Номер. \en Number. - -public : - /// \ru Конструктор. \en Constructor. - MathItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) - : MbProperty( name, change ) - , value( initValue ) - , number( n ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~MathItemProperty() {} - -public : - // \ru Выдать тип свойства. \en Get type of property. - virtual PrePropType IsA() const { return PropType::propId; } - // \ru Выдать строковое значение свойства. \en Get string value of the property. - virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, value, number, v ); } - // \ru Выдать свойства неатомарного объекта. \en Get properties of the non-atomic object. - virtual void GetProperties( MbProperties & ); - // \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. - virtual void SetProperties( const MbProperties & ); - // \ru Выдать значение свойства. \en Get value of the property. - virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = value; } - // \ru Установить новое значение свойства. \en Set the new value of the property. - virtual void SetPropertyValue( TCHAR * ) {} - -OBVIOUS_PRIVATE_COPY( MathItemProperty ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойство объекта. -\en The property of the object. \~ -\details \ru Обертка, реализующая свойство объекта с настройкой владения ним.\n -\en Wrapper that implements property of an object with its ownership setting.\n \~ -\ingroup Model_Properties -*/ -// --- -template -class MathItemCopyProperty : public MbProperty { -public: - Type value; ///< \ru Объект. \en Object. - uint32 number; ///< \ru Номер. \en Number. - -public: - /// \ru Конструктор. \en Constructor. - MathItemCopyProperty( MbePrompt name, const Type & initValue, bool change, uint32 n = 0 ) - : MbProperty( name, change ) - , value( initValue ) - , number( n ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~MathItemCopyProperty() {} - -public: - // \ru Выдать тип свойства. \en Get type of property. - virtual PrePropType IsA() const { return PropType::propId; } - // \ru Выдать строковое значение свойства. \en Get string value of the property. - virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, &value, number, v ); } - // \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. - virtual void GetProperties( MbProperties & ); - // \ru Выдать значение свойства. \en Get value of the property. - virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = const_cast(&value); } - // \ru Установить новое значение свойства. \en Set the new value of the property. - virtual void SetPropertyValue( TCHAR * ) {} - -OBVIOUS_PRIVATE_COPY( MathItemCopyProperty ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Cвойство объекта. - \en The property of the object. \~ - \details \ru Обертка, реализующая свойство объекта со счетчиком ссылок.\n - \en Wrapper that implements property of an object with reference counter.\n \~ - \ingroup Model_Properties -*/ -// --- -template -class RefItemProperty : public MbProperty { -public : - SPtr value; ///< \ru Объект. \en Object. - uint32 number; ///< \ru Номер. \en Number. - -public : - /// \ru Конструктор. \en Constructor. - RefItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) - : MbProperty( name, change ) - , value ( initValue ) - , number( n ) - {} - /// \ru Деструктор. \en Destructor. - virtual ~RefItemProperty() {} - - // \ru Выдать тип свойства. \en Get type of property. - virtual PrePropType IsA() const { return PropType::propId; } - // \ru Выдать строковое значение свойства. \en Get string value of the property. - virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, value.get(), number, v ); } - // \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. - virtual void GetProperties( MbProperties & ); - // \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. - virtual void SetProperties( const MbProperties & ); - // \ru Выдать значение свойства. \en Get value of the property. - virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = value.get(); } - // \ru Установить новое значение свойства. \en Set the new value of the property. - virtual void SetPropertyValue( TCHAR * ) {} - -OBVIOUS_PRIVATE_COPY( RefItemProperty ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Множество свойств объекта. - \en Set of object properties. \~ - \details \ru Множество свойств объекта представляет собой контейнер, вызывающий деструктор своих элементов. \n - \en Set of object properties is container that calls destructor of its elements. \n \~ - \ingroup Model_Properties -*/ -// --- -class MATH_CLASS MbProperties : public PArray -{ - MbePrompt name; ///< \ru Имя объекта. \en A name of an object. - -public: - /// \ru Конструктор. \en Constructor. - MbProperties() - : PArray() - , name( IDS_ITEM_0000 ) {} - -public: - /// \ru Выдать имя объекта. \en Get name of object. - MbePrompt & SetName() { return name; } - /// \ru Выдать имя объекта. \en Get name of object. - 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. - void SetName( MbePrompt s ) { name = s; } - /// \ru Установить имя объекта. \en Set name of the object. - 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; - -OBVIOUS_PRIVATE_COPY( MbProperties ) -}; // MbProperties - -//---------------------------------------------------------------------------------------- -// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. -//--- -template -void MathItemProperty::GetProperties( MbProperties & props ) -{ - if ( value ) - value->GetProperties( props ); -} - -//---------------------------------------------------------------------------------------- -// \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. -//--- -template -void MathItemProperty::SetProperties( const MbProperties & props ) -{ - if ( value ) - value->SetProperties( props ); -} - -//---------------------------------------------------------------------------------------- -// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. -//--- -template -void MathItemCopyProperty::GetProperties( MbProperties & props ) -{ - value.GetProperties( props ); -} - -//---------------------------------------------------------------------------------------- -// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. -//--- -template -void RefItemProperty::GetProperties( MbProperties & props ) -{ - if ( value ) - value->GetProperties( props ); -} - -//---------------------------------------------------------------------------------------- -// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. -//--- -template -void RefItemProperty::SetProperties( const MbProperties & props ) -{ - if ( value ) - value->SetProperties( props ); -} - - -#endif // __PROPERTY_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Свойства математических объектов. + \en Properties of mathematical objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_PROPERTY_H +#define __MB_PROPERTY_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define GET_PROPERTY_VALUE( v ) _GetPropertyValue( &(v), sizeof(v) ) + + +class MbAttribute; +class MbCurve; +class MbCurve3D; +class MbMultiline; +class MbMatrix3D; +class MbFloatPoint; +class MbFloatPoint3D; +class MbFloatVector3D; +class MbTriangle; +class MbQuadrangle; +class MbElement; +class MbApex3D; +class MbPolygon3D; +class MbGrid; +class MbNamedAttributeContainer; +class MbPlacement3D; +class MbMarker; +class MbSurface; +class MbPoint3D; +class MbPointFrame; +class MbWireFrame; +class MbSolid; +class MbInstance; +class MbAssembly; +class MbConstraintSystem; +class MbMesh; +class MbItem; +class MbSpaceInstance; +class MbPlaneInstance; +class MbAssistingItem; +class MbCollection; +class MbModel; +class MbRegion; +class MbDirection; +class MbPlacement; +class MbMatrix; +class MbMultiline; +class MbRegion; +class MbSymbol; +class MbThread; +class MbFunction; +class MbVertex; +class MbEdge; +class MbCurveEdge; +class MbOrientedEdge; +class MbLoop; +class MbFace; +class MbFaceShell; +class MbName; +class MbCreator; +class MbAttributeContainer; +class MbAttributeAction; +class MbTransactions; +template +class MbPntMatingData; +class MbProperties; + + +//---------------------------------------------------------------------------------------- + /** \brief \ru Типы свойств. + \en Types of properties. \~ + \details \ru Типы свойств. \n + Свойства дают доступ к внутренним данным объектов. + \en Types of properties. \n + Properties give access to internal data of objects. \~ + \ingroup Geometric_Items + */ +// --- +enum PrePropType +{ + pt_UndefinedProp, ///< \ru Свойство неизвестного типа данных. \en Property of unknown datatype. \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 + + // \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 + + // \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 + + // \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 + + // \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 + + // \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_LastPropType, ///< \ru Последний тип свойства, все остальные добавлять перед ним. \en Last type of property, any other ones must be added before. +}; + + +//----------------------------------------------------------------------------- +/// \ru Структура соответствия типа объекта и типа свойства. \en Object type and property type correspondence structure. +//--- +template +struct PropType { static const PrePropType propId = pt_UndefinedProp; }; + + +//----------------------------------------------------------------------------- +// \ru Специализация шаблона PropType - организует таблицу соответствий \en PropType template specialization - organizes lookup table +//--- +template<> struct PropType { static const PrePropType propId = pt_CartPointProp; }; +template<> struct PropType { static const PrePropType propId = pt_VectorProp; }; +template<> struct PropType { static const PrePropType propId = pt_DirectionProp; }; +template<> struct PropType { static const PrePropType propId = pt_PlacementProp; }; +template<> struct PropType { static const PrePropType propId = pt_MatrixProp; }; +template<> struct PropType { static const PrePropType propId = pt_CurveProp; }; +template<> struct PropType { static const PrePropType propId = pt_MultilineProp; }; +template<> struct PropType { static const PrePropType propId = pt_RegionProp; }; +template<> struct PropType { static const PrePropType propId = pt_SymbolProp; }; +template<> struct PropType { static const PrePropType propId = pt_ThreadProp; }; +template<> struct PropType { static const PrePropType propId = pt_CartPoint3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_Vector3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_Placement3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_Matrix3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_FloatPointProp; }; +template<> struct PropType { static const PrePropType propId = pt_FloatPoint3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_FloatVector3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_TriangleProp; }; +template<> struct PropType { static const PrePropType propId = pt_QuadrangleProp; }; +template<> struct PropType { static const PrePropType propId = pt_ElementProp; }; +template<> struct PropType { static const PrePropType propId = pt_Apex3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_Polygon3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_GridProp; }; +template<> struct PropType { static const PrePropType propId = pt_MarkerProp; }; +template<> struct PropType { static const PrePropType propId = pt_Curve3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_SurfaceProp; }; +template<> struct PropType { static const PrePropType propId = pt_Point3DProp; }; +template<> struct PropType { static const PrePropType propId = pt_PointFrameProp; }; +template<> struct PropType { static const PrePropType propId = pt_WireFrameProp; }; +template<> struct PropType { static const PrePropType propId = pt_SolidProp; }; +template<> struct PropType { static const PrePropType propId = pt_InstanceProp; }; +template<> struct PropType { static const PrePropType propId = pt_AssemblyProp; }; +template<> struct PropType { static const PrePropType propId = pt_ConstraintSystem; }; +template<> struct PropType { static const PrePropType propId = pt_MeshProp; }; +template<> struct PropType { static const PrePropType propId = pt_ItemProp; }; +template<> struct PropType { static const PrePropType propId = pt_SpaceInstanceProp; }; +template<> struct PropType { static const PrePropType propId = pt_PlaneInstanceProp; }; +template<> struct PropType { static const PrePropType propId = pt_AssistingItemProp; }; +template<> struct PropType { static const PrePropType propId = pt_CollectionProp; }; +template<> struct PropType { static const PrePropType propId = pt_ModelProp; }; +template<> struct PropType { static const PrePropType propId = pt_FunctionProp; }; +template<> struct PropType { static const PrePropType propId = pt_VertexProp; }; +template<> struct PropType { static const PrePropType propId = pt_EdgeProp; }; +template<> struct PropType { static const PrePropType propId = pt_CurveEdgeProp; }; +template<> struct PropType { static const PrePropType propId = pt_OrientedEdgeProp; }; +template<> struct PropType { static const PrePropType propId = pt_LoopProp; }; +template<> struct PropType { static const PrePropType propId = pt_FaceProp; }; +template<> struct PropType { static const PrePropType propId = pt_FaceShellProp; }; +template<> struct PropType { static const PrePropType propId = pt_NameProp; }; +template<> struct PropType { static const PrePropType propId = pt_CreatorProp; }; +template<> struct PropType { static const PrePropType propId = pt_AttributeContainerProp; }; +template<> struct PropType { static const PrePropType propId = pt_AttributeProp; }; +template<> struct PropType { static const PrePropType propId = pt_AttributeActionProp; }; +template<> struct PropType { static const PrePropType propId = pt_TransactionsProp; }; +template<> struct PropType { static const PrePropType propId = pt_NamedAttributeContainerProp; }; +template<> struct PropType > { static const PrePropType propId = pt_PntMatingProp; }; +template<> struct PropType > { static const PrePropType propId = pt_Pnt3DMatingProp; }; + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойство. + \en Property. \~ + \details \ru Свойство является базовым классом для доступа к внутренним данным объектов. + Наследники свойства содержать внутренние данные объектов или их копии. + Свойства предназначены для просмотра и модификации внутренних данных объектов. + \en Property is the base class for access to internal data of objects. + Inheritors of property may contain internal data of objects or its copies. + Properties are intended for reading and changing internal data of objects. \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS MbProperty +{ +private: + MbePrompt prompt; ///< \ru Номер подсказки. \en Number of hint string. + bool changeable; ///< \ru Признак редактируемости. \en Attribute of editability. + +public: + /// \ru Конструктор. \en Constructor. + 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 Выдать значение свойства. \en Get value of the property. + virtual void _GetPropertyValue( void * v, size_t size ) const = 0; + /// \ru Установить новое значение свойства. \en Set the new value of the property. + virtual void SetPropertyValue( TCHAR * v ) = 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). + virtual void SetProperties( const MbProperties & ) {} + /// \ru Выдать подсказку. \en Get a hint. + virtual size_t GetPrompt() const { return prompt; } + /// \ru Выдать подсказку. \en Get a hint. + MbePrompt & SetPrompt() { return prompt; } + /// \ru Можно ли изменять данные. \en Is it possible to change data. + bool IsChangeable() const { return changeable; } + +OBVIOUS_PRIVATE_COPY( MbProperty ) +}; // MbProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru bool свойство. + \en Bool property. \~ + \details \ru bool свойство предназначено для просмотра и модификации данных типа bool.\n + \en Bool property is intended for reading and changing data of boolean type.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS BoolProperty : public MbProperty { +public : + bool value; ///< \ru Значение. \en Value. + + /// \ru Конструктор. \en Constructor. + BoolProperty( MbePrompt name, bool initValue, bool change = true ) + : MbProperty( name, change ) + , value( initValue ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~BoolProperty(); + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( BoolProperty ) +}; // BoolProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru int свойство. + \en Int property. \~ + \details \ru int свойство предназначено для просмотра и модификации данных типа int.\n + \en Int property is intended for reading and changing data of integer type.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS IntProperty : public MbProperty { +public : + int64 value; ///< \ru Значение. \en Value. + + /// \ru Конструктор. \en Constructor. + IntProperty( MbePrompt name, int64 initValue, bool change = true ) + : MbProperty( name, change ) + , value( (int64)initValue ) + {} + + /// \ru Деструктор. \en Destructor. + virtual ~IntProperty(); + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( IntProperty ) +}; // IntProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru uint свойство. + \en Uint property. \~ + \details \ru uint свойство предназначено для просмотра и модификации данных типа uint64.\n + \en Uint property is intended for reading and changing data of uint64 type.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS UIntProperty : public MbProperty { +public : + uint64 value; ///< \ru Значение. \en Value. + + /// \ru Конструктор. \en Constructor. + UIntProperty( MbePrompt name, size_t initValue, bool change = true ) + : MbProperty( name, change ) + , value( (uint64)initValue ) + {} + + /// \ru Деструктор. \en Destructor. + virtual ~UIntProperty(); + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( UIntProperty ) +}; // UIntProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru double свойство. + \en Double property. \~ + \details \ru double свойство предназначено для просмотра и модификации данных типа double.\n + \en Double property is intended for reading and changing data of double type.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS DoubleProperty : public MbProperty { +public : + double value; ///< \ru Значение. \en Value. + + /// \ru Конструктор. \en Constructor. + DoubleProperty( MbePrompt name, double initValue, bool change = true ) + : MbProperty( name, change ) + , value( initValue ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~DoubleProperty(); + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( DoubleProperty ) +}; // DoubleProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru double свойство с номером. + \en Double property with number. \~ + \details \ru double свойство с номером предназначено для просмотра и модификации данных типа double, имеющих порядковый номер.\n + \en Double property with number is intended for reading and changing data of double type which have number.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS NDoubleProperty : public MbProperty { +public : + double value; ///< \ru Значение. \en Value. + uint32 number; ///< \ru Номер. \en Number. + + /// \ru Конструктор. \en Constructor. + NDoubleProperty( MbePrompt name, double initValue, bool change = true, uint32 n = 0 ) + : MbProperty( name, change ) + , value( initValue ) + , number( n ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~NDoubleProperty(); + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( NDoubleProperty ) +}; // NDoubleProperty + + +//---------------------------------------------------------------------------------------- +/** \brief \ru string свойство. + \en String property. \~ + \details \ru string свойство предназначено для просмотра и модификации данных типа TCHAR *.\n + \en String property is intended for reading and changing TCHAR * like data.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS StringProperty : public MbProperty +{ + TCHAR * value; ///< \ru Значение. \en Value. + +public: + /// \ru Конструктор. \en Constructor. + 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. + 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; } + +OBVIOUS_PRIVATE_COPY(StringProperty) +}; // StringProperty + + +typedef StringProperty CharProperty; + + +//------------------------------------------------------------------------------ +/** \brief \ru Version свойство. + \en Version property. \~ + \details \ru Version свойство предназначено для просмотра и модификации данных типа VERSION.\n + \en Version property is intended for reading and changing VERSION like data.\n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS VersionProperty : public MbProperty { +public : + VERSION value; ///< \ru Значение. \en Value. + + /// \ru Конструктор. \en Constructor. + VersionProperty( MbePrompt name, VERSION initValue, bool change = true ) + : MbProperty( name, change ) + , value( initValue ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~VersionProperty() {} + + 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. + virtual void SetPropertyValue( TCHAR * v ); // \ru Установить новое значение свойства. \en Set the new value of the property. + +OBVIOUS_PRIVATE_COPY( VersionProperty ) +}; // IntProperty + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать строковое значение данного свойства для данного его поля. + \en Get string value of given property for its given field. \~ + \details \ru Функция определена для случая "по умолчанию", для конкретных типов FieldType, + следует перегрузить для статического сопоставления типов компилятором.\n + \en In "default" case function is defined for explicit types FieldType, + it should be overloaded for static mapping of types by compiler.\n \~ + \ingroup Model_Properties +*/ +//--- +template +inline void GetCharValue( const PropType *, const FieldType *, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( v != NULL ); + if ( v != NULL ) { + if ( n == 0 ) { + v[0] = _T(' '); + v[1] = _T('\0'); + } + else + _sntprintf( v, 64, _T("%d\t"), n ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства двумерной точки. + \en Get properties of two-dimensional point. \~ + \details \ru Выдать свойства двумерной точки MbCartPoint.\n + \en Get properties of two-dimensional point MbCartPoint.\n \~ + \ingroup Model_Properties +*/ +//--- +template +inline void GetCharValue( const PropType *, const MbCartPoint * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( value != NULL && v != NULL ); + if ( value != NULL && v != NULL ) { + if ( n == 0 ) + _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); + else + _sntprintf( v, 64, _T("%d %.3f\t%.3f"), n, value->x, value->y ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства двумерного вектора. + \en Get properties of two-dimensional vector. \~ + \details \ru Выдать свойства двумерного вектора MbVector.\n + \en Get properties of two-dimensional vector MbVector.\n \~ + \ingroup Model_Properties +*/ +// --- +template +inline void GetCharValue( const PropType *, const MbVector * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( value != NULL && v != NULL ); + if ( value != NULL && v != NULL ) { + if ( n == 0 ) + _sntprintf( v, 64, _T("%.3f\t%.3f"), value->x, value->y ); + else + _sntprintf( v, 64, _T("%d %.3f\t%.3f"), n, value->x, value->y ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства двумерного нормированного вектора. + \en Get properties of two-dimensional normalized vector. \~ + \details \ru Выдать свойства двумерного нормированного вектора MbDirection.\n + \en Get properties of two-dimensional normalized vector MbDirection.\n \~ + \ingroup Model_Properties +*/ +// --- +template +inline void GetCharValue( const PropType *, const MbDirection * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( value != NULL && v != NULL ); + if ( value != NULL && v != NULL ) { + double angle(0.0); + if ( value->ax==0 && value->ay==0 ) + angle = 0.0; + else + angle = 180 / M_PI * atan2( value->ay, value->ax ); + if ( n == 0 ) + _sntprintf( v, 64, _T("%.3f\t"), angle ); + else + _sntprintf( v, 64, _T("%d %.3f\t"), n, angle ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства трёхмерной точки. + \en Get properties of three-dimensional point. \~ + \details \ru Выдать свойства трёхмерной точки MbCartPoint3D.\n + \en Get properties of three-dimensional point MbCartPoint3D.\n \~ + \ingroup Model_Properties +*/ +// --- +template +inline void GetCharValue( const PropType *, const MbCartPoint3D * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( value != NULL && v != NULL ); + if ( value != NULL && v != NULL ) { + if ( n == 0 ) + _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); + else + _sntprintf( v, 64, _T("%d %.3f\t%.3f\t%.3f"), n, value->x, value->y, value->z ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства трёхмерного вектора. + \en Get properties of three-dimensional vector. \~ + \details \ru Выдать свойства трёхмерного вектора MbVector3D.\n + \en Get properties of three-dimensional vector MbVector3D.\n \~ + \ingroup Model_Properties +*/ +// --- +template +inline void GetCharValue( const PropType *, const MbVector3D * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( value != NULL && v != NULL ); + if ( value != NULL && v != NULL ) { + if ( n == 0 ) + _sntprintf( v, 64, _T("%.3f\t%.3f\t%.3f"), value->x, value->y, value->z ); + else + _sntprintf( v, 64, _T("%d %.3f\t%.3f\t%.3f"), n, value->x, value->y, value->z ); + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Выдать свойства имени объекта. + \en Get properties of object name. \~ + \details \ru Выдать свойства имени объекта MbName.\n + \en Get properties of object name MbName.\n \~ + \ingroup Model_Properties +*/ +// --- +template +inline void GetCharValue( const PropType *, const MbName * value, uint32 n, TCHAR * v ) +{ + C3D_ASSERT( v != NULL ); + if ( v != NULL ) { + if ( value != NULL ) { + c3d::string_t str; + value->ToString( str ); + + if ( n !=0 ) { + _sntprintf( v, 64, _T("%d "), n ); + _tcscat( v, str.c_str() ); + } + else { + _tcscpy( v, str.c_str() ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойство объекта. + \en The property of the object. \~ + \details \ru Обертка, реализующая свойство объекта с настройкой владения ним.\n + \en Wrapper that implements property of an object with its ownership setting.\n \~ + \ingroup Model_Properties +*/ +// --- +template +class MathItemProperty : public MbProperty { +public : + Type * value; ///< \ru Объект. \en Object. + uint32 number; ///< \ru Номер. \en Number. + +public : + /// \ru Конструктор. \en Constructor. + MathItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) + : MbProperty( name, change ) + , value( initValue ) + , number( n ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~MathItemProperty() {} + +public : + // \ru Выдать тип свойства. \en Get type of property. + virtual PrePropType IsA() const { return PropType::propId; } + // \ru Выдать строковое значение свойства. \en Get string value of the property. + virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, value, number, v ); } + // \ru Выдать свойства неатомарного объекта. \en Get properties of the non-atomic object. + virtual void GetProperties( MbProperties & ); + // \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. + virtual void SetProperties( const MbProperties & ); + // \ru Выдать значение свойства. \en Get value of the property. + virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = value; } + // \ru Установить новое значение свойства. \en Set the new value of the property. + virtual void SetPropertyValue( TCHAR * ) {} + +OBVIOUS_PRIVATE_COPY( MathItemProperty ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойство объекта. +\en The property of the object. \~ +\details \ru Обертка, реализующая свойство объекта с настройкой владения ним.\n +\en Wrapper that implements property of an object with its ownership setting.\n \~ +\ingroup Model_Properties +*/ +// --- +template +class MathItemCopyProperty : public MbProperty { +public: + Type value; ///< \ru Объект. \en Object. + uint32 number; ///< \ru Номер. \en Number. + +public: + /// \ru Конструктор. \en Constructor. + MathItemCopyProperty( MbePrompt name, const Type & initValue, bool change, uint32 n = 0 ) + : MbProperty( name, change ) + , value( initValue ) + , number( n ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~MathItemCopyProperty() {} + +public: + // \ru Выдать тип свойства. \en Get type of property. + virtual PrePropType IsA() const { return PropType::propId; } + // \ru Выдать строковое значение свойства. \en Get string value of the property. + virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, &value, number, v ); } + // \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. + virtual void GetProperties( MbProperties & ); + // \ru Выдать значение свойства. \en Get value of the property. + virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = const_cast(&value); } + // \ru Установить новое значение свойства. \en Set the new value of the property. + virtual void SetPropertyValue( TCHAR * ) {} + +OBVIOUS_PRIVATE_COPY( MathItemCopyProperty ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Cвойство объекта. + \en The property of the object. \~ + \details \ru Обертка, реализующая свойство объекта со счетчиком ссылок.\n + \en Wrapper that implements property of an object with reference counter.\n \~ + \ingroup Model_Properties +*/ +// --- +template +class RefItemProperty : public MbProperty { +public : + SPtr value; ///< \ru Объект. \en Object. + uint32 number; ///< \ru Номер. \en Number. + +public : + /// \ru Конструктор. \en Constructor. + RefItemProperty( MbePrompt name, Type * initValue, bool change, uint32 n = 0 ) + : MbProperty( name, change ) + , value ( initValue ) + , number( n ) + {} + /// \ru Деструктор. \en Destructor. + virtual ~RefItemProperty() {} + + // \ru Выдать тип свойства. \en Get type of property. + virtual PrePropType IsA() const { return PropType::propId; } + // \ru Выдать строковое значение свойства. \en Get string value of the property. + virtual void GetCharValue( TCHAR * v ) const { ::GetCharValue( this, value.get(), number, v ); } + // \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. + virtual void GetProperties( MbProperties & ); + // \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. + virtual void SetProperties( const MbProperties & ); + // \ru Выдать значение свойства. \en Get value of the property. + virtual void _GetPropertyValue( void * v, size_t /*size*/ ) const { *(Type**)v = value.get(); } + // \ru Установить новое значение свойства. \en Set the new value of the property. + virtual void SetPropertyValue( TCHAR * ) {} + +OBVIOUS_PRIVATE_COPY( RefItemProperty ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Множество свойств объекта. + \en Set of object properties. \~ + \details \ru Множество свойств объекта представляет собой контейнер, вызывающий деструктор своих элементов. \n + \en Set of object properties is container that calls destructor of its elements. \n \~ + \ingroup Model_Properties +*/ +// --- +class MATH_CLASS MbProperties : public PArray +{ + MbePrompt name; ///< \ru Имя объекта. \en A name of an object. + +public: + /// \ru Конструктор. \en Constructor. + MbProperties() + : PArray() + , name( IDS_ITEM_0000 ) {} + +public: + /// \ru Выдать имя объекта. \en Get name of object. + MbePrompt & SetName() { return name; } + /// \ru Выдать имя объекта. \en Get name of object. + 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. + void SetName( MbePrompt s ) { name = s; } + /// \ru Установить имя объекта. \en Set name of the object. + 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; + +OBVIOUS_PRIVATE_COPY( MbProperties ) +}; // MbProperties + +//---------------------------------------------------------------------------------------- +// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. +//--- +template +void MathItemProperty::GetProperties( MbProperties & props ) +{ + if ( value ) + value->GetProperties( props ); +} + +//---------------------------------------------------------------------------------------- +// \ru Задать свойства неатомарного объекта объекта. \en Set properties of the non-atomic object. +//--- +template +void MathItemProperty::SetProperties( const MbProperties & props ) +{ + if ( value ) + value->SetProperties( props ); +} + +//---------------------------------------------------------------------------------------- +// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. +//--- +template +void MathItemCopyProperty::GetProperties( MbProperties & props ) +{ + value.GetProperties( props ); +} + +//---------------------------------------------------------------------------------------- +// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. +//--- +template +void RefItemProperty::GetProperties( MbProperties & props ) +{ + if ( value ) + value->GetProperties( props ); +} + +//---------------------------------------------------------------------------------------- +// \ru Выдать свойства неатомарного объекта объекта. \en Get properties of the non-atomic object. +//--- +template +void RefItemProperty::SetProperties( const MbProperties & props ) +{ + if ( value ) + value->SetProperties( props ); +} + + +#endif // __PROPERTY_H diff --git a/C3d/Include/mb_property_title.h b/C3d/Include/mb_property_title.h index 2973de4..deedaef 100644 --- a/C3d/Include/mb_property_title.h +++ b/C3d/Include/mb_property_title.h @@ -1,1173 +1,1216 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Свойства математических объектов. - \en Properties of mathematical objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MB_PROPERTY_TITLE_H -#define __MB_PROPERTY_TITLE_H - - -//------------------------------------------------------------------------------ -/** \brief \ru Свойства математических объектов. - \en Properties of mathematical objects. \~ - \attention \ru Целочисленные значения данного перечислительного типа могут быть изменены! - \en Integer values of the enum can be changed! - \ingroup Base_Items -*/ -// --- -enum MbePrompt -{ - IDS_ITEM_0000 = 0, ///< \ru Неопределенный объект. - -// \ru Базовые объекты двумерной математики. \en Base 2D objects. - - IDS_ITEM_0001, ///< \ru Двумерная точка. \en A two-dimensional point. - IDS_ITEM_0002, ///< \ru Двумерный вектор. \en Two-dimensional vector. - IDS_ITEM_0003, ///< \ru Двумерная матрица преобразования. \en Two-dimensional matrix of transformation. - IDS_ITEM_0004, ///< \ru Двумерная локальная система. \en Two-dimensional local system. - IDS_ITEM_0005, ///< \ru Двумерный единичный вектор. \en Two-dimensional unit vector - -// \ru Типы двумерных кривых. \en Types of two-dimensional curves. - - IDS_ITEM_0011, ///< \ru Двумерная кривая. \en Two-dimensional curve - - IDS_ITEM_0013, ///< \ru Двумерная прямая. \en Two-dimensional line. - IDS_ITEM_0014, ///< \ru Двумерный отрезок. \en Two-dimensional segment. - IDS_ITEM_0015, ///< \ru Двумерный отрезок прямой. \en Two-dimensional line segment. - IDS_ITEM_0016, ///< \ru Двумерная дуга окружности. \en Two-dimensional circular arc. - IDS_ITEM_0017, ///< \ru Двумерная усеченная кривая. \en Two-dimensional truncated curve. - IDS_ITEM_0018, ///< \ru Двумерная эквидистантная кривая. \en Two-dimensional offset curve. - IDS_ITEM_0019, ///< \ru Двумерная эквидистанта. \en Two-dimensional equidistant. - IDS_ITEM_0020, ///< \ru Двумерная окружность. \en Two-dimensional circle. - IDS_ITEM_0021, ///< \ru Двумерный эллипс. \en Two-dimensional ellipse. - IDS_ITEM_0022, ///< \ru Двумерная парабола. \en Two-dimensional parabola. - IDS_ITEM_0023, ///< \ru Двумерная дуга эллипса. \en Two-dimensional elliptical arc. - IDS_ITEM_0024, ///< \ru Двумерная ломаная. \en Two-dimensional polyline. - IDS_ITEM_0025, ///< \ru Двумерная NURBS кривая. \en Two-dimensional NURBS curve. - IDS_ITEM_0026, ///< \ru Двумерный сплайн Эрмита. \en Two-dimensional Hermite spline. - IDS_ITEM_0027, ///< \ru Двумерный сплайн Безье. \en Two-dimensional Bezier spline. - IDS_ITEM_0028, ///< \ru Двумерный кубический сплайн. \en Two-dimensional cubic spline. - IDS_ITEM_0029, ///< \ru Двумерная репараметризованная кривая. \en Two-dimensional reparametrized curve. - IDS_ITEM_0030, ///< \ru Двумерный контур. \en Two-dimensional contour. - IDS_ITEM_0031, ///< \ru Двумерная косинусоида. \en Two-dimensional cosine curve. - IDS_ITEM_0032, ///< \ru Двумерная точечная кривая. \en Two-dimensional point curve. - IDS_ITEM_0040, ///< \ru Двумерная область. \en Two-dimensional region. - IDS_ITEM_0050, ///< \ru Двумерный объект. \en Two-dimensional object. - IDS_ITEM_0051, ///< \ru Двумерная мультилиния. \en Two-dimensional multiline. - IDS_ITEM_0052, ///< \ru Двумерная кривая на конусе, соответствующая кривой на коническом изгибе плоскости. \en Two-dimensional curve on cone corresponding to a curve on conic bend of a plane. - IDS_ITEM_0053, ///< \ru Двумерная кривая на плоскости, соответствующая кривой на изгибе конуса. \en Two-dimensional curve on plane corresponding to a curve on a bend of cone - IDS_ITEM_0054, ///< \ru Двумерная кривая, координатные функции которой заданы в символьном виде. \en Functionally defined two-dimensional curve. - IDS_ITEM_0055, ///< \ru Образ трехмерной кривой на поверхности при движении по направляющей. \en Image of a three-dimensional curve on surface while moving along the guide curve. - -// \ru Типы полигональных объектов. \en Types of simplified forms of an object. - - IDS_ITEM_0060, ///< \ru Параметр. \en Parameter. - IDS_ITEM_0061, ///< \ru Вершина. \en Vertex. - IDS_ITEM_0062, ///< \ru Нормаль. \en Normal. - IDS_ITEM_0063, ///< \ru Треугольник. \en Triangle. - IDS_ITEM_0064, ///< \ru Четырехугольник. \en Quadrangle. - IDS_ITEM_0071, ///< \ru Полигональный объект на числах double. \en Polygonal object on double data. - IDS_ITEM_0072, ///< \ru Апекс на числах double. \en Apex on double data. - IDS_ITEM_0073, ///< \ru Полигон на числах double. \en Polygon on double data. - IDS_ITEM_0074, ///< \ru Триангуляция на числах double. \en Triangulation on double data. - IDS_ITEM_0075, ///< \ru Полигональный объект на числах float. \en Polygonal object on float data. - IDS_ITEM_0076, ///< \ru Апекс на числах float. \en Apex on float data. - IDS_ITEM_0077, ///< \ru Полигон на числах float. \en Polygon on float data. - IDS_ITEM_0078, ///< \ru Триангуляция на числах float. \en Triangulation on float data. - -// \ru Базовые объекты трехмерной математики. \en Base objects of three-dimensional mathematics. - - IDS_ITEM_0101, ///< \ru Точка. \en Point. - IDS_ITEM_0102, ///< \ru Вектор. \en Vector. - IDS_ITEM_0103, ///< \ru Матрица преобразования. \en Transformation matrix. - IDS_ITEM_0104, ///< \ru Локальная система координат. \en Local coordinate system. - -// \ru Типы функций \en Types of functions - - IDS_ITEM_0111, ///< \ru Kонстантная функция. \en Constant function. - IDS_ITEM_0112, ///< \ru Линейная функция. \en Linear function. - IDS_ITEM_0113, ///< \ru Kубическая функция. \en Cubic function. - IDS_ITEM_0114, ///< \ru Kубическай сплайн-функция. \en Cubic spline function. - IDS_ITEM_0115, ///< \ru Символьная функция. \en Symbolic function. - IDS_ITEM_0116, ///< \ru Степенная функция. \en Power function. - IDS_ITEM_0117, ///< \ru Синус функция. \en Sinus function. - -// \ru Типы трехмерных кривы.х \en Types of three-dimensional curves. - - IDS_ITEM_0201, ///< \ru Кривая. \en Curve. - IDS_ITEM_0202, ///< \ru B-сплайн. \en B-spline. - IDS_ITEM_0213, ///< \ru Прямая линия. \en Straight line. - IDS_ITEM_0214, ///< \ru Отрезок. \en Segment. - IDS_ITEM_0215, ///< \ru Дуга эллипса. \en Elliptic arc. - IDS_ITEM_0216, ///< \ru Дуга окружности. \en Circular arc. - IDS_ITEM_0217, ///< \ru Усеченная кривая. \en Truncated curve. - IDS_ITEM_0218, ///< \ru Эквидистантная кривая. \en Offset curve. - IDS_ITEM_0219, ///< \ru Коническая спираль. \en Conical spiral. - IDS_ITEM_0220, ///< \ru Oкружность. \en Circle. - IDS_ITEM_0221, ///< \ru Эллипс. \en Ellipse. - IDS_ITEM_0222, ///< \ru Парабола. \en Parabola. - IDS_ITEM_0223, ///< \ru Гипербола. \en Hyperbola. - IDS_ITEM_0224, ///< \ru Ломаная линия. \en Polyline. - IDS_ITEM_0225, ///< \ru NURBS кривая. \en NURBS curve. - IDS_ITEM_0226, ///< \ru Сплайн Эрмита. \en Hermite spline. - IDS_ITEM_0227, ///< \ru Сплайн Безье. \en Bezier spline. - IDS_ITEM_0228, ///< \ru Кубический сплайн. \en Cubic spline. - IDS_ITEM_0229, ///< \ru Репараметризованная кривая. \en Reparametrized curve. - IDS_ITEM_0231, ///< \ru Плоская кривая. \en Plane curve. - IDS_ITEM_0232, ///< \ru Спираль с переменым радиусом. \en Spiral with variable radius. - IDS_ITEM_0233, ///< \ru Спираль с криволинейной осью. \en Spiral with a curved axis. - IDS_ITEM_0234, ///< \ru Кривая-мостик. \en Bridge curve. - IDS_ITEM_0235, ///< \ru Символьная кривая. \en Functionally defined curve. - IDS_ITEM_0236, ///< \ru Кривая на поверхности. \en Curve on a surface. - IDS_ITEM_0237, ///< \ru Линия пересечения поверхностей. \en Intersection curve of surfaces. - IDS_ITEM_0238, ///< \ru Контур на поверхности. \en Contour on a surface. - IDS_ITEM_0239, ///< \ru Контур на плоскости. \en Contour on a plane. - IDS_ITEM_0240, ///< \ru Контур. \en Contour. - IDS_ITEM_0241, ///< \ru Проекционная кривая. \en Projection curve. - IDS_ITEM_0242, ///< \ru Силуэтная кривая. \en Silhouette curve. - IDS_ITEM_0243, ///< \ru Кривая сопряжения кривых. \en Curve of curves conjugation. - IDS_ITEM_0244, ///< \ru Кривая производных поверхности Кунса. \en Curve of Coons surface derivetives. - IDS_ITEM_0249, ///< \ru Направляющая кривая. \en Guide curve. - IDS_ITEM_0250, ///< \ru Кривая пересечения. \en Intersection curve. - -// \ru Типы параметрических поверхностей. \en Types of parametric surfaces. - - IDS_ITEM_0301, ///< \ru Поверхность. \en Surface. - IDS_ITEM_0302, ///< \ru Поверхность заметания. \en Sweep surface. - IDS_ITEM_0303, ///< \ru Поверхность сдвига. \en Motion surface. - IDS_ITEM_0304, ///< \ru Поверхность выдавливания. \en Extrusion surface. - IDS_ITEM_0305, ///< \ru Поверхность вращения. \en Revolution surface. - IDS_ITEM_0306, ///< \ru Линейчатая поверхность. \en Ruled surface. - IDS_ITEM_0307, ///< \ru Поверхность по кривой и точке. \en Surface defined by a curve and a point. - IDS_ITEM_0308, ///< \ru Четырехугольная поверхность. \en Quadrangular surface. - IDS_ITEM_0309, ///< \ru Треугольная поверхность. \en Triangular surface. - IDS_ITEM_0310, ///< \ru Поверхность движения с доворотом. \en Sweep with guide curve surface with rotating ends. - IDS_ITEM_0311, ///< \ru Поверхность на семействе кривых и напрвляющей. \en Loft surface with guide curve. - IDS_ITEM_0312, ///< \ru Спиральная поверхность. \en Spiral surface. - IDS_ITEM_0313, ///< \ru Цилиндрически согнутая поверхность. \en Cylindrically bent surface. - IDS_ITEM_0314, ///< \ru Цилиндрически разогнутая поверхность. \en Cylindrically unbent surface. - IDS_ITEM_0315, ///< \ru Конически согнутая поверхность. \en Conically bent surface. - IDS_ITEM_0316, ///< \ru Конически разогнутая поверхность. \en Conically unbent surface. - IDS_ITEM_0317, ///< \ru Поверхность заметания с изменением образующей. \en Sweep surface with changin generatin. - IDS_ITEM_0319, ///< \ru Плоскость. \en Plane. - IDS_ITEM_0320, ///< \ru Сферическая поверхность. \en Spherical surface. - IDS_ITEM_0321, ///< \ru Тороидальная поверхность. \en Toroidal surface. - IDS_ITEM_0322, ///< \ru Цилиндрическая поверхность. \en Cylindrical surface. - IDS_ITEM_0323, ///< \ru Коническая поверхность. \en Conical surface. - IDS_ITEM_0325, ///< \ru NURBS поверхность. \en NURBS surface. - IDS_ITEM_0326, ///< \ru Треугольная NURBS поверхность. \en Triangular NURBS surface. - IDS_ITEM_0327, ///< \ru Поверхность Безье. \en Bezier surface. - IDS_ITEM_0328, ///< \ru Эквидистантная поверхность. \en Offset surface. - IDS_ITEM_0329, ///< \ru Деформированная поверхность. \en Deformed surface. - IDS_ITEM_0330, ///< \ru Поверхность Грегори. \en Gregory Surface. - IDS_ITEM_0331, ///< \ru Поверхность соединения. \en Joint surface. - IDS_ITEM_0332, ///< \ru Поверхность объединения. \en Join surface. - IDS_ITEM_0333, ///< \ru Поверхность на трех кривых. \en Surface based on three curves. - IDS_ITEM_0334, ///< \ru Поверхность на четырех кривых. \en Surface based on four curves. - IDS_ITEM_0335, ///< \ru Поверхность-фаска. \en Chamfer surface. - IDS_ITEM_0336, ///< \ru Поверхность скругления. \en Fillet surface. - IDS_ITEM_0337, ///< \ru Переменная поверхность скругления. \en Variable fillet surface. - IDS_ITEM_0338, ///< \ru Поверхность на семействе кривых. \en Lofted surface. - IDS_ITEM_0339, ///< \ru Поверхность на сетке кривых. \en Surface defined on a mesh of curves. - IDS_ITEM_0340, ///< \ru Поверхность скругления по кромке. \en Surface of fillet by border. - IDS_ITEM_0341, ///< \ru Поверхность по замкнутому контуру. \en Surface on closed contour. - IDS_ITEM_0342, ///< \ru Плазовая поверхность. \en Spiling surface. - IDS_ITEM_0343, ///< \ru Поверхность Кунса. \en Coons surface. - IDS_ITEM_0345, ///< \ru Поверхность на сетке точек. \en Surface based on a point grid. - IDS_ITEM_0346, ///< \ru Треугольная поверхность Безье. \en Triangular Bezier surface. - IDS_ITEM_0349, ///< \ru Усеченная контурами поверхность. \en Curve bounded surface. - IDS_ITEM_0350, ///< \ru Поверхность-копия. \en Copy surface. - IDS_ITEM_0351, ///< \ru Поверхность соединения. \en Joint surface. - IDS_ITEM_0352, ///< \ru Поверхность полного скругления. \en Full fillet surface. - IDS_ITEM_0353, ///< \ru Поверхность заметания с масштабированием. \en Swept surface with scaling. - -// \ru Типы тел \en Types of solids - - IDS_ITEM_0401, ///< \ru Тело. \en Solid. - IDS_ITEM_0402, ///< \ru Оболочка. \en Shell. - IDS_ITEM_0403, ///< \ru Проволочный каркас. \en Wireframe. - IDS_ITEM_0404, ///< \ru Точечный каркас. \en Point frame. - IDS_ITEM_0405, ///< \ru Коллекция элементов. \en Collection of elements. - -// \ru Типы строителей. \en Types of creators. - - IDS_ITEM_0501, ///< \ru Журнал построения. \en Build log. - IDS_ITEM_0502, ///< \ru Шар. \en Sphere. - IDS_ITEM_0503, ///< \ru Тор. \en Torus. - IDS_ITEM_0504, ///< \ru Цилиндр. \en Cylinder. - IDS_ITEM_0505, ///< \ru Конус. \en Cone. - IDS_ITEM_0506, ///< \ru Блок. \en Block. - IDS_ITEM_0507, ///< \ru Клин. \en Wedge. - IDS_ITEM_0508, ///< \ru Призма. \en Prism. - IDS_ITEM_0509, ///< \ru Пирамида. \en Pyramid. - IDS_ITEM_0510, ///< \ru Твёрдое тело. \en Solid. - - IDS_ITEM_0515, ///< \ru Объединение оболочек. \en Shells union. - IDS_ITEM_0516, ///< \ru Пересечение оболочек. \en Shells intersection. - IDS_ITEM_0517, ///< \ru Разность оболочек. \en Shells subtraction. - - IDS_ITEM_0520, ///< \ru Отверстие. \en Hole. - IDS_ITEM_0521, ///< \ru Карман/Бобышка. \en Pocket/Boss. - IDS_ITEM_0522, ///< \ru Паз. \en Groove. - IDS_ITEM_0523, ///< \ru Заплатка. \en Patch. - IDS_ITEM_0524, ///< \ru Тонкая оболочка. \en Thin shell. - - IDS_ITEM_0526, ///< \ru Оболочка на семействе кривых. \en Shell defined by a set of curves. - IDS_ITEM_0527, ///< \ru Продолженная оболочка. \en Extended shell. - IDS_ITEM_0528, ///< \ru Эквидистантная оболочка. \en Offset shell. - IDS_ITEM_0529, ///< \ru Срединная оболочка. \en Median shell. - - IDS_ITEM_0531, ///< \ru Булево объединение тел. \en Boolean union of solids. - IDS_ITEM_0532, ///< \ru Булево пересечение тел. \en Boolean intersection of solids. - IDS_ITEM_0533, ///< \ru Булевa разность тел. \en Boolean subtraction of solids. - IDS_ITEM_0534, ///< \ru Разрезанное тело. \en Cut solid. - IDS_ITEM_0535, ///< \ru Фаски ребер. \en Edges chamfers. - IDS_ITEM_0536, ///< \ru Скругление ребер. \en Edges fillets. - IDS_ITEM_0537, ///< \ru Симметричное тело. \en Symmetric solid. - IDS_ITEM_0538, ///< \ru Оболочечное тело. \en Thin shell solid. - IDS_ITEM_0539, ///< \ru Тело приданием толщины. \en Solid of thickening. - IDS_ITEM_0540, ///< \ru Оболочка с удалёнными гранями. \en Shell with removed faces. - IDS_ITEM_0541, ///< \ru Коробчатое тело. \en Box-like solid. - IDS_ITEM_0542, ///< \ru Кинематическое тело. \en Sweeping solid. - IDS_ITEM_0543, ///< \ru Тело заметания. \en Swept solid. - IDS_ITEM_0544, ///< \ru Тело выдавливания. \en Extrusion solid. - IDS_ITEM_0545, ///< \ru Тело вращения. \en Revolution solid. - IDS_ITEM_0546, ///< \ru Тело по сечениям. \en Loft solid. - IDS_ITEM_0547, ///< \ru Простое тело. \en Simple solid. - IDS_ITEM_0548, ///< \ru Ребро жесткости тела. \en Rib of a solid. - IDS_ITEM_0549, ///< \ru Набор тел. \en Set of solids. - IDS_ITEM_0550, ///< \ru Часть набора тел. \en Set of solids part. - IDS_ITEM_0551, ///< \ru Клон граней тела. \en Solid's faces drafting. - IDS_ITEM_0552, ///< \ru Разбивка граней тела. \en Splitting of solid's faces. - IDS_ITEM_0553, ///< \ru Сшитое из оболочек тело. \en Stitched solid. - IDS_ITEM_0554, ///< \ru Сшитая из оболочек оболочка. \en Shell stitched from shells. - IDS_ITEM_0555, ///< \ru Оболочка из NURBS-поверхностей. \en Shell from NURBS-surfaces. - IDS_ITEM_0556, ///< \ru Трансформированное тело. \en Transformed solid. - IDS_ITEM_0557, ///< \ru Модифицированное тело. \en Modified solid. - IDS_ITEM_0558, ///< \ru Оболочка из линейчатых поверхностей. \en Shell from ruled surfaces. - IDS_ITEM_0559, ///< \ru Усеченная оболочка. \en Truncated shell. - IDS_ITEM_0560, ///< \ru Оболочка соединения. \en Joint shell. - IDS_ITEM_0561, ///< \ru Тело с восстановленными боковыми рёбрами. \en Solid with restored lateral edges. - IDS_ITEM_0562, ///< \ru Объединение с кинематическим телом. \en Union with a sweeping solid. - IDS_ITEM_0563, ///< \ru Модифицированное тело NURBS-поверхностями. \en Solid modified with NURBS-surfaces. - IDS_ITEM_0564, ///< \ru Объединение с телом выдавливания. \en Union with an extrusion solid. - IDS_ITEM_0565, ///< \ru Объединение с телом вращения. \en Union with a revolution solid. - IDS_ITEM_0566, ///< \ru Объединение с телом по сечениям. \en Union with a lofted solid. - IDS_ITEM_0567, ///< \ru Объединение с простым телом. \en Union with an elementary solid. - IDS_ITEM_0568, ///< \ru Модифицированная NURBS-поверхность грани. \en Modified NURBS-surface of the face. - IDS_ITEM_0569, ///< \ru Объединение с набором тел. \en Union with a solid set. - IDS_ITEM_0570, ///< \ru Оболочка грани соединения. \en Joint face shell. - IDS_ITEM_0571, ///< \ru Скругление граней. \en Faces fillet. - IDS_ITEM_0572, ///< \ru Разность с кинематическим телом. \en Subtraction with a sweeping solid. - IDS_ITEM_0573, ///< \ru Удаление результата операции. \en Delete the result of the operation. - IDS_ITEM_0574, ///< \ru Разность с телом выдавливания. \en Subtraction with an extrusion solid. - IDS_ITEM_0575, ///< \ru Разность с телом вращения. \en Subtraction with a revolution solid. - IDS_ITEM_0576, ///< \ru Разность с телом по сечениям. \en Subtraction with a lofted solid. - IDS_ITEM_0577, ///< \ru Разность с простым телом. \en Subtraction with an elementary solid. - IDS_ITEM_0578, ///< \ru Упрощение развёртки. \en The flat pattern simplification. - IDS_ITEM_0579, ///< \ru Разность с набором тел. \en Subtraction with a set of solids. - IDS_ITEM_0780, ///< \ru Вывернутое тело. \en Reversed solid. - IDS_ITEM_0581, ///< \ru Сгиб нелистового тела. \en Bend of a non-sheet solid. - IDS_ITEM_0582, ///< \ru Пересечение с кинематическим телом. \en Intersection with a sweeping solid. - IDS_ITEM_0583, ///< \ru Сферическая штамповка. \en Spherical stamping. - IDS_ITEM_0584, ///< \ru Пересечение с телом выдавливания. \en Intersection with an extrusion solid. - IDS_ITEM_0585, ///< \ru Пересечение с телом вращения. \en Intersection with a revolution solid. - IDS_ITEM_0586, ///< \ru Пересечение с телом по сечениям. \en Intersection with a lofted solid. - IDS_ITEM_0587, ///< \ru Пересечение с простым телом. \en Intersection with an elementary solid. - IDS_ITEM_0588, ///< \ru Обечайка. \en Ruled shell. - IDS_ITEM_0589, ///< \ru Пересечение с набором тел. \en Intersection with a set of solids. - IDS_ITEM_0590, ///< \ru Оболочка по сети кривых. \en Shell defined by a mesh of curves. - IDS_ITEM_0591, ///< \ru Комбинированный сгиб. \en Combined bend. - IDS_ITEM_0592, ///< \ru Кинематическая оболочка. \en Sweep with guide curve shell. - IDS_ITEM_0593, ///< \ru Жалюзи. \en Jalousie. - IDS_ITEM_0594, ///< \ru Оболочка выдавливания. \en Extrusion shell. - IDS_ITEM_0595, ///< \ru Оболочка вращения. \en Revolution shell. - IDS_ITEM_0596, ///< \ru Оболочка по сечениям. \en Loft shell. - IDS_ITEM_0597, ///< \ru Тонкая оболочка. \en Thin shell. - IDS_ITEM_0598, ///< \ru Разрезанная оболочка. \en Cut shell. - IDS_ITEM_0599, ///< \ru Буртик. \en Bead. - IDS_ITEM_0600, ///< \ru Сгиб/разгиб листового тела. \en Bend/unbend of a sheet solid. - IDS_ITEM_0601, ///< \ru Сгиб листового тела по отрезку. \en Bend of a sheet solid by a segment. - IDS_ITEM_0602, ///< \ru Сгиб листового тела по рёбрам. \en Bend of a sheet solid along edges. - IDS_ITEM_0603, ///< \ru Замыкание угла листового тела. \en Closure of a sheet solid corner. - IDS_ITEM_0604, ///< \ru Листовое тело. \en Sheet solid. - IDS_ITEM_0605, ///< \ru Пластина листового тела. \en Sheet solid plate. - IDS_ITEM_0606, ///< \ru Вырез листового тела. \en Cut of a sheet solid. - IDS_ITEM_0607, ///< \ru Пересечение листового тела. \en Sheet solid intersection. - IDS_ITEM_0608, ///< \ru Подсечка листового тела. \en Jog of a sheet solid. - IDS_ITEM_0609, ///< \ru Штамповка. \en Stamping. - -// \ru Способы построения оболочек. \en Shells construction methods. - - IDS_ITEM_0610, ///< \ru Оболочка. \en Shell. - IDS_ITEM_0611, ///< \ru Оболочка на базе поверхности. \en Shell based on a surface. - - IDS_ITEM_0614, ///< \ru Оболочка тела. \en Shell. - IDS_ITEM_0615, ///< \ru Журнал построения. \en Build log. - IDS_ITEM_0616, ///< \ru Атрибуты объекта. \en Object Attributes. - - IDS_ITEM_0620, ///< \ru Оболочка тела. \en Shell. - IDS_ITEM_0621, ///< \ru Ориентированное ребро цикла. \en Oriented edge of a loop. - IDS_ITEM_0622, ///< \ru Цикл грани. \en Face loop. - IDS_ITEM_0623, ///< \ru Грань оболочки. \en Face of a shell. - IDS_ITEM_0624, ///< \ru Вершина. \en Vertex. - IDS_ITEM_0625, ///< \ru Ребро оболочки. \en Edge of a shell. - IDS_ITEM_0626, ///< \ru Ребро каркаса. \en Edge of a frame. - - IDS_ITEM_0627, ///< \ru Вершина. \en Vertex. - - IDS_ITEM_0628, ///< \ru Разделенная оболочка. \en Divided shell. - -// \ru Способы построения проекций тела\оболочки. \en Solid/shell projections creation methods. - - IDS_ITEM_0650, ///< \ru Проекция тела. \en Solid projection. - IDS_ITEM_0651, ///< \ru Разрез тела. \en Solid cutting. - IDS_ITEM_0652, ///< \ru Сечение тела. \en Solid section. - - IDS_ITEM_0653, ///< \ru Размножение тела. \en Duplication of solids. - -// \ru Вспомогательный объект. \en The helper object. - - IDS_ITEM_0669, ///< \ru Вспомогательный объект. \en The helper object. - -// \ru Резьба. \en A thread. - - IDS_ITEM_0670, ///< \ru Резьба. \en Thread. - -// \ru Обозначение \en 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. - -// \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_0732, ///< \ru Атрибут. \en Attribute. - IDS_ITEM_0733, ///< \ru Имя примитива. \en Primitive name. - IDS_ITEM_0734, ///< \ru Поведение атрибутов. \en Attributes behavior. - - 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_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_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_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_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_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. - -// \ru Сообщения. \en Messages. - - IDS_ITEM_0900, ///< \ru ! Ошибка !. \en ! Error ! - IDS_ITEM_0901, ///< \ru Остановлено. \en Stopped. - IDS_ITEM_0902, ///< \ru Пропущено. \en Missed. - -// \ru Состав объектов \en Structure of objects - - IDS_PROP_0000, ///< \ru Пусто. \en Empty. - - IDS_PROP_0001, ///< \ru Кривая на плоскости. \en Curve on a plane. - IDS_PROP_0002, ///< \ru Параметр кривой. \en Parameter of a curve. - IDS_PROP_0003, ///< \ru Кривая 1 на плоскости. \en Curve 1 on the plane. - IDS_PROP_0004, ///< \ru Кривая 2 на плоскости. \en Curve 2 on the plane. - IDS_PROP_0005, ///< \ru Параметр кривой 1. \en Parameter of curve 1. - IDS_PROP_0006, ///< \ru Параметр кривой 2. \en Parameter of curve 2. - IDS_PROP_0007, ///< \ru Начальная точка. \en Start point. - IDS_PROP_0008, ///< \ru Направление. \en Direction. - IDS_PROP_0009, ///< \ru Конечная точка. \en End point. - IDS_PROP_0014, ///< \ru Начальный параметр усечения. \en Start parameter of truncation. - IDS_PROP_0015, ///< \ru Конечный параметр усечения. \en End parameter of truncation. - IDS_PROP_0016, ///< \ru Совпадение направления. \en Coincidence of direction. - IDS_PROP_0017, ///< \ru Циклическая частота. \en Cyclic frequency. - IDS_PROP_0018, ///< \ru Начальная фаза (град). \en Initial phase (degrees). - IDS_PROP_0019, ///< \ru Амплитуда. \en Amplitude. - IDS_PROP_0020, ///< \ru Перевернуть направление. \en Reverse the direction. - IDS_PROP_0021, ///< \ru Неподвижная точка. \en Fixed point. - IDS_PROP_0022, ///< \ru Использовать точку. \en Use a point. - IDS_PROP_0023, ///< \ru Равномерное преобразование. \en Uniform transformation. - IDS_PROP_0024, ///< \ru Точность. \en Tolerance. - IDS_PROP_0025, ///< \ru Начальное значение. \en Start value. - IDS_PROP_0026, ///< \ru Коэффициент усиления. \en Scale gain. - IDS_PROP_0027, ///< \ru Амплитуда. \en Amplitude. - IDS_PROP_0028, ///< \ru Сдвиг параметра. \en Parameter shift. - IDS_PROP_0029, ///< \ru Степень возведения. \en Exponent parameter. - IDS_PROP_0030, ///< \ru Циклическая частота. \en Frequency. - IDS_PROP_0031, ///< \ru Эквидистантное смещение. \en The offset range. - IDS_PROP_0032, ///< \ru Тип кривой. \en Type of curve. - - IDS_PROP_0101, ///< \ru Координата X. \en Coordinate X. - IDS_PROP_0102, ///< \ru Координата Y. \en Coordinate Y. - IDS_PROP_0103, ///< \ru Координата Z. \en Coordinate Z. - IDS_PROP_0104, ///< \ru Матрица. \en Matrix. - IDS_PROP_0107, ///< \ru Угол с осью X. \en Angle with axis X. - IDS_PROP_0108, ///< \ru Угол с осью Y. \en Angle with axis Y. - IDS_PROP_0109, ///< \ru Угол с осью Z. \en Angle with axis Z. - IDS_PROP_0110, ///< \ru Точка. \en Point. - IDS_PROP_0111, ///< \ru Компонента 1.X. \en Component 1.X. - IDS_PROP_0112, ///< \ru Компонента 1.Y. \en Component 1.Y. - IDS_PROP_0113, ///< \ru Компонента 1.Z. \en Component 1.Z. - IDS_PROP_0114, ///< \ru Компонента 2.X. \en Component 2.X. - IDS_PROP_0115, ///< \ru Компонента 2.Y. \en Component 2.Y. - IDS_PROP_0116, ///< \ru Компонента 2.Z. \en Component 2.Z. - IDS_PROP_0117, ///< \ru Компонента 3.X. \en Component 3.X. - IDS_PROP_0118, ///< \ru Компонента 3.Y. \en Component 3.Y. - IDS_PROP_0119, ///< \ru Компонента 3.Z. \en Component 3.Z. - IDS_PROP_0120, ///< \ru Вектор. \en Vector. - IDS_PROP_0121, ///< \ru Сдвиг по X. \en Shift by X. - IDS_PROP_0122, ///< \ru Сдвиг по Y. \en Shift by Y. - IDS_PROP_0123, ///< \ru Сдвиг по Z. \en Shift by Z. - IDS_PROP_0124, ///< \ru Ось X. \en Axis X. - IDS_PROP_0125, ///< \ru Ось Y. \en Axis Y. - IDS_PROP_0126, ///< \ru Ось Z. \en Axis Z. - IDS_PROP_0127, ///< \ru Длина оси X. \en Length of axis X. - IDS_PROP_0128, ///< \ru Длина оси Y. \en Length of axis Y. - IDS_PROP_0129, ///< \ru Длина оси Z. \en Length of axis Z. - IDS_PROP_0130, ///< \ru Центр. \en Center. - IDS_PROP_0131, ///< \ru Левая система. \en Left system. - IDS_PROP_0132, ///< \ru Прямоугольная. \en Rectangular. - IDS_PROP_0133, ///< \ru Базовая точка. \en Base point. - IDS_PROP_0134, ///< \ru Строка. \en String. - IDS_PROP_0135, ///< \ru Шрифт. \en Font. - IDS_PROP_0136, ///< \ru Позиция начала. \en Start position. - IDS_PROP_0137, ///< \ru Высота. \en Height. - IDS_PROP_0138, ///< \ru Сужение. \en Taper. - IDS_PROP_0139, ///< \ru Угол наклона. \en Slope angle. - IDS_PROP_0140, ///< \ru Радиус. \en Radius. - IDS_PROP_0141, ///< \ru Масштаб по X. \en Scale by X. - IDS_PROP_0142, ///< \ru Масштаб по Y. \en Scale by Y. - IDS_PROP_0143, ///< \ru Масштаб по Z. \en Scale by Z. - IDS_PROP_0144, ///< \ru Функция масштабирования. \en The function of scaling. - IDS_PROP_0145, ///< \ru Функция вращения. \en The function of rotation. - - IDS_PROP_0150, ///< \ru Угол. \en Angle. - IDS_PROP_0151, ///< \ru Шаг. \en Step. - 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_0156, ///< \ru Зеркальность. \en Specularity. - IDS_PROP_0157, ///< \ru Только ортогональность. \en Orthogonality only. - IDS_PROP_0158, ///< \ru Объект общего вида. \en General object. - IDS_PROP_0159, ///< \ru Перспектива. \en Perspective. - IDS_PROP_0160, ///< \ru Локальная система координат. \en Local coordinate system. - IDS_PROP_0161, ///< \ru Начальное значение. \en Start value. - IDS_PROP_0162, ///< \ru Конечное значение. \en End value. - IDS_PROP_0163, ///< \ru Значение. \en Value. - IDS_PROP_0164, ///< \ru Функция изменения радиусов. \en Radius function. - IDS_PROP_0165, ///< \ru Функция изменения веса. \en Weight function. - IDS_PROP_0166, ///< \ru Функция. \en Function. - IDS_PROP_0167, ///< \ru Минимум. \en Minimum. - IDS_PROP_0168, ///< \ru Максимум. \en Maximum - - IDS_PROP_0169, ///< \ru Продлевать вверх?. \en Extend upwards?. - IDS_PROP_0170, ///< \ru Поворот оси вокруг нормали. \en Rotation of axis about the normal. - IDS_PROP_0171, ///< \ru Угол между осью и нормалью. \en Angle between the axis and the normal. - IDS_PROP_0172, ///< \ru Диаметр головки. \en Cap diameter. - IDS_PROP_0173, ///< \ru Глубина под головку. \en Depth for a cap. - IDS_PROP_0174, ///< \ru Угол фаски под головку. \en Chamfer angle for a cap. - IDS_PROP_0175, ///< \ru Диаметр отверстия под резьбу. \en Diameter of hole for a cap. - IDS_PROP_0176, ///< \ru Глубина отверстия под резьбу. \en Depth of hole for a cap. - IDS_PROP_0177, ///< \ru Угол конусности отверстия. \en Taper angle of hole. - IDS_PROP_0178, ///< \ru Угол раствора конца отверстия. \en Apical angle of hole end. - IDS_PROP_0179, ///< \ru Тип отверстия. \en Hole type. - IDS_PROP_0180, ///< \ru Способ модификации. \en Method of modification. - - IDS_PROP_0181, ///< \ru Тип(true-бобышка, false- карман). \en Type(true-boss, false- pocket). - IDS_PROP_0182, ///< \ru Тип. \en Type. - IDS_PROP_0183, ///< \ru Ширина. \en Width. - IDS_PROP_0184, ///< \ru Ширина. \en Width. - IDS_PROP_0185, ///< \ru Способ. \en Method. - IDS_PROP_0186, ///< \ru Новая грань. \en New face. - - IDS_PROP_0188, ///< \ru Направление (вниз/вверх). \en Direction (down/up). - IDS_PROP_0189, ///< \ru Радиус дуги. \en Arc radius. - -// \ru Параметры. \en Parameters. - - IDS_PROP_0201, ///< \ru Объект на числах double. \en Object on double data. - IDS_PROP_0202, ///< \ru Объект на числах float. \en Object on float data. - IDS_PROP_0203, ///< \ru Кривая 1. \en Curve 1. - IDS_PROP_0204, ///< \ru Кривая 2. \en Curve 2. - IDS_PROP_0205, ///< \ru Кривая 3. \en Curve 3. - IDS_PROP_0206, ///< \ru Кривая 4. \en Curve 4 - IDS_PROP_0207, ///< \ru Начальная точка. \en Start point. - IDS_PROP_0208, ///< \ru Направляющий вектор. \en Direction vector. - IDS_PROP_0209, ///< \ru Конечная точка. \en End point. - IDS_PROP_0210, ///< \ru Нормаль к плоскости.\en Normal to surface. - IDS_PROP_0211, ///< \ru Первая полуось. \en First semiaxis. - IDS_PROP_0212, ///< \ru Вторая полуось. \en Second semiaxis. - IDS_PROP_0213, ///< \ru Фокусное расстояние. \en Focal distance. - IDS_PROP_0214, ///< \ru Параметр min. \en Parameter min. - IDS_PROP_0215, ///< \ru Параметр max. \en Parameter max. - IDS_PROP_0216, ///< \ru Действительная полуось. \en Real semiaxis. - IDS_PROP_0217, ///< \ru Мнимая полуось. \en Imaginary semiaxis. - IDS_PROP_0218, ///< \ru Приращение начального параметра. \en Increment of start parameter. - IDS_PROP_0219, ///< \ru Приращение конечного параметра. \en Increment of end parameter. - IDS_PROP_0220, ///< \ru Замкнутость. \en Closedness. - IDS_PROP_0221, ///< \ru Порядок. \en Order. - IDS_PROP_0222, ///< \ru Количество точек. \en Number of points. - IDS_PROP_0223, ///< \ru Точка. \en Point. - IDS_PROP_0224, ///< \ru Начальный параметр. \en Start parameter. - IDS_PROP_0225, ///< \ru Производная параметра. \en Derivative of parameter. - IDS_PROP_0226, ///< \ru Параметрическая длина. \en Parametric length. - IDS_PROP_0227, ///< \ru Положительное направление. \en Positive direction. - IDS_PROP_0228, ///< \ru Вес. \en Weight. - // IDS_PROP_0229, ///< \ru Касание. \en Tangency. (МА 2019 Лишнее?) - IDS_PROP_0230, ///< \ru Расстояние. \en Distance. - IDS_PROP_0232, ///< \ru Число кривых контура. \en Number of curves of contour. - IDS_PROP_0233, ///< \ru Кривая. \en Curve. - IDS_PROP_0234, ///< \ru Начальный параметр кривой. \en Start parameter of a curve. - IDS_PROP_0235, ///< \ru Конечный параметр кривой. \en End parameter of a curve. - IDS_PROP_0236, ///< \ru Число узлов. \en Number of knots. - IDS_PROP_0237, ///< \ru Значение узла. \en Knot value. - IDS_PROP_0238, ///< \ru Вторая производная в точке. \en Second derivative at a point. - IDS_PROP_0239, ///< \ru Производная. \en Derivative. - IDS_PROP_0240, ///< \ru Кривая. \en Curve. - IDS_PROP_0241, ///< \ru Зависимость по X. \en Dependency by X. - IDS_PROP_0242, ///< \ru Зависимость по Y. \en Dependency by Y. - IDS_PROP_0243, ///< \ru Зависимость по Z. \en Dependency by Z. - IDS_PROP_0244, ///< \ru Расширение minPar. \en Extension minPar. - IDS_PROP_0245, ///< \ru Расширение maxPar. \en Extension maxPar. - IDS_PROP_0246, ///< \ru Количество сплайнов. \en Number of splines. - IDS_PROP_0250, ///< \ru Базовая кривая. \en Base curve. - IDS_PROP_0260, ///< \ru Двумерная кривая. \en Two-dimensional curve. - IDS_PROP_0263, ///< \ru Угол между OX плоскости и прямой касания ее с конусом. \en Angle of OX axis of a plane and the line of its tangency with a cone. - IDS_PROP_0264, ///< \ru Расстояние от листовой грани до нейтрального слоя. \en Distance from a sheet face to the neutral layer. - IDS_PROP_0265, ///< \ru Угол образующей конуса, касательной к плоскости при разгибе. \en Angle of a cone generatrix tangent to the plane while unbending. - IDS_PROP_0266, ///< \ru Количество образующих кривых. \en Number of generating lines. - IDS_PROP_0267, ///< \ru Объект модифицирован. \en Object is modified. - IDS_PROP_0268, ///< \ru Количество нормалей. \en Number of normals. - IDS_PROP_0269, ///< \ru Нормаль. \en Normal. - IDS_PROP_0270, ///< \ru Аппроксимационная кривая. \en Approximation curve. - - IDS_PROP_0271, ///< \ru Удаление выбранных граней. \en Remove selected faces. - IDS_PROP_0272, ///< \ru Создание тела из выбранных граней. \en Solid creation by selected faces. - IDS_PROP_0273, ///< \ru Перемещение выбранных граней. \en Move selected faces. - IDS_PROP_0274, ///< \ru Смещение выбранных граней по нормали. \en Offset selected faces. - IDS_PROP_0275, ///< \ru Изменение радиусов выбранных скруглений. \en Change selected fillets. - IDS_PROP_0276, ///< \ru Замена выбранных граней деформируемыми. \en Replace selected faces by deformed. - IDS_PROP_0277, ///< \ru Удаление выбранных скруглений. \en Remove selected features. - IDS_PROP_0278, ///< \ru Слияние вершин выбранных ребер. \en Merging vertices of selected edges. - - IDS_PROP_0282, ///< \ru Вектор модификации. \en The vector of modification. - IDS_PROP_0283, ///< \ru Количество модифицированных граней. \en Number of modified faces. - IDS_PROP_0284, ///< \ru Положение срединной оболочки тела. \en Position of median shell. - IDS_PROP_0285, ///< \ru Минимальное расстояние между гранями. \en Minimal equidistation value. - IDS_PROP_0286, ///< \ru Максимальное расстояние между гранями. \en Maximal equidistant value. - - IDS_PROP_0301, ///< \ru Начальный параметр U. \en Start parameter U. - IDS_PROP_0302, ///< \ru Начальный параметр V. \en Start parameter V. - IDS_PROP_0303, ///< \ru Положительное направление U. \en Positive direction by U. - IDS_PROP_0304, ///< \ru Положительное направление V. \en Positive direction by V. - IDS_PROP_0305, ///< \ru Параметрическая длина U. \en Parametric length by U. - IDS_PROP_0306, ///< \ru Параметрическая длина V. \en Parametric length by V. - IDS_PROP_0307, ///< \ru Положительное направление 1. \en Positive direction 1. - IDS_PROP_0308, ///< \ru Положительное направление 2. \en Positive direction 2. - IDS_PROP_0309, ///< \ru Тип сопряжения. \en Conjugation type. - IDS_PROP_0310, ///< \ru Точка. \en Point. - IDS_PROP_0311, ///< \ru Замкнутость по U. \en Closedness by U. - IDS_PROP_0312, ///< \ru Замкнутость по V. \en Closedness by V. - IDS_PROP_0313, ///< \ru Число порций по U. \en Number of portions by U. - IDS_PROP_0314, ///< \ru Число порций по V. \en Number of portions by V. - IDS_PROP_0315, ///< \ru Порядок по U. \en Order by U. - IDS_PROP_0316, ///< \ru Порядок по V. \en Order by V. - IDS_PROP_0317, ///< \ru Число точек по U. \en Number of points by U. - IDS_PROP_0318, ///< \ru Число точек по V. \en Number of points by V. - IDS_PROP_0320, ///< \ru Локальная система. \en Local system. - IDS_PROP_0321, ///< \ru Радиус основания. \en Radius of base. - IDS_PROP_0322, ///< \ru Высота. \en Height. - IDS_PROP_0323, ///< \ru Половина угла. \en Half-angle. - IDS_PROP_0324, ///< \ru Большой радиус. \en Major radius. - IDS_PROP_0325, ///< \ru Малый радиус. \en Minor radius. - IDS_PROP_0326, ///< \ru Длина. \en Length. - IDS_PROP_0327, ///< \ru Смещение. \en Shift. - 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_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. - IDS_PROP_0339, ///< \ru Значение V узла. \en Value of V knot. - IDS_PROP_0340, ///< \ru Поверхность. \en Surface. - IDS_PROP_0341, ///< \ru Направляющая кривая. \en Guide curve . - IDS_PROP_0342, ///< \ru Образующая кривая. \en Generating curve. - IDS_PROP_0343, ///< \ru Вектор смещения. \en Translation vector. - IDS_PROP_0344, ///< \ru Вектор направления. \en Direction vector. - IDS_PROP_0345, ///< \ru Точка оси вращения. \en Point of the rotation axis. - IDS_PROP_0346, ///< \ru Направление оси. \en Axis direction. - IDS_PROP_0347, ///< \ru Угол вращения. \en Rotation angle. - IDS_PROP_0348, ///< \ru Вершина. \en Vertex. - IDS_PROP_0350, ///< \ru Базовая поверхность. \en Base surface. - IDS_PROP_0351, ///< \ru Поверхность 1. \en Surface 1. - IDS_PROP_0352, ///< \ru Поверхность 2. \en Surface 2. - IDS_PROP_0353, ///< \ru Контур. \en Contour. - IDS_PROP_0354, ///< \ru Число контуров. \en Number of contours. - IDS_PROP_0355, ///< \ru Двумерный контур. \en Two-dimensional contour. - IDS_PROP_0356, ///< \ru Двумерная кривая. \en Two-dimensional curve. - IDS_PROP_0357, ///< \ru Контур 1. \en Contour 1. - IDS_PROP_0358, ///< \ru Контур 2. \en Contour 2. - IDS_PROP_0360, ///< \ru Плоскость. \en Plane. - IDS_PROP_0361, ///< \ru Вес поверхности 1. \en Weight of surface 1. - IDS_PROP_0362, ///< \ru Вес поверхности 2. \en Weight of surface 2. - IDS_PROP_0363, ///< \ru Производная в начале. \en Derivative at the beginning. - IDS_PROP_0364, ///< \ru Производная в конце. \en Derivative at the end. - IDS_PROP_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_0374, ///< \ru Параметр Umin. \en Parameter Umin. - IDS_PROP_0375, ///< \ru Параметр Umax. \en Parameter Umax. - IDS_PROP_0376, ///< \ru Параметр Vmin. \en Parameter Vmin. - IDS_PROP_0377, ///< \ru Параметр Vmax. \en Parameter Vmax. - IDS_PROP_0378, ///< \ru Производная dU. \en Derivative dU. - IDS_PROP_0379, ///< \ru Производная dV. \en Derivative dV. - IDS_PROP_0380, ///< \ru Кромка проходит по Vmin. \en Boundary passes through Vmin. - IDS_PROP_0384, ///< \ru Расширение minUPar. \en Extension minUPar. - IDS_PROP_0385, ///< \ru Расширение maxUPar. \en Extension maxUPar. - IDS_PROP_0386, ///< \ru Расширение minVPar. \en Extension minVPar. - IDS_PROP_0387, ///< \ru Расширение maxVPar. \en Extension maxVPar. - IDS_PROP_0390, ///< \ru Число кривых. \en Number of curves. - IDS_PROP_0391, ///< \ru Кривая по U. \en Curve by U - IDS_PROP_0392, ///< \ru Кривая по V. \en Curve by V. - IDS_PROP_0393, ///< \ru Число кривых по U. \en Number of curves by U. - IDS_PROP_0394, ///< \ru Число кривых по V. \en Number of curves by V. - IDS_PROP_0395, ///< \ru Тип поверхности. \en Type of surface. - IDS_PROP_0397, ///< \ru Нейтральная плоскость. \en Neutral plane. - IDS_PROP_0398, ///< \ru Плоскость контура. \en Plane of the contour. - IDS_PROP_0399, ///< \ru Через элементы. \en Through elements. - IDS_PROP_0400, ///< \ru Сопряжение на границе. \en Conjugation on the boundary. - IDS_PROP_0401, ///< \ru Натяжение на границе. \en Tension on the boundary. - IDS_PROP_0402, ///< \ru Параметр определения длины производных. \en Parameter of derivatives length definition. - IDS_PROP_0403, ///< \ru Не сохранять длину производной. \en Do not keep the derivative length. - IDS_PROP_0404, ///< \ru Тип сопряжения (0-4). \en Conjugation type (0-4). - IDS_PROP_0405, ///< \ru Использовать готовый узловой вектор. \en Use prepared knot vector. - IDS_PROP_0406, ///< \ru Количество узлов. \en Number of knots. - IDS_PROP_0407, ///< \ru Проверка самопересечений. \en Check for self-intersections. - IDS_PROP_0408, ///< \ru Используется общий вес точек. \en The common weight of points is used. - IDS_PROP_0409, ///< \ru Построена по пласту точек. \en Build from a cloud of points. - IDS_PROP_0410, ///< \ru Построена по сети точек. \en Build from a mesh of points. - IDS_PROP_0411, ///< \ru В виде набора треугольников. \en As a set of triangles. - IDS_PROP_0412, ///< \ru Использовать проекционную кривую. \en Use projection curve. - IDS_PROP_0413, ///< \ru Усекать границами. \en Truncate by bounds. - IDS_PROP_0414, ///< \ru Привязка к началу. \en Binding to the beginning. - IDS_PROP_0415, ///< \ru Соединять скруглениями.\en Join by fillets. - IDS_PROP_0416, ///< \ru Сохранять радиус. \en Keep the radius. - IDS_PROP_0417, ///< \ru Притуплять острый угол. \en Blunt a sharp angle. - IDS_PROP_0418, ///< \ru Проверка пересечений. \en Check for intersections. - IDS_PROP_0419, ///< \ru Слияние подобных граней. \en Merging of similar faces. - IDS_PROP_0420, ///< \ru Слияние подобных ребер. \en Merging of similar edges. - - IDS_PROP_0421, ///< \ru Номер соседнего объекта. \en The number of neighbour object. - - IDS_PROP_0450, ///< \ru Начальный радиус (поверхность). \en Start radius (surface). - IDS_PROP_0451, ///< \ru Конечный радиус (резьба). \en End radius (thread). - IDS_PROP_0452, ///< \ru Длина резьбы. \en Thread length. - IDS_PROP_0453, ///< \ru Угол коничности резьбы. \en Taper angle of the thread. - - IDS_PROP_0461, ///< \ru Триангуляция. \en Triangulation. - IDS_PROP_0462, ///< \ru Количество точек триангуляции. \en Number of points of triangulation. - IDS_PROP_0463, ///< \ru Количество двумерных точек. \en Number of two-dimension points. - IDS_PROP_0464, ///< \ru Количество точек полигонов. \en Number of points of polygons. - - IDS_PROP_0501, ///< \ru Число вершин. \en Number of vertices. - IDS_PROP_0502, ///< \ru Число ребер. \en Number of edges. - IDS_PROP_0503, ///< \ru Число граней. \en Number of faces. - IDS_PROP_0504, ///< \ru Ориентация вершины. \en Vertex orientation. - IDS_PROP_0505, ///< \ru Ориентация ребра. \en Edge orientation. - IDS_PROP_0506, ///< \ru Ориентация грани. \en Face orientation. - IDS_PROP_0508, ///< \ru Ребро. \en Edge. - IDS_PROP_0509, ///< \ru Грань. \en Face. - IDS_PROP_0510, ///< \ru Число циклов. \en Number of loops. - IDS_PROP_0511, ///< \ru Цикл. \en Loop. - IDS_PROP_0512, ///< \ru Автоопределение. \en Automatic identification. - IDS_PROP_0513, ///< \ru Автоматическое. \en Automatic. - - IDS_PROP_0514, ///< \ru Тип размножения. \en Type of duplication. - IDS_PROP_0515, ///< \ru Кол-во шагов. \en Number of steps. - IDS_PROP_0516, ///< \ru Шаг. \en Step. - 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_0521, ///< \ru Длина Lx. \en Length Lx. - IDS_PROP_0522, ///< \ru Ширина Ly. \en Width Ly. - IDS_PROP_0523, ///< \ru Высота Lz. \en Height Lz. - IDS_PROP_0524, ///< \ru Малая длина lx. \en Minor length lx. - IDS_PROP_0525, ///< \ru Толщина. \en Thickness. - 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_0530, ///< \ru Продолжить далее. \en Continue. - IDS_PROP_0531, ///< \ru Катет 1. \en Cathetus 1. - IDS_PROP_0532, ///< \ru Катет 2. \en Cathetus 2. - IDS_PROP_0533, ///< \ru Число фасок. \en Number of chamfers. - IDS_PROP_0534, ///< \ru Число скруглений. \en Number of fillets. - IDS_PROP_0535, ///< \ru Радиус скругления. \en Fillet radius. - IDS_PROP_0536, ///< \ru Номер грани. \en Face number. - IDS_PROP_0537, ///< \ru Параметр U. \en Parameter U. - IDS_PROP_0538, ///< \ru Параметр V. \en Parameter V. - IDS_PROP_0539, ///< \ru Число модифицированных граней. \en Number of modified faces. - IDS_PROP_0540, ///< \ru Тело. \en Solid. - IDS_PROP_0541, ///< \ru Строитель тела. \en Construct solid. - IDS_PROP_0542, ///< \ru Количество четырёхугольников. \en Number of quadrangles. - IDS_PROP_0543, ///< \ru Остановка от начала. \en Termination from the start. - IDS_PROP_0544, ///< \ru Остановка до конца. \en Termination to the end. - IDS_PROP_0545, ///< \ru Радиус скругления 1. \en Fillet radius 1. - IDS_PROP_0546, ///< \ru Радиус скругления 2. \en Fillet radius 2. - IDS_PROP_0547, ///< \ru Коэффициент полноты. \en Coefficient of completeness. - IDS_PROP_0548, ///< \ru Способ обработки углов стыковки рёбер. \en Method of processing corners of edges connection. - IDS_PROP_0549, ///< \ru Четырехугольник. \en Quadrangle. - - IDS_PROP_0550, ///< \ru Базовое тело. \en Base solid. - IDS_PROP_0551, ///< \ru Тело 1. \en Solid 1. - IDS_PROP_0552, ///< \ru Тело 2. \en Solid 2. - IDS_PROP_0553, ///< \ru Исходное тело. \en Initial solid. - IDS_PROP_0554, ///< \ru Режущая поверхность. \en Cutting surface. - IDS_PROP_0555, ///< \ru Оставляемая часть. \en A part to keep. - IDS_PROP_0556, ///< \ru Точка симметрии. \en Symmetry point. - IDS_PROP_0557, ///< \ru Ось X симметрии. \en Axis X of symmetry. - IDS_PROP_0558, ///< \ru Ось Y симметрии. \en Axis Y of symmetry. - IDS_PROP_0559, ///< \ru Поверхность. \en Surface. - IDS_PROP_0560, ///< \ru Внешняя оболочка. \en Outer shell. - IDS_PROP_0561, ///< \ru Пустотная оболочка. \en Void shell. - IDS_PROP_0562, ///< \ru Число пустот. \en Number of voids. - IDS_PROP_0563, ///< \ru Глубина 1. \en Depth 1. - IDS_PROP_0564, ///< \ru Глубина 2. \en Depth 2. - IDS_PROP_0565, ///< \ru Угол уклона 1. \en Slope angle 1. - IDS_PROP_0566, ///< \ru Угол уклона 2. \en Slope angle 2. - IDS_PROP_0567, ///< \ru Толщина стенки 1. \en Wall thickness 1. - IDS_PROP_0568, ///< \ru Толщина стенки 2. \en Wall thickness 2. - IDS_PROP_0569, ///< \ru Толщина. \en Thickness. - IDS_PROP_0570, ///< \ru Глубина. \en Depth. - - IDS_PROP_0571, ///< \ru Способ построения. \en Method of construction. - IDS_PROP_0572, ///< \ru Число оболочек. \en Number of shells. - IDS_PROP_0573, ///< \ru Количество треугольников. \en Number of triangles. - IDS_PROP_0575, ///< \ru Угол вращения 1. \en Rotation angle 1. - IDS_PROP_0576, ///< \ru Угол вращения 2. \en Rotation angle 2. - - IDS_PROP_0577, ///< \ru Первая вершина. \en The first vertex. - IDS_PROP_0578, ///< \ru Вторая вершина. \en The second vertex. - IDS_PROP_0579, ///< \ru Третья вершина. \en The third vertex. - IDS_PROP_0580, ///< \ru Четвертая вершина. \en The fourth vertex. - - IDS_PROP_0581, ///< \ru Способ построения 1. \en Method of construction 1. - IDS_PROP_0582, ///< \ru Способ построения 2. \en Method of construction 2. - IDS_PROP_0583, ///< \ru Расстояние 1. \en Distance 1. - IDS_PROP_0584, ///< \ru Расстояние 2. \en Distance 2. - IDS_PROP_0585, ///< \ru Треугольник. \en Triangle. - IDS_PROP_0586, ///< \ru Количество апексов. \en Number of apices. - IDS_PROP_0587, ///< \ru Количество полигонов. \en Number of polygons. - IDS_PROP_0588, ///< \ru Количество триангуляций. \en Number of triangulations. - IDS_PROP_0589, ///< \ru Контур. \en Contour. - IDS_PROP_0590, ///< \ru Число сечений. \en Number of sections. - IDS_PROP_0591, ///< \ru Сечение. \en Section. - IDS_PROP_0592, ///< \ru Параллельность. \en Parallelization. - IDS_PROP_0593, ///< \ru Ориентация образующей. \en Generatrix orientation. - IDS_PROP_0594, ///< \ru Положение образующей. \en Generatrix position. - IDS_PROP_0595, ///< \ru Сфероид (0) или тороид (1). \en Spheroid (0) or toroid (1). - IDS_PROP_0596, ///< \ru Полюс в начале. \en Pole at the beginning. - IDS_PROP_0597, ///< \ru Полюс в конце. \en Pole at the end. - IDS_PROP_0598, ///< \ru Продолжение. \en Extension. - IDS_PROP_0599, ///< \ru Смещение. \en Shift. - - IDS_PROP_0600, ///< \ru Оболочка тела. \en Shell. - IDS_PROP_0601, ///< \ru Ориентация ребра в цикле. \en Sense of edge in the loop. - IDS_PROP_0602, ///< \ru Ориентация кривой ребра. \en Edge curve orientation. - IDS_PROP_0603, ///< \ru Ориентация нормали оболочки. \en Orientation of a shell normal. - IDS_PROP_0604, ///< \ru Кривая ребра. \en Edge curve. - IDS_PROP_0605, ///< \ru Двумерная кривая ребра. \en Two-dimensional edge curve. - IDS_PROP_0606, ///< \ru Поверхность грани. \en Surface of a face. - IDS_PROP_0607, ///< \ru Вершина-начало. \en Start vertex. - IDS_PROP_0608, ///< \ru Вершина-конец. \en End vertex. - IDS_PROP_0609, ///< \ru Количество ссылок. \en References count. - IDS_PROP_0611, ///< \ru Грань плюс. \en Face plus. - IDS_PROP_0612, ///< \ru Грань минус. \en Face minus. - IDS_PROP_0613, ///< \ru Указатель на грань. \en Pointer to a face. - 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_0651, ///< \ru Разрезанное тело. \en Cutting solid. - IDS_PROP_0652, ///< \ru Плоскость раскроя. \en Cutting plane. - IDS_PROP_0654, ///< \ru Наличие штриховки. \en Whether there is hatching. - IDS_PROP_0655, ///< \ru Шаг штриховки. \en Hatching step. - IDS_PROP_0656, ///< \ru Угол штриховки. \en Hatching angle. - IDS_PROP_0657, ///< \ru Проекционная плоскость. \en Projection plane. - IDS_PROP_0658, ///< \ru Наличие невидимых линий. \en Whether there are invisible lines. - IDS_PROP_0659, ///< \ru Hash имени. \en Hash of name. - - IDS_PROP_0660, ///< \ru Коэффициент нейтрального слоя. \en Neutral layer coefficient. - IDS_PROP_0661, ///< \ru Радиус сгиба. \en Bend radius. - IDS_PROP_0662, ///< \ru Угол сгиба. \en Bend angle. - IDS_PROP_0663, ///< \ru Длина продолжения сгиба. \en Bend extension length. - IDS_PROP_0664, ///< \ru Смещение сгиба. \en Bend shift. - IDS_PROP_0665, ///< \ru Отступ от края сгиба 1. \en Distance from the bound of bend 1. - IDS_PROP_0666, ///< \ru Отступ от края сгиба 2. \en Distance from the bound of bend 2. - IDS_PROP_0667, ///< \ru Угол уклона края сгиба 1. \en Slope angle of the bound of bend 1. - IDS_PROP_0668, ///< \ru Угол уклона края сгиба 2. \en Slope angle of the bound of bend 2. - IDS_PROP_0669, ///< \ru Угол уклона продолжения сгиба 1. \en Slope angle of bend extension 1. - IDS_PROP_0670, ///< \ru Угол уклона продолжения сгиба 2. \en Slope angle of bend extension 2. - IDS_PROP_0671, ///< \ru Расширение продолжения сгиба 1. \en Expansion of extension of bend 1. - IDS_PROP_0672, ///< \ru Расширение продолжения сгиба 2. \en Expansion of extension of bend 2. - IDS_PROP_0673, ///< \ru Ширина разгрузки сгиба. \en Width of bend relief. - IDS_PROP_0674, ///< \ru Глубина разгрузки сгиба. \en Depth of bend relief. - IDS_PROP_0675, ///< \ru Радиус скругления разгрузки. \en Radius of relief rounding. - IDS_PROP_0676, ///< \ru Способ освобождения углов. \en Method of freeing the corners. - IDS_PROP_0677, ///< \ru Фиксированная часть грани слева. \en Fixed part of a face on the left. - IDS_PROP_0678, ///< \ru Строить разогнутым. \en Build in unbent state. - IDS_PROP_0679, ///< \ru Зазор. \en Gap. - IDS_PROP_0680, ///< \ru Перехлёстывающая сторона слева. \en Overlapping side on the left. - IDS_PROP_0681, ///< \ru С добавлением материала. \en With addition of material. - IDS_PROP_0682, ///< \ru Высота. \en Height. - IDS_PROP_0683, ///< \ru Коэффициент сгиба 1. \en Coefficient of bend 1. - IDS_PROP_0684, ///< \ru Радиус сгиба 1. \en Radius of bend 1. - IDS_PROP_0685, ///< \ru Коэффициент сгиба 2. \en Coefficient of bend 2. - IDS_PROP_0686, ///< \ru Радиус сгиба 2. \en Radius of bend 2. - IDS_PROP_0687, ///< \ru Радиус скругления эскиза. \en Radius of a sketch fillet. - IDS_PROP_0688, ///< \ru Радиус скругления основания. \en Radius of a base fillet. - IDS_PROP_0689, ///< \ru Радиус скругления дна. \en Radius of a bottom fillet. - IDS_PROP_0690, ///< \ru Открытая штамповка. \en Open stamping. - IDS_PROP_0691, ///< \ru Боковая стенка внутри. \en Side wall is inside. - IDS_PROP_0692, ///< \ru Ширина основания. \en Width of base. - IDS_PROP_0693, ///< \ru Ширина выпуклой части. \en Width of a salient part. - IDS_PROP_0694, ///< \ru Зазор рубленой законцовки. \en Gap of a cropped tip. - IDS_PROP_0695, ///< \ru Тип буртика. \en Bead type. - IDS_PROP_0696, ///< \ru Тип законцовки. \en Type of a tip. - IDS_PROP_0697, ///< \ru Вытяжка. \en Stretch. - IDS_PROP_0698, ///< \ru По нормали к толщине. \en By the normal to thickness. - IDS_PROP_0699, ///< \ru Способ замыкания цилиндрических частей. \en Method of cylindric parts closure. - IDS_PROP_0700, ///< \ru Разрешение на замыкание углов. \en Permission for corners closure. - - IDS_PROP_0701, ///< \ru Имя. \en Name. - IDS_PROP_0702, ///< \ru Значение. \en Value. - IDS_PROP_0703, ///< \ru Положение. \en Position. - IDS_PROP_0704, ///< \ru Число. \en Number. - IDS_PROP_0705, ///< \ru Ориентация. \en Orientation. - IDS_PROP_0706, ///< \ru Длина. \en Length. - IDS_PROP_0707, ///< \ru Толщина. \en Thickness. - IDS_PROP_0708, ///< \ru Угол. \en Angle. - IDS_PROP_0709, ///< \ru Параметр. \en Parameter. - IDS_PROP_0710, ///< \ru Геометрический объект. \en Geometric object. - IDS_PROP_0711, ///< \ru Точка. \en Point. - IDS_PROP_0712, ///< \ru Кривая. \en Curve. - IDS_PROP_0713, ///< \ru Поверхность. \en Surface. - IDS_PROP_0714, ///< \ru Вершина. \en Vertex. - IDS_PROP_0715, ///< \ru Ребро грани. \en Edge of a face. - IDS_PROP_0716, ///< \ru Цикл грани. \en Face loop. - IDS_PROP_0717, ///< \ru Грань. \en Face. - IDS_PROP_0718, ///< \ru Полюс при umin. \en Pole at umin. - IDS_PROP_0719, ///< \ru Полюс при umax. \en Pole at umax. - IDS_PROP_0720, ///< \ru Полюс при vmin. \en Pole at vmin. - IDS_PROP_0721, ///< \ru Полюс при vmax. \en Pole at vmax. - IDS_PROP_0724, ///< \ru Вершина. \en Vertex. - IDS_PROP_0725, ///< \ru Ребро. \en Edge. - IDS_PROP_0726, ///< \ru Цикл. \en Loop. - IDS_PROP_0727, ///< \ru Грань. \en Face. - IDS_PROP_0729, ///< \ru Количество граней. \en Number of faces. - IDS_PROP_0730, ///< \ru Количество операций. \en Number of operations. - IDS_PROP_0731, ///< \ru Количество объектов. \en Number of objects. - IDS_PROP_0732, ///< \ru Объединение граней. \en Faces unification. - IDS_PROP_0733, ///< \ru Обработка углов. \en Corners treatment. - IDS_PROP_0734, ///< \ru Операция объединения. \en Union operation. - IDS_PROP_0735, ///< \ru Операция пересечения. \en Intersection operation. - IDS_PROP_0736, ///< \ru Операция разности. \en Subtraction operation. - IDS_PROP_0737, ///< \ru Базовая операция. \en Base operations. - IDS_PROP_0738, ///< \ru Флаг состояния. \en Flag of state. - IDS_PROP_0739, ///< \ru Параметр полюса по U. \en Parameter of a pole by U. - IDS_PROP_0740, ///< \ru Номер грани. \en Number of a face. - IDS_PROP_0741, ///< \ru Номер ребра. \en Number of an edge. - IDS_PROP_0742, ///< \ru Номер грани плюс. \en Number of a face plus. - IDS_PROP_0743, ///< \ru Номер грани минус. \en Number of a face minus. - IDS_PROP_0744, ///< \ru Формировать твёрдое тело. \en Create a solid. - IDS_PROP_0745, ///< \ru Точность сшивки. \en Stitching tolerance. - IDS_PROP_0746, ///< \ru Через сгиб. \en Through a bend. - IDS_PROP_0747, ///< \ru Полюс. \en Pole. - IDS_PROP_0748, ///< \ru Край. \en Border. - IDS_PROP_0749, ///< \ru Шов. \en Seam. - IDS_PROP_0750, ///< \ru Линия перехода. \en Transition line. - IDS_PROP_0751, ///< \ru Адрес начальной вершины. \en Start vertex address. - IDS_PROP_0752, ///< \ru Адрес конечной вершины. \en End vertex address. - IDS_PROP_0753, ///< \ru Адрес грани слева. \en Address of a face on the left. - IDS_PROP_0754, ///< \ru Адрес грани справа. \en Address of a face on the right. - IDS_PROP_0755, ///< \ru Примитив разрезан. \en Primitive is cut. - IDS_PROP_0756, ///< \ru Листовой примитив. \en Sheet primitive. - IDS_PROP_0757, ///< \ru Внутренняя грань сгиба. \en Internal face of a bend. - IDS_PROP_0758, ///< \ru Внешняя грань сгиба. \en External face of a bend. - IDS_PROP_0759, ///< \ru Угол раствора конуса. \en Cone angle. - -// \ru Версии \en Versions - - IDS_PROP_0760, ///< \ru Версия. \en Version. - IDS_PROP_0761, ///< \ru Версия имени. \en Version of name. - IDS_PROP_0762, ///< \ru Версия операции. \en Version of operation. - IDS_PROP_0763, ///< \ru Версия объекта. \en Version of object. - -// \ru Информация от геометрической модели \en Information from geometric model - - IDS_PROP_0771, ///< \ru Количество вершин. \en Number of vertices. - IDS_PROP_0772, ///< \ru Количество кривых. \en Number of curves. - IDS_PROP_0773, ///< \ru Количество поверхностей. \en Number of surfaces. - IDS_PROP_0774, ///< \ru Количество тел. \en Number of solids. - IDS_PROP_0775, ///< \ru Количество полигональных объектов. \en Number of polygonal objects. - IDS_PROP_0776, ///< \ru Количество проволочных каркасов. \en Number of wireframes. - IDS_PROP_0777, ///< \ru Количество точечных каркасов. \en Number of point frames. - IDS_PROP_0778, ///< \ru Количество сборочных единиц. \en Number of assembly units. - IDS_PROP_0779, ///< \ru Количество вставок. \en Number of instances. - IDS_PROP_0780, ///< \ru Количество других объектов. \en Number of other objects. - IDS_PROP_0781, ///< \ru Количество регионов. \en Number of regions. - IDS_PROP_0782, ///< \ru Количество элементов. \en Number of elements. - IDS_PROP_0783, ///< \ru Количество сегментов. \en Number of segments. - IDS_PROP_0784, ///< \ru Количество всех граней. \en Number of all faces. - IDS_PROP_0785, ///< \ru Количество всех уникальных граней. \en Number of all unique faces. - - IDS_PROP_0791, ///< \ru Первая деформация. \en First strain. - IDS_PROP_0792, ///< \ru Вторая деформация. \en Second strain. - IDS_PROP_0793, ///< \ru Третья деформация. \en Third strain. - - IDS_PROP_0797, ///< \ru Модуль Юнга. \en Young's modulus. - IDS_PROP_0798, ///< \ru Коэффициент Пуассона. \en Poisson's ratio. - - IDS_PROP_0830, ///< \ru Число радиусов эквидистант. \en Number of offsets radii. - IDS_PROP_0831, ///< \ru Гладкий стык. \en Smooth joint. - IDS_PROP_0832, ///< \ru Тип обхода угла. \en Type of corner bypass. - IDS_PROP_0833, ///< \ru Радиус специального скругления. \en Radius of a special fillet. - IDS_PROP_0834, ///< \ru Тип законцовки. \en Type of a tip. - IDS_PROP_0835, ///< \ru Законцовка первого сегмента. \en Tip of the first segment. - IDS_PROP_0836, ///< \ru Тип законцовки в начале. \en Type of tip at the beginning. - IDS_PROP_0837, ///< \ru Тип законцовки в конце. \en Type of tip at the end. - IDS_PROP_0838, ///< \ru Параметр законцовки. \en Parameter of a tip. - - IDS_PROP_0839, ///< \ru Параметр построения заплатки. \en Parameter of a patch construction. - IDS_PROP_0840, ///< \ru Число кривых образующего контура. \en Number of curves of a generating contour. - IDS_PROP_0841, ///< \ru Даны образующие грани. \en The generating faces are given. - IDS_PROP_0842, ///< \ru Кривая образующего контура. \en Curve of a generaing contour. - IDS_PROP_0843, ///< \ru Ориентация кривой контура. \en Orientation of a curve of the contour. - IDS_PROP_0844, ///< \ru Сторона существующей грани оболочки. \en Side of an existent face of the shell. - IDS_PROP_0845, ///< \ru Да. \en Yes. - IDS_PROP_0846, ///< \ru Нет. \en No. - -// \ru Контейнер атрибутов \en Attribute container - - IDS_PROP_0847, ///< \ru Поставщик атрибутов. \en Attribute provider. - IDS_PROP_0848, ///< \ru Количество контейнеров. \en Number of containers. - IDS_PROP_0849, ///< \ru Контейнер. \en Container. - - IDS_PROP_0851, ///< \ru Количество атрибутов. \en Number of attributes. - - IDS_PROP_0853, ///< \ru При изменении. \en While changing. - IDS_PROP_0854, ///< \ru При конвертации. \en While convertation. - IDS_PROP_0855, ///< \ru При трансформировании. \en While transforming. - IDS_PROP_0856, ///< \ru При копировании. \en While copying. - IDS_PROP_0857, ///< \ru При объединении. \en While joining. - IDS_PROP_0858, ///< \ru При замене. \en While replacing. - IDS_PROP_0859, ///< \ru При разделении. \en While splitting. - IDS_PROP_0860, ///< \ru При удалении. \en While deleting. - IDS_PROP_0861, ///< \ru Объект свободен. \en The object is free. - IDS_PROP_0862, ///< \ru Копируемость. \en Whether it can be copied. - IDS_PROP_0863, ///< \ru Количество u-линий. \en The number of u-lines. - IDS_PROP_0864, ///< \ru Количество v-линий. \en The number of v-lines. - - IDS_PROP_0869, ///< \ru Имя исполнения. \en Embodiment name. - IDS_PROP_0870, ///< \ru Имя родительского исполнения. \en Parent embodiment name. - IDS_PROP_0871, ///< \ru Красный. \en Red. - IDS_PROP_0872, ///< \ru Зелёный. \en Green. - IDS_PROP_0873, ///< \ru Синий. \en Blue. - IDS_PROP_0874, ///< \ru Толщина. \en Thickness. - IDS_PROP_0875, ///< \ru Стиль. \en Slyle. - IDS_PROP_0876, ///< \ru Плотность. \en Density. - IDS_PROP_0877, ///< \ru Идентификатор. \en Identifier. - IDS_PROP_0878, ///< \ru Селектированность. \en Selectivity. - IDS_PROP_0879, ///< \ru Видимость. \en Visibility. - IDS_PROP_0880, ///< \ru Изменённость. \en Modified. - IDS_PROP_0881, ///< \ru Общий фон. \en Background. - IDS_PROP_0882, ///< \ru Диффузное отражение. \en Diffuse reflection. - IDS_PROP_0883, ///< \ru Зеркальное отражение. \en Specular reflection. - IDS_PROP_0884, ///< \ru Блеск. \en Shininess. - IDS_PROP_0885, ///< \ru Непрозрачность. \en Opacity. - IDS_PROP_0886, ///< \ru Излучение. \en Emission. - IDS_PROP_0887, ///< \ru Количество родительских объектов. \en Number of parent objects. - IDS_PROP_0888, ///< \ru Родительский объект. \en Parent object. - IDS_PROP_0889, ///< \ru Имя топологического объекта. \en Topological object name. - IDS_PROP_0890, ///< \ru Имя объекта. \en Object name. - IDS_PROP_0891, ///< \ru Хэш имени объекта. \en Object name hash. - - IDS_PROP_0900, ///< \ru Сопряжение в точке. \en Conjugation at point. - IDS_PROP_0901, ///< \ru Тип сопряжения. \en Conjugation type. - IDS_PROP_0902, ///< \ru Без сопряжения. \en Without conjugation. - IDS_PROP_0903, ///< \ru По позиции. \en By position. - IDS_PROP_0904, ///< \ru По касательной. \en By tangent. - IDS_PROP_0905, ///< \ru По нормали. \en By normal. - IDS_PROP_0906, ///< \ru По G2. \en By G2. - IDS_PROP_0907, ///< \ru По G3. \en By G3. - IDS_PROP_0908, ///< \ru Касательный вектор. \en Tangent vector. - IDS_PROP_0909, ///< \ru Первая производная касательного вектора. \en First derivative of tangent vector. - IDS_PROP_0910, ///< \ru Вторая производная касательного вектора. \en Second derivative of tangent vector. - IDS_PROP_0911, ///< \ru Можно ли двигать точки. \en Whether points can be moved. - IDS_PROP_0912, ///< \ru Только по направлению. \en Only along the direction. - IDS_PROP_0913, ///< \ru Сопряжение. \en Conjugation. - - IDS_PROP_0920, ///< \ru Тип параметризации. \en Parametrization type. - IDS_PROP_0921, ///< \ru Пользовательская. \en Custom. - IDS_PROP_0922, ///< \ru Равномерная. \en Uniform. - IDS_PROP_0923, ///< \ru По длине хорды. \en By chord length. - IDS_PROP_0924, ///< \ru Центростремительная. \en Centripetal. - - IDS_PROP_0925, ///< \ru Через вершины. \en Through vertices. - IDS_PROP_0926, ///< \ru Равномерная параметризация. \en Uniform parametrization. - - IDS_PROP_0927, ///< \ru Признак текущего исполнения. \en Mark of current embodiment. - -// \ru Конвертеры \en Converters - - IDS_PROP_1000, ///< \ru Заголовок. \en Title. - IDS_PROP_1001, ///< \ru Название. \en Name. - IDS_PROP_1002, ///< \ru Дата и время. \en Date and time. - IDS_PROP_1003, ///< \ru Автор(ы). \en Author(s)). - IDS_PROP_1004, ///< \ru Организация(и). \en Organization(s). - IDS_PROP_1005, ///< \ru Процессор STEP. \en Processor STEP. - IDS_PROP_1006, ///< \ru Система. \en System. - IDS_PROP_1007, ///< \ru Авторизация. \en Authorization. - - IDS_PROP_1010, ///< \ru Лицо и организация. \en Person and organization. - IDS_PROP_1011, ///< \ru Идентификатор лица. \en Identifier of a person. - IDS_PROP_1012, ///< \ru Фамилия. \en Surname. - IDS_PROP_1013, ///< \ru Имя. \en Name. - IDS_PROP_1014, ///< \ru Средние имена. \en Middle names. - IDS_PROP_1015, ///< \ru Титулы предшествующие. \en Prefix titles. - IDS_PROP_1016, ///< \ru Титулы завершающие. \en Suffix titles. - IDS_PROP_1017, ///< \ru Идентификатор организации. \en Identifier of organization. - IDS_PROP_1018, ///< \ru Название организации. \en Name of organization. - IDS_PROP_1019, ///< \ru Описание организации. \en Description of organization. - - IDS_PROP_1030, ///< \ru Изделие. \en Product. - IDS_PROP_1031, ///< \ru Идентификатор. \en Identifier. - IDS_PROP_1032, ///< \ru Название. \en Name. - IDS_PROP_1033, ///< \ru Описание. \en Description. - - IDS_PROP_1043, ///< \ru Элемент описания. \en Description element. - - /* - 1100 .. 1199 is a range for C3D Solver - */ - IDS_PROP_1100, ///< \ru Геометрический решатель. \en Geom solver. - IDS_PROP_1101, ///< \ru Схема сопряжений. \en Scheme of matings. - IDS_PROP_1102, ///< \ru Система ограничений. \en Constraint system. - IDS_PROP_1103, ///< \ru Ограничение. \en Constraint. - IDS_PROP_1104, ///< \ru Тип сопряжения. \en Type of mating. - IDS_PROP_1105, ///< \ru Тип ограничения. \en Type of constraint. - IDS_PROP_1106, ///< \ru Выравнивание. \en Alignment. - IDS_PROP_1107, ///< \ru Количество ограничений. \en Number of constraints. - IDS_PROP_1108, ///< \ru Тип взаимоориентации. \en Coorientation type. - IDS_PROP_1109, ///< \ru Сопряжение. \en Mate. - IDS_PROP_1110, ///< \ru Базовый объект. \en Base object. - IDS_PROP_1111, ///< \ru Объект 1. \en Object 1. - IDS_PROP_1112, ///< \ru Объект 2. \en Object 2. - IDS_PROP_1113, ///< \ru Вещественный параметр. \en Real parameter. - IDS_PROP_1114, ///< \ru Величина взаимоориентации. \en Value of coorientation. - - /* - Types of geometric constraint - */ - IDS_PROP_1130, ///< \ru Совпадение \en Coincident - IDS_PROP_1131, ///< \ru Параллельность \en Parallel - IDS_PROP_1132, ///< \ru Перпендикулярность \en Perpendicular - IDS_PROP_1133, ///< \ru Касание \en Tangent. - IDS_PROP_1134, ///< \ru Концентричность \en Concentric - IDS_PROP_1135, ///< \ru На расстоянии \en Distance - IDS_PROP_1136, ///< \ru По углом \en Angle - IDS_PROP_1137, ///< \ru По месту \en In place - IDS_PROP_1138, ///< \ru Механическая передача \en Transmittion - IDS_PROP_1139, ///< \ru Кулачковый механизм \en Cam mechanism - IDS_PROP_1140, ///< \ru Радиальный размер. \en Radial dimension. - IDS_PROP_1145, ///< \ru Симметричность \en Symmetric - IDS_PROP_1146, ///< \ru Зависимый объект \en Dependent - IDS_PROP_1147, ///< \ru Элемент паттерна \en Patterned - IDS_PROP_1148, ///< \ru Линейный паттерн \en Linear pattern - IDS_PROP_1149, ///< \ru Угловой паттерн \en Angular pattern - IDS_PROP_1199, // The last id for C3D Solver - - /* - \ru Новые описания без группировки \en New unsorted descriptions - */ - - IDS_PROP_2001, ///< \ru Внимание: \en Attention: - IDS_PROP_2002, ///< \ru Начало общих операций. \en Beginning of the shared operations. - IDS_PROP_2003, ///< \ru Начало группы операций. \en Beginning of the operations group. - IDS_PROP_2004, ///< \ru Начало первой группы операций. \en Beginning of the first operations group. - IDS_PROP_2005, ///< \ru Начало второй группы операций. \en Beginning of the second operations group. - IDS_PROP_2006, ///< \ru Начало объекта. \en Beginning of an object. - IDS_PROP_2007, ///< \ru Начало первого объекта. \en Beginning of the first object. - IDS_PROP_2008, ///< \ru Начало второго объекта. \en Beginning of the second object. - IDS_PROP_2009, ///< \ru Копировать атрибуты. \en Copy attributes. - IDS_PROP_2010, ///< \ru Количество общих групп операций. \en Number of shared operations groups. - IDS_PROP_2011, ///< \ru Количество выбранных граней. \en Number of selected faces. - IDS_PROP_2012, ///< \ru Количество выбранных ребёр. \en Number of selected edges. - IDS_PROP_2013, ///< \ru Количество выбранных вершин. \en Number of selected vertices. - IDS_PROP_2014, ///< \ru Секущий эскиз. \en Cutting sketch. - IDS_PROP_2015, ///< \ru Секущие 3D-кривые. \en Cutting 3D-curves. - IDS_PROP_2016, ///< \ru Секущие поверхности. \en Cutting surfaces. - IDS_PROP_2017, ///< \ru Секущее тело. \en Cutting solid. - - IDS_PROP_2018, ///< \ru Поверхность сопряжения на границе 0. \en Adjacent surface on the border 0. - IDS_PROP_2019, ///< \ru Поверхность сопряжения на границе 1. \en Adjacent surface on the border 1. - IDS_PROP_2020, ///< \ru Поверхность сопряжения на границе 2. \en Adjacent surface on the border 2. - IDS_PROP_2021, ///< \ru Поверхность сопряжения на границе 3. \en Adjacent surface on the border 3. - IDS_PROP_2022, ///< \ru Поверхность сопряжения на границе 4. \en Adjacent surface on the border 4. - IDS_PROP_2023, ///< \ru Сопряжение на границе 0. \en Conjugation on the boundary 0. - IDS_PROP_2024, ///< \ru Сопряжение на границе 1. \en Conjugation on the boundary 1. - IDS_PROP_2025, ///< \ru Сопряжение на границе 2. \en Conjugation on the boundary 2. - IDS_PROP_2026, ///< \ru Сопряжение на границе 3. \en Conjugation on the boundary 3. - IDS_PROP_2027, ///< \ru Сопряжение на границе 4. \en Conjugation on the boundary 4. - - IDS_PROP_LAST = 9999, ///< \ru Наибольшее значение. \en The greatest value. -}; - - -#endif // __MB_PROPERTY_TITLE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Свойства математических объектов. + \en Properties of mathematical objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MB_PROPERTY_TITLE_H +#define __MB_PROPERTY_TITLE_H + + +//------------------------------------------------------------------------------ +/** \brief \ru Свойства математических объектов. + \en Properties of mathematical objects. \~ + \attention \ru Целочисленные значения данного перечислительного типа могут быть изменены! + \en Integer values of the enum can be changed! + \ingroup Base_Items +*/ +// --- +enum MbePrompt +{ + IDS_ITEM_0000 = 0, ///< \ru Неопределенный объект. + +// \ru Базовые объекты двумерной математики. \en Base 2D objects. + + IDS_ITEM_0001, ///< \ru Двумерная точка. \en A two-dimensional point. + IDS_ITEM_0002, ///< \ru Двумерный вектор. \en Two-dimensional vector. + IDS_ITEM_0003, ///< \ru Двумерная матрица преобразования. \en Two-dimensional matrix of transformation. + IDS_ITEM_0004, ///< \ru Двумерная локальная система. \en Two-dimensional local system. + IDS_ITEM_0005, ///< \ru Двумерный единичный вектор. \en Two-dimensional unit vector + +// \ru Типы двумерных кривых. \en Types of two-dimensional curves. + + IDS_ITEM_0011, ///< \ru Двумерная кривая. \en Two-dimensional curve + + IDS_ITEM_0013, ///< \ru Двумерная прямая. \en Two-dimensional line. + IDS_ITEM_0014, ///< \ru Двумерный отрезок. \en Two-dimensional segment. + IDS_ITEM_0015, ///< \ru Двумерный отрезок прямой. \en Two-dimensional line segment. + IDS_ITEM_0016, ///< \ru Двумерная дуга окружности. \en Two-dimensional circular arc. + IDS_ITEM_0017, ///< \ru Двумерная усеченная кривая. \en Two-dimensional truncated curve. + IDS_ITEM_0018, ///< \ru Двумерная эквидистантная кривая. \en Two-dimensional offset curve. + IDS_ITEM_0019, ///< \ru Двумерная эквидистанта. \en Two-dimensional equidistant. + IDS_ITEM_0020, ///< \ru Двумерная окружность. \en Two-dimensional circle. + IDS_ITEM_0021, ///< \ru Двумерный эллипс. \en Two-dimensional ellipse. + IDS_ITEM_0022, ///< \ru Двумерная парабола. \en Two-dimensional parabola. + IDS_ITEM_0023, ///< \ru Двумерная дуга эллипса. \en Two-dimensional elliptical arc. + IDS_ITEM_0024, ///< \ru Двумерная ломаная. \en Two-dimensional polyline. + IDS_ITEM_0025, ///< \ru Двумерная NURBS кривая. \en Two-dimensional NURBS curve. + IDS_ITEM_0026, ///< \ru Двумерный сплайн Эрмита. \en Two-dimensional Hermite spline. + IDS_ITEM_0027, ///< \ru Двумерный сплайн Безье. \en Two-dimensional Bezier spline. + IDS_ITEM_0028, ///< \ru Двумерный кубический сплайн. \en Two-dimensional cubic spline. + IDS_ITEM_0029, ///< \ru Двумерная репараметризованная кривая. \en Two-dimensional reparametrized curve. + IDS_ITEM_0030, ///< \ru Двумерный контур. \en Two-dimensional contour. + IDS_ITEM_0031, ///< \ru Двумерная косинусоида. \en Two-dimensional cosine curve. + IDS_ITEM_0032, ///< \ru Двумерная точечная кривая. \en Two-dimensional point curve. + IDS_ITEM_0040, ///< \ru Двумерная область. \en Two-dimensional region. + IDS_ITEM_0050, ///< \ru Двумерный объект. \en Two-dimensional object. + IDS_ITEM_0051, ///< \ru Двумерная мультилиния. \en Two-dimensional multiline. + IDS_ITEM_0052, ///< \ru Двумерная кривая на конусе, соответствующая кривой на коническом изгибе плоскости. \en Two-dimensional curve on cone corresponding to a curve on conic bend of a plane. + IDS_ITEM_0053, ///< \ru Двумерная кривая на плоскости, соответствующая кривой на изгибе конуса. \en Two-dimensional curve on plane corresponding to a curve on a bend of cone + IDS_ITEM_0054, ///< \ru Двумерная кривая, координатные функции которой заданы в символьном виде. \en Functionally defined two-dimensional curve. + IDS_ITEM_0055, ///< \ru Образ трехмерной кривой на поверхности при движении по направляющей. \en Image of a three-dimensional curve on surface while moving along the guide curve. + +// \ru Типы полигональных объектов. \en Types of simplified forms of an object. + + IDS_ITEM_0060, ///< \ru Параметр. \en Parameter. + IDS_ITEM_0061, ///< \ru Вершина. \en Vertex. + IDS_ITEM_0062, ///< \ru Нормаль. \en Normal. + IDS_ITEM_0063, ///< \ru Треугольник. \en Triangle. + IDS_ITEM_0064, ///< \ru Четырехугольник. \en Quadrangle. + IDS_ITEM_0071, ///< \ru Полигональный объект на числах double. \en Polygonal object on double data. + IDS_ITEM_0072, ///< \ru Апекс на числах double. \en Apex on double data. + IDS_ITEM_0073, ///< \ru Полигон на числах double. \en Polygon on double data. + IDS_ITEM_0074, ///< \ru Триангуляция на числах double. \en Triangulation on double data. + IDS_ITEM_0075, ///< \ru Полигональный объект на числах float. \en Polygonal object on float data. + IDS_ITEM_0076, ///< \ru Апекс на числах float. \en Apex on float data. + IDS_ITEM_0077, ///< \ru Полигон на числах float. \en Polygon on float data. + IDS_ITEM_0078, ///< \ru Триангуляция на числах float. \en Triangulation on float data. + +// \ru Базовые объекты трехмерной математики. \en Base objects of three-dimensional mathematics. + + IDS_ITEM_0101, ///< \ru Точка. \en Point. + IDS_ITEM_0102, ///< \ru Вектор. \en Vector. + IDS_ITEM_0103, ///< \ru Матрица преобразования. \en Transformation matrix. + IDS_ITEM_0104, ///< \ru Локальная система координат. \en Local coordinate system. + +// \ru Типы функций \en Types of functions + + IDS_ITEM_0111, ///< \ru Kонстантная функция. \en Constant Function. + IDS_ITEM_0112, ///< \ru Линейная функция. \en Linear Function. + IDS_ITEM_0113, ///< \ru Kубическая функция. \en Cubic Function. + IDS_ITEM_0114, ///< \ru Kубическай сплайн-функция. \en Cubic spline Function. + IDS_ITEM_0115, ///< \ru Символьная функция. \en Symbolic Function. + IDS_ITEM_0116, ///< \ru Степенная функция. \en Power Function. + IDS_ITEM_0117, ///< \ru Синус функция. \en Sinus Function. + +// \ru Типы трехмерных кривы.х \en Types of three-dimensional curves. + + IDS_ITEM_0201, ///< \ru Кривая. \en Curve. + IDS_ITEM_0202, ///< \ru B-сплайн. \en B-spline. + IDS_ITEM_0213, ///< \ru Прямая линия. \en Straight Line. + IDS_ITEM_0214, ///< \ru Отрезок. \en Segment. + IDS_ITEM_0215, ///< \ru Дуга эллипса. \en Elliptic Arc. + IDS_ITEM_0216, ///< \ru Дуга окружности. \en Circular Arc. + IDS_ITEM_0217, ///< \ru Усеченная кривая. \en Truncated Curve. + IDS_ITEM_0218, ///< \ru Эквидистантная кривая. \en Offset Curve. + IDS_ITEM_0219, ///< \ru Коническая спираль. \en Conical Spiral. + IDS_ITEM_0220, ///< \ru Oкружность. \en Circle. + IDS_ITEM_0221, ///< \ru Эллипс. \en Ellipse. + IDS_ITEM_0222, ///< \ru Парабола. \en Parabola. + IDS_ITEM_0223, ///< \ru Гипербола. \en Hyperbola. + IDS_ITEM_0224, ///< \ru Ломаная линия. \en Polyline. + IDS_ITEM_0225, ///< \ru NURBS кривая. \en NURBS Curve. + IDS_ITEM_0226, ///< \ru Сплайн Эрмита. \en Hermite Spline. + IDS_ITEM_0227, ///< \ru Сплайн Безье. \en Bezier Spline. + IDS_ITEM_0228, ///< \ru Кубический сплайн. \en Cubic Spline. + IDS_ITEM_0229, ///< \ru Репараметризованная кривая. \en Reparametrized Curve. + IDS_ITEM_0231, ///< \ru Плоская кривая. \en Plane curve. + IDS_ITEM_0232, ///< \ru Спираль с переменым радиусом. \en Spiral with Variable Radius. + IDS_ITEM_0233, ///< \ru Спираль с криволинейной осью. \en Spiral with a Curved Axis. + IDS_ITEM_0234, ///< \ru Кривая-мостик. \en Bridge Curve. + IDS_ITEM_0235, ///< \ru Символьная кривая. \en Functionally Defined Curve. + IDS_ITEM_0236, ///< \ru Кривая на поверхности. \en Curve on a Surface. + IDS_ITEM_0237, ///< \ru Линия пересечения поверхностей. \en Intersection Curve of Surfaces. + IDS_ITEM_0238, ///< \ru Контур на поверхности. \en Contour on a Surface. + IDS_ITEM_0239, ///< \ru Контур на плоскости. \en Contour on a Plane. + IDS_ITEM_0240, ///< \ru Контур. \en Contour. + IDS_ITEM_0241, ///< \ru Проекционная кривая. \en Projection Curve. + IDS_ITEM_0242, ///< \ru Силуэтная кривая. \en Silhouette Curve. + IDS_ITEM_0243, ///< \ru Кривая сопряжения кривых. \en Curve of Curves Conjugation. + IDS_ITEM_0244, ///< \ru Кривая производных поверхности Кунса. \en Curve of Coons Surface Derivetives. + IDS_ITEM_0249, ///< \ru Направляющая кривая. \en Guide Curve. + IDS_ITEM_0250, ///< \ru Кривая пересечения. \en Intersection Curve. + + 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_0256, ///< \ru Второе направляющее ребро. \en Second Guide Edge. + IDS_ITEM_0257, ///< \ru Вторая направляющая кривая. \en Second Guide Curve. + IDS_ITEM_0258, ///< \ru Вторая грань для стыковки. \en Second Mating Face. + +// \ru Типы параметрических поверхностей. \en Types of parametric surfaces. + + IDS_ITEM_0301, ///< \ru Поверхность. \en Surface. + IDS_ITEM_0302, ///< \ru Поверхность заметания. \en Sweep Surface. + IDS_ITEM_0303, ///< \ru Поверхность сдвига. \en Motion Surface. + IDS_ITEM_0304, ///< \ru Поверхность выдавливания. \en Extrusion Surface. + IDS_ITEM_0305, ///< \ru Поверхность вращения. \en Revolution Surface. + IDS_ITEM_0306, ///< \ru Линейчатая поверхность. \en Ruled Surface. + IDS_ITEM_0307, ///< \ru Поверхность по кривой и точке. \en Surface Defined by a Curve and a Point. + IDS_ITEM_0308, ///< \ru Четырехугольная поверхность. \en Quadrangular Surface. + IDS_ITEM_0309, ///< \ru Треугольная поверхность. \en Triangular Surface. + IDS_ITEM_0310, ///< \ru Поверхность движения с доворотом. \en Sweep with Guide Curve Surface with Rotating Ends. + IDS_ITEM_0311, ///< \ru Поверхность на семействе кривых и напрвляющей. \en Loft Surface with Guide Curve. + IDS_ITEM_0312, ///< \ru Спиральная поверхность. \en Spiral Surface. + IDS_ITEM_0313, ///< \ru Цилиндрически согнутая поверхность. \en Cylindrically Bent Surface. + IDS_ITEM_0314, ///< \ru Цилиндрически разогнутая поверхность. \en Cylindrically Unbent Surface. + IDS_ITEM_0315, ///< \ru Конически согнутая поверхность. \en Conically Bent Surface. + IDS_ITEM_0316, ///< \ru Конически разогнутая поверхность. \en Conically Unbent Surface. + IDS_ITEM_0317, ///< \ru Поверхность заметания с изменением образующей. \en Sweep Surface with Changin Generatin. + IDS_ITEM_0319, ///< \ru Плоскость. \en Plane. + IDS_ITEM_0320, ///< \ru Сферическая поверхность. \en Spherical Surface. + IDS_ITEM_0321, ///< \ru Тороидальная поверхность. \en Toroidal Surface. + IDS_ITEM_0322, ///< \ru Цилиндрическая поверхность. \en Cylindrical Surface. + IDS_ITEM_0323, ///< \ru Коническая поверхность. \en Conical Surface. + IDS_ITEM_0325, ///< \ru NURBS поверхность. \en NURBS Surface. + IDS_ITEM_0326, ///< \ru Треугольная NURBS поверхность. \en Triangular NURBS Surface. + IDS_ITEM_0327, ///< \ru Поверхность Безье. \en Bezier Surface. + IDS_ITEM_0328, ///< \ru Эквидистантная поверхность. \en Offset Surface. + IDS_ITEM_0329, ///< \ru Деформированная поверхность. \en Deformed Surface. + IDS_ITEM_0330, ///< \ru Поверхность Грегори. \en Gregory Surface. + IDS_ITEM_0331, ///< \ru Поверхность соединения. \en Joint Surface. + IDS_ITEM_0332, ///< \ru Поверхность объединения. \en Join Surface. + IDS_ITEM_0333, ///< \ru Поверхность на трех кривых. \en Surface Based on Three Curves. + IDS_ITEM_0334, ///< \ru Поверхность на четырех кривых. \en Surface Based on Four Curves. + IDS_ITEM_0335, ///< \ru Поверхность-фаска. \en Chamfer Surface. + IDS_ITEM_0336, ///< \ru Поверхность скругления. \en Fillet Surface. + IDS_ITEM_0337, ///< \ru Переменная поверхность скругления. \en Variable Fillet Surface. + IDS_ITEM_0338, ///< \ru Поверхность на семействе кривых. \en Lofted Surface. + IDS_ITEM_0339, ///< \ru Поверхность на сетке кривых. \en Surface defined on a mesh of curves. + IDS_ITEM_0340, ///< \ru Поверхность скругления по кромке. \en Surface of Fillet by Border. + IDS_ITEM_0341, ///< \ru Поверхность по замкнутому контуру. \en Surface on Closed Contour. + IDS_ITEM_0342, ///< \ru Плазовая поверхность. \en Spiling Surface. + IDS_ITEM_0343, ///< \ru Поверхность Кунса. \en Coons Surface. + IDS_ITEM_0345, ///< \ru Поверхность на сетке точек. \en Surface Based on a Point Grid. + IDS_ITEM_0346, ///< \ru Треугольная поверхность Безье. \en Triangular Bezier Surface. + IDS_ITEM_0349, ///< \ru Усеченная контурами поверхность. \en Curve bounded Surface. + IDS_ITEM_0350, ///< \ru Поверхность-копия. \en Copy Surface. + IDS_ITEM_0351, ///< \ru Поверхность соединения. \en Joint Surface. + IDS_ITEM_0352, ///< \ru Поверхность полного скругления. \en Full Fillet Surface. + IDS_ITEM_0353, ///< \ru Поверхность заметания с масштабированием. \en Swept Surface with Scaling. + IDS_ITEM_0354, ///< \ru Поверхность переменного сечения. \en The Swept Mutable Section Surface. + +// \ru Типы тел \en Types of solids + + IDS_ITEM_0401, ///< \ru Тело. \en Solid. + IDS_ITEM_0402, ///< \ru Оболочка. \en Shell. + IDS_ITEM_0403, ///< \ru Проволочный каркас. \en Wire Frame. + IDS_ITEM_0404, ///< \ru Точечный каркас. \en Point Frame. + IDS_ITEM_0405, ///< \ru Коллекция элементов. \en Collection of Elements. + +// \ru Типы строителей. \en Types of creators. + + IDS_ITEM_0501, ///< \ru Журнал построения. \en Build log. + IDS_ITEM_0502, ///< \ru Шар. \en Sphere. + IDS_ITEM_0503, ///< \ru Тор. \en Torus. + IDS_ITEM_0504, ///< \ru Цилиндр. \en Cylinder. + IDS_ITEM_0505, ///< \ru Конус. \en Cone. + IDS_ITEM_0506, ///< \ru Блок. \en Block. + IDS_ITEM_0507, ///< \ru Клин. \en Wedge. + IDS_ITEM_0508, ///< \ru Призма. \en Prism. + IDS_ITEM_0509, ///< \ru Пирамида. \en Pyramid. + IDS_ITEM_0510, ///< \ru Твёрдое тело. \en Solid. + IDS_ITEM_0511, ///< \ru Плита. \en Plate. + IDS_ITEM_0512, ///< \ru Икосаэдр. \en Icosahedron. + IDS_ITEM_0513, ///< \ru Многогранник. \en Polyhedron. + + IDS_ITEM_0515, ///< \ru Объединение оболочек. \en Shells union. + IDS_ITEM_0516, ///< \ru Пересечение оболочек. \en Shells intersection. + IDS_ITEM_0517, ///< \ru Разность оболочек. \en Shells subtraction. + + IDS_ITEM_0520, ///< \ru Отверстие. \en Hole. + IDS_ITEM_0521, ///< \ru Карман/Бобышка. \en Pocket/Boss. + IDS_ITEM_0522, ///< \ru Паз. \en Groove. + IDS_ITEM_0523, ///< \ru Заплатка. \en Patch. + IDS_ITEM_0524, ///< \ru Тонкая оболочка. \en Thin Shell. + + IDS_ITEM_0526, ///< \ru Оболочка на семействе кривых. \en Shell Defined by a Set of Curves. + IDS_ITEM_0527, ///< \ru Продолженная оболочка. \en Extended Shell. + IDS_ITEM_0528, ///< \ru Эквидистантная оболочка. \en Offset Shell. + IDS_ITEM_0529, ///< \ru Срединная оболочка. \en Median Shell. + IDS_ITEM_0530, ///< \ru Оболочка переменного сечения. \en The Swept Mutable Section Shell. + IDS_ITEM_0531, ///< \ru Булево объединение тел. \en Boolean Union of Solids. + IDS_ITEM_0532, ///< \ru Булево пересечение тел. \en Boolean Intersection of Solids. + IDS_ITEM_0533, ///< \ru Булевa разность тел. \en Boolean Subtraction of Solids. + IDS_ITEM_0534, ///< \ru Разрезанное тело. \en Cut Solid. + IDS_ITEM_0535, ///< \ru Фаски ребер. \en Edges Chamfers. + IDS_ITEM_0536, ///< \ru Скругление ребер. \en Edges Fillets. + IDS_ITEM_0537, ///< \ru Симметричное тело. \en Symmetric Solid. + IDS_ITEM_0538, ///< \ru Оболочечное тело. \en Thin Shell Solid. + IDS_ITEM_0539, ///< \ru Тело приданием толщины. \en Solid of Thickening. + IDS_ITEM_0540, ///< \ru Оболочка с удалёнными гранями. \en Shell with Removed Faces. + IDS_ITEM_0541, ///< \ru Коробчатое тело. \en Box-like Solid. + IDS_ITEM_0542, ///< \ru Кинематическое тело. \en Sweeping Solid. + IDS_ITEM_0543, ///< \ru Тело заметания. \en Swept Solid. + IDS_ITEM_0544, ///< \ru Тело выдавливания. \en Extrusion Solid. + IDS_ITEM_0545, ///< \ru Тело вращения. \en Revolution Solid. + IDS_ITEM_0546, ///< \ru Тело по сечениям. \en Loft Solid. + IDS_ITEM_0547, ///< \ru Простое тело. \en Simple Solid. + IDS_ITEM_0548, ///< \ru Ребро жесткости тела. \en Rib of a Solid. + IDS_ITEM_0549, ///< \ru Набор тел. \en Set of solids. + IDS_ITEM_0550, ///< \ru Часть набора тел. \en Set of solids part. + IDS_ITEM_0551, ///< \ru Клон граней тела. \en Solid's faces drafting. + IDS_ITEM_0552, ///< \ru Разбивка граней тела. \en Splitting of Solid's faces. + IDS_ITEM_0553, ///< \ru Сшитое из оболочек тело. \en Stitched Solid. + IDS_ITEM_0554, ///< \ru Сшитая из оболочек оболочка. \en Shell stitched from shells. + IDS_ITEM_0555, ///< \ru Оболочка из NURBS-поверхностей. \en Shell from NURBS-surfaces. + IDS_ITEM_0556, ///< \ru Трансформированное тело. \en Transformed Solid. + IDS_ITEM_0557, ///< \ru Модифицированное тело. \en Modified Solid. + IDS_ITEM_0558, ///< \ru Оболочка из линейчатых поверхностей. \en Shell from ruled surfaces. + IDS_ITEM_0559, ///< \ru Усеченная оболочка. \en Truncated Shell. + IDS_ITEM_0560, ///< \ru Оболочка соединения. \en Joint Shell. + IDS_ITEM_0561, ///< \ru Тело с восстановленными боковыми рёбрами. \en Solid with restored lateral edges. + IDS_ITEM_0562, ///< \ru Объединение с кинематическим телом. \en Union with a sweeping Solid. + IDS_ITEM_0563, ///< \ru Модифицированное тело NURBS-поверхностями. \en Solid modified with NURBS-surfaces. + IDS_ITEM_0564, ///< \ru Объединение с телом выдавливания. \en Union with an extrusion Solid. + IDS_ITEM_0565, ///< \ru Объединение с телом вращения. \en Union with a revolution Solid. + IDS_ITEM_0566, ///< \ru Объединение с телом по сечениям. \en Union with a lofted Solid. + IDS_ITEM_0567, ///< \ru Объединение с простым телом. \en Union with an elementary Solid. + IDS_ITEM_0568, ///< \ru Модифицированная NURBS-поверхность грани. \en Modified NURBS-surface of the face. + IDS_ITEM_0569, ///< \ru Объединение с набором тел. \en Union with a Solid set. + IDS_ITEM_0570, ///< \ru Оболочка грани соединения. \en Joint face Shell. + IDS_ITEM_0571, ///< \ru Скругление граней. \en Faces fillet. + IDS_ITEM_0572, ///< \ru Разность с кинематическим телом. \en Subtraction with a sweeping Solid. + IDS_ITEM_0573, ///< \ru Удаление результата операции. \en Delete the result of the operation. + IDS_ITEM_0574, ///< \ru Разность с телом выдавливания. \en Subtraction with an extrusion Solid. + IDS_ITEM_0575, ///< \ru Разность с телом вращения. \en Subtraction with a revolution Solid. + IDS_ITEM_0576, ///< \ru Разность с телом по сечениям. \en Subtraction with a lofted Solid. + IDS_ITEM_0577, ///< \ru Разность с простым телом. \en Subtraction with an elementary Solid. + IDS_ITEM_0578, ///< \ru Упрощение развёртки. \en The flat pattern simplification. + IDS_ITEM_0579, ///< \ru Разность с набором тел. \en Subtraction with a Set of Solids. + IDS_ITEM_0580, ///< \ru Вывернутое тело. \en Reversed Solid. + IDS_ITEM_0581, ///< \ru Сгиб нелистового тела. \en Bend of a non-sheet Solid. + IDS_ITEM_0582, ///< \ru Пересечение с кинематическим телом. \en Intersection with a sweeping Solid. + IDS_ITEM_0583, ///< \ru Сферическая штамповка. \en Spherical stamping. + IDS_ITEM_0584, ///< \ru Пересечение с телом выдавливания. \en Intersection with an extrusion Solid. + IDS_ITEM_0585, ///< \ru Пересечение с телом вращения. \en Intersection with a revolution Solid. + IDS_ITEM_0586, ///< \ru Пересечение с телом по сечениям. \en Intersection with a lofted Solid. + IDS_ITEM_0587, ///< \ru Пересечение с простым телом. \en Intersection with an elementary Solid. + IDS_ITEM_0588, ///< \ru Обечайка. \en Ruled Shell. + IDS_ITEM_0589, ///< \ru Пересечение с набором тел. \en Intersection with a set of solids. + IDS_ITEM_0590, ///< \ru Оболочка по сети кривых. \en Shell defined by a mesh of curves. + IDS_ITEM_0591, ///< \ru Комбинированный сгиб. \en Combined bend. + IDS_ITEM_0592, ///< \ru Кинематическая оболочка. \en Sweep with guide curve Shell. + IDS_ITEM_0593, ///< \ru Жалюзи. \en Jalousie. + IDS_ITEM_0594, ///< \ru Оболочка выдавливания. \en Extrusion Shell. + IDS_ITEM_0595, ///< \ru Оболочка вращения. \en Revolution Shell. + IDS_ITEM_0596, ///< \ru Оболочка по сечениям. \en Loft Shell. + IDS_ITEM_0597, ///< \ru Тонкая оболочка. \en Thin Shell. + IDS_ITEM_0598, ///< \ru Разрезанная оболочка. \en Cut Shell. + IDS_ITEM_0599, ///< \ru Буртик. \en Bead. + IDS_ITEM_0600, ///< \ru Сгиб/разгиб листового тела. \en Bend/Unbend of a Sheet Solid. + IDS_ITEM_0601, ///< \ru Сгиб листового тела по отрезку. \en Bend of a sheet Solid by a segment. + IDS_ITEM_0602, ///< \ru Сгиб листового тела по рёбрам. \en Bend of a sheet Solid along edges. + IDS_ITEM_0603, ///< \ru Замыкание угла листового тела. \en Closure of a sheet Solid corner. + IDS_ITEM_0604, ///< \ru Листовое тело. \en Sheet Solid. + IDS_ITEM_0605, ///< \ru Пластина листового тела. \en Sheet Solid plate. + IDS_ITEM_0606, ///< \ru Вырез листового тела. \en Cut of a sheet Solid. + IDS_ITEM_0607, ///< \ru Пересечение листового тела. \en Sheet Solid intersection. + IDS_ITEM_0608, ///< \ru Подсечка листового тела. \en Jog of a sheet Solid. + IDS_ITEM_0609, ///< \ru Штамповка. \en Stamping. + +// \ru Способы построения оболочек. \en Shells construction methods. + + IDS_ITEM_0610, ///< \ru Оболочка. \en Shell. + IDS_ITEM_0611, ///< \ru Оболочка на базе поверхности. \en Shell based on a surface. + + IDS_ITEM_0614, ///< \ru Оболочка тела. \en Shell. + IDS_ITEM_0615, ///< \ru Журнал построения. \en Build log. + IDS_ITEM_0616, ///< \ru Атрибуты объекта. \en Object Attributes. + + IDS_ITEM_0620, ///< \ru Оболочка тела. \en Shell. + IDS_ITEM_0621, ///< \ru Ориентированное ребро цикла. \en Oriented edge of a loop. + IDS_ITEM_0622, ///< \ru Цикл грани. \en Face loop. + IDS_ITEM_0623, ///< \ru Грань оболочки. \en Face of a Shell. + IDS_ITEM_0624, ///< \ru Вершина. \en Vertex. + IDS_ITEM_0625, ///< \ru Ребро оболочки. \en Edge of a Shell. + IDS_ITEM_0626, ///< \ru Ребро каркаса. \en Edge of a frame. + + IDS_ITEM_0627, ///< \ru Вершина. \en Vertex. + + IDS_ITEM_0628, ///< \ru Разделенная оболочка. \en Divided Shell. + + IDS_ITEM_0630, ///< \ru Оболочка кругового сечения. \en Round Section Shell. + IDS_ITEM_0631, ///< \ru Оболочка лигнейчатого сечения. \en Ruled Section Shell. + IDS_ITEM_0632, ///< \ru Оболочка конического сечения. \en Conic Section Shell. + IDS_ITEM_0633, ///< \ru Оболочка кубического сечения. \en Cubic Section Shell. + IDS_ITEM_0634, ///< \ru Оболочка сплайнового сечения. \en Spline Section Shell. + +// \ru Способы построения проекций тела\оболочки. \en Solid/Shell projections creation methods. + + IDS_ITEM_0650, ///< \ru Проекция тела. \en Solid Projection. + IDS_ITEM_0651, ///< \ru Разрез тела. \en Solid Cutting. + IDS_ITEM_0652, ///< \ru Сечение тела. \en Solid Section. + + IDS_ITEM_0653, ///< \ru Размножение тела. \en Duplication of solids. + +// \ru Вспомогательный объект. \en The helper object. + + IDS_ITEM_0669, ///< \ru Вспомогательный объект. \en The helper object. + +// \ru Резьба. \en A thread. + + IDS_ITEM_0670, ///< \ru Резьба. \en Thread. + +// \ru Обозначение \en 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. + +// \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_0732, ///< \ru Атрибут. \en Attribute. + IDS_ITEM_0733, ///< \ru Имя примитива. \en Primitive name. + IDS_ITEM_0734, ///< \ru Поведение атрибутов. \en Attributes behavior. + + 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_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_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_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_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_0789, ///< \ru Пояснение. \en Prompt. + 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. + +// \ru Состав объектов \en Structure of objects + + IDS_PROP_0000, ///< \ru Пусто. \en Empty. + + IDS_PROP_0001, ///< \ru Кривая на плоскости. \en Curve on a plane. + IDS_PROP_0002, ///< \ru Параметр кривой. \en Parameter of a curve. + IDS_PROP_0003, ///< \ru Кривая 1 на плоскости. \en Curve 1 on the plane. + IDS_PROP_0004, ///< \ru Кривая 2 на плоскости. \en Curve 2 on the plane. + IDS_PROP_0005, ///< \ru Параметр кривой 1. \en Parameter of curve 1. + IDS_PROP_0006, ///< \ru Параметр кривой 2. \en Parameter of curve 2. + IDS_PROP_0007, ///< \ru Начальная точка. \en Start point. + IDS_PROP_0008, ///< \ru Направление. \en Direction. + IDS_PROP_0009, ///< \ru Конечная точка. \en End point. + IDS_PROP_0014, ///< \ru Начальный параметр усечения. \en Start parameter of truncation. + IDS_PROP_0015, ///< \ru Конечный параметр усечения. \en End parameter of truncation. + IDS_PROP_0016, ///< \ru Совпадение направления. \en Coincidence of direction. + IDS_PROP_0017, ///< \ru Циклическая частота. \en Cyclic frequency. + IDS_PROP_0018, ///< \ru Начальная фаза (град). \en Initial phase (degrees). + IDS_PROP_0019, ///< \ru Амплитуда. \en Amplitude. + IDS_PROP_0020, ///< \ru Перевернуть направление. \en Reverse the direction. + IDS_PROP_0021, ///< \ru Неподвижная точка. \en Fixed point. + IDS_PROP_0022, ///< \ru Использовать точку. \en Use a point. + IDS_PROP_0023, ///< \ru Равномерное преобразование. \en Uniform transformation. + IDS_PROP_0024, ///< \ru Точность. \en Tolerance. + IDS_PROP_0025, ///< \ru Начальное значение. \en Start value. + IDS_PROP_0026, ///< \ru Коэффициент усиления. \en Scale gain. + IDS_PROP_0027, ///< \ru Амплитуда. \en Amplitude. + IDS_PROP_0028, ///< \ru Сдвиг параметра. \en Parameter shift. + IDS_PROP_0029, ///< \ru Степень возведения. \en Exponent parameter. + IDS_PROP_0030, ///< \ru Циклическая частота. \en Frequency. + IDS_PROP_0031, ///< \ru Эквидистантное смещение. \en The offset range. + IDS_PROP_0032, ///< \ru Тип кривой. \en Type of curve. + + IDS_PROP_0033, ///< \ru Прогиб. \en The sag. + IDS_PROP_0034, ///< \ru Угловое отклонение. \en The angular deviation. + IDS_PROP_0035, ///< \ru Расстояние. \en The distance. + + IDS_PROP_0101, ///< \ru Координата X. \en Coordinate X. + IDS_PROP_0102, ///< \ru Координата Y. \en Coordinate Y. + IDS_PROP_0103, ///< \ru Координата Z. \en Coordinate Z. + IDS_PROP_0104, ///< \ru Матрица. \en Matrix. + IDS_PROP_0107, ///< \ru Угол с осью X. \en Angle with axis X. + IDS_PROP_0108, ///< \ru Угол с осью Y. \en Angle with axis Y. + IDS_PROP_0109, ///< \ru Угол с осью Z. \en Angle with axis Z. + IDS_PROP_0110, ///< \ru Точка. \en Point. + IDS_PROP_0111, ///< \ru Компонента 1.X. \en Component 1.X. + IDS_PROP_0112, ///< \ru Компонента 1.Y. \en Component 1.Y. + IDS_PROP_0113, ///< \ru Компонента 1.Z. \en Component 1.Z. + IDS_PROP_0114, ///< \ru Компонента 2.X. \en Component 2.X. + IDS_PROP_0115, ///< \ru Компонента 2.Y. \en Component 2.Y. + IDS_PROP_0116, ///< \ru Компонента 2.Z. \en Component 2.Z. + IDS_PROP_0117, ///< \ru Компонента 3.X. \en Component 3.X. + IDS_PROP_0118, ///< \ru Компонента 3.Y. \en Component 3.Y. + IDS_PROP_0119, ///< \ru Компонента 3.Z. \en Component 3.Z. + IDS_PROP_0120, ///< \ru Вектор. \en Vector. + IDS_PROP_0121, ///< \ru Сдвиг по X. \en Shift by X. + IDS_PROP_0122, ///< \ru Сдвиг по Y. \en Shift by Y. + IDS_PROP_0123, ///< \ru Сдвиг по Z. \en Shift by Z. + IDS_PROP_0124, ///< \ru Ось X. \en Axis X. + IDS_PROP_0125, ///< \ru Ось Y. \en Axis Y. + IDS_PROP_0126, ///< \ru Ось Z. \en Axis Z. + IDS_PROP_0127, ///< \ru Длина оси X. \en Length of axis X. + IDS_PROP_0128, ///< \ru Длина оси Y. \en Length of axis Y. + IDS_PROP_0129, ///< \ru Длина оси Z. \en Length of axis Z. + IDS_PROP_0130, ///< \ru Центр. \en Center. + IDS_PROP_0131, ///< \ru Левая система. \en Left system. + IDS_PROP_0132, ///< \ru Прямоугольная. \en Rectangular. + IDS_PROP_0133, ///< \ru Базовая точка. \en Base point. + IDS_PROP_0134, ///< \ru Строка. \en String. + IDS_PROP_0135, ///< \ru Шрифт. \en Font. + IDS_PROP_0136, ///< \ru Позиция начала. \en Start position. + IDS_PROP_0137, ///< \ru Высота. \en Height. + IDS_PROP_0138, ///< \ru Сужение. \en Taper. + IDS_PROP_0139, ///< \ru Угол наклона. \en Slope angle. + IDS_PROP_0140, ///< \ru Радиус. \en Radius. + IDS_PROP_0141, ///< \ru Масштаб по X. \en Scale by X. + IDS_PROP_0142, ///< \ru Масштаб по Y. \en Scale by Y. + IDS_PROP_0143, ///< \ru Масштаб по Z. \en Scale by Z. + IDS_PROP_0144, ///< \ru Функция масштабирования. \en The function of scaling. + IDS_PROP_0145, ///< \ru Функция вращения. \en The function of rotation. + IDS_PROP_0146, ///< \ru Толерантность. \en The tolerance. + + IDS_PROP_0150, ///< \ru Угол. \en Angle. + IDS_PROP_0151, ///< \ru Шаг. \en Step. + 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_0156, ///< \ru Зеркальность. \en Specularity. + IDS_PROP_0157, ///< \ru Только ортогональность. \en Orthogonality only. + IDS_PROP_0158, ///< \ru Объект общего вида. \en General object. + IDS_PROP_0159, ///< \ru Перспектива. \en Perspective. + IDS_PROP_0160, ///< \ru Локальная система координат. \en Local coordinate system. + IDS_PROP_0161, ///< \ru Начальное значение. \en Start value. + IDS_PROP_0162, ///< \ru Конечное значение. \en End value. + IDS_PROP_0163, ///< \ru Значение. \en Value. + IDS_PROP_0164, ///< \ru Функция изменения радиусов. \en Radius function. + IDS_PROP_0165, ///< \ru Функция изменения веса. \en Weight function. + IDS_PROP_0166, ///< \ru Функция. \en Function. + IDS_PROP_0167, ///< \ru Минимум. \en Minimum. + IDS_PROP_0168, ///< \ru Максимум. \en Maximum + + IDS_PROP_0169, ///< \ru Продлевать вверх?. \en Extend upwards?. + IDS_PROP_0170, ///< \ru Поворот оси вокруг нормали. \en Rotation of axis about the normal. + IDS_PROP_0171, ///< \ru Угол между осью и нормалью. \en Angle between the axis and the normal. + IDS_PROP_0172, ///< \ru Диаметр головки. \en Cap diameter. + IDS_PROP_0173, ///< \ru Глубина под головку. \en Depth for a cap. + IDS_PROP_0174, ///< \ru Угол фаски под головку. \en Chamfer angle for a cap. + IDS_PROP_0175, ///< \ru Диаметр отверстия под резьбу. \en Diameter of hole for a cap. + IDS_PROP_0176, ///< \ru Глубина отверстия под резьбу. \en Depth of hole for a cap. + IDS_PROP_0177, ///< \ru Угол конусности отверстия. \en Taper angle of hole. + IDS_PROP_0178, ///< \ru Угол раствора конца отверстия. \en Apical angle of hole end. + IDS_PROP_0179, ///< \ru Тип отверстия. \en Hole type. + IDS_PROP_0180, ///< \ru Способ модификации. \en Method of modification. + + IDS_PROP_0181, ///< \ru Тип(true-бобышка, false- карман). \en Type(true-boss, false- pocket). + IDS_PROP_0182, ///< \ru Тип. \en Type. + IDS_PROP_0183, ///< \ru Ширина. \en Width. + IDS_PROP_0184, ///< \ru Ширина. \en Width. + IDS_PROP_0185, ///< \ru Способ. \en Method. + IDS_PROP_0186, ///< \ru Новая грань. \en New face. + + IDS_PROP_0188, ///< \ru Направление (вниз/вверх). \en Direction (down/up). + IDS_PROP_0189, ///< \ru Радиус дуги. \en Arc radius. + IDS_PROP_0190, ///< \ru Функция дискриминанта. \en Discriminant function. + +// \ru Параметры. \en Parameters. + + IDS_PROP_0201, ///< \ru Объект на числах double. \en Object on double data. + IDS_PROP_0202, ///< \ru Объект на числах float. \en Object on float data. + IDS_PROP_0203, ///< \ru Кривая 1. \en Curve 1. + IDS_PROP_0204, ///< \ru Кривая 2. \en Curve 2. + IDS_PROP_0205, ///< \ru Кривая 3. \en Curve 3. + IDS_PROP_0206, ///< \ru Кривая 4. \en Curve 4 + IDS_PROP_0207, ///< \ru Начальная точка. \en Start point. + IDS_PROP_0208, ///< \ru Направляющий вектор. \en Direction vector. + IDS_PROP_0209, ///< \ru Конечная точка. \en End point. + IDS_PROP_0210, ///< \ru Нормаль к плоскости.\en Normal to surface. + IDS_PROP_0211, ///< \ru Первая полуось. \en First semiaxis. + IDS_PROP_0212, ///< \ru Вторая полуось. \en Second semiaxis. + IDS_PROP_0213, ///< \ru Фокусное расстояние. \en Focal distance. + IDS_PROP_0214, ///< \ru Параметр min. \en Parameter min. + IDS_PROP_0215, ///< \ru Параметр max. \en Parameter max. + IDS_PROP_0216, ///< \ru Действительная полуось. \en Real semiaxis. + IDS_PROP_0217, ///< \ru Мнимая полуось. \en Imaginary semiaxis. + IDS_PROP_0218, ///< \ru Приращение начального параметра. \en Increment of start parameter. + IDS_PROP_0219, ///< \ru Приращение конечного параметра. \en Increment of end parameter. + IDS_PROP_0220, ///< \ru Замкнутость. \en Closedness. + IDS_PROP_0221, ///< \ru Порядок. \en Order. + IDS_PROP_0222, ///< \ru Количество точек. \en Number of points. + IDS_PROP_0223, ///< \ru Точка. \en Point. + IDS_PROP_0224, ///< \ru Начальный параметр. \en Start parameter. + IDS_PROP_0225, ///< \ru Производная параметра. \en Derivative of parameter. + IDS_PROP_0226, ///< \ru Параметрическая длина. \en Parametric length. + IDS_PROP_0227, ///< \ru Положительное направление. \en Positive direction. + IDS_PROP_0228, ///< \ru Вес. \en Weight. + // IDS_PROP_0229, ///< \ru Касание. \en Tangency. (МА 2019 Лишнее?) + IDS_PROP_0230, ///< \ru Расстояние. \en Distance. + IDS_PROP_0232, ///< \ru Число кривых контура. \en Number of curves of contour. + IDS_PROP_0233, ///< \ru Кривая. \en Curve. + IDS_PROP_0234, ///< \ru Начальный параметр кривой. \en Start parameter of a curve. + IDS_PROP_0235, ///< \ru Конечный параметр кривой. \en End parameter of a curve. + IDS_PROP_0236, ///< \ru Число узлов. \en Number of knots. + IDS_PROP_0237, ///< \ru Значение узла. \en Knot value. + IDS_PROP_0238, ///< \ru Вторая производная в точке. \en Second derivative at a point. + IDS_PROP_0239, ///< \ru Производная. \en Derivative. + IDS_PROP_0240, ///< \ru Опорная кривая. \en Reference curve. + IDS_PROP_0241, ///< \ru Зависимость по X. \en Dependency by X. + IDS_PROP_0242, ///< \ru Зависимость по Y. \en Dependency by Y. + IDS_PROP_0243, ///< \ru Зависимость по Z. \en Dependency by Z. + IDS_PROP_0244, ///< \ru Расширение minPar. \en Extension minPar. + IDS_PROP_0245, ///< \ru Расширение maxPar. \en Extension maxPar. + IDS_PROP_0246, ///< \ru Количество сплайнов. \en Number of splines. + IDS_PROP_0250, ///< \ru Базовая кривая. \en Base curve. + IDS_PROP_0260, ///< \ru Двумерная кривая. \en Two-dimensional curve. + IDS_PROP_0263, ///< \ru Угол между OX плоскости и прямой касания ее с конусом. \en Angle of OX axis of a plane and the line of its tangency with a cone. + IDS_PROP_0264, ///< \ru Расстояние от листовой грани до нейтрального слоя. \en Distance from a sheet face to the neutral layer. + IDS_PROP_0265, ///< \ru Угол образующей конуса, касательной к плоскости при разгибе. \en Angle of a cone generatrix tangent to the plane while unbending. + IDS_PROP_0266, ///< \ru Количество образующих кривых. \en Number of generating lines. + IDS_PROP_0267, ///< \ru Объект модифицирован. \en Object is modified. + IDS_PROP_0268, ///< \ru Количество нормалей. \en Number of normals. + IDS_PROP_0269, ///< \ru Нормаль. \en Normal. + IDS_PROP_0270, ///< \ru Аппроксимационная кривая. \en Approximation curve. + + IDS_PROP_0271, ///< \ru Удаление выбранных граней. \en Remove selected faces. + IDS_PROP_0272, ///< \ru Создание тела из выбранных граней. \en Solid creation by selected faces. + IDS_PROP_0273, ///< \ru Перемещение выбранных граней. \en Move selected faces. + IDS_PROP_0274, ///< \ru Смещение выбранных граней по нормали. \en Offset selected faces. + IDS_PROP_0275, ///< \ru Изменение радиусов выбранных скруглений. \en Change selected fillets. + IDS_PROP_0276, ///< \ru Замена выбранных граней деформируемыми. \en Replace selected faces by deformed. + IDS_PROP_0277, ///< \ru Удаление выбранных скруглений. \en Remove selected features. + IDS_PROP_0278, ///< \ru Слияние вершин выбранных ребер. \en Merging vertices of selected edges. + IDS_PROP_0279, ///< \ru Замена гладко стыкующихся граней одной гранью. \en Replacing smoothly joined faces with one face. + + IDS_PROP_0282, ///< \ru Вектор модификации. \en The vector of modification. + IDS_PROP_0283, ///< \ru Количество модифицированных граней. \en Number of modified faces. + IDS_PROP_0284, ///< \ru Положение срединной оболочки тела. \en Position of median shell. + IDS_PROP_0285, ///< \ru Минимальное расстояние между гранями. \en Minimal equidistant value. + IDS_PROP_0286, ///< \ru Максимальное расстояние между гранями. \en Maximal equidistant value. + + IDS_PROP_0287, ///< \ru Окружность в сечении поверхности. \en The surface section is a circle. + IDS_PROP_0288, ///< \ru Отрезок прямой в сечении поверхности. \en The surface section is a line segment. + IDS_PROP_0289, ///< \ru Коническое сечение в сечении поверхности. \en The surface section is a conic section. + IDS_PROP_0290, ///< \ru Кубическая кривая в сечении поверхности. \en The surface section is a cubic curve. + IDS_PROP_0291, ///< \ru Сплайн в сечении поверхности. \en The surface section is a spline. + + IDS_PROP_0301, ///< \ru Начальный параметр U. \en Start parameter U. + IDS_PROP_0302, ///< \ru Начальный параметр V. \en Start parameter V. + IDS_PROP_0303, ///< \ru Положительное направление U. \en Positive direction by U. + IDS_PROP_0304, ///< \ru Положительное направление V. \en Positive direction by V. + IDS_PROP_0305, ///< \ru Параметрическая длина U. \en Parametric length by U. + IDS_PROP_0306, ///< \ru Параметрическая длина V. \en Parametric length by V. + IDS_PROP_0307, ///< \ru Положительное направление 1. \en Positive direction 1. + IDS_PROP_0308, ///< \ru Положительное направление 2. \en Positive direction 2. + IDS_PROP_0309, ///< \ru Тип сопряжения. \en Conjugation type. + IDS_PROP_0310, ///< \ru Точка. \en Point. + IDS_PROP_0311, ///< \ru Замкнутость по U. \en Closedness by U. + IDS_PROP_0312, ///< \ru Замкнутость по V. \en Closedness by V. + IDS_PROP_0313, ///< \ru Число порций по U. \en Number of portions by U. + IDS_PROP_0314, ///< \ru Число порций по V. \en Number of portions by V. + IDS_PROP_0315, ///< \ru Порядок по U. \en Order by U. + IDS_PROP_0316, ///< \ru Порядок по V. \en Order by V. + IDS_PROP_0317, ///< \ru Число точек по U. \en Number of points by U. + IDS_PROP_0318, ///< \ru Число точек по V. \en Number of points by V. + IDS_PROP_0320, ///< \ru Локальная система. \en Local system. + IDS_PROP_0321, ///< \ru Радиус основания. \en Radius of base. + IDS_PROP_0322, ///< \ru Высота. \en Height. + IDS_PROP_0323, ///< \ru Половина угла. \en Half-angle. + IDS_PROP_0324, ///< \ru Большой радиус. \en Major radius. + IDS_PROP_0325, ///< \ru Малый радиус. \en Minor radius. + IDS_PROP_0326, ///< \ru Длина. \en Length. + IDS_PROP_0327, ///< \ru Смещение. \en Shift. + 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_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. + IDS_PROP_0339, ///< \ru Значение V узла. \en Value of V knot. + IDS_PROP_0340, ///< \ru Поверхность. \en Surface. + IDS_PROP_0341, ///< \ru Направляющая кривая. \en Guide curve . + IDS_PROP_0342, ///< \ru Образующая кривая. \en Generating curve. + IDS_PROP_0343, ///< \ru Вектор смещения. \en Translation vector. + IDS_PROP_0344, ///< \ru Вектор направления. \en Direction vector. + IDS_PROP_0345, ///< \ru Точка оси вращения. \en Point of the rotation axis. + IDS_PROP_0346, ///< \ru Направление оси. \en Axis direction. + IDS_PROP_0347, ///< \ru Угол вращения. \en Rotation angle. + IDS_PROP_0348, ///< \ru Вершина. \en Vertex. + IDS_PROP_0350, ///< \ru Базовая поверхность. \en Base surface. + IDS_PROP_0351, ///< \ru Поверхность 1. \en Surface 1. + IDS_PROP_0352, ///< \ru Поверхность 2. \en Surface 2. + IDS_PROP_0353, ///< \ru Контур. \en Contour. + IDS_PROP_0354, ///< \ru Число контуров. \en Number of contours. + IDS_PROP_0355, ///< \ru Двумерный контур. \en Two-dimensional contour. + IDS_PROP_0356, ///< \ru Двумерная кривая. \en Two-dimensional curve. + IDS_PROP_0357, ///< \ru Контур 1. \en Contour 1. + IDS_PROP_0358, ///< \ru Контур 2. \en Contour 2. + IDS_PROP_0360, ///< \ru Плоскость. \en Plane. + IDS_PROP_0361, ///< \ru Вес поверхности 1. \en Weight of surface 1. + IDS_PROP_0362, ///< \ru Вес поверхности 2. \en Weight of surface 2. + IDS_PROP_0363, ///< \ru Производная в начале. \en Derivative at the beginning. + IDS_PROP_0364, ///< \ru Производная в конце. \en Derivative at the end. + IDS_PROP_0365, ///< \ru Установлена нормаль в начале. \en The normal is set at the beginning. + IDS_PROP_0366, ///< \ru Установлена нормаль в конце. \en The normal is set at the end. + IDS_PROP_0367, ///< \ru Множитель длины производной в начале. \en The derivative length modifier at the beginning. + IDS_PROP_0368, ///< \ru Множитель длины производной в конце. \en The derivative length modifier at the end. + IDS_PROP_0370, ///< \ru Кривая на поверхности 0. \en Curve on surface 0. + 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_0374, ///< \ru Параметр Umin. \en Parameter Umin. + IDS_PROP_0375, ///< \ru Параметр Umax. \en Parameter Umax. + IDS_PROP_0376, ///< \ru Параметр Vmin. \en Parameter Vmin. + IDS_PROP_0377, ///< \ru Параметр Vmax. \en Parameter Vmax. + IDS_PROP_0378, ///< \ru Производная dU. \en Derivative dU. + IDS_PROP_0379, ///< \ru Производная dV. \en Derivative dV. + IDS_PROP_0380, ///< \ru Кромка проходит по Vmin. \en Boundary passes through Vmin. + IDS_PROP_0384, ///< \ru Расширение minUPar. \en Extension minUPar. + IDS_PROP_0385, ///< \ru Расширение maxUPar. \en Extension maxUPar. + IDS_PROP_0386, ///< \ru Расширение minVPar. \en Extension minVPar. + IDS_PROP_0387, ///< \ru Расширение maxVPar. \en Extension maxVPar. + IDS_PROP_0390, ///< \ru Число кривых. \en Number of curves. + IDS_PROP_0391, ///< \ru Кривая по U. \en Curve by U + IDS_PROP_0392, ///< \ru Кривая по V. \en Curve by V. + IDS_PROP_0393, ///< \ru Число кривых по U. \en Number of curves by U. + IDS_PROP_0394, ///< \ru Число кривых по V. \en Number of curves by V. + IDS_PROP_0395, ///< \ru Тип поверхности. \en Type of surface. + IDS_PROP_0397, ///< \ru Нейтральная плоскость. \en Neutral plane. + IDS_PROP_0398, ///< \ru Плоскость контура. \en Plane of the contour. + IDS_PROP_0399, ///< \ru Через элементы. \en Through elements. + IDS_PROP_0400, ///< \ru Сопряжение на границе. \en Conjugation on the boundary. + IDS_PROP_0401, ///< \ru Натяжение на границе. \en Tension on the boundary. + IDS_PROP_0402, ///< \ru Параметр определения длины производных. \en Parameter of derivatives length definition. + IDS_PROP_0403, ///< \ru Не сохранять длину производной. \en Do not keep the derivative length. + IDS_PROP_0404, ///< \ru Тип сопряжения (0-4). \en Conjugation type (0-4). + IDS_PROP_0405, ///< \ru Использовать готовый узловой вектор. \en Use prepared knot vector. + IDS_PROP_0406, ///< \ru Количество узлов. \en Number of knots. + IDS_PROP_0407, ///< \ru Проверка самопересечений. \en Check for self-intersections. + IDS_PROP_0408, ///< \ru Используется общий вес точек. \en The common weight of points is used. + IDS_PROP_0409, ///< \ru Построена по пласту точек. \en Build from a cloud of points. + IDS_PROP_0410, ///< \ru Построена по сети точек. \en Build from a mesh of points. + IDS_PROP_0411, ///< \ru В виде набора треугольников. \en As a set of triangles. + IDS_PROP_0412, ///< \ru Использовать проекционную кривую. \en Use projection curve. + IDS_PROP_0413, ///< \ru Усекать границами. \en Truncate by bounds. + IDS_PROP_0414, ///< \ru Привязка к началу. \en Binding to the beginning. + IDS_PROP_0415, ///< \ru Соединять скруглениями.\en Join by fillets. + IDS_PROP_0416, ///< \ru Сохранять радиус. \en Keep the radius. + IDS_PROP_0417, ///< \ru Притуплять острый угол. \en Blunt a sharp angle. + IDS_PROP_0418, ///< \ru Проверка пересечений. \en Check for intersections. + IDS_PROP_0419, ///< \ru Слияние подобных граней. \en Merging of similar faces. + IDS_PROP_0420, ///< \ru Слияние подобных ребер. \en Merging of similar edges. + + IDS_PROP_0421, ///< \ru Номер соседнего объекта. \en The number of neighbour object. + + IDS_PROP_0450, ///< \ru Начальный радиус (поверхность). \en Start radius (surface). + IDS_PROP_0451, ///< \ru Конечный радиус (резьба). \en End radius (thread). + IDS_PROP_0452, ///< \ru Длина резьбы. \en Thread length. + IDS_PROP_0453, ///< \ru Угол коничности резьбы. \en Taper angle of the thread. + + IDS_PROP_0461, ///< \ru Триангуляция. \en Triangulation. + IDS_PROP_0462, ///< \ru Количество точек триангуляции. \en Number of points of triangulation. + IDS_PROP_0463, ///< \ru Количество двумерных точек. \en Number of two-dimension points. + IDS_PROP_0464, ///< \ru Количество точек полигонов. \en Number of points of polygons. + + IDS_PROP_0501, ///< \ru Число вершин. \en Number of vertices. + IDS_PROP_0502, ///< \ru Число ребер. \en Number of edges. + IDS_PROP_0503, ///< \ru Число граней. \en Number of faces. + IDS_PROP_0504, ///< \ru Ориентация вершины. \en Vertex orientation. + IDS_PROP_0505, ///< \ru Ориентация ребра. \en Edge orientation. + IDS_PROP_0506, ///< \ru Ориентация грани. \en Face orientation. + IDS_PROP_0508, ///< \ru Ребро. \en Edge. + IDS_PROP_0509, ///< \ru Грань. \en Face. + IDS_PROP_0510, ///< \ru Число циклов. \en Number of loops. + IDS_PROP_0511, ///< \ru Цикл. \en Loop. + IDS_PROP_0512, ///< \ru Автоопределение. \en Automatic identification. + IDS_PROP_0513, ///< \ru Автоматическое. \en Automatic. + + IDS_PROP_0514, ///< \ru Тип размножения. \en Type of duplication. + IDS_PROP_0515, ///< \ru Кол-во шагов. \en Number of steps. + IDS_PROP_0516, ///< \ru Шаг. \en Step. + 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_0521, ///< \ru Длина Lx. \en Length Lx. + IDS_PROP_0522, ///< \ru Ширина Ly. \en Width Ly. + IDS_PROP_0523, ///< \ru Высота Lz. \en Height Lz. + IDS_PROP_0524, ///< \ru Малая длина lx. \en Minor length lx. + IDS_PROP_0525, ///< \ru Толщина. \en Thickness. + 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_0530, ///< \ru Продолжить далее. \en Continue. + IDS_PROP_0531, ///< \ru Катет 1. \en Cathetus 1. + IDS_PROP_0532, ///< \ru Катет 2. \en Cathetus 2. + IDS_PROP_0533, ///< \ru Число фасок. \en Number of chamfers. + IDS_PROP_0534, ///< \ru Число скруглений. \en Number of fillets. + IDS_PROP_0535, ///< \ru Радиус скругления. \en Fillet radius. + IDS_PROP_0536, ///< \ru Номер грани. \en Face number. + IDS_PROP_0537, ///< \ru Параметр U. \en Parameter U. + IDS_PROP_0538, ///< \ru Параметр V. \en Parameter V. + IDS_PROP_0539, ///< \ru Число модифицированных граней. \en Number of modified faces. + IDS_PROP_0540, ///< \ru Тело. \en Solid. + IDS_PROP_0541, ///< \ru Строитель тела. \en Construct solid. + IDS_PROP_0542, ///< \ru Количество четырёхугольников. \en Number of quadrangles. + IDS_PROP_0543, ///< \ru Остановка от начала. \en Termination from the start. + IDS_PROP_0544, ///< \ru Остановка до конца. \en Termination to the end. + IDS_PROP_0545, ///< \ru Радиус скругления 1. \en Fillet radius 1. + IDS_PROP_0546, ///< \ru Радиус скругления 2. \en Fillet radius 2. + IDS_PROP_0547, ///< \ru Коэффициент полноты. \en Coefficient of completeness. + IDS_PROP_0548, ///< \ru Способ обработки углов стыковки рёбер. \en Method of processing corners of edges connection. + IDS_PROP_0549, ///< \ru Четырехугольник. \en Quadrangle. + + IDS_PROP_0550, ///< \ru Базовое тело. \en Base solid. + IDS_PROP_0551, ///< \ru Тело 1. \en Solid 1. + IDS_PROP_0552, ///< \ru Тело 2. \en Solid 2. + IDS_PROP_0553, ///< \ru Исходное тело. \en Initial solid. + IDS_PROP_0554, ///< \ru Режущая поверхность. \en Cutting surface. + IDS_PROP_0555, ///< \ru Оставляемая часть. \en A part to keep. + IDS_PROP_0556, ///< \ru Точка симметрии. \en Symmetry point. + IDS_PROP_0557, ///< \ru Ось X симметрии. \en Axis X of symmetry. + IDS_PROP_0558, ///< \ru Ось Y симметрии. \en Axis Y of symmetry. + IDS_PROP_0559, ///< \ru Поверхность. \en Surface. + IDS_PROP_0560, ///< \ru Внешняя оболочка. \en Outer shell. + IDS_PROP_0561, ///< \ru Пустотная оболочка. \en Void shell. + IDS_PROP_0562, ///< \ru Число пустот. \en Number of voids. + IDS_PROP_0563, ///< \ru Глубина 1. \en Depth 1. + IDS_PROP_0564, ///< \ru Глубина 2. \en Depth 2. + IDS_PROP_0565, ///< \ru Угол уклона 1. \en Slope angle 1. + IDS_PROP_0566, ///< \ru Угол уклона 2. \en Slope angle 2. + IDS_PROP_0567, ///< \ru Толщина стенки 1. \en Wall thickness 1. + IDS_PROP_0568, ///< \ru Толщина стенки 2. \en Wall thickness 2. + IDS_PROP_0569, ///< \ru Толщина. \en Thickness. + IDS_PROP_0570, ///< \ru Глубина. \en Depth. + + IDS_PROP_0571, ///< \ru Способ построения. \en Method of construction. + IDS_PROP_0572, ///< \ru Число оболочек. \en Number of shells. + IDS_PROP_0573, ///< \ru Количество треугольников. \en Number of triangles. + IDS_PROP_0575, ///< \ru Угол вращения 1. \en Rotation angle 1. + IDS_PROP_0576, ///< \ru Угол вращения 2. \en Rotation angle 2. + + IDS_PROP_0577, ///< \ru Первая вершина. \en The first vertex. + IDS_PROP_0578, ///< \ru Вторая вершина. \en The second vertex. + IDS_PROP_0579, ///< \ru Третья вершина. \en The third vertex. + IDS_PROP_0580, ///< \ru Четвертая вершина. \en The fourth vertex. + + IDS_PROP_0581, ///< \ru Способ построения 1. \en Method of construction 1. + IDS_PROP_0582, ///< \ru Способ построения 2. \en Method of construction 2. + IDS_PROP_0583, ///< \ru Расстояние 1. \en Distance 1. + IDS_PROP_0584, ///< \ru Расстояние 2. \en Distance 2. + IDS_PROP_0585, ///< \ru Треугольник. \en Triangle. + IDS_PROP_0586, ///< \ru Количество апексов. \en Number of apices. + IDS_PROP_0587, ///< \ru Количество полигонов. \en Number of polygons. + IDS_PROP_0588, ///< \ru Количество триангуляций. \en Number of triangulations. + IDS_PROP_0589, ///< \ru Контур. \en Contour. + IDS_PROP_0590, ///< \ru Число сечений. \en Number of sections. + IDS_PROP_0591, ///< \ru Сечение. \en Section. + IDS_PROP_0592, ///< \ru Параллельность. \en Parallelization. + IDS_PROP_0593, ///< \ru Ориентация образующей. \en Generatrix orientation. + IDS_PROP_0594, ///< \ru Положение образующей. \en Generatrix position. + IDS_PROP_0595, ///< \ru Сфероид (0) или тороид (1). \en Spheroid (0) or toroid (1). + IDS_PROP_0596, ///< \ru Полюс в начале. \en Pole at the beginning. + IDS_PROP_0597, ///< \ru Полюс в конце. \en Pole at the end. + IDS_PROP_0598, ///< \ru Продолжение. \en Extension. + IDS_PROP_0599, ///< \ru Смещение. \en Shift. + + IDS_PROP_0600, ///< \ru Оболочка тела. \en Shell. + IDS_PROP_0601, ///< \ru Ориентация ребра в цикле. \en Sense of edge in the loop. + IDS_PROP_0602, ///< \ru Ориентация кривой ребра. \en Edge curve orientation. + IDS_PROP_0603, ///< \ru Ориентация нормали оболочки. \en Orientation of a shell normal. + IDS_PROP_0604, ///< \ru Кривая ребра. \en Edge curve. + IDS_PROP_0605, ///< \ru Двумерная кривая ребра. \en Two-dimensional edge curve. + IDS_PROP_0606, ///< \ru Поверхность грани. \en Surface of a face. + IDS_PROP_0607, ///< \ru Вершина-начало. \en Start vertex. + IDS_PROP_0608, ///< \ru Вершина-конец. \en End vertex. + IDS_PROP_0609, ///< \ru Количество ссылок. \en References count. + IDS_PROP_0611, ///< \ru Грань плюс. \en Face plus. + IDS_PROP_0612, ///< \ru Грань минус. \en Face minus. + IDS_PROP_0613, ///< \ru Указатель на грань. \en Pointer to a face. + 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_0651, ///< \ru Разрезанное тело. \en Cutting solid. + IDS_PROP_0652, ///< \ru Плоскость раскроя. \en Cutting plane. + IDS_PROP_0654, ///< \ru Наличие штриховки. \en Whether there is hatching. + IDS_PROP_0655, ///< \ru Шаг штриховки. \en Hatching step. + IDS_PROP_0656, ///< \ru Угол штриховки. \en Hatching angle. + IDS_PROP_0657, ///< \ru Проекционная плоскость. \en Projection plane. + IDS_PROP_0658, ///< \ru Наличие невидимых линий. \en Whether there are invisible lines. + IDS_PROP_0659, ///< \ru Hash имени. \en Hash of name. + + IDS_PROP_0660, ///< \ru Коэффициент нейтрального слоя. \en Neutral layer coefficient. + IDS_PROP_0661, ///< \ru Радиус сгиба. \en Bend radius. + IDS_PROP_0662, ///< \ru Угол сгиба. \en Bend angle. + IDS_PROP_0663, ///< \ru Длина продолжения сгиба. \en Bend extension length. + IDS_PROP_0664, ///< \ru Смещение сгиба. \en Bend shift. + IDS_PROP_0665, ///< \ru Отступ от края сгиба 1. \en Distance from the bound of bend 1. + IDS_PROP_0666, ///< \ru Отступ от края сгиба 2. \en Distance from the bound of bend 2. + IDS_PROP_0667, ///< \ru Угол уклона края сгиба 1. \en Slope angle of the bound of bend 1. + IDS_PROP_0668, ///< \ru Угол уклона края сгиба 2. \en Slope angle of the bound of bend 2. + IDS_PROP_0669, ///< \ru Угол уклона продолжения сгиба 1. \en Slope angle of bend extension 1. + IDS_PROP_0670, ///< \ru Угол уклона продолжения сгиба 2. \en Slope angle of bend extension 2. + IDS_PROP_0671, ///< \ru Расширение продолжения сгиба 1. \en Expansion of extension of bend 1. + IDS_PROP_0672, ///< \ru Расширение продолжения сгиба 2. \en Expansion of extension of bend 2. + IDS_PROP_0673, ///< \ru Ширина разгрузки сгиба. \en Width of bend relief. + IDS_PROP_0674, ///< \ru Глубина разгрузки сгиба. \en Depth of bend relief. + IDS_PROP_0675, ///< \ru Радиус скругления разгрузки. \en Radius of relief rounding. + IDS_PROP_0676, ///< \ru Способ освобождения углов. \en Method of freeing the corners. + IDS_PROP_0677, ///< \ru Фиксированная часть грани слева. \en Fixed part of a face on the left. + IDS_PROP_0678, ///< \ru Строить разогнутым. \en Build in unbent state. + IDS_PROP_0679, ///< \ru Зазор. \en Gap. + IDS_PROP_0680, ///< \ru Перехлёстывающая сторона слева. \en Overlapping side on the left. + IDS_PROP_0681, ///< \ru С добавлением материала. \en With addition of material. + IDS_PROP_0682, ///< \ru Высота. \en Height. + IDS_PROP_0683, ///< \ru Коэффициент сгиба 1. \en Coefficient of bend 1. + IDS_PROP_0684, ///< \ru Радиус сгиба 1. \en Radius of bend 1. + IDS_PROP_0685, ///< \ru Коэффициент сгиба 2. \en Coefficient of bend 2. + IDS_PROP_0686, ///< \ru Радиус сгиба 2. \en Radius of bend 2. + IDS_PROP_0687, ///< \ru Радиус скругления эскиза. \en Radius of a sketch fillet. + IDS_PROP_0688, ///< \ru Радиус скругления основания. \en Radius of a base fillet. + IDS_PROP_0689, ///< \ru Радиус скругления дна. \en Radius of a bottom fillet. + IDS_PROP_0690, ///< \ru Открытая штамповка. \en Open stamping. + IDS_PROP_0691, ///< \ru Боковая стенка внутри. \en Side wall is inside. + IDS_PROP_0692, ///< \ru Ширина основания. \en Width of base. + IDS_PROP_0693, ///< \ru Ширина выпуклой части. \en Width of a salient part. + IDS_PROP_0694, ///< \ru Зазор рубленой законцовки. \en Gap of a cropped tip. + IDS_PROP_0695, ///< \ru Тип буртика. \en Bead type. + IDS_PROP_0696, ///< \ru Тип законцовки. \en Type of a tip. + IDS_PROP_0697, ///< \ru Вытяжка. \en Stretch. + IDS_PROP_0698, ///< \ru По нормали к толщине. \en By the normal to thickness. + IDS_PROP_0699, ///< \ru Способ замыкания цилиндрических частей. \en Method of cylindric parts closure. + IDS_PROP_0700, ///< \ru Разрешение на замыкание углов. \en Permission for corners closure. + + IDS_PROP_0701, ///< \ru Имя. \en Name. + IDS_PROP_0702, ///< \ru Значение. \en Value. + IDS_PROP_0703, ///< \ru Положение. \en Position. + IDS_PROP_0704, ///< \ru Число. \en Number. + IDS_PROP_0705, ///< \ru Ориентация. \en Orientation. + IDS_PROP_0706, ///< \ru Длина. \en Length. + IDS_PROP_0707, ///< \ru Толщина. \en Thickness. + IDS_PROP_0708, ///< \ru Угол. \en Angle. + IDS_PROP_0709, ///< \ru Параметр. \en Parameter. + IDS_PROP_0710, ///< \ru Геометрический объект. \en Geometric object. + IDS_PROP_0711, ///< \ru Точка. \en Point. + IDS_PROP_0712, ///< \ru Контрольная кривая. \en Control curve. + IDS_PROP_0713, ///< \ru Поверхность. \en Surface. + IDS_PROP_0714, ///< \ru Вершина. \en Vertex. + IDS_PROP_0715, ///< \ru Ребро грани. \en Edge of a face. + IDS_PROP_0716, ///< \ru Цикл грани. \en Face loop. + IDS_PROP_0717, ///< \ru Грань. \en Face. + IDS_PROP_0718, ///< \ru Полюс при umin. \en Pole at umin. + IDS_PROP_0719, ///< \ru Полюс при umax. \en Pole at umax. + IDS_PROP_0720, ///< \ru Полюс при vmin. \en Pole at vmin. + IDS_PROP_0721, ///< \ru Полюс при vmax. \en Pole at vmax. + IDS_PROP_0724, ///< \ru Вершина. \en Vertex. + IDS_PROP_0725, ///< \ru Ребро. \en Edge. + IDS_PROP_0726, ///< \ru Цикл. \en Loop. + IDS_PROP_0727, ///< \ru Грань. \en Face. + IDS_PROP_0729, ///< \ru Количество граней. \en Number of faces. + IDS_PROP_0730, ///< \ru Количество операций. \en Number of operations. + IDS_PROP_0731, ///< \ru Количество объектов. \en Number of objects. + IDS_PROP_0732, ///< \ru Объединение граней. \en Faces unification. + IDS_PROP_0733, ///< \ru Обработка углов. \en Corners treatment. + IDS_PROP_0734, ///< \ru Операция объединения. \en Union operation. + IDS_PROP_0735, ///< \ru Операция пересечения. \en Intersection operation. + IDS_PROP_0736, ///< \ru Операция разности. \en Subtraction operation. + IDS_PROP_0737, ///< \ru Базовая операция. \en Base operations. + IDS_PROP_0738, ///< \ru Флаг состояния. \en Flag of state. + IDS_PROP_0739, ///< \ru Параметр полюса по U. \en Parameter of a pole by U. + IDS_PROP_0740, ///< \ru Номер грани. \en Number of a face. + IDS_PROP_0741, ///< \ru Номер ребра. \en Number of an edge. + IDS_PROP_0742, ///< \ru Номер грани плюс. \en Number of a face plus. + IDS_PROP_0743, ///< \ru Номер грани минус. \en Number of a face minus. + IDS_PROP_0744, ///< \ru Формировать твёрдое тело. \en Create a solid. + IDS_PROP_0745, ///< \ru Точность сшивки. \en Stitching tolerance. + IDS_PROP_0746, ///< \ru Через сгиб. \en Through a bend. + IDS_PROP_0747, ///< \ru Полюс. \en Pole. + IDS_PROP_0748, ///< \ru Край. \en Border. + IDS_PROP_0749, ///< \ru Шов. \en Seam. + IDS_PROP_0750, ///< \ru Линия перехода. \en Transition line. + IDS_PROP_0751, ///< \ru Адрес начальной вершины. \en Start vertex address. + IDS_PROP_0752, ///< \ru Адрес конечной вершины. \en End vertex address. + IDS_PROP_0753, ///< \ru Адрес грани слева. \en Address of a face on the left. + IDS_PROP_0754, ///< \ru Адрес грани справа. \en Address of a face on the right. + IDS_PROP_0755, ///< \ru Примитив разрезан. \en Primitive is cut. + IDS_PROP_0756, ///< \ru Листовой примитив. \en Sheet primitive. + IDS_PROP_0757, ///< \ru Внутренняя грань сгиба. \en Internal face of a bend. + IDS_PROP_0758, ///< \ru Внешняя грань сгиба. \en External face of a bend. + IDS_PROP_0759, ///< \ru Угол раствора конуса. \en Cone angle. + +// \ru Версии \en Versions + + IDS_PROP_0760, ///< \ru Версия. \en Version. + IDS_PROP_0761, ///< \ru Версия имени. \en Version of name. + IDS_PROP_0762, ///< \ru Версия операции. \en Version of operation. + IDS_PROP_0763, ///< \ru Версия объекта. \en Version of object. + +// \ru Информация от геометрической модели \en Information from geometric model + + IDS_PROP_0771, ///< \ru Количество вершин. \en Number of vertices. + IDS_PROP_0772, ///< \ru Количество кривых. \en Number of curves. + IDS_PROP_0773, ///< \ru Количество поверхностей. \en Number of surfaces. + IDS_PROP_0774, ///< \ru Количество тел. \en Number of solids. + IDS_PROP_0775, ///< \ru Количество полигональных объектов. \en Number of polygonal objects. + IDS_PROP_0776, ///< \ru Количество проволочных каркасов. \en Number of wireframes. + IDS_PROP_0777, ///< \ru Количество точечных каркасов. \en Number of point frames. + IDS_PROP_0778, ///< \ru Количество сборочных единиц. \en Number of assembly units. + IDS_PROP_0779, ///< \ru Количество вставок. \en Number of instances. + IDS_PROP_0780, ///< \ru Количество других объектов. \en Number of other objects. + IDS_PROP_0781, ///< \ru Количество регионов. \en Number of regions. + IDS_PROP_0782, ///< \ru Количество элементов. \en Number of elements. + IDS_PROP_0783, ///< \ru Количество сегментов. \en Number of segments. + IDS_PROP_0784, ///< \ru Количество всех граней. \en Number of all faces. + IDS_PROP_0785, ///< \ru Количество всех уникальных граней. \en Number of all unique faces. + + IDS_PROP_0791, ///< \ru Первая деформация. \en First strain. + IDS_PROP_0792, ///< \ru Вторая деформация. \en Second strain. + IDS_PROP_0793, ///< \ru Третья деформация. \en Third strain. + + IDS_PROP_0797, ///< \ru Модуль Юнга. \en Young's modulus. + IDS_PROP_0798, ///< \ru Коэффициент Пуассона. \en Poisson's ratio. + + IDS_PROP_0830, ///< \ru Число радиусов эквидистант. \en Number of offsets radii. + IDS_PROP_0831, ///< \ru Гладкий стык. \en Smooth joint. + IDS_PROP_0832, ///< \ru Тип обхода угла. \en Type of corner bypass. + IDS_PROP_0833, ///< \ru Радиус специального скругления. \en Radius of a special fillet. + IDS_PROP_0834, ///< \ru Тип законцовки. \en Type of a tip. + IDS_PROP_0835, ///< \ru Законцовка первого сегмента. \en Tip of the first segment. + IDS_PROP_0836, ///< \ru Тип законцовки в начале. \en Type of tip at the beginning. + IDS_PROP_0837, ///< \ru Тип законцовки в конце. \en Type of tip at the end. + IDS_PROP_0838, ///< \ru Параметр законцовки. \en Parameter of a tip. + + IDS_PROP_0839, ///< \ru Параметр построения заплатки. \en Parameter of a patch construction. + IDS_PROP_0840, ///< \ru Число кривых образующего контура. \en Number of curves of a generating contour. + IDS_PROP_0841, ///< \ru Даны образующие грани. \en The generating faces are given. + IDS_PROP_0842, ///< \ru Кривая образующего контура. \en Curve of a generating contour. + IDS_PROP_0843, ///< \ru Ориентация кривой контура. \en Orientation of a curve of the contour. + IDS_PROP_0844, ///< \ru Сторона существующей грани оболочки. \en Side of an existent face of the shell. + IDS_PROP_0845, ///< \ru Да. \en Yes. + IDS_PROP_0846, ///< \ru Нет. \en No. + +// \ru Контейнер атрибутов \en Attribute container + + IDS_PROP_0847, ///< \ru Поставщик атрибутов. \en Attribute provider. + IDS_PROP_0848, ///< \ru Количество контейнеров. \en Number of containers. + IDS_PROP_0849, ///< \ru Контейнер. \en Container. + + IDS_PROP_0851, ///< \ru Количество атрибутов. \en Number of attributes. + + IDS_PROP_0853, ///< \ru При изменении. \en While changing. + IDS_PROP_0854, ///< \ru При конвертации. \en While convertation. + IDS_PROP_0855, ///< \ru При трансформировании. \en While transforming. + IDS_PROP_0856, ///< \ru При копировании. \en While copying. + IDS_PROP_0857, ///< \ru При объединении. \en While joining. + IDS_PROP_0858, ///< \ru При замене. \en While replacing. + IDS_PROP_0859, ///< \ru При разделении. \en While splitting. + IDS_PROP_0860, ///< \ru При удалении. \en While deleting. + IDS_PROP_0861, ///< \ru Объект свободен. \en The object is free. + IDS_PROP_0862, ///< \ru Копируемость. \en Whether it can be copied. + IDS_PROP_0863, ///< \ru Количество u-линий. \en The number of u-lines. + IDS_PROP_0864, ///< \ru Количество v-линий. \en The number of v-lines. + + IDS_PROP_0869, ///< \ru Имя исполнения. \en Embodiment name. + IDS_PROP_0870, ///< \ru Имя родительского исполнения. \en Parent embodiment name. + IDS_PROP_0871, ///< \ru Красный. \en Red. + IDS_PROP_0872, ///< \ru Зелёный. \en Green. + IDS_PROP_0873, ///< \ru Синий. \en Blue. + IDS_PROP_0874, ///< \ru Толщина. \en Thickness. + IDS_PROP_0875, ///< \ru Стиль. \en Style. + IDS_PROP_0876, ///< \ru Плотность. \en Density. + IDS_PROP_0877, ///< \ru Идентификатор. \en Identifier. + IDS_PROP_0878, ///< \ru Селектированность. \en Selectivity. + IDS_PROP_0879, ///< \ru Видимость. \en Visibility. + IDS_PROP_0880, ///< \ru Изменённость. \en Modified. + IDS_PROP_0881, ///< \ru Общий фон. \en Background. + IDS_PROP_0882, ///< \ru Диффузное отражение. \en Diffuse reflection. + IDS_PROP_0883, ///< \ru Зеркальное отражение. \en Specular reflection. + IDS_PROP_0884, ///< \ru Блеск. \en Shininess. + IDS_PROP_0885, ///< \ru Непрозрачность. \en Opacity. + IDS_PROP_0886, ///< \ru Излучение. \en Emission. + IDS_PROP_0887, ///< \ru Количество родительских объектов. \en Number of parent objects. + IDS_PROP_0888, ///< \ru Родительский объект. \en Parent object. + IDS_PROP_0889, ///< \ru Имя топологического объекта. \en Topological object name. + IDS_PROP_0890, ///< \ru Имя объекта. \en Object name. + IDS_PROP_0891, ///< \ru Хэш имени объекта. \en Object name hash. + + IDS_PROP_0900, ///< \ru Сопряжение в точке. \en Conjugation at point. + IDS_PROP_0901, ///< \ru Тип сопряжения. \en Conjugation type. + IDS_PROP_0902, ///< \ru Без сопряжения. \en Without conjugation. + IDS_PROP_0903, ///< \ru По позиции. \en By position. + IDS_PROP_0904, ///< \ru По касательной. \en By tangent. + IDS_PROP_0905, ///< \ru По нормали. \en By normal. + IDS_PROP_0906, ///< \ru По G2. \en By G2. + IDS_PROP_0907, ///< \ru По G3. \en By G3. + IDS_PROP_0908, ///< \ru Касательный вектор. \en Tangent vector. + IDS_PROP_0909, ///< \ru Первая производная касательного вектора. \en First derivative of tangent vector. + IDS_PROP_0910, ///< \ru Вторая производная касательного вектора. \en Second derivative of tangent vector. + IDS_PROP_0911, ///< \ru Можно ли двигать точки. \en Whether points can be moved. + IDS_PROP_0912, ///< \ru Только по направлению. \en Only along the direction. + IDS_PROP_0913, ///< \ru Сопряжение. \en Conjugation. + + IDS_PROP_0920, ///< \ru Тип параметризации. \en Parametrization type. + IDS_PROP_0921, ///< \ru Пользовательская. \en Custom. + IDS_PROP_0922, ///< \ru Равномерная. \en Uniform. + IDS_PROP_0923, ///< \ru По длине хорды. \en By chord length. + IDS_PROP_0924, ///< \ru Центростремительная. \en Centripetal. + + IDS_PROP_0925, ///< \ru Через вершины. \en Through vertices. + IDS_PROP_0926, ///< \ru Равномерная параметризация. \en Uniform parametrization. + + IDS_PROP_0927, ///< \ru Признак текущего исполнения. \en Mark of current embodiment. + +// \ru Конвертеры \en Converters + + IDS_PROP_1000, ///< \ru Заголовок. \en Title. + IDS_PROP_1001, ///< \ru Название. \en Name. + IDS_PROP_1002, ///< \ru Дата и время. \en Date and time. + IDS_PROP_1003, ///< \ru Автор(ы). \en Author(s)). + IDS_PROP_1004, ///< \ru Организация(и). \en Organization(s). + IDS_PROP_1005, ///< \ru Процессор STEP. \en Processor STEP. + IDS_PROP_1006, ///< \ru Система. \en System. + IDS_PROP_1007, ///< \ru Авторизация. \en Authorization. + + IDS_PROP_1010, ///< \ru Лицо и организация. \en Person and organization. + IDS_PROP_1011, ///< \ru Идентификатор лица. \en Identifier of a person. + IDS_PROP_1012, ///< \ru Фамилия. \en Surname. + IDS_PROP_1013, ///< \ru Имя. \en Name. + IDS_PROP_1014, ///< \ru Средние имена. \en Middle names. + IDS_PROP_1015, ///< \ru Титулы предшествующие. \en Prefix titles. + IDS_PROP_1016, ///< \ru Титулы завершающие. \en Suffix titles. + IDS_PROP_1017, ///< \ru Идентификатор организации. \en Identifier of organization. + IDS_PROP_1018, ///< \ru Название организации. \en Name of organization. + IDS_PROP_1019, ///< \ru Описание организации. \en Description of organization. + + IDS_PROP_1030, ///< \ru Изделие. \en Product. + IDS_PROP_1031, ///< \ru Идентификатор. \en Identifier. + IDS_PROP_1032, ///< \ru Название. \en Name. + IDS_PROP_1033, ///< \ru Описание. \en Description. + + IDS_PROP_1043, ///< \ru Элемент описания. \en Description element. + + /* + 1100 .. 1199 is a range for C3D Solver + */ + IDS_PROP_1100, ///< \ru Геометрический решатель. \en Geom solver. + IDS_PROP_1101, ///< \ru Схема сопряжений. \en Scheme of matings. + IDS_PROP_1102, ///< \ru Система ограничений. \en Constraint system. + IDS_PROP_1103, ///< \ru Ограничение. \en Constraint. + IDS_PROP_1104, ///< \ru Тип сопряжения. \en Type of mating. + IDS_PROP_1105, ///< \ru Тип ограничения. \en Type of constraint. + IDS_PROP_1106, ///< \ru Выравнивание. \en Alignment. + IDS_PROP_1107, ///< \ru Количество ограничений. \en Number of constraints. + IDS_PROP_1108, ///< \ru Тип взаимоориентации. \en Coorientation type. + IDS_PROP_1109, ///< \ru Сопряжение. \en Mate. + IDS_PROP_1110, ///< \ru Базовый объект. \en Base object. + IDS_PROP_1111, ///< \ru Объект 1. \en Object 1. + IDS_PROP_1112, ///< \ru Объект 2. \en Object 2. + IDS_PROP_1113, ///< \ru Вещественный параметр. \en Real parameter. + IDS_PROP_1114, ///< \ru Величина взаимоориентации. \en Value of coorientation. + + /* + Types of geometric constraint + */ + IDS_PROP_1130, ///< \ru Совпадение \en Coincident + IDS_PROP_1131, ///< \ru Параллельность \en Parallel + IDS_PROP_1132, ///< \ru Перпендикулярность \en Perpendicular + IDS_PROP_1133, ///< \ru Касание \en Tangent. + IDS_PROP_1134, ///< \ru Концентричность \en Concentric + IDS_PROP_1135, ///< \ru На расстоянии \en Distance + IDS_PROP_1136, ///< \ru По углом \en Angle + IDS_PROP_1137, ///< \ru По месту \en In place + IDS_PROP_1138, ///< \ru Механическая передача \en Transmittion + IDS_PROP_1139, ///< \ru Кулачковый механизм \en Cam mechanism + IDS_PROP_1140, ///< \ru Радиальный размер. \en Radial dimension. + IDS_PROP_1141, ///< \ru Точка по проценту. \en Percent point. + IDS_PROP_1145, ///< \ru Симметричность. \en Symmetric. + IDS_PROP_1146, ///< \ru Зависимый объект. \en Dependent. + IDS_PROP_1147, ///< \ru Элемент паттерна. \en Patterned. + IDS_PROP_1148, ///< \ru Линейный паттерн. \en Linear pattern. + IDS_PROP_1149, ///< \ru Угловой паттерн. \en Angular pattern. + IDS_PROP_1150, ///< \ru Фиксация. \en Fixing. + IDS_ITEM_1151, // "Горизонтальность" + IDS_ITEM_1152, // "Вертикальность" + IDS_ITEM_1153, // "Длина" + IDS_ITEM_1154, // "Угол наклона" + IDS_PROP_1199, // The last id for C3D Solver + + /* + \ru Новые описания без группировки \en New unsorted descriptions + */ + + IDS_PROP_2001, ///< \ru Внимание: \en Attention: + IDS_PROP_2002, ///< \ru Начало общих операций. \en Beginning of the shared operations. + IDS_PROP_2003, ///< \ru Начало группы операций. \en Beginning of the operations group. + IDS_PROP_2004, ///< \ru Начало первой группы операций. \en Beginning of the first operations group. + IDS_PROP_2005, ///< \ru Начало второй группы операций. \en Beginning of the second operations group. + IDS_PROP_2006, ///< \ru Начало объекта. \en Beginning of an object. + IDS_PROP_2007, ///< \ru Начало первого объекта. \en Beginning of the first object. + IDS_PROP_2008, ///< \ru Начало второго объекта. \en Beginning of the second object. + IDS_PROP_2009, ///< \ru Копировать атрибуты. \en Copy attributes. + IDS_PROP_2010, ///< \ru Количество общих групп операций. \en Number of shared operations groups. + IDS_PROP_2011, ///< \ru Количество выбранных граней. \en Number of selected faces. + IDS_PROP_2012, ///< \ru Количество выбранных ребёр. \en Number of selected edges. + IDS_PROP_2013, ///< \ru Количество выбранных вершин. \en Number of selected vertices. + IDS_PROP_2014, ///< \ru Секущий эскиз. \en Cutting sketch. + IDS_PROP_2015, ///< \ru Секущие 3D-кривые. \en Cutting 3D-curves. + IDS_PROP_2016, ///< \ru Секущие поверхности. \en Cutting surfaces. + IDS_PROP_2017, ///< \ru Секущее тело. \en Cutting solid. + + IDS_PROP_2018, ///< \ru Поверхность сопряжения на границе 0. \en Adjacent surface on the border 0. + IDS_PROP_2019, ///< \ru Поверхность сопряжения на границе 1. \en Adjacent surface on the border 1. + IDS_PROP_2020, ///< \ru Поверхность сопряжения на границе 2. \en Adjacent surface on the border 2. + IDS_PROP_2021, ///< \ru Поверхность сопряжения на границе 3. \en Adjacent surface on the border 3. + IDS_PROP_2022, ///< \ru Поверхность сопряжения на границе 4. \en Adjacent surface on the border 4. + IDS_PROP_2023, ///< \ru Сопряжение на границе 0. \en Conjugation on the boundary 0. + IDS_PROP_2024, ///< \ru Сопряжение на границе 1. \en Conjugation on the boundary 1. + IDS_PROP_2025, ///< \ru Сопряжение на границе 2. \en Conjugation on the boundary 2. + IDS_PROP_2026, ///< \ru Сопряжение на границе 3. \en Conjugation on the boundary 3. + IDS_PROP_2027, ///< \ru Сопряжение на границе 4. \en Conjugation on the boundary 4. + + IDS_PROP_LAST = 9999, ///< \ru Наибольшее значение. \en The greatest value. +}; + + +#endif // __MB_PROPERTY_TITLE_H diff --git a/C3d/Include/mb_rect.h b/C3d/Include/mb_rect.h index 2e87a8a..9289f56 100644 --- a/C3d/Include/mb_rect.h +++ b/C3d/Include/mb_rect.h @@ -246,16 +246,16 @@ public: /// \ru Включить в себя координату Y. \en Enclose an Y-coordinate. void IncludeY( double y ); /// \ru Включить в себя интервал от X - dx до X + dx. \en Enclose a range from X - dx to X + dx. - void IncludeXInterval( double x, double dx ); + void IncludeXInterval( double x, double dx ); /// \ru Включить в себя интервал от Y - dy до Y + dy. \en Enclose a range from Y - dy to Y + dy. - void IncludeYInterval( double y, double dy ); + void IncludeYInterval( double y, double dy ); // \ru Сдвинуть прямоугольник \en Move rectangle /// \ru Cдвинуть прямоугольник. \en Move rectangle. void Move( const MbVector & to ); /// \ru Cдвинуть прямоугольник. \en Move rectangle. void Move( double dx, double dy ); /// \ru Масштабировать относительно 0. \en Scale relative to 0. - void Scale( double scale ); + void Scale( double scale ); /// \ru Расширить прямоугольник. \en Extend rectangle. void Enlarge( double x, double y ); @@ -290,9 +290,11 @@ public: /// \ru Количество координат точки. \en The number of point coordinates. static size_t GetDimension() { return 2; } /// \ru Доступ к координате по индексу. \en Access to a coordinate by an index. - double GetMin( size_t k ) const { return k ? bottom : left; }; + double GetMin( size_t k ) const { return k ? bottom : left; } /// \ru Доступ к координате по индексу. \en Access to a coordinate by an index. - double GetMax( size_t k ) const { return k ? top : right; }; + double GetMax( size_t k ) const { return k ? top : right; } + /// \ru Дать длина по стороне. \en Get side length. + double GetSideLength( size_t k ) const { return k ? ::fabs( GetLengthY() ) : ::fabs( GetLengthX() ); } /// \ru Получить ссылку на себя. \en Get reference to itself. const MbRect & GetCube() const { return *this; } diff --git a/C3d/Include/mb_thread.h b/C3d/Include/mb_thread.h index faf7b58..0ac9375 100644 --- a/C3d/Include/mb_thread.h +++ b/C3d/Include/mb_thread.h @@ -788,26 +788,32 @@ bool CheckThreads( ThreadsVector & threads, const MbPlacement3D * placeSec, bool for ( size_t i = threads.size(); i--; ) { MbThread * thr = threads[i]; - if ( (thr == NULL) || !thr->IsValid() ) + if ( (thr == C3D_NULL_PTR) || !thr->IsValid() ) { threads.erase( threads.begin() + i ); - else if ( checkThreadNames && (thr->GetName() == NULL) ) // C3D-695 : KOMPAS-25125 + thr = C3D_NULL_PTR; + } + else if ( checkThreadNames && (thr->GetName() == C3D_NULL_PTR) ) { // C3D-695 : KOMPAS-25125 threads.erase( threads.begin() + i ); + thr = C3D_NULL_PTR; + } else { if ( threads.size() > 1 ) { for ( ptrdiff_t j = i - 1; j >= 0; j-- ) { if ( thr == threads[j] ) { - threads[i] = NULL; + threads[i] = C3D_NULL_PTR; threads.erase( threads.begin() + i ); C3D_ASSERT_UNCONDITIONAL( false ); // Error case! + thr = C3D_NULL_PTR; break; } } } } - thr->DetachWrongBodies(); + if ( thr != C3D_NULL_PTR ) // KOMPAS-37171 + thr->DetachWrongBodies(); } - if ( !threads.empty() && (placeSec != NULL) ) { + if ( !threads.empty() && (placeSec != C3D_NULL_PTR) ) { 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 e6396ec..25e08e5 100644 --- a/C3d/Include/mb_variables.h +++ b/C3d/Include/mb_variables.h @@ -19,182 +19,188 @@ /** \ru \name Общие константы \en \name Common constants \{ */ -#define MB_MAXDOUBLE (1.0E+300) ///< \ru Максимальное значение double 1.7976931348623158E+308. \en Maximum value of double 1.7976931348623158E+308. -#define MB_MINDOUBLE (1.0E-300) ///< \ru Минимальное значение double 2.2250738585072014E-308. \en Minimum value of double 2.2250738585072014E-308. +const_expr double MB_MAXDOUBLE = 1.0E+300; ///< \ru Максимальное значение double 1.7976931348623158E+308. \en Maximum value of double 1.7976931348623158E+308. +const_expr double MB_MINDOUBLE = 1.0E-300; ///< \ru Минимальное значение double 2.2250738585072014E-308. \en Minimum value of double 2.2250738585072014E-308. // \ru Математические константы, округленные до 21 значащей цифры, определены в math.h \en Mathematical constants rounded to 21 significant digits, defined in math.h #if !defined( _MATH_DEFINES_DEFINED ) #ifdef C3D_WINDOWS// _MSC_VER // \ru Константы определены в math.h [Linux] \en Constants defined in math.h [Linux] -#define M_E 2.71828182845904523536 ///< \ru Экспонента. \en Exponent. -#define M_LOG2E 1.44269504088896340736 ///< \ru Логарифм M_E по основанию 2. \en Logarithm M_E to base 2. -#define M_LOG10E 0.434294481903251827651 ///< \ru Логарифм M_E по основанию 10. \en Logarithm M_E to base 10. -#define M_LN2 0.693147180559945309417 ///< \ru Натуральный логарифм 2. \en Natural logarithm 2. -#define M_PI_4 0.785398163397448309616 ///< M_PI / 4.0 -#define M_1_PI 0.318309886183790671538 ///< 1.0 / M_PI -#define M_2_PI 0.636619772367581343076 ///< 2.0 / M_PI -#define M_SQRT1_2 0.707106781186547524401 ///< \ru Корень из одной второй, sqrt(1/2). \en Root of one half, sqrt(1/2). +const_expr double M_E = 2.71828182845904523536; ///< \ru Экспонента. \en Exponent. +const_expr double M_LOG2E = 1.44269504088896340736; ///< \ru Логарифм M_E по основанию 2. \en Logarithm M_E to base 2. +const_expr double M_LOG10E = 0.434294481903251827651; ///< \ru Логарифм M_E по основанию 10. \en Logarithm M_E to base 10. +const_expr double M_LN2 = 0.693147180559945309417; ///< \ru Натуральный логарифм 2. \en Natural logarithm 2. +const_expr double M_PI_4 = 0.785398163397448309616; ///< M_PI / 4.0 +const_expr double M_1_PI = 0.318309886183790671538; ///< 1.0 / M_PI +const_expr double M_2_PI = 0.636619772367581343076; ///< 2.0 / M_PI +const_expr double M_SQRT1_2 = 0.707106781186547524401; ///< \ru Корень из одной второй, sqrt(1/2). \en Root of one half, sqrt(1/2). #else // C3D_WINDOWS - #ifndef M_E - #define M_E 2.71828182845904523536 ///< \ru Экспонента. \en Exponent. - #endif // M_E - #ifndef M_LOG2E - #define M_LOG2E 1.44269504088896340736 ///< \ru Логарифм M_E по основанию 2. \en Logarithm M_E to base 2. - #endif // M_LOG2E - #ifndef M_LOG10E - #define M_LOG10E 0.434294481903251827651 ///< \ru Логарифм M_E по основанию 10. \en Logarithm M_E to base 10. - #endif // M_LOG10E - #ifndef M_LN2 - #define M_LN2 0.693147180559945309417 ///< \ru Натуральный логарифм 2. \en Natural logarithm 2. - #endif // M_LN2 - #ifndef M_PI_4 - #define M_PI_4 0.785398163397448309616 ///< M_PI / 4.0 - #endif // M_PI_4 - #ifndef M_1_PI - #define M_1_PI 0.318309886183790671538 ///< 1.0 / M_PI - #endif // M_1_PI - #ifndef M_2_PI - #define M_2_PI 0.636619772367581343076 ///< 2.0 / M_PI - #endif // M_2_PI - #ifndef M_SQRT1_2 - #define M_SQRT1_2 0.707106781186547524401 ///< \ru Корень из одной второй, sqrt(1/2). \en Root of one half, sqrt(1/2). - #endif // M_SQRT1_2 +#ifndef M_E +const_expr double M_E = 2.71828182845904523536; ///< \ru Экспонента. \en Exponent. +#endif // M_E +#ifndef M_LOG2E +const_expr double M_LOG2E = 1.44269504088896340736; ///< \ru Логарифм M_E по основанию 2. \en Logarithm M_E to base 2. +#endif // M_LOG2E +#ifndef M_LOG10E +const_expr double M_LOG10E = 0.434294481903251827651; ///< \ru Логарифм M_E по основанию 10. \en Logarithm M_E to base 10. +#endif // M_LOG10E +#ifndef M_LN2 +const_expr double M_LN2 = 0.693147180559945309417; ///< \ru Натуральный логарифм 2. \en Natural logarithm 2. +#endif // M_LN2 +#ifndef M_PI_4 +const_expr double M_PI_4 = 0.785398163397448309616; ///< M_PI / 4.0 +#endif // M_PI_4 +#ifndef M_1_PI +const_expr double M_1_PI = 0.318309886183790671538; ///< 1.0 / M_PI +#endif // M_1_PI +#ifndef M_2_PI +const_expr double M_2_PI = 0.636619772367581343076; ///< 2.0 / M_PI +#endif // M_2_PI +#ifndef M_SQRT1_2 +const_expr double M_SQRT1_2 = 0.707106781186547524401; ///< \ru Корень из одной второй, sqrt(1/2). \en Root of one half, sqrt(1/2). +#endif // M_SQRT1_2 #endif // C3D_WINDOWS + #ifndef M_LN10 - #define M_LN10 2.30258509299404568402 ///< \ru Натуральный логарифм 10, ln(10). \en Natural logarithm 10, ln(10). +const_expr double M_LN10 = 2.30258509299404568402; ///< \ru Натуральный логарифм 10, ln(10). \en Natural logarithm 10, ln(10). #endif #ifndef M_PI - #define M_PI 3.14159265358979323846 ///< \ru Отношение длины окружности к её диаметру, pi. \en Relation between circle length and its diameter, pi. +const_expr double M_PI = 3.14159265358979323846; ///< \ru Отношение длины окружности к её диаметру, pi. \en Relation between circle length and its diameter, pi. #endif #ifndef M_PI_2 - #define M_PI_2 1.57079632679489661923 ///< M_PI / 2.0 +const_expr double M_PI_2 = 1.57079632679489661923; ///< M_PI / 2.0 #endif #ifndef M_2_SQRTPI - #define M_2_SQRTPI 1.12837916709551257390 ///< \ru Два разделить на корень из числа пи, 2/sqrt(pi). \en Two divided by root of pi, 2/sqrt(pi). +const_expr double M_2_SQRTPI = 1.12837916709551257390; ///< \ru Два разделить на корень из числа пи, 2/sqrt(pi). \en Two divided by root of pi, 2/sqrt(pi). #endif #ifndef M_SQRT2 - #define M_SQRT2 1.41421356237309504880 ///< \ru Корень из двух, sqrt(2). \en Root of two, sqrt(2). +const_expr double M_SQRT2 = 1.41421356237309504880; ///< \ru Корень из двух, sqrt(2). \en Root of two, sqrt(2). #endif #endif // _MATH_DEFINES_DEFINED -#define M_1_SQRTPI 0.564189583547756286948 ///< \ru Единица, деленная на корень из числа пи, 1/sqrt(pi). \en One divided by root of pi, 1/sqrt(pi). -#define M_PI2 (M_PI*2.0) ///< \ru Отношение длины окружности к её радиусу, 2.0 * M_PI, 6.28318530717958647692 \en Relation between circle length and its radius, 2.0 * M_PI, 6.28318530717958647692 -#define M_DEGRAD (M_PI/180.0) ///< \ru Коэффициент перевода градусов в радианы. \en Factor of conversion from degrees to radians. -#define M_RADDEG (180.0/M_PI) ///< \ru Коэффициент перевода радиан в градусы. \en Factor of conversion from radians to degrees. -#define M_FI 1.61803398874989484 ///< \ru Число золотого сечения, 1/M_FI = 0.6180339887499. \en Golden ratio, 1/M_FI = 0.6180339887499. -#define MM_INCH 25.4 ///< \ru Количество миллиметров в дюйме. \en Millimeters per inch. + +const_expr double M_1_SQRTPI = 0.564189583547756286948; ///< \ru Единица, деленная на корень из числа пи, 1/sqrt(pi). \en One divided by root of pi, 1/sqrt(pi). +const_expr double M_FI = 1.61803398874989484; ///< \ru Число золотого сечения, 1/M_FI = 0.6180339887499. \en Golden ratio, 1/M_FI = 0.6180339887499. +const_expr double MM_INCH = 25.4; ///< \ru Количество миллиметров в дюйме. \en Millimeters per inch. -#define EPSILON 1E-10 ///< \ru Погрешность. \en Tolerance. -#define MAXIMON 1E+10 ///< \ru 10 в 10-й степени. \en 10 to the power of 10. -#define MAX_OVERALL_DIM 1E+12 ///< \ru Максимальное значение габарита. \en Maximal value of bounding box. +const_expr double EPSILON = 1E-10; ///< \ru Погрешность. \en Tolerance. +const_expr double MAXIMON = 1E+10; ///< \ru 10 в 10-й степени. \en 10 to the power of 10. +const_expr double MAX_OVERALL_DIM = 1E+12; ///< \ru Максимальное значение габарита. \en Maximal value of bounding box. -#define DETERMINANT_MAX 1E+137 ///< \ru Максимальная величина. \en Maximal value. -#define DETERMINANT_MIN 1E-171 ///< \ru Минимальная величина. \en Minimal value. +const_expr double DETERMINANT_MAX = 1E+137; ///< \ru Максимальная величина. \en Maximal value. +const_expr double DETERMINANT_MIN = 1E-171; ///< \ru Минимальная величина. \en Minimal value. -#define UNDEFINED_DBL -MB_MAXDOUBLE ///< \ru Неопределенный double. \en Undefined double. -#define UNDEFINED_INT_T SYS_MIN_ST ///< \ru Неопределенный int. \en Undefined int. +const_expr double NULL_EPSILON = 1E-30; ///< \ru Погрешность для проверки на равенство нулю. \en Tolerance for equality to zero. +const_expr double NULL_REGION = 1E-20; ///< \ru Погрешность для проверки на равенство нулю. \en Tolerance for equality to zero. -#define DEVIATION_SAG M_PI * 0.04 ///< \ru Угловая толерантность. \en Angular tolerance. +const_expr double DOUBLE_EPSILON = 1E-16; ///< \ru Погрешность. \en Tolerance. +const_expr double DOUBLE_REGION = 1E-15; ///< \ru Погрешность. \en Tolerance. +#ifdef C3D_STANDARD_CXX_11 +const_expr double EXTENT_EQUAL = 1E-14; ///< \ru Погрешность. \en Tolerance. +#else +#define EXTENT_EQUAL 1E-14 ///< \ru Погрешность. \en Tolerance. +#endif +const_expr double EXTENT_EPSILON = 1E-12; ///< \ru Погрешность. \en Tolerance. +const_expr double EXTENT_REGION = 1E-11; ///< \ru Погрешность. \en Tolerance. +const_expr double LENGTH_EPSILON = 1E-10; ///< \ru Погрешность длины. \en Tolerance for length. +const_expr double LENGTH_REGION = 1E-9; ///< \ru Погрешность региона. \en Tolerance for region. -#define NULL_EPSILON 1E-30 ///< \ru Погрешность для проверки на равенство нулю. \en Tolerance for equality to zero. -#define NULL_REGION 1E-20 ///< \ru Погрешность для проверки на равенство нулю. \en Tolerance for equality to zero. +const_expr double METRIC_EPSILON = 1E-8; ///< \ru Погрешность расстояния в итерационных функциях. \en Tolerance for distance in iterative functions. +const_expr double METRIC_REGION = 1E-7; ///< \ru Неразличимая метрическая область. \en Indistinguishable metric region. +const_expr double METRIC_PRECISION = 1E-6; ///< \ru Метрическая погрешность. \en Metric tolerance. +const_expr double METRIC_ACCURACY = 1E-5; ///< \ru Наибольшая метрическая погрешность (абсолютная точность в мм ("размер" атома 5e-8 мм)). \en The largest metric tolerance (absolute tolerance expressed in mm ("size" of atom is 5e-8 mm)). +const_expr double METRIC_NEAR = 1E-4; ///< \ru Метрическая близость. \en Metric proximity tolerance. -#define DOUBLE_EPSILON 1E-16 ///< \ru Погрешность. \en Tolerance. -#define DOUBLE_REGION 1E-15 ///< \ru Погрешность. \en Tolerance. -#define EXTENT_EQUAL 1E-14 ///< \ru Погрешность. \en Tolerance. -#define EXTENT_EPSILON 1E-12 ///< \ru Погрешность. \en Tolerance. -#define EXTENT_REGION 1E-11 ///< \ru Погрешность. \en Tolerance. -#define LENGTH_EPSILON 1E-10 ///< \ru Погрешность длины. \en Tolerance for length. -#define LENGTH_REGION 1E-9 ///< \ru Погрешность региона. \en Tolerance for region. +const_expr double PARAM_EPSILON = 1E-8; ///< \ru Погрешность параметра в итерационных функциях. \en Tolerance for parameter in iterative functions. +const_expr double PARAM_REGION = 1E-7; ///< \ru Неразличимая параметрическая область. \en Indistinguishable parametric region. +const_expr double PARAM_PRECISION = 1E-6; ///< \ru Параметрическая погрешность. \en Parametric tolerance. +const_expr double PARAM_ACCURACY = 1E-5; ///< \ru Наибольшая параметрическая погрешность. \en The largest parametric tolerance. +const_expr double PARAM_NEAR = 1E-4; ///< \ru Параметрическая близость. \en Parametric proximity. -#define METRIC_EPSILON 1E-8 ///< \ru Погрешность расстояния в итерационных функциях. \en Tolerance for distance in iterative functions. -#define METRIC_REGION 1E-7 ///< \ru Неразличимая метрическая область. \en Indistinguishable metric region. -#define METRIC_PRECISION 1E-6 ///< \ru Метрическая погрешность. \en Metric tolerance. -#define METRIC_ACCURACY 1E-5 ///< \ru Наибольшая метрическая погрешность (абсолютная точность в мм ("размер" атома 5e-8 мм)). \en The largest metric tolerance (absolute tolerance expressed in mm ("size" of atom is 5e-8 mm)). -#define METRIC_NEAR 1E-4 ///< \ru Метрическая близость. \en Metric proximity tolerance. +const_expr ptrdiff_t UNDEFINED_INT_T = SYS_MIN_ST; ///< \ru Неопределенный int. \en Undefined int. +const_expr size_t FAIR_MAX_DEGREE = 11; ///< \ru Максимальный порядок NURBS при аппроксимации. \en Maxinum degree of the NURBS approximation. -#define PARAM_EPSILON 1E-8 ///< \ru Погрешность параметра в итерационных функциях. \en Tolerance for parameter in iterative functions. -#define PARAM_REGION 1E-7 ///< \ru Неразличимая параметрическая область. \en Indistinguishable parametric region. -#define PARAM_PRECISION 1E-6 ///< \ru Параметрическая погрешность. \en Parametric tolerance. -#define PARAM_ACCURACY 1E-5 ///< \ru Наибольшая параметрическая погрешность. \en The largest parametric tolerance. -#define PARAM_NEAR 1E-4 ///< \ru Параметрическая близость. \en Parametric proximity. - -#define ANGLE_EPSILON PARAM_EPSILON*M_PI ///< \ru Погрешность угла. \en Angular tolerance. -#define ANGLE_REGION ANGLE_EPSILON*40 ///< \ru Погрешность угла, при которой углы считаются равными. \en Angular tolerance for equality of angles. - -#define FAIR_MAX_DEGREE 11 ///< \ru Максимальный порядок NURBS при аппроксимации. \en Maxinum degree of the NURBS approximation. +const_expr double M_PI2 = M_PI * 2.0; ///< \ru Отношение длины окружности к её радиусу, 2.0 * M_PI, 6.28318530717958647692 \en Relation between circle length and its radius, 2.0 * M_PI, 6.28318530717958647692 +const_expr double M_DEGRAD = M_PI / 180.0; ///< \ru Коэффициент перевода градусов в радианы. \en Factor of conversion from degrees to radians. +const_expr double M_RADDEG = 180.0 / M_PI; ///< \ru Коэффициент перевода радиан в градусы. \en Factor of conversion from radians to degrees. +const_expr double UNDEFINED_DBL = -MB_MAXDOUBLE; ///< \ru Неопределенный double. \en Undefined double. +const_expr double DEVIATION_SAG = M_PI * 0.04; ///< \ru Угловая толерантность. \en Angular tolerance. +const_expr double ANGLE_EPSILON = PARAM_EPSILON * M_PI; ///< \ru Погрешность угла. \en Angular tolerance. +const_expr double ANGLE_REGION = ANGLE_EPSILON * 40; ///< \ru Погрешность угла, при которой углы считаются равными. \en Angular tolerance for equality of angles. namespace c3d // namespace C3D { -const double METRIC_DELTA = 0.05; ///< \ru Величина отшагивания. \en Metric offset. -const double PARAM_DELTA_MIN = 0.005; ///< \ru Минимальная доля приращения параметра. \en Minimal portion of parameter increment. -const double PARAM_DELTA_MAX = 1.0; ///< \ru Максимальная доля приращения параметра. \en Maximal portion of parameter increment. +const_expr double METRIC_PORTION = 0.075; ///< \ru Доля расстояния между контрольными точками. \en Proportion of distance between control points. +const_expr double METRIC_DELTA = 0.05; ///< \ru Величина отшагивания. \en Metric offset. +const_expr double PARAM_DELTA_MIN = 0.005; ///< \ru Минимальная доля приращения параметра. \en Minimal portion of parameter increment. +const_expr double PARAM_DELTA_MAX = 1.0; ///< \ru Максимальная доля приращения параметра. \en Maximal portion of parameter increment. -const double MIN_LENGTH = 1.0E-4; ///< \ru Минимальная длина объекта. \en Minimal object length. -const double MAX_LENGTH = 5.0E+7; ///< \ru Максимальная длина объекта. \en Maximal object length. -const double MIN_RADIUS = 1.0E-4; ///< \ru Минимальный радиус объекта. \en Minimal object radius. -const double MAX_RADIUS = 2.5E+7; ///< \ru Максимальный радиус объекта. \en Maximal object radius. +const_expr double MIN_LENGTH = 1.0E-4; ///< \ru Минимальная длина объекта. \en Minimal object length. +const_expr double MAX_LENGTH = 5.0E+7; ///< \ru Максимальная длина объекта. \en Maximal object length. +const_expr double MIN_RADIUS = 1.0E-4; ///< \ru Минимальный радиус объекта. \en Minimal object radius. +const_expr double MAX_RADIUS = 2.5E+7; ///< \ru Максимальный радиус объекта. \en Maximal object radius. -const double DELTA_MIN = 1E-3; ///< \ru Коэффициент уменьшения. \en Reduction factor. -const double DELTA_MID = 1E-2; ///< \ru Коэффициент уменьшения. \en Reduction factor. -const double DELTA_MOD = 1E-1; ///< \ru Коэффициент уменьшения. \en Reduction factor. -const double DELTA_MAX = 1E+3; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double POWER_1 = 1E+1; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double POWER_2 = 1E+2; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double POWER_3 = 1E+3; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double POWER_4 = 1E+4; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double POWER_5 = 1E+5; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double DELTA_MIN = 1E-3; ///< \ru Коэффициент уменьшения. \en Reduction factor. +const_expr double DELTA_MID = 1E-2; ///< \ru Коэффициент уменьшения. \en Reduction factor. +const_expr double DELTA_MOD = 1E-1; ///< \ru Коэффициент уменьшения. \en Reduction factor. +const_expr double DELTA_MAX = 1E+3; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double POWER_1 = 1E+1; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double POWER_2 = 1E+2; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double POWER_3 = 1E+3; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double POWER_4 = 1E+4; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr double POWER_5 = 1E+5; ///< \ru Коэффициент увеличения. \en Magnification factor. -const double ONE_THIRD = 0.33333333333333333333; ///< 1/3. -const double TWO_THIRD = 0.66666666666666666666; ///< 2/3. -const double ONE_SIXTH = 0.166666666666666666667; ///< 1/6. -const double ONE_FIFTH = 0.2; ///< 1/5. -const double TWO_FIFTH = 0.4; ///< 2/5. -const double ONE_QUARTER = 0.25; ///< 1/4. -const double ONE_EIGHTH = 0.125; ///< 1/8. -const double ONE_HALF = 0.5; ///< 1/2. +const_expr double ONE_THIRD = 0.33333333333333333333; ///< 1/3. +const_expr double TWO_THIRD = 0.66666666666666666666; ///< 2/3. +const_expr double ONE_SIXTH = 0.166666666666666666667; ///< 1/6. +const_expr double ONE_FIFTH = 0.2; ///< 1/5. +const_expr double TWO_FIFTH = 0.4; ///< 2/5. +const_expr double ONE_QUARTER = 0.25; ///< 1/4. +const_expr double ONE_HALF = 0.5; ///< 1/2. +const_expr double ONE_SEVENTH = 0.14285714285714285714; ///< 1/7. +const_expr double ONE_EIGHTH = 0.125; ///< 1/8. // \ru Способы построения поверхности сопряжения (скругления или фаски). \en Ways for construction of smooth surface (fillet or chamfer). -const double _CONIC_MIN_ = 0.05; ///< \ru Минимальный коэффициент полноты сечения поверхности сопряжения (при 0.5 - парабола, меньше - эллипс). \en Minimum factor of smooth surface section completeness (0.5 for parabola, less for ellipse). -const double _CONIC_MAX_ = 0.95; ///< \ru Максимальный коэффициент полноты сечения поверхности сопряжения (при 0.5 - парабола, больше - гипербола). \en Maximum factor of smooth surface section completeness (0.5 for parabola, greater for hyperbola). -const double _ARC_ = 0.0; ///< \ru Коэффициент полноты сечения поверхности скругления при u = const соответствует дуге окружности. \en Factor of smooth surface section completeness in case of u = const corresponds to circle arc. +const_expr double _CONIC_MIN_ = 0.05; ///< \ru Минимальный коэффициент полноты сечения поверхности сопряжения (при 0.5 - парабола, меньше - эллипс). \en Minimum factor of smooth surface section completeness (0.5 for parabola, less for ellipse). +const_expr double _CONIC_MAX_ = 0.95; ///< \ru Максимальный коэффициент полноты сечения поверхности сопряжения (при 0.5 - парабола, больше - гипербола). \en Maximum factor of smooth surface section completeness (0.5 for parabola, greater for hyperbola). +const_expr double _ARC_ = 0.0; ///< \ru Коэффициент полноты сечения поверхности скругления при u = const соответствует дуге окружности. \en Factor of smooth surface section completeness in case of u = const corresponds to circle arc. -const int32 TEN = 10; ///< \ru Число 10. \en Number 10. -const int32 TWENTY = 20; ///< \ru Число 20. \en Number 20. -const int32 TESSERA_MAX = 4000; ///< \ru Максимальное количество ячеек в строке и ряду триангуляционной сетки. \en Maximum count of cell in rows and columns for triangulation grid. -const int32 COUNT_MAX = 512; ///< \ru Коэффициент увеличения. \en Magnification factor. -const int32 COUNT_MID = 256; ///< \ru Коэффициент увеличения. \en Magnification factor. -const int32 COUNT_MIN = 128; ///< \ru Коэффициент увеличения. \en Magnification factor. -const int32 COUNT_BIN = 64; ///< \ru Уровень вложенности. \en Inclusion level. -const int32 WIRE_MAX = 256; ///< \ru Максимальное количество линий отрисовочной сетки. \en The maximum number of mesh lines. +const_expr int32 TEN = 10; ///< \ru Число 10. \en Number 10. +const_expr int32 TWENTY = 20; ///< \ru Число 20. \en Number 20. +const_expr int32 TESSERA_MAX = 4000; ///< \ru Максимальное количество ячеек в строке и ряду триангуляционной сетки. \en Maximum count of cell in rows and columns for triangulation grid. +const_expr int32 COUNT_MAX = 512; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr int32 COUNT_MID = 256; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr int32 COUNT_MIN = 128; ///< \ru Коэффициент увеличения. \en Magnification factor. +const_expr int32 COUNT_BIN = 64; ///< \ru Уровень вложенности. \en Inclusion level. +const_expr int32 WIRE_MAX = 256; ///< \ru Максимальное количество линий отрисовочной сетки. \en The maximum number of mesh lines. -const int32 ITERATE_COUNT = 16; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 ITERATE_LIMIT = 32; ///< \ru Количество итераций для построения касательных окружностей. \en Count of iterations for construction of tangent circles. +const_expr int32 ITERATE_COUNT = 16; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 ITERATE_LIMIT = 32; ///< \ru Количество итераций для построения касательных окружностей. \en Count of iterations for construction of tangent circles. -const int32 NEWTON_COUNT = 8; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 NEWTON_COUNT_2X = 16; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 NEWTON_COUNT_3X = 24; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 NEWTON_COUNT_4X = 32; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 NEWTON_COUNT_8X = 64; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 NEWTON_COUNT = 8; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 NEWTON_COUNT_2X = 16; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 NEWTON_COUNT_3X = 24; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 NEWTON_COUNT_4X = 32; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 NEWTON_COUNT_8X = 64; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 LIMIT_COUNT = 4; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. -const int32 COUNT_DELTA = 10; ///< \ru Коэффициент увеличения или уменьшения. \en Reduction or magnification factor. -const int32 COUNT_DELTA_2X = 20; ///< \ru Коэффициент увеличения или уменьшения. \en Reduction or magnification factor. -const int32 ITEMS_COUNT = 12; ///< \ru Число точек в шаговом методе. \en Number of points in step method. +const_expr int32 LIMIT_COUNT = 4; ///< \ru Число приближений в итерационном методе. \en Number of approximations in iterative method. +const_expr int32 COUNT_DELTA = 10; ///< \ru Коэффициент увеличения или уменьшения. \en Reduction or magnification factor. +const_expr int32 COUNT_DELTA_2X = 20; ///< \ru Коэффициент увеличения или уменьшения. \en Reduction or magnification factor. +const_expr int32 ITEMS_COUNT = 12; ///< \ru Число точек в шаговом методе. \en Number of points in step method. -const int32 BEZIER_DEGREE = 4; ///< \ru Порядок Безье-сплайна по умолчанию. \en Default degree of Bezier-spline. -const int32 NURBS_DEGREE = 4; ///< \ru Порядок NURBS по умолчанию. \en Degree of NURBS. +const_expr int32 BEZIER_DEGREE = 4; ///< \ru Порядок Безье-сплайна по умолчанию. \en Default degree of Bezier-spline. +const_expr int32 NURBS_DEGREE = 4; ///< \ru Порядок NURBS по умолчанию. \en Degree of NURBS. -const int32 NURBS_POINTS_COUNT = 6; ///< \ru Число точек для NURBS по умолчанию для прямого редактирования. \en Default number of points for NURBS direct editing. -const int32 NURBS_POINTS_MAX_COUNT = 100; ///< \ru Максимальное число точек для NURBS по умолчанию для прямого редактирования. \en Default maximum number of points for NURBS direct editing. -const int32 APPROX_POINTS_MUL_COEFF = 3; ///< \ru Коэффициент увеличения количества точек для метода наименьших квадратов. \en Factor of points count incrementing in method of least squares. +const_expr int32 NURBS_POINTS_COUNT = 6; ///< \ru Число точек для NURBS по умолчанию для прямого редактирования. \en Default number of points for NURBS direct editing. +const_expr int32 NURBS_POINTS_MAX_COUNT = 100; ///< \ru Максимальное число точек для NURBS по умолчанию для прямого редактирования. \en Default maximum number of points for NURBS direct editing. +const_expr int32 APPROX_POINTS_MUL_COEFF = 3; ///< \ru Коэффициент увеличения количества точек для метода наименьших квадратов. \en Factor of points count incrementing in method of least squares. -const int32 SPACE_DIM = 3; ///< \ru Размерность 3D-пространства. \en Dimension of 3D space. +const_expr int32 SPACE_DIM = 3; ///< \ru Размерность 3D-пространства. \en Dimension of 3D space. -const int32 TRT_FREE = 0; ///< \ru Сопряжение отсутствует. \en No conjugation. -const int32 TRT_TANGENT = 1; ///< \ru Сопряжение по касательной. \en Tangent conjugation. -const int32 TRT_NORMAL = 2; ///< \ru Сопряжение по нормали. \en Normal conjugation. +const_expr int32 TRT_FREE = 0; ///< \ru Сопряжение отсутствует. \en No conjugation. +const_expr int32 TRT_TANGENT = 1; ///< \ru Сопряжение по касательной. \en Tangent conjugation. +const_expr int32 TRT_NORMAL = 2; ///< \ru Сопряжение по нормали. \en Normal conjugation. /** \ru \name Способ информирования о нарушении требований.~ @@ -209,27 +215,27 @@ enum eAssertViolationNotify { } // namespace C3D -#define MB_AMBIENT 0.4 ///< \ru Коэффициент рассеянного освещения (фон). \en Coefficient of backlighting. -#define MB_DIFFUSE 0.7 ///< \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. -#define MB_SPECULARITY 0.8 ///< \ru Коэффициент зеркального отражения. \en Coefficient of specular reflection. -#define MB_SHININESS 50.0 ///< \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). -#define MB_OPACITY 1.0 ///< \ru Коэффициент суммарного отражения (коэффициент непрозрачности). \en Coefficient of total reflection (opacity coefficient). -#define MB_EMISSION 0.0 ///< \ru Коэффициент излучения. \en Emissivity coefficient. +const_expr float MB_AMBIENT = 0.4f; ///< \ru Коэффициент рассеянного освещения (фон). \en Coefficient of backlighting. +const_expr float MB_DIFFUSE = 0.7f; ///< \ru Коэффициент диффузного отражения. \en Coefficient of diffuse reflection. +const_expr float MB_SPECULARITY = 0.8f; ///< \ru Коэффициент зеркального отражения. \en Coefficient of specular reflection. +const_expr float MB_SHININESS = 50.0f; ///< \ru Блеск (показатель степени в законе зеркального отражения). \en Shininess (index according to the law of specular reflection). +const_expr float MB_OPACITY = 1.0f; ///< \ru Коэффициент суммарного отражения (коэффициент непрозрачности). \en Coefficient of total reflection (opacity coefficient). +const_expr float MB_EMISSION = 0.0f; ///< \ru Коэффициент излучения. \en Emissivity coefficient. -#define MB_DEFCOLOR 0x7F7F7F ///< \ru Цвет по умолчанию при импорте и экспорте (серый). \en Default color for import and export (grey). -#define MB_C3DCOLOR 0xFF7F00 ///< \ru Цвет по умолчанию для геометрических объектов. \en Default color for geometric objects. +const_expr uint32 MB_DEFCOLOR = 0x7F7F7F; ///< \ru Цвет по умолчанию при импорте и экспорте (серый). \en Default color for import and export (grey). +const_expr uint32 MB_C3DCOLOR = 0xFF7F00; ///< \ru Цвет по умолчанию для геометрических объектов. \en Default color for geometric objects. /// \ru Битовые флаги для матрицы и локальной системы координат. \en Bit flags for matrix and local coordinate system. -#define MB_IDENTITY 0x00 ///< \ru Единичная матрица. \en Identity. -#define MB_TRANSLATION 0x01 ///< \ru Присутствует смещение. \en Translation. -#define MB_ROTATION 0x02 ///< \ru Присутствует вращение. \en Rotation. -#define MB_SCALING 0x04 ///< \ru Присутствует масштабирование (компонент не 1.0). \en Scaling (factor is not equal to 1.0). -#define MB_REFLECTION 0x08 ///< \ru Присутствует зеркальная инверсия. \en Reflection. -#define MB_LEFT 0x08 ///< \ru Присутствует зеркальная инверсия (признак левой системы координат). \en Reflection (left coordinate system attribute). -#define MB_ORTOGONAL 0x10 ///< \ru Присутствует ортогональность, взводится только в случае аффинности. \en Orthogonality, is set up in case of affinity. -#define MB_AFFINE 0x20 ///< \ru Отсутствует ортогональность и нормированность (аффинное преобразование). \en Absence of orthogonality and normalization (affine transformation). -#define MB_PERSPECTIVE 0x40 ///< \ru Присутствует вектор перспективы (не нулевой). \en Vector of perspective (non-zero). -#define MB_UNSET 0x80 ///< \ru Битовые флаги не установлены. \en Bit flags not set. +const_expr uint8 MB_IDENTITY = 0x00; ///< \ru Единичная матрица. \en Identity. +const_expr uint8 MB_TRANSLATION = 0x01; ///< \ru Присутствует смещение. \en Translation. +const_expr uint8 MB_ROTATION = 0x02; ///< \ru Присутствует вращение. \en Rotation. +const_expr uint8 MB_SCALING = 0x04; ///< \ru Присутствует масштабирование (компонент не 1.0). \en Scaling (factor is not equal to 1.0). +const_expr uint8 MB_REFLECTION = 0x08; ///< \ru Присутствует зеркальная инверсия. \en Reflection. +const_expr uint8 MB_LEFT = 0x08; ///< \ru Присутствует зеркальная инверсия (признак левой системы координат). \en Reflection (left coordinate system attribute). +const_expr uint8 MB_ORTOGONAL = 0x10; ///< \ru Присутствует ортогональность, взводится только в случае аффинности. \en Orthogonality, is set up in case of affinity. +const_expr uint8 MB_AFFINE = 0x20; ///< \ru Отсутствует ортогональность и нормированность (аффинное преобразование). \en Absence of orthogonality and normalization (affine transformation). +const_expr uint8 MB_PERSPECTIVE = 0x40; ///< \ru Присутствует вектор перспективы (не нулевой). \en Vector of perspective (non-zero). +const_expr uint8 MB_UNSET = 0x80; ///< \ru Битовые флаги не установлены. \en Bit flags not set. /** \} */ @@ -330,6 +336,7 @@ private: static bool namesComplete; ///< \ru Флаг полного именования объекта. \en Flag of object full naming. ///< \ru Проименовать грани, рёбра, вершины оболочки после её создания (true) \en Name faces, edges, vertices of shell after creation (true) ///< \ru Проименовать только грани оболочки после её создания (false) \en Name only faces of shell after creation (false) + static bool supressCreators; ///< \ru Флаг отключения работы построителей. \en Constructor disable flag. static MbeMultithreadedMode multithreadedMode; ///< \ru Флаг режима многопоточных вычислений (по умолчанию максимальный). \en Flag of multithreading mode (maximum by default). ///< \ru mtm_Off - Многопоточные вычисления отключены. \en Multithreading is off. ///< \ru mtm_Standard - Включена многопоточность ядра при обработке независимых объектов. \en Kernel multithreading is ON for independent objects. @@ -390,6 +397,22 @@ public: */ static void SetNamesComplete( bool b ); +/** \brief \ru Необходимо ли отключить работу построителей. + \en Is it necessary to disable the work of constructors. \~ + \details \ru Необходимо ли отключить работу построителей. \n + \en Is it necessary to disable the work of constructors. \n \~ + \ingroup Base_Items +*/ + static bool SupressCreators(); + +/** \brief \ru Установить флаг отключения работы построителей. + \en Set the flag to disable the constructors. \~ + \details \ru Установить флаг отключения работы построителей. \n + \en Set the flag to disable the constructors. \~ + \ingroup Base_Items +*/ + static void SetSupressCreators( bool b ); + /** \brief \ru Используются ли многопоточные вычисления? \en Are multithreaded calculations used? \~ \details \ru Используются ли многопоточные вычисления? \n @@ -460,6 +483,9 @@ MATH_FUNC( const char* ) C3DFileNameOnly( const char* path ); #define C3D_ASSERT_AS_CERR(expr) fprintf(stderr, "C3D ASSERT VIOLATION in file %s, %d:\n `%s' in function: %s.\n", C3DFileNameOnly(__FILE__), __LINE__, #expr, __PRETTY_FUNCTION__); #endif +// Supress a warning "unreferenced formal parameter" +#define C3D_UNUSED_PARAMETER( param ) (void*)(¶m) + #ifdef C3D_DEBUG #define C3D_ASSERT_UNCONDITIONAL(expr) \ { const c3d::eAssertViolationNotify notify = Math::CheckAssertNotify(); \ @@ -480,5 +506,11 @@ MATH_FUNC( const char* ) C3DFileNameOnly( const char* path ); #define C3D_ASSERT(expr) ((void)0) #endif +extern "C" +{ + extern MATH_SYMBOL const char * const c3dVersionInfo; ///< \ru Информация о версии c3d.dll \en c3d.dll version information + extern MATH_SYMBOL const char * const c3dBuildInfo; ///< \ru Информация о сборке c3d.dll \en c3d.dll building information +} + #endif // __MB_VARIABLES_H diff --git a/C3d/Include/mb_vector.h b/C3d/Include/mb_vector.h index 83eae5d..08185f1 100644 --- a/C3d/Include/mb_vector.h +++ b/C3d/Include/mb_vector.h @@ -53,7 +53,7 @@ public : /// \ru Конструктор копирования. \en Copy constructor. MbVector ( const MbVector & dir ) : x( dir.x ), y( dir.y ) {} /// \ru Конструктор по двум точкам. \en The constructor by two points. - MbVector ( const MbCartPoint & p1, const MbCartPoint & p2 ) { Init( p1, p2 ); } + MbVector ( const MbCartPoint & p1, const MbCartPoint & p2 ) { Init( p1, p2 ); } /// \ru Конструктор по точке. \en Constructor by point. MbVector ( const MbCartPoint & p ); /// \ru Конструктор по углу. \en Constructor by angle. @@ -700,7 +700,7 @@ public : /// \ru Найти положение вектора относительно текущего вектора. \en Find vector location relative to current vector. int Relative( const MbDirection & ) const; /// \ru Проверить на вырожденность. \en Check for degeneracy. - bool IsDegenerate( double lenEps = Math::LengthEps ) const; + bool IsDegenerate( double lenEps = Math::LengthEps ) const; /// \ru Выдать свойства объекта. \en Get properties of the object. void GetProperties( MbProperties &properties ); diff --git a/C3d/Include/mesh.h b/C3d/Include/mesh.h index c9afdfc..e1bf88f 100644 --- a/C3d/Include/mesh.h +++ b/C3d/Include/mesh.h @@ -185,12 +185,12 @@ public: gr->DecRef(); gridsVector.push_back( gr ); } - grids.clear(); -#ifdef STANDARD_C11 - grids.shrink_to_fit(); -#endif - cube.SetEmpty(); } + grids.clear(); +#ifdef C3D_STANDARD_CXX_11_PARTIAL + grids.shrink_to_fit(); +#endif + 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 ); } @@ -224,12 +224,12 @@ public: pl->DecRef(); polyVector.push_back( pl ); } - wires.clear(); -#ifdef STANDARD_C11 - wires.shrink_to_fit(); -#endif - cube.SetEmpty(); } + wires.clear(); +#ifdef C3D_STANDARD_CXX_11_PARTIAL + wires.shrink_to_fit(); +#endif + 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 ); } @@ -263,12 +263,12 @@ public: peak->DecRef(); peakVector.push_back( peak ); } - peaks.clear(); -#ifdef STANDARD_C11 - peaks.shrink_to_fit(); -#endif - cube.SetEmpty(); } + peaks.clear(); +#ifdef C3D_STANDARD_CXX_11_PARTIAL + peaks.shrink_to_fit(); +#endif + 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 ); } diff --git a/C3d/Include/mesh_float_point3d.h b/C3d/Include/mesh_float_point3d.h index 4203509..63a7fd5 100644 --- a/C3d/Include/mesh_float_point3d.h +++ b/C3d/Include/mesh_float_point3d.h @@ -13,7 +13,7 @@ #include -#define MB_MAXFLOAT MAXIMON // \ru Максимальное значение. \en Maximum value. +const_expr float MB_MAXFLOAT = (float)MAXIMON; // \ru Максимальное значение. \en Maximum value. class MATH_CLASS MbFloatVector3D; diff --git a/C3d/Include/mesh_grid.h b/C3d/Include/mesh_grid.h index 5e37c7b..0f3d9e1 100644 --- a/C3d/Include/mesh_grid.h +++ b/C3d/Include/mesh_grid.h @@ -1,902 +1,906 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Tриангуляция. - \en Triangulation. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MESH_GRID_H -#define __MESH_GRID_H - - -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbRect; - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Триангуляция на числах double. - \en Triangulation on double data. \~ - \details \ru Триангуляция представляет собой набор треугольных и четырёхугольных пластин, стыкующихся друг с другом по общим сторонам.\n - Триангуляция состоит из согласованных наборов точек, нормалей, параметров триангулируемой поверхности и наборов треугольников и четырехугольников. - Каждый треугольник - это три номера из набора точек, определяющих вершины треугольника, каждый четырехугольник - это четыре номера из набора точек, определяющих вершины четырехугольника. \n - \en Triangulation represents a set of triangular and quadrangular plates which are joined to each other by their common sides.\n - The triangulation consists of a sets of points, normals, surface parameters and a sets of triangles and quadrangles. - The triangle is represented as three indices from the set of points defining vertices of triangle, the quadrangle is represented as four indices from the set of points defining vertices of quadrangle.\n \~ - \ingroup Polygonal_Objects -*/ -//////////////////////////////////////////////////////////////////////////////// -class MATH_CLASS MbExactGrid : public MbGrid { -private: - std::vector points; ///< \ru Множество контрольных точек триангуляции (согласовано с множеством параметров, если последнее не пустое, или пусто, если не пусто множество параметров). \en Set of control points of triangulation (synchronized with set of parameters if the last is not empty, or empty if the set of parameters isn't empty). - std::vector normals; ///< \ru Множество нормалей в контрольных точках согласовано с множеством контрольных точек. \en Set of normals at control points is synchronized with the set of control points. - std::vector params; ///< \ru Множество параметров - двумерных точек на параметрической области триангулируемой поверхности (может быть пустым). \en Set of parameters of two-dimensional points in parametric domain of surface being triangulated(can be empty). - std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbExactGrid( const MbExactGrid & init ); - // \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbExactGrid( const MbExactGrid & init, MbRegDuplicate * iReg ); -public: - // \ru Конструктор без параметров. \en Constructor without parameters. - MbExactGrid(); - // \ru Деструктор. \en Destructor. - virtual ~MbExactGrid(); - -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 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. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. - virtual double DistanceToPoint( const MbCartPoint3D & pnt ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual double DistanceToLine( const MbAxis3D & axis, double maxDistance, double & t ) const; // \ru Вычислить расстояние до оси. \en Calculate the distance to 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. - - // \ru Выдать количество точек. \en Get the number of points. - virtual size_t PointsCount() const { return points.size(); } - // \ru Выдать количество нормалей. \en Get the number of normals. - virtual size_t NormalsCount() const { return normals.size(); } - // \ru Выдать количество параметров. \en Get the number of parameters. - virtual size_t ParamsCount() const { return params.size(); } - // \ru Выдать количество значений. \en Get count of values. - virtual size_t EscortsCount() const { return escorts.size(); } - // \ru Выдать количество точек минус 1 (максимальный индекс). \en Get the number of points minus one (maximal index). - virtual ptrdiff_t PointsMaxIndex() const { ptrdiff_t n = points.size(); return ( n - 1 ); } - // \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). - virtual ptrdiff_t NormalsMaxIndex() const { ptrdiff_t n = normals.size(); return ( n - 1 ); } - // \ru Выдать количество параметров минус 1 (максимальный индекс). \en Get the number of parameters minus one (maximal index). - virtual ptrdiff_t ParamsMaxIndex() const { ptrdiff_t n = params.size(); return ( n - 1 ); } - - // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. - virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D, const MbVector3D & n3D ); - // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. - virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D ); - // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. - virtual void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ); - // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. - virtual void AddPoint ( const MbCartPoint3D & p3D ); - // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. - virtual void AddNormal( const MbVector3D & n3D ); - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - virtual void AddParam ( const MbCartPoint & p2D ); - - // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. - virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. - virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D ); - // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. - virtual void AddPoint ( const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. - virtual void AddPoint( const MbFloatPoint3D & p3D ); - // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. - virtual void AddNormal( const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - virtual void AddParam( const MbFloatPoint & p2D ); - - // \ru Добавить в триангуляцию точки. \en Add points to triangulation. - template - void AddPoints ( const PointsVector & pnts ) { - size_t addCnt = pnts.size(); - points.reserve( points.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - points.push_back( pnts[k] ); - } - // \ru Добавить в триангуляцию нормали. \en Add normals to triangulation. - template - void AddNormals( const NormalsVector & nrms ) { - size_t addCnt = nrms.size(); - normals.reserve( normals.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - normals.push_back( nrms[k] ); - } - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - template - void AddParams( const ParamsVector & prms ) { - size_t addCnt = prms.size(); - params.reserve( params.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - params.push_back( prms[k] ); - } - - // \ru Добавить в коллекцию данных. \en Add scores to collection. - virtual void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } - - // \ru Выдать точку по её номеру. \en Get point by its index. - virtual void GetPoint ( size_t i, MbCartPoint3D & p ) const; - // \ru Выдать нормаль по её номеру. \en Get normal by its index. - virtual void GetNormal( size_t i, MbVector3D & n ) const; - // \ru Выдать параметр по его номеру. \en Get parameter by its index. - virtual void GetParam ( size_t i, MbCartPoint & p ) const; - // \ru Выдать дополнительную информацию по её номеру. \en Get additional information by its index. - virtual const uint32 & GetEscort( size_t i ) const; - - /// \ru Выдать точку по её номеру. \en Get point by its index. - virtual void GetPoint ( size_t i, MbFloatPoint3D & p ) const; - /// \ru Выдать нормаль по её номеру. \en Get normal by its index. - virtual void GetNormal( size_t i, MbFloatVector3D & n ) const; - /// \ru Выдать параметр по его номеру. \en Get parameter by its index. - virtual void GetParam ( size_t i, MbFloatPoint & p ) const; - - // \ru Выдать точку с заданным номером. \en Get point by the given index. - const MbCartPoint3D & GetPoint ( size_t i ) const; - // \ru Выдать нормаль с заданным номером. \en Get normal by the given index. - const MbVector3D & GetNormal( size_t i ) const; - // \ru Выдать параметр с заданным номером. \en Get parameter by the given index. - const MbCartPoint & GetParam ( size_t i ) const; - - // \ru Установить точку с заданным номером. \en Set point by the given index. - virtual void SetPoint ( size_t i, const MbCartPoint3D & p ); - // \ru Установить нормаль с заданным номером. \en Set normal by the given index. - virtual void SetNormal( size_t i, const MbVector3D & n ); - // \ru Установить параметр с заданным номером. \en Set parameter by the given index. - virtual void SetParam ( size_t i, const MbCartPoint & p ); - // \ru Установить дополнительную информацию по её номеру. \en Set additional information by its index. - virtual void SetEscort( size_t i, const uint32 & e ); - - // \ru Удалить точку с заданным номером. \en Delete point by the given index. - virtual void PointRemove ( size_t i ); - // \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. - virtual void NormalRemove( size_t i ); - // \ru Удалить параметры поверхности с заданным номером. \en Delete parameters of surface by the given index. - virtual void ParamRemove ( size_t i ); - - // \ru Удалить точки. \en Delete points. - virtual void PointsDelete(); - // \ru Удалить нормали. \en Delete normal. - virtual void NormalsDelete(); - // \ru Удалить параметры. \en Delete papams. - virtual void PapamsDelete(); - // \ru Удалить дополнительную информацию. \en Delete additional information. - virtual void EscortsDelete(); - - /// \ru Инвертировать нормали. \en Invert normals. - virtual void NormalsInvert(); - - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th triangle in general numbering (with strips). - virtual bool GetTriangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). - virtual bool GetTrianglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). - virtual bool GetTrianglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). - virtual bool GetTriangleNormals ( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D & n2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). - virtual bool GetTriangleNormals ( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2 ) const; - - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2, MbCartPoint & r3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadranglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadranglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2, MbFloatPoint3D & n3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleNormals( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D &n2, MbVector3D & n3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleNormals( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2, MbFloatVector3D & n3 ) const; - - // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). - virtual bool GetSingleNormal ( MbVector3D & ) const; - // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). - virtual bool GetSingleNormal ( MbFloatVector3D & ) const; - // \ru Если количество точек больше количества нормалей, то добавить недостающие нормали (только для плоской триангуляции). \en If count of points is greater than count of normals, then add missing normals (only for planar triangulation). - virtual void SynchronizNormals (); - - // \ru Выдать контейнер параметров. \en Get the container of parameters. - template - void GetParams( ParamsVector & paramsVector ) const { - paramsVector.reserve( paramsVector.size() + params.size() ); - for ( size_t i = 0, iCount = params.size(); i < iCount; i++ ) - paramsVector.push_back( params[i] ); - } - // \ru Выдать контейнер точек. \en Get the container of points. - template - void GetPoints( PointsVector & pointsVector ) const { - pointsVector.reserve( pointsVector.size() + points.size() ); - for ( size_t i = 0, iCount = points.size(); i < iCount; i++ ) - pointsVector.push_back( points[i] ); - } - // \ru Выдать контейнер нормалей. \en Get the container of normals. - template - void GetNormals( NormalsVector & normalsVector ) const { - normalsVector.reserve( normalsVector.size() + normals.size() ); - for ( size_t i = 0, iCount = normals.size(); i < iCount; i++ ) - normalsVector.push_back( normals[i] ); - } - - // \ru Расширить присланный габаритный прямоугольник так, чтобы он включал в себя проекцию данного объекта на глобальную плоскость XY. \en Extend given bounding box so that it enclose projection of this object to the global XY-plane. - virtual void AddRect( MbRect & rect ) const; - // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. - virtual void AddCube( MbCube & r ) const; - - // \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с заданным номером с присланным прямоугольником. \en Determine whether the projection of triangle with a given index to the global XY-plane intersects the given rectangle. - bool TriangleIntersectRect( size_t i, MbRect & rect ) const { return (i points; ///< \ru Множество контрольных точек триангуляции (согласовано с множеством параметров, если последнее не пустое, или пусто, если не пусто множество параметров). \en Set of control points of triangulation (synchronized with set of parameters if the last is not empty, or empty if the set of parameters isn't empty). - std::vector normals; ///< \ru Множество нормалей в контрольных точках согласовано с множеством контрольных точек. \en Set of normals at control points is synchronized with the set of control points. - std::vector params; ///< \ru Множество параметров - двумерных точек на параметрической области триангулируемой поверхности (может быть пустым). \en Set of parameters of two-dimensional points in parametric domain of surface being triangulated(can be empty). - std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbFloatGrid( const MbFloatGrid & init ); - // \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbFloatGrid( const MbFloatGrid & init, MbRegDuplicate * iReg ); -public: - // \ru Конструктор без параметров. \en Constructor without parameters. - MbFloatGrid(); - // \ru Деструктор. \en Destructor. - virtual ~MbFloatGrid(); - -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 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. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. - virtual double DistanceToPoint( const MbCartPoint3D & pnt ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. - virtual double DistanceToLine( const MbAxis3D & axis, double maxDistance, double & t ) const; // \ru Вычислить расстояние до оси. \en Calculate the distance to 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. - - // \ru Выдать количество точек. \en Get the number of points. - virtual size_t PointsCount() const { return points.size(); } - // \ru Выдать количество нормалей. \en Get the number of normals. - virtual size_t NormalsCount() const { return normals.size(); } - // \ru Выдать количество параметров. \en Get the number of parameters. - virtual size_t ParamsCount() const { return params.size(); } - // \ru Выдать количество значений. \en Get count of values. - virtual size_t EscortsCount() const { return escorts.size(); } - // \ru Выдать количество точек минус 1 (максимальный индекс). \en Get the number of points minus one (maximal index). - virtual ptrdiff_t PointsMaxIndex() const { ptrdiff_t n = points.size(); return ( n - 1 ); } - // \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). - virtual ptrdiff_t NormalsMaxIndex() const { ptrdiff_t n = normals.size(); return ( n - 1 ); } - // \ru Выдать количество параметров минус 1 (максимальный индекс). \en Get the number of parameters minus one (maximal index). - virtual ptrdiff_t ParamsMaxIndex() const { ptrdiff_t n = params.size(); return ( n - 1 ); } - - // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. - virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D, const MbVector3D & n3D ); - // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. - virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D ); - // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. - virtual void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ); - // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. - virtual void AddPoint ( const MbCartPoint3D & p3D ); - // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. - virtual void AddNormal( const MbVector3D & n3D ); - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - virtual void AddParam ( const MbCartPoint & p2D ); - - // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. - virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. - virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D ); - // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. - virtual void AddPoint ( const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. - virtual void AddPoint( const MbFloatPoint3D & p3D ); - // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. - virtual void AddNormal( const MbFloatVector3D & n3D ); - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - virtual void AddParam( const MbFloatPoint & p2D ); - - // \ru Добавить в триангуляцию точки. \en Add points to triangulation. - template - void AddPoints ( const PointsVector & pnts ) { - size_t addCnt = pnts.size(); - points.reserve( points.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - points.push_back( pnts[k] ); - } - // \ru Добавить в триангуляцию нормали. \en Add normals to triangulation. - template - void AddNormals( const NormalsVector & nrms ) { - size_t addCnt = nrms.size(); - normals.reserve( normals.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - normals.push_back( nrms[k] ); - } - // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. - template - void AddParams( const ParamsVector & prms ) { - size_t addCnt = prms.size(); - params.reserve( params.size() + addCnt ); - for ( size_t k = 0; k < addCnt; k++ ) - params.push_back( prms[k] ); - } - - // \ru Добавить в коллекцию данных. \en Add scores to collection. - virtual void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } - - // \ru Выдать точку по её номеру. \en Get point by its index. - virtual void GetPoint ( size_t i, MbCartPoint3D & p ) const; - // \ru Выдать нормаль по её номеру. \en Get normal by its index. - virtual void GetNormal( size_t i, MbVector3D & n ) const; - // \ru Выдать параметр по его номеру. \en Get parameter by its index. - virtual void GetParam ( size_t i, MbCartPoint & p ) const; - // \ru Выдать дополнительную информацию по её номеру. \en Get additional information by its index. - virtual const uint32 & GetEscort( size_t i ) const; - - /// \ru Выдать точку по её номеру. \en Get point by its index. - virtual void GetPoint ( size_t i, MbFloatPoint3D & p ) const; - /// \ru Выдать нормаль по её номеру. \en Get normal by its index. - virtual void GetNormal( size_t i, MbFloatVector3D & n ) const; - /// \ru Выдать параметр по его номеру. \en Get parameter by its index. - virtual void GetParam ( size_t i, MbFloatPoint & p ) const; - - // \ru Выдать точку с заданным номером. \en Get point by the given index. - const MbFloatPoint3D & GetPoint ( size_t i ) const; - // \ru Выдать нормаль с заданным номером. \en Get normal by the given index. - const MbFloatVector3D & GetNormal( size_t i ) const; - // \ru Выдать параметр с заданным номером. \en Get parameter by the given index. - const MbFloatPoint & GetParam ( size_t i ) const; - - // \ru Установить точку с заданным номером. \en Set point by the given index. - virtual void SetPoint ( size_t i, const MbCartPoint3D & p ); - // \ru Установить нормаль с заданным номером. \en Set normal by the given index. - virtual void SetNormal( size_t i, const MbVector3D & n ); - // \ru Установить параметр с заданным номером. \en Set parameter by the given index. - virtual void SetParam ( size_t i, const MbCartPoint & p ); - // \ru Установить дополнительную информацию по её номеру. \en Set additional information by its index. - virtual void SetEscort( size_t i, const uint32 & e ); - - // \ru Удалить точку с заданным номером. \en Delete point by the given index. - virtual void PointRemove ( size_t i ); - // \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. - virtual void NormalRemove( size_t i ); - // \ru Удалить параметры поверхности с заданным номером. \en Delete parameters of surface by the given index. - virtual void ParamRemove ( size_t i ); - - // \ru Удалить точки. \en Delete points. - virtual void PointsDelete(); - // \ru Удалить нормали. \en Delete normal. - virtual void NormalsDelete(); - // \ru Удалить параметры. \en Delete papams. - virtual void PapamsDelete(); - // \ru Удалить дополнительную информацию. \en Delete additional information. - virtual void EscortsDelete(); - - /// \ru Инвертировать нормали. \en Invert normals. - virtual void NormalsInvert(); - - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th triangle in general numbering (with strips). - virtual bool GetTriangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). - virtual bool GetTrianglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). - virtual bool GetTrianglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). - virtual bool GetTriangleNormals ( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D & n2 ) const; - // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). - virtual bool GetTriangleNormals ( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2 ) const; - - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2, MbCartPoint & r3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadranglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadranglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2, MbFloatPoint3D & n3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleNormals( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D &n2, MbVector3D & n3 ) const; - // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). - virtual bool GetQuadrangleNormals( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2, MbFloatVector3D & n3 ) const; - - // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). - virtual bool GetSingleNormal ( MbVector3D & ) const; - // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). - virtual bool GetSingleNormal ( MbFloatVector3D & ) const; - // \ru Если количество точек больше количества нормалей, то добавить недостающие нормали (только для плоской триангуляции). \en If count of points is greater than count of normals, then add missing normals (only for planar triangulation). - virtual void SynchronizNormals (); - - // \ru Выдать контейнер параметров. \en Get the container of parameters. - template - void GetParams( ParamsVector & paramsVector ) const { - paramsVector.reserve( paramsVector.size() + params.size() ); - for ( size_t i = 0, iCount = params.size(); i < iCount; i++ ) - paramsVector.push_back( params[i] ); - } - // \ru Выдать контейнер точек. \en Get the container of points. - template - void GetPoints( PointsVector & pointsVector ) const { - pointsVector.reserve( pointsVector.size() + points.size() ); - for ( size_t i = 0, iCount = points.size(); i < iCount; i++ ) - pointsVector.push_back( points[i] ); - } - // \ru Выдать контейнер нормалей. \en Get the container of normals. - template - void GetNormals( NormalsVector & normalsVector ) const { - normalsVector.reserve( normalsVector.size() + normals.size() ); - for ( size_t i = 0, iCount = normals.size(); i < iCount; i++ ) - normalsVector.push_back( normals[i] ); - } - - // \ru Расширить присланный габаритный прямоугольник так, чтобы он включал в себя проекцию данного объекта на глобальную плоскость XY. \en Extend given bounding box so that it enclose projection of this object to the global XY-plane. - virtual void AddRect( MbRect & rect ) const; - // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. - virtual void AddCube( MbCube & r ) const; - - // \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с заданным номером с присланным прямоугольником. \en Determine whether the projection of triangle with a given index to the global XY-plane intersects the given rectangle. - virtual bool TriangleIntersectRect( size_t i, MbRect & rect ) const { return (i & cutPlaces, - MbFloatPoint3D & crossPnt, - float & tRes ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Найти пересечение прямой линии и триангуляции. - \en Find the intersection of a straight line with the triangulation. \~ - \details \ru Для всех треугольников определяется пересечение с прямой линии и вычисляется минимальное значение - параметра точки пересечения на секущей прямой линии. \n - \en For all the triangles the intersection with the straight line is determined and the minimum value of - the intersection point parameter on the secant straight line is calculated. \n \~ - \param[in] grid - \ru Триангуляция. - \en Triangulation. \~ - \param[in] line - \ru Прямая линия, для которой вычисляется пересечение с триангуляцией. - \en Straight line to calculate the intersection of triangulation with. \~ - \param[out] tRes - \ru Параметр точки пересечения линии. - \en Parameter of the intersection point on the line. \~ - \return \ru Найдено ли пересечение (true - В случае успеха). - \en Whether the intersection is found (true if success). \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC (bool) LineGridIntersect( const MbGrid & grid, - const MbFloatAxis3D & line, - float & tRes ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить квадрат расстояния от линии до полигона. - \en Calculate squared distance from a line to a polygon. \~ - \details \ru При вычислении квадрата расстояния от линии до полигона проверяется расстояние от каждого - сегмента полигона до первого попадания в окрестность delta. - Возвращается значение параметра ближайшей точки на линии tRes и квадрат расстояния - от этой точки до сегмента полигона. \n - \en During calculation of squared distance from a line to a polygon the distance from each - segment of the polygon is checked until the first getting to 'delta' neighborhood. - Returns the value of the nearest point parameter on tRes line and the squared distance - from this point to a segment of the polygon. \n \~ - \param[in] grid - \ru Триангуляция. - \en Triangulation. \~ - \param[in] edgeInd - \ru Индекс тестируемого полигона. - \en Index of polygon to check. \~ - \param[in] line - \ru Линия, до которой вычисляется расстояние. - \en Line to calculate the distance to. \~ - \param[in] delta - \ru Радиус окрестности вокруг линии. - \en Neighborhood radius around the line. \~ - \param[out] tRes - \ru Значение параметра ближайшей точки линии. - \en The value of parameter of the nearest point on the line. \~ - \return \ru Квадрат расстояния ближайшей точки до линии. - \en Squared distance between the nearest point and the line. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC(float) LineToGridEdgeDistanceSquared( const MbGrid & grid, - size_t edgeInd, - const MbFloatAxis3D & line, - float delta, - float & tRes ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Вычислить квадрат расстояния от линии до полигона. - \en Calculate squared distance from a line to a polygon. \~ - \details \ru При вычислении квадрата расстояния от линии до полигона проверяется расстояние от каждого - сегмента полигона до первого попадания в окрестность delta. - Возвращается значение параметра ближайшей точки на линии tRes, вектор между ближайшими точками и квадрат - расстояния от этой точки до сегмента полигона. \n - \en During calculation of squared distance from a line to a polygon the distance from each - segment of the polygon is checked until the first getting to 'delta' neighborhood. - Returns the value of the nearest point parameter on the line, the vector between the nearest points - and the squared distance from this point to a segment of the polygon. \n \~ - \param[in] grid - \ru Триангуляция. - \en Triangulation. \~ - \param[in] edgeInd - \ru Индекс тестируемого полигона. - \en Index of polygon to check. \~ - \param[in] line - \ru Линия, до которой вычисляется расстояние. - \en Line to calculate the distance to. \~ - \param[in] vDelta - \ru Габарит окрестности вокруг линии. - \en The dimensions of the area around the line. \~ - \param[out] vRes - \ru Вектор от ближайшей точки на линии до ближайшей точки на полигоне. - \en Vector from the nearest point on the line to the nearest point on the polygon. \~ - \param[out] tRes - \ru Значение параметра ближайшей точки линии. - \en The value of parameter of the nearest point on the line. \~ - \return \ru Квадрат расстояния ближайшей точки до линии. - \en Squared distance between the nearest point and the line. \~ - \ingroup Algorithms_3D -*/ -// --- -MATH_FUNC(float) LineToGridEdgeDistanceSquared( const MbGrid & grid, - size_t edgeInd, - const MbFloatAxis3D & line, - const MbFloatVector3D & vDelta, - MbFloatVector3D & vRes, - float & tRes ); - - -#endif // __MESH_GRID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Tриангуляция. + \en Triangulation. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MESH_GRID_H +#define __MESH_GRID_H + + +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbRect; + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Триангуляция на числах double. + \en Triangulation on double data. \~ + \details \ru Триангуляция представляет собой набор треугольных и четырёхугольных пластин, стыкующихся друг с другом по общим сторонам.\n + Триангуляция состоит из согласованных наборов точек, нормалей, параметров триангулируемой поверхности и наборов треугольников и четырехугольников. + Каждый треугольник - это три номера из набора точек, определяющих вершины треугольника, каждый четырехугольник - это четыре номера из набора точек, определяющих вершины четырехугольника. \n + \en Triangulation represents a set of triangular and quadrangular plates which are joined to each other by their common sides.\n + The triangulation consists of a sets of points, normals, surface parameters and a sets of triangles and quadrangles. + The triangle is represented as three indices from the set of points defining vertices of triangle, the quadrangle is represented as four indices from the set of points defining vertices of quadrangle.\n \~ + \ingroup Polygonal_Objects +*/ +//////////////////////////////////////////////////////////////////////////////// +class MATH_CLASS MbExactGrid : public MbGrid { +private: + std::vector points; ///< \ru Множество контрольных точек триангуляции (согласовано с множеством параметров, если последнее не пустое, или пусто, если не пусто множество параметров). \en Set of control points of triangulation (synchronized with set of parameters if the last is not empty, or empty if the set of parameters isn't empty). + std::vector normals; ///< \ru Множество нормалей в контрольных точках согласовано с множеством контрольных точек. \en Set of normals at control points is synchronized with the set of control points. + std::vector params; ///< \ru Множество параметров - двумерных точек на параметрической области триангулируемой поверхности (может быть пустым). \en Set of parameters of two-dimensional points in parametric domain of surface being triangulated(can be empty). + std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbExactGrid( const MbExactGrid & init ); + // \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbExactGrid( const MbExactGrid & init, MbRegDuplicate * iReg ); +public: + // \ru Конструктор без параметров. \en Constructor without parameters. + MbExactGrid(); + // \ru Деструктор. \en Destructor. + virtual ~MbExactGrid(); + +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 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. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. + virtual double DistanceToPoint( const MbCartPoint3D & pnt ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual double DistanceToLine( const MbAxis3D & axis, double maxDistance, double & t ) const; // \ru Вычислить расстояние до оси. \en Calculate the distance to 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. + + // \ru Выдать количество точек. \en Get the number of points. + virtual size_t PointsCount() const { return points.size(); } + // \ru Выдать количество нормалей. \en Get the number of normals. + virtual size_t NormalsCount() const { return normals.size(); } + // \ru Выдать количество параметров. \en Get the number of parameters. + virtual size_t ParamsCount() const { return params.size(); } + // \ru Выдать количество значений. \en Get count of values. + virtual size_t EscortsCount() const { return escorts.size(); } + // \ru Выдать количество точек минус 1 (максимальный индекс). \en Get the number of points minus one (maximal index). + virtual ptrdiff_t PointsMaxIndex() const { ptrdiff_t n = points.size(); return ( n - 1 ); } + // \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). + virtual ptrdiff_t NormalsMaxIndex() const { ptrdiff_t n = normals.size(); return ( n - 1 ); } + // \ru Выдать количество параметров минус 1 (максимальный индекс). \en Get the number of parameters minus one (maximal index). + virtual ptrdiff_t ParamsMaxIndex() const { ptrdiff_t n = params.size(); return ( n - 1 ); } + + // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. + virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D, const MbVector3D & n3D ); + // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. + virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D ); + // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. + virtual void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ); + // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. + virtual void AddPoint ( const MbCartPoint3D & p3D ); + // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. + virtual void AddNormal( const MbVector3D & n3D ); + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + virtual void AddParam ( const MbCartPoint & p2D ); + + // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. + virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. + virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D ); + // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. + virtual void AddPoint ( const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. + virtual void AddPoint( const MbFloatPoint3D & p3D ); + // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. + virtual void AddNormal( const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + virtual void AddParam( const MbFloatPoint & p2D ); + + // \ru Добавить в триангуляцию точки. \en Add points to triangulation. + template + void AddPoints ( const PointsVector & pnts ) { + size_t addCnt = pnts.size(); + points.reserve( points.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + points.push_back( pnts[k] ); + } + // \ru Добавить в триангуляцию нормали. \en Add normals to triangulation. + template + void AddNormals( const NormalsVector & nrms ) { + size_t addCnt = nrms.size(); + normals.reserve( normals.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + normals.push_back( nrms[k] ); + } + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + template + void AddParams( const ParamsVector & prms ) { + size_t addCnt = prms.size(); + params.reserve( params.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + params.push_back( prms[k] ); + } + + // \ru Добавить в коллекцию данных. \en Add scores to collection. + virtual void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } + // \ru Добавить в коллекцию данных цвет точки (0 <= r,g,b,a <= 1). \en Add color to collection (0 <= r,g,b,a <= 1). + virtual void AddColor( float r, float g, float b, float a ); + + // \ru Выдать точку по её номеру. \en Get point by its index. + virtual void GetPoint ( size_t i, MbCartPoint3D & p ) const; + // \ru Выдать нормаль по её номеру. \en Get normal by its index. + virtual void GetNormal( size_t i, MbVector3D & n ) const; + // \ru Выдать параметр по его номеру. \en Get parameter by its index. + virtual void GetParam ( size_t i, MbCartPoint & p ) const; + // \ru Выдать дополнительную информацию по её номеру. \en Get additional information by its index. + virtual const uint32 & GetEscort( size_t i ) const; + + /// \ru Выдать точку по её номеру. \en Get point by its index. + virtual void GetPoint ( size_t i, MbFloatPoint3D & p ) const; + /// \ru Выдать нормаль по её номеру. \en Get normal by its index. + virtual void GetNormal( size_t i, MbFloatVector3D & n ) const; + /// \ru Выдать параметр по его номеру. \en Get parameter by its index. + virtual void GetParam ( size_t i, MbFloatPoint & p ) const; + + // \ru Выдать точку с заданным номером. \en Get point by the given index. + const MbCartPoint3D & GetPoint ( size_t i ) const; + // \ru Выдать нормаль с заданным номером. \en Get normal by the given index. + const MbVector3D & GetNormal( size_t i ) const; + // \ru Выдать параметр с заданным номером. \en Get parameter by the given index. + const MbCartPoint & GetParam ( size_t i ) const; + + // \ru Установить точку с заданным номером. \en Set point by the given index. + virtual void SetPoint ( size_t i, const MbCartPoint3D & p ); + // \ru Установить нормаль с заданным номером. \en Set normal by the given index. + virtual void SetNormal( size_t i, const MbVector3D & n ); + // \ru Установить параметр с заданным номером. \en Set parameter by the given index. + virtual void SetParam ( size_t i, const MbCartPoint & p ); + // \ru Установить дополнительную информацию по её номеру. \en Set additional information by its index. + virtual void SetEscort( size_t i, const uint32 & e ); + + // \ru Удалить точку с заданным номером. \en Delete point by the given index. + virtual void PointRemove ( size_t i ); + // \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. + virtual void NormalRemove( size_t i ); + // \ru Удалить параметры поверхности с заданным номером. \en Delete parameters of surface by the given index. + virtual void ParamRemove ( size_t i ); + + // \ru Удалить точки. \en Delete points. + virtual void PointsDelete(); + // \ru Удалить нормали. \en Delete normal. + virtual void NormalsDelete(); + // \ru Удалить параметры. \en Delete papams. + virtual void PapamsDelete(); + // \ru Удалить дополнительную информацию. \en Delete additional information. + virtual void EscortsDelete(); + + /// \ru Инвертировать нормали. \en Invert normals. + virtual void NormalsInvert(); + + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th triangle in general numbering (with strips). + virtual bool GetTriangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). + virtual bool GetTrianglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). + virtual bool GetTrianglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). + virtual bool GetTriangleNormals ( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D & n2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). + virtual bool GetTriangleNormals ( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2 ) const; + + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2, MbCartPoint & r3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadranglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadranglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2, MbFloatPoint3D & n3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleNormals( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D &n2, MbVector3D & n3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleNormals( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2, MbFloatVector3D & n3 ) const; + + // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). + virtual bool GetSingleNormal ( MbVector3D & ) const; + // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). + virtual bool GetSingleNormal ( MbFloatVector3D & ) const; + // \ru Если количество точек больше количества нормалей, то добавить недостающие нормали (только для плоской триангуляции). \en If count of points is greater than count of normals, then add missing normals (only for planar triangulation). + virtual void SynchronizNormals (); + + // \ru Выдать контейнер параметров. \en Get the container of parameters. + template + void GetParams( ParamsVector & paramsVector ) const { + paramsVector.reserve( paramsVector.size() + params.size() ); + for ( size_t i = 0, iCount = params.size(); i < iCount; i++ ) + paramsVector.push_back( params[i] ); + } + // \ru Выдать контейнер точек. \en Get the container of points. + template + void GetPoints( PointsVector & pointsVector ) const { + pointsVector.reserve( pointsVector.size() + points.size() ); + for ( size_t i = 0, iCount = points.size(); i < iCount; i++ ) + pointsVector.push_back( points[i] ); + } + // \ru Выдать контейнер нормалей. \en Get the container of normals. + template + void GetNormals( NormalsVector & normalsVector ) const { + normalsVector.reserve( normalsVector.size() + normals.size() ); + for ( size_t i = 0, iCount = normals.size(); i < iCount; i++ ) + normalsVector.push_back( normals[i] ); + } + + // \ru Расширить присланный габаритный прямоугольник так, чтобы он включал в себя проекцию данного объекта на глобальную плоскость XY. \en Extend given bounding box so that it enclose projection of this object to the global XY-plane. + virtual void AddRect( MbRect & rect ) const; + // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. + virtual void AddCube( MbCube & r ) const; + + // \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с заданным номером с присланным прямоугольником. \en Determine whether the projection of triangle with a given index to the global XY-plane intersects the given rectangle. + bool TriangleIntersectRect( size_t i, MbRect & rect ) const { return (i points; ///< \ru Множество контрольных точек триангуляции (согласовано с множеством параметров, если последнее не пустое, или пусто, если не пусто множество параметров). \en Set of control points of triangulation (synchronized with set of parameters if the last is not empty, or empty if the set of parameters isn't empty). + std::vector normals; ///< \ru Множество нормалей в контрольных точках согласовано с множеством контрольных точек. \en Set of normals at control points is synchronized with the set of control points. + std::vector params; ///< \ru Множество параметров - двумерных точек на параметрической области триангулируемой поверхности (может быть пустым). \en Set of parameters of two-dimensional points in parametric domain of surface being triangulated(can be empty). + std::vector escorts; ///< \ru Множество значений для дополнительной информации в точках. \en The set of values for additional information of points. + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbFloatGrid( const MbFloatGrid & init ); + // \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbFloatGrid( const MbFloatGrid & init, MbRegDuplicate * iReg ); +public: + // \ru Конструктор без параметров. \en Constructor without parameters. + MbFloatGrid(); + // \ru Деструктор. \en Destructor. + virtual ~MbFloatGrid(); + +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 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. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. + virtual double DistanceToPoint( const MbCartPoint3D & pnt ) const; // \ru Вычислить расстояние до точки. \en Calculate distance to point. + virtual double DistanceToLine( const MbAxis3D & axis, double maxDistance, double & t ) const; // \ru Вычислить расстояние до оси. \en Calculate the distance to 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. + + // \ru Выдать количество точек. \en Get the number of points. + virtual size_t PointsCount() const { return points.size(); } + // \ru Выдать количество нормалей. \en Get the number of normals. + virtual size_t NormalsCount() const { return normals.size(); } + // \ru Выдать количество параметров. \en Get the number of parameters. + virtual size_t ParamsCount() const { return params.size(); } + // \ru Выдать количество значений. \en Get count of values. + virtual size_t EscortsCount() const { return escorts.size(); } + // \ru Выдать количество точек минус 1 (максимальный индекс). \en Get the number of points minus one (maximal index). + virtual ptrdiff_t PointsMaxIndex() const { ptrdiff_t n = points.size(); return ( n - 1 ); } + // \ru Выдать количество нормалей минус 1 (максимальный индекс). \en Get the number of normals minus one (maximal index). + virtual ptrdiff_t NormalsMaxIndex() const { ptrdiff_t n = normals.size(); return ( n - 1 ); } + // \ru Выдать количество параметров минус 1 (максимальный индекс). \en Get the number of parameters minus one (maximal index). + virtual ptrdiff_t ParamsMaxIndex() const { ptrdiff_t n = params.size(); return ( n - 1 ); } + + // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. + virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D, const MbVector3D & n3D ); + // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. + virtual void AddPoint ( const MbCartPoint & p2D, const MbCartPoint3D & p3D ); + // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. + virtual void AddPoint ( const MbCartPoint3D & p3D, const MbVector3D & n3D ); + // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. + virtual void AddPoint ( const MbCartPoint3D & p3D ); + // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. + virtual void AddNormal( const MbVector3D & n3D ); + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + virtual void AddParam ( const MbCartPoint & p2D ); + + // \ru Добавить в триангуляцию параметры, точку и нормаль триангулируемой поверхности в точке. \en Add parameters, point and normal of triangulated surface at point to triangulation. + virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию параметры и точку. \en Add parameters and a point to triangulation. + virtual void AddPoint ( const MbFloatPoint & p2D, const MbFloatPoint3D & p3D ); + // \ru Добавить в триангуляцию точку и нормаль в точке. \en Add a point and normal at the point to triangulation. + virtual void AddPoint ( const MbFloatPoint3D & p3D, const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию точку. \en Add a point to triangulation. + virtual void AddPoint( const MbFloatPoint3D & p3D ); + // \ru Добавить в триангуляцию нормаль. \en Add a normal to triangulation. + virtual void AddNormal( const MbFloatVector3D & n3D ); + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + virtual void AddParam( const MbFloatPoint & p2D ); + + // \ru Добавить в триангуляцию точки. \en Add points to triangulation. + template + void AddPoints ( const PointsVector & pnts ) { + size_t addCnt = pnts.size(); + points.reserve( points.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + points.push_back( pnts[k] ); + } + // \ru Добавить в триангуляцию нормали. \en Add normals to triangulation. + template + void AddNormals( const NormalsVector & nrms ) { + size_t addCnt = nrms.size(); + normals.reserve( normals.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + normals.push_back( nrms[k] ); + } + // \ru Добавить в триангуляцию параметры триангулируемой поверхности. \en Add parameters of triangulated surface to triangulation. + template + void AddParams( const ParamsVector & prms ) { + size_t addCnt = prms.size(); + params.reserve( params.size() + addCnt ); + for ( size_t k = 0; k < addCnt; k++ ) + params.push_back( prms[k] ); + } + + // \ru Добавить в коллекцию данных. \en Add scores to collection. + virtual void AddEscorts( const std::vector & scores ) { escorts.insert(escorts.end(), scores.begin(), scores.end()); } + // \ru Добавить в коллекцию данных цвет точки (0 <= r,g,b,a <= 1). \en Add color to collection (0 <= r,g,b,a <= 1). + virtual void AddColor( float r, float g, float b, float a ); + + // \ru Выдать точку по её номеру. \en Get point by its index. + virtual void GetPoint ( size_t i, MbCartPoint3D & p ) const; + // \ru Выдать нормаль по её номеру. \en Get normal by its index. + virtual void GetNormal( size_t i, MbVector3D & n ) const; + // \ru Выдать параметр по его номеру. \en Get parameter by its index. + virtual void GetParam ( size_t i, MbCartPoint & p ) const; + // \ru Выдать дополнительную информацию по её номеру. \en Get additional information by its index. + virtual const uint32 & GetEscort( size_t i ) const; + + /// \ru Выдать точку по её номеру. \en Get point by its index. + virtual void GetPoint ( size_t i, MbFloatPoint3D & p ) const; + /// \ru Выдать нормаль по её номеру. \en Get normal by its index. + virtual void GetNormal( size_t i, MbFloatVector3D & n ) const; + /// \ru Выдать параметр по его номеру. \en Get parameter by its index. + virtual void GetParam ( size_t i, MbFloatPoint & p ) const; + + // \ru Выдать точку с заданным номером. \en Get point by the given index. + const MbFloatPoint3D & GetPoint ( size_t i ) const; + // \ru Выдать нормаль с заданным номером. \en Get normal by the given index. + const MbFloatVector3D & GetNormal( size_t i ) const; + // \ru Выдать параметр с заданным номером. \en Get parameter by the given index. + const MbFloatPoint & GetParam ( size_t i ) const; + + // \ru Установить точку с заданным номером. \en Set point by the given index. + virtual void SetPoint ( size_t i, const MbCartPoint3D & p ); + // \ru Установить нормаль с заданным номером. \en Set normal by the given index. + virtual void SetNormal( size_t i, const MbVector3D & n ); + // \ru Установить параметр с заданным номером. \en Set parameter by the given index. + virtual void SetParam ( size_t i, const MbCartPoint & p ); + // \ru Установить дополнительную информацию по её номеру. \en Set additional information by its index. + virtual void SetEscort( size_t i, const uint32 & e ); + + // \ru Удалить точку с заданным номером. \en Delete point by the given index. + virtual void PointRemove ( size_t i ); + // \ru Удалить нормаль с заданным номером. \en Delete normal by the given index. + virtual void NormalRemove( size_t i ); + // \ru Удалить параметры поверхности с заданным номером. \en Delete parameters of surface by the given index. + virtual void ParamRemove ( size_t i ); + + // \ru Удалить точки. \en Delete points. + virtual void PointsDelete(); + // \ru Удалить нормали. \en Delete normal. + virtual void NormalsDelete(); + // \ru Удалить параметры. \en Delete papams. + virtual void PapamsDelete(); + // \ru Удалить дополнительную информацию. \en Delete additional information. + virtual void EscortsDelete(); + + /// \ru Инвертировать нормали. \en Invert normals. + virtual void NormalsInvert(); + + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th triangle in general numbering (with strips). + virtual bool GetTriangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). + virtual bool GetTrianglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th triangle in general numbering (with strips). + virtual bool GetTrianglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). + virtual bool GetTriangleNormals ( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D & n2 ) const; + // \ru Выдать для треугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th triangle in general numbering (with strips). + virtual bool GetTriangleNormals ( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2 ) const; + + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) параметры поверхности. \en Get parameters of surface for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleParams ( size_t i, MbCartPoint & r0, MbCartPoint & r1, MbCartPoint & r2, MbCartPoint & r3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadranglePoints ( size_t i, MbCartPoint3D & p0, MbCartPoint3D & p1, MbCartPoint3D & p2, MbCartPoint3D & p3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) точки вершин. \en Get points of vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadranglePoints ( size_t i, MbFloatPoint3D & p0, MbFloatPoint3D & p1, MbFloatPoint3D & p2, MbFloatPoint3D & n3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleNormals( size_t i, MbVector3D & n0, MbVector3D & n1, MbVector3D &n2, MbVector3D & n3 ) const; + // \ru Выдать для четырёхугольника с номером i в общей нумерации (с полосами) нормали в вершинах. \en Get normals at vertices for i-th quadrangle in general numbering (with strips). + virtual bool GetQuadrangleNormals( size_t i, MbFloatVector3D & n0, MbFloatVector3D & n1, MbFloatVector3D & n2, MbFloatVector3D & n3 ) const; + + // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). + virtual bool GetSingleNormal ( MbVector3D & ) const; + // \ru Выдать первую нормаль для плоской триангуляции, если количество точек больше количества нормалей (только для плоской триангуляции). \en Get first normal for flat triangulation if count of points is greater than count of normals (only for planar triangulation). + virtual bool GetSingleNormal ( MbFloatVector3D & ) const; + // \ru Если количество точек больше количества нормалей, то добавить недостающие нормали (только для плоской триангуляции). \en If count of points is greater than count of normals, then add missing normals (only for planar triangulation). + virtual void SynchronizNormals (); + + // \ru Выдать контейнер параметров. \en Get the container of parameters. + template + void GetParams( ParamsVector & paramsVector ) const { + paramsVector.reserve( paramsVector.size() + params.size() ); + for ( size_t i = 0, iCount = params.size(); i < iCount; i++ ) + paramsVector.push_back( params[i] ); + } + // \ru Выдать контейнер точек. \en Get the container of points. + template + void GetPoints( PointsVector & pointsVector ) const { + pointsVector.reserve( pointsVector.size() + points.size() ); + for ( size_t i = 0, iCount = points.size(); i < iCount; i++ ) + pointsVector.push_back( points[i] ); + } + // \ru Выдать контейнер нормалей. \en Get the container of normals. + template + void GetNormals( NormalsVector & normalsVector ) const { + normalsVector.reserve( normalsVector.size() + normals.size() ); + for ( size_t i = 0, iCount = normals.size(); i < iCount; i++ ) + normalsVector.push_back( normals[i] ); + } + + // \ru Расширить присланный габаритный прямоугольник так, чтобы он включал в себя проекцию данного объекта на глобальную плоскость XY. \en Extend given bounding box so that it enclose projection of this object to the global XY-plane. + virtual void AddRect( MbRect & rect ) const; + // \ru Расширить присланный габаритный куб так, чтобы он включал в себя данный объект. \en Extend given bounding box so that it encloses the given object. + virtual void AddCube( MbCube & r ) const; + + // \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с заданным номером с присланным прямоугольником. \en Determine whether the projection of triangle with a given index to the global XY-plane intersects the given rectangle. + virtual bool TriangleIntersectRect( size_t i, MbRect & rect ) const { return (i & cutPlaces, + MbFloatPoint3D & crossPnt, + float & tRes ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Найти пересечение прямой линии и триангуляции. + \en Find the intersection of a straight line with the triangulation. \~ + \details \ru Для всех треугольников определяется пересечение с прямой линии и вычисляется минимальное значение + параметра точки пересечения на секущей прямой линии. \n + \en For all the triangles the intersection with the straight line is determined and the minimum value of + the intersection point parameter on the secant straight line is calculated. \n \~ + \param[in] grid - \ru Триангуляция. + \en Triangulation. \~ + \param[in] line - \ru Прямая линия, для которой вычисляется пересечение с триангуляцией. + \en Straight line to calculate the intersection of triangulation with. \~ + \param[out] tRes - \ru Параметр точки пересечения линии. + \en Parameter of the intersection point on the line. \~ + \return \ru Найдено ли пересечение (true - В случае успеха). + \en Whether the intersection is found (true if success). \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC (bool) LineGridIntersect( const MbGrid & grid, + const MbFloatAxis3D & line, + float & tRes ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить квадрат расстояния от линии до полигона. + \en Calculate squared distance from a line to a polygon. \~ + \details \ru При вычислении квадрата расстояния от линии до полигона проверяется расстояние от каждого + сегмента полигона до первого попадания в окрестность delta. + Возвращается значение параметра ближайшей точки на линии tRes и квадрат расстояния + от этой точки до сегмента полигона. \n + \en During calculation of squared distance from a line to a polygon the distance from each + segment of the polygon is checked until the first getting to 'delta' neighborhood. + Returns the value of the nearest point parameter on tRes line and the squared distance + from this point to a segment of the polygon. \n \~ + \param[in] grid - \ru Триангуляция. + \en Triangulation. \~ + \param[in] edgeInd - \ru Индекс тестируемого полигона. + \en Index of polygon to check. \~ + \param[in] line - \ru Линия, до которой вычисляется расстояние. + \en Line to calculate the distance to. \~ + \param[in] delta - \ru Радиус окрестности вокруг линии. + \en Neighborhood radius around the line. \~ + \param[out] tRes - \ru Значение параметра ближайшей точки линии. + \en The value of parameter of the nearest point on the line. \~ + \return \ru Квадрат расстояния ближайшей точки до линии. + \en Squared distance between the nearest point and the line. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC(float) LineToGridEdgeDistanceSquared( const MbGrid & grid, + size_t edgeInd, + const MbFloatAxis3D & line, + float delta, + float & tRes ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Вычислить квадрат расстояния от линии до полигона. + \en Calculate squared distance from a line to a polygon. \~ + \details \ru При вычислении квадрата расстояния от линии до полигона проверяется расстояние от каждого + сегмента полигона до первого попадания в окрестность delta. + Возвращается значение параметра ближайшей точки на линии tRes, вектор между ближайшими точками и квадрат + расстояния от этой точки до сегмента полигона. \n + \en During calculation of squared distance from a line to a polygon the distance from each + segment of the polygon is checked until the first getting to 'delta' neighborhood. + Returns the value of the nearest point parameter on the line, the vector between the nearest points + and the squared distance from this point to a segment of the polygon. \n \~ + \param[in] grid - \ru Триангуляция. + \en Triangulation. \~ + \param[in] edgeInd - \ru Индекс тестируемого полигона. + \en Index of polygon to check. \~ + \param[in] line - \ru Линия, до которой вычисляется расстояние. + \en Line to calculate the distance to. \~ + \param[in] vDelta - \ru Габарит окрестности вокруг линии. + \en The dimensions of the area around the line. \~ + \param[out] vRes - \ru Вектор от ближайшей точки на линии до ближайшей точки на полигоне. + \en Vector from the nearest point on the line to the nearest point on the polygon. \~ + \param[out] tRes - \ru Значение параметра ближайшей точки линии. + \en The value of parameter of the nearest point on the line. \~ + \return \ru Квадрат расстояния ближайшей точки до линии. + \en Squared distance between the nearest point and the line. \~ + \ingroup Algorithms_3D +*/ +// --- +MATH_FUNC(float) LineToGridEdgeDistanceSquared( const MbGrid & grid, + size_t edgeInd, + const MbFloatAxis3D & line, + const MbFloatVector3D & vDelta, + MbFloatVector3D & vRes, + float & tRes ); + + +#endif // __MESH_GRID_H diff --git a/C3d/Include/mesh_plane_grid.h b/C3d/Include/mesh_plane_grid.h index 9d630cd..10328c4 100644 --- a/C3d/Include/mesh_plane_grid.h +++ b/C3d/Include/mesh_plane_grid.h @@ -1,356 +1,356 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Tриангуляция двумерной области. - \en Triangulation of two-dimensional region. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// "PGrid.cpp" -// \ru PGrid.h - заголовочный файл триангуляции массива двумерных точек. \en PGrid.h - header file of two-dimensional point array triangulation. -// \ru Содержит следующие разделы: \en Contains the following sections: -// \ru - Триангуляция двумерной области \en - Triangulation of a two-dimensional region -// \ru - Вершина полигона \en - Vertex of a polygon -// \ru - Многоугольник \en - Polygon -// \ru - Аппроксимация плоской области треугольными пластинами \en - Approximation of a planar region by triangular plates -// \ru - Трингуляция двумерного региона \en - Triangulation of a two-dimensional region -// \ru - Выпуклая триангуляция неупорядоченного массива двумерных точек \en - Convex triangulation of unordered array of two-dimensional points -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MESH_PLANE_GRID_H -#define __MESH_PLANE_GRID_H - -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbRegion; -class MATH_CLASS MbMatrix3D; -class MATH_CLASS ProgressBarWrapper; - - -//------------------------------------------------------------------------------ -/** \brief \ru Tреугольник. - \en Triangle. \~ - \details \ru Tреугольник определен, как тройка точек, заданных индексами - вершин триангуляции MbPlanarGrid. \n - \en Triangle is defined as triple of points defined by indices - of vertices of MbPlanarGrid triangulation. \n \~ - \ingroup Algorithms_2D -*/ -// --- -class MbTri { -protected : - size_t pIndex[3]; // \ru Номера вершин треугольника в массиве точек \en Indices of triangle vertices in array of points - -public : - MbTri() { pIndex[0] = pIndex[1] = pIndex[2] = SYS_MAX_T; } - MbTri( size_t j0, size_t j1, size_t j2, bool orientation ) { Init( j0, j1, j2, orientation ); } - ~MbTri() {} -private: - MbTri( const MbTri & ); // \ru Не реализовано \en Not implemented - void operator = ( const MbTri & ); // \ru Не реализовано \en Not implemented -public : - - void Init( size_t j0, size_t j1, size_t j2, bool orientation ) - { - if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides - pIndex[0] = j0; - pIndex[1] = j1; - pIndex[2] = j2; - } - else { - pIndex[1] = j1; - pIndex[2] = j0; - pIndex[0] = j2; - } - } - - bool GetTriangle ( size_t & i0, size_t & i1, size_t & i2 ) const - { - i0 = pIndex[0]; - i1 = pIndex[1]; - i2 = pIndex[2]; - return true; - } - - size_t GetIndex( size_t n ) const { return pIndex[n % 3]; } - - bool IsTriangleEdge( size_t k0, size_t k1, size_t & eInd ) const - { - eInd = SYS_MAX_T; - - if ( k0 == pIndex[0] && k1 == pIndex[1] ) - eInd = 0; - else if ( k0 == pIndex[1] && k1 == pIndex[2] ) - eInd = 1; - else if ( k0 == pIndex[2] && k1 == pIndex[0] ) - eInd = 2; - - return (eInd != SYS_MAX_T); - } -}; // MbTri - - -//------------------------------------------------------------------------------ -/** \brief \ru Tриангуляция двумерной области. - \en Triangulation of a two-dimensional region. \~ - \details \ru Tриангуляция двумерной области. \n - \en Triangulation of a two-dimensional region. \n \~ - \ingroup Algorithms_2D -*/ -// --- -class MATH_CLASS MbPlanarGrid { -private: - SArray points; ///< \ru Вершины триангуляции. \en Vertices of triangulation. - SArray triangles; ///< \ru Множество треугольников. \en Array of triangles. - -public: - MbPlanarGrid() : points( 0, 1 ), triangles( 0, 1 ) {} - ~MbPlanarGrid() {}; - -public: - void PointsReserve ( size_t size ) { points.Reserve( size ); } - void TrianglesReserve ( size_t size ) { triangles.Reserve( size ); } - void PointsSetMaxDelta ( uint16 size ) { points.SetMaxDelta( size ); } - void TrianglesSetMaxDelta( uint16 size ) { triangles.SetMaxDelta( size ); } - void PointsAdjust() { points.Adjust(); } - void TrianglesAdjust() { triangles.Adjust(); } - - size_t GetPointsCount () const { return points.Count(); } - size_t GetTrianglesCount() const { return triangles.Count(); } - - void AddTriangle( size_t j0, size_t j1, size_t j2, bool o ) { triangles.Add()->Init( j0, j1, j2,o ); } - void AddPoint ( const MbFloatPoint & p ) { points.Add( p ); } - void AddPoint ( const MbCartPoint & p ) { points.Add( p ); } - /// \ru Выдать декартову точку. \en Get Cartesian point. - bool GetPoint ( size_t k, MbCartPoint & p ) const; - /// \ru Выдать точку. \en Get point. - bool GetPoint ( size_t k, MbFloatPoint & p ) const; - /// \ru Получить индексы точек треугольника. \en Get indices of points of the triangle. - bool GetTriangle( size_t k, size_t & i0, size_t & i1, size_t & i2 ) const; - /// \ru Получить точки треугольника. \en Get points of the triangle. - bool GetTrianglePoints( size_t k, MbCartPoint & p0, MbCartPoint & p1, MbCartPoint & p2 ) const; - -OBVIOUS_PRIVATE_COPY( MbPlanarGrid ) -}; - - -//------------------------------------------------------------------------------ -/// \ru Выдать декартову точку \en Get Cartesian point -// --- -inline bool MbPlanarGrid::GetPoint( size_t k, MbCartPoint & p ) const -{ - if ( k < points.Count() ) { - p = points[k]; - return true; - } - return false; -} - - -//------------------------------------------------------------------------------ -/// \ru Выдать точку \en Get point -// --- -inline bool MbPlanarGrid::GetPoint( size_t k, MbFloatPoint & p ) const -{ - if ( k < points.Count() ) { - p = points[k]; - return true; - } - return false; -} - - -//------------------------------------------------------------------------------ -/// \ru Вершина полигона \en Vertex of a polygon -// --- -class TriVertex { -private: - TriVertex * next; ///< \ru Следующая вершина \en Next vertex - TriVertex * prev; ///< \ru Предыдущая вершина \en Previous vertex - size_t index; ///< \ru Номер точки в массиве точек триангуляции \en Index of point in array of points of triangulation - -public: - TriVertex( size_t i ) : index(i) { next = this; prev = this; } - -public: - ~TriVertex() {} - -public: - /// \ru Смежная вершина (следующая или предыдущая). \en Adjacent vertex (next or previous). - TriVertex * Neighbor ( MbeMoveType ) const; - /// \ru Следующая вершина. \en Next vertex. - TriVertex * Next () const { return next; } - /// \ru Предыдущая вершина. \en Previous vertex. - TriVertex * Prev () const { return prev; } - /// \ru Номер точки текущей вершины. \en Index of point of current vertex. - size_t Index () const { return index; } - /// \ru Вставить вершину после текущей. \en Insert vertex after the current one. - TriVertex * Insert ( TriVertex & ); - /// \ru Исключить текущую вершину (возвращает исключенную, текущей становится предыдущая) \en Exclude the current vertex (returns excluded vertex, previous vertex becomes the current one) - TriVertex * Detach (); - /// \ru Соединить две цепочки вершин. \en Connect two vertex chains. - void Splice ( TriVertex & ); - /// \ru Разделить цепочку вершин вершиной. \en Disconnect vertex chain by a vertex. - TriVertex * Split ( TriVertex & ); - -OBVIOUS_PRIVATE_COPY( TriVertex ) -}; - - -//------------------------------------------------------------------------------ -/// \ru Многоугольник \en Polygon -// --- -class TriPoly { -private: - TriVertex * vertex; ///< \ru Текущая вершина. \en Current vertex. - intptr_t size; ///< \ru Количество вершин. \en Count of vertices. - -public: - TriPoly() : vertex( NULL ), size( 0 ) {} - TriPoly( TriVertex * vert ) : vertex( vert ), size( 0 ) { Resize(); } - -public: - ~TriPoly(); - -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 - - TriVertex * This() const { return vertex; } ///< \ru Текущая вершина \en Current vertex - TriVertex * Next() const; ///< \ru Следующая вершина \en Next vertex - TriVertex * Prev() const; ///< \ru Предыдущая вершина \en Previous vertex - TriVertex * Neighbor( MbeMoveType rotation ) const; ///< \ru Соседняя вершина \en Neighboring vertex - - TriVertex * Advance ( MbeMoveType rotation ); ///< \ru Перемещение указателя текущей вершины на соседа \en Move current vertex pointer to the neighbor - TriVertex * SetVertex( TriVertex * ); ///< \ru Перемещение указателя текущей вершины на указанную \en Move current vertex pointer to the given one - - TriVertex * Insert( TriVertex & ); ///< \ru Вставка новой вершины \en Insert new vertex - void Remove(); ///< \ru Удаление текущей вершины \en Remove the current vertex - - TriPoly * Split( TriVertex &, bool createNew ); ///< \ru Резка многоугольника вдоль хорды \en Cutting of polygon along a chord - bool GetTriangle( size_t & k0, size_t & k1, size_t & k2 ) const; ///< \ru Получить индексы вершин треугольника (когда вершин больше 2) \en Get indices of triangle vertices (when there are more than 2 vertices) - - template - bool CalculateGab( const SArray & pnts, Gab & rect ) const; - -private: - void Resize(); ///< \ru Обновление размера \en Set size to zero - -OBVIOUS_PRIVATE_COPY( TriPoly ) -}; - - -//------------------------------------------------------------------------------ -// \ru Посчитать габарит цепочки вершин \en Calculate bounding box of vertex chain -// --- -template -bool TriPoly::CalculateGab( const SArray & pnts, Gab & rect ) const -{ - bool isDone = false; - - rect.SetEmpty(); - size_t pntsCnt = pnts.Count(); - - if ( Size() > 0 && pntsCnt > 0 ) { - const TriVertex * v0 = This(); - size_t ind0 = v0->Index(); - - if ( ind0 < pntsCnt ) { - isDone = true; - const Point & pnt0 = pnts[ind0]; - rect |= pnt0; - - TriVertex * v = v0->Next(); - while( v0 != v && isDone ) { - isDone = false; - size_t ind = v->Index(); - if ( ind < pntsCnt ) { - const Point & pnt = pnts[ind]; - rect |= pnt; - v = v->Next(); - isDone = true; - } - } - } - } - - C3D_ASSERT( isDone ); - return isDone; -} - - -/* -//------------------------------------------------------------------------------ -// \ru Треугольник со ссылками на смежные(соседние) с ним треугольники \en Triangle with references to triangles adjacent (neighboring) to it -// --- -class MbLinkedTri : public MbTri { -protected: - MbTri * neighbors[3]; // \ru Соседние треугольники \en Neighboring triangles - // \ru Нумерация соседних треугольников: \en Numeration of neighboring triangles: - // \ru 0 - смежный через ребро на вершинах 0,1 \en 0 - adjacent at edge with vertices 0,1 - // \ru 1 - смежный через ребро на вершинах 1,2 \en 1 - adjacent at edge with vertices 1,2 - // \ru 2 - смедный через ребра на вершинах 2,0 \en 2 - adjacent at edge with vertices 2,0 - -public: - MbLinkedTri() : MbTri() { neighbors[0] = neighbors[1] = neighbors[2] = NULL; }; - ~MbLinkedTri() {}; -public: - MbTri * GetNeighbor( size_t n ) const { return neighbors[n % 3]; } - void SetNeighbor( size_t n, MbTri * neighbor ) { neighbors[n % 3] = neighbor; } - bool IsBoundary() const; // \ru Является ли треугольник граничным \en Whether the triangle is boundary - -OBVIOUS_PRIVATE_COPY( MbLinkedTri ) -}; - - -//------------------------------------------------------------------------------ -// \ru Является ли треугольник граничным \en Whether the triangle is boundary -// --- -inline bool MbLinkedTri::IsBoundary() const -{ - bool isBoundary = (neighbors[0] == NULL) || - (neighbors[1] == NULL) || - (neighbors[2] == NULL); - return isBoundary; -} -// */ - - -//------------------------------------------------------------------------------ -// \ru Аппроксимация плоской области треугольными пластинами \en Approximation of planar region by triangular plates -// \ru Функция удаляет полигионы точек из массива \en The function removes polygons of points from the array -// --- -MATH_FUNC (void) CalculatePlanarGrid( PArray< SArray > & poly, MbPlanarGrid & grid ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Трингуляция двумерного региона - \en Triangulation of a two-dimensional region \~ - \details \ru Трингуляция двумерного региона. - Регион region должен быть корректным (на некорректном работает неправильно) - \en Triangulation of a two-dimensional region. - 'region' region has to be correct (improper handling of incorrect ones) \~ - \ingroup Polygonal_Objects -*/ -// --- -MATH_FUNC (void) TriangulateRegion( const MbRegion & region, double sag, MbPlanarGrid & grid ); - - -//------------------------------------------------------------------------------ -/// \ru Выпуклая триангуляция неупорядоченного массива двумерных точек \en Convex triangulation of unordered array of two-dimensional points -// --- -MATH_FUNC (bool) TriangulateConvexCloud( const SArray & uvPnts, double xEps, double yEps, const MbMatrix3D & from, - SArray & triangles, - ProgressBarWrapper * progBar ); - - -#endif // __PGRID_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Tриангуляция двумерной области. + \en Triangulation of two-dimensional region. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// "PGrid.cpp" +// \ru PGrid.h - заголовочный файл триангуляции массива двумерных точек. \en PGrid.h - header file of two-dimensional point array triangulation. +// \ru Содержит следующие разделы: \en Contains the following sections: +// \ru - Триангуляция двумерной области \en - Triangulation of a two-dimensional region +// \ru - Вершина полигона \en - Vertex of a polygon +// \ru - Многоугольник \en - Polygon +// \ru - Аппроксимация плоской области треугольными пластинами \en - Approximation of a planar region by triangular plates +// \ru - Трингуляция двумерного региона \en - Triangulation of a two-dimensional region +// \ru - Выпуклая триангуляция неупорядоченного массива двумерных точек \en - Convex triangulation of unordered array of two-dimensional points +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MESH_PLANE_GRID_H +#define __MESH_PLANE_GRID_H + +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbRegion; +class MATH_CLASS MbMatrix3D; +class MATH_CLASS ProgressBarWrapper; + + +//------------------------------------------------------------------------------ +/** \brief \ru Tреугольник. + \en Triangle. \~ + \details \ru Tреугольник определен, как тройка точек, заданных индексами + вершин триангуляции MbPlanarGrid. \n + \en Triangle is defined as triple of points defined by indices + of vertices of MbPlanarGrid triangulation. \n \~ + \ingroup Algorithms_2D +*/ +// --- +class MbTri { +protected : + size_t pIndex[3]; // \ru Номера вершин треугольника в массиве точек \en Indices of triangle vertices in array of points + +public : + MbTri() { pIndex[0] = pIndex[1] = pIndex[2] = SYS_MAX_T; } + MbTri( size_t j0, size_t j1, size_t j2, bool orientation ) { Init( j0, j1, j2, orientation ); } + ~MbTri() {} +private: + MbTri( const MbTri & ); // \ru Не реализовано \en Not implemented + void operator = ( const MbTri & ); // \ru Не реализовано \en Not implemented +public : + + void Init( size_t j0, size_t j1, size_t j2, bool orientation ) + { + if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides + pIndex[0] = j0; + pIndex[1] = j1; + pIndex[2] = j2; + } + else { + pIndex[1] = j1; + pIndex[2] = j0; + pIndex[0] = j2; + } + } + + bool GetTriangle ( size_t & i0, size_t & i1, size_t & i2 ) const + { + i0 = pIndex[0]; + i1 = pIndex[1]; + i2 = pIndex[2]; + return true; + } + + size_t GetIndex( size_t n ) const { return pIndex[n % 3]; } + + bool IsTriangleEdge( size_t k0, size_t k1, size_t & eInd ) const + { + eInd = SYS_MAX_T; + + if ( k0 == pIndex[0] && k1 == pIndex[1] ) + eInd = 0; + else if ( k0 == pIndex[1] && k1 == pIndex[2] ) + eInd = 1; + else if ( k0 == pIndex[2] && k1 == pIndex[0] ) + eInd = 2; + + return (eInd != SYS_MAX_T); + } +}; // MbTri + + +//------------------------------------------------------------------------------ +/** \brief \ru Tриангуляция двумерной области. + \en Triangulation of a two-dimensional region. \~ + \details \ru Tриангуляция двумерной области. \n + \en Triangulation of a two-dimensional region. \n \~ + \ingroup Algorithms_2D +*/ +// --- +class MATH_CLASS MbPlanarGrid { +private: + SArray points; ///< \ru Вершины триангуляции. \en Vertices of triangulation. + SArray triangles; ///< \ru Множество треугольников. \en Array of triangles. + +public: + MbPlanarGrid() : points( 0, 1 ), triangles( 0, 1 ) {} + ~MbPlanarGrid() {}; + +public: + void PointsReserve ( size_t size ) { points.Reserve( size ); } + void TrianglesReserve ( size_t size ) { triangles.Reserve( size ); } + void PointsSetMaxDelta ( uint16 size ) { points.SetMaxDelta( size ); } + void TrianglesSetMaxDelta( uint16 size ) { triangles.SetMaxDelta( size ); } + void PointsAdjust() { points.Adjust(); } + void TrianglesAdjust() { triangles.Adjust(); } + + size_t GetPointsCount () const { return points.Count(); } + size_t GetTrianglesCount() const { return triangles.Count(); } + + void AddTriangle( size_t j0, size_t j1, size_t j2, bool o ) { triangles.Add()->Init( j0, j1, j2,o ); } + void AddPoint ( const MbFloatPoint & p ) { points.Add( p ); } + void AddPoint ( const MbCartPoint & p ) { points.Add( p ); } + /// \ru Выдать декартову точку. \en Get Cartesian point. + bool GetPoint ( size_t k, MbCartPoint & p ) const; + /// \ru Выдать точку. \en Get point. + bool GetPoint ( size_t k, MbFloatPoint & p ) const; + /// \ru Получить индексы точек треугольника. \en Get indices of points of the triangle. + bool GetTriangle( size_t k, size_t & i0, size_t & i1, size_t & i2 ) const; + /// \ru Получить точки треугольника. \en Get points of the triangle. + bool GetTrianglePoints( size_t k, MbCartPoint & p0, MbCartPoint & p1, MbCartPoint & p2 ) const; + +OBVIOUS_PRIVATE_COPY( MbPlanarGrid ) +}; + + +//------------------------------------------------------------------------------ +/// \ru Выдать декартову точку \en Get Cartesian point +// --- +inline bool MbPlanarGrid::GetPoint( size_t k, MbCartPoint & p ) const +{ + if ( k < points.Count() ) { + p = points[k]; + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +/// \ru Выдать точку \en Get point +// --- +inline bool MbPlanarGrid::GetPoint( size_t k, MbFloatPoint & p ) const +{ + if ( k < points.Count() ) { + p = points[k]; + return true; + } + return false; +} + + +//------------------------------------------------------------------------------ +/// \ru Вершина полигона \en Vertex of a polygon +// --- +class TriVertex { +private: + TriVertex * next; ///< \ru Следующая вершина \en Next vertex + TriVertex * prev; ///< \ru Предыдущая вершина \en Previous vertex + size_t index; ///< \ru Номер точки в массиве точек триангуляции \en Index of point in array of points of triangulation + +public: + TriVertex( size_t i ) : index(i) { next = this; prev = this; } + +public: + ~TriVertex() {} + +public: + /// \ru Смежная вершина (следующая или предыдущая). \en Adjacent vertex (next or previous). + TriVertex * Neighbor ( MbeMoveType ) const; + /// \ru Следующая вершина. \en Next vertex. + TriVertex * Next () const { return next; } + /// \ru Предыдущая вершина. \en Previous vertex. + TriVertex * Prev () const { return prev; } + /// \ru Номер точки текущей вершины. \en Index of point of current vertex. + size_t Index () const { return index; } + /// \ru Вставить вершину после текущей. \en Insert vertex after the current one. + TriVertex * Insert ( TriVertex & ); + /// \ru Исключить текущую вершину (возвращает исключенную, текущей становится предыдущая) \en Exclude the current vertex (returns excluded vertex, previous vertex becomes the current one) + TriVertex * Detach (); + /// \ru Соединить две цепочки вершин. \en Connect two vertex chains. + void Splice ( TriVertex & ); + /// \ru Разделить цепочку вершин вершиной. \en Disconnect vertex chain by a vertex. + TriVertex * Split ( TriVertex & ); + +OBVIOUS_PRIVATE_COPY( TriVertex ) +}; + + +//------------------------------------------------------------------------------ +/// \ru Многоугольник \en Polygon +// --- +class TriPoly { +private: + TriVertex * vertex; ///< \ru Текущая вершина. \en Current vertex. + intptr_t size; ///< \ru Количество вершин. \en Count of vertices. + +public: + TriPoly() : vertex( NULL ), size( 0 ) {} + TriPoly( TriVertex * vert ) : vertex( vert ), size( 0 ) { Resize(); } + +public: + ~TriPoly(); + +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 + + TriVertex * This() const { return vertex; } ///< \ru Текущая вершина \en Current vertex + TriVertex * Next() const; ///< \ru Следующая вершина \en Next vertex + TriVertex * Prev() const; ///< \ru Предыдущая вершина \en Previous vertex + TriVertex * Neighbor( MbeMoveType rotation ) const; ///< \ru Соседняя вершина \en Neighboring vertex + + TriVertex * Advance ( MbeMoveType rotation ); ///< \ru Перемещение указателя текущей вершины на соседа \en Move current vertex pointer to the neighbor + TriVertex * SetVertex( TriVertex * ); ///< \ru Перемещение указателя текущей вершины на указанную \en Move current vertex pointer to the given one + + TriVertex * Insert( TriVertex & ); ///< \ru Вставка новой вершины \en Insert new vertex + void Remove(); ///< \ru Удаление текущей вершины \en Remove the current vertex + + TriPoly * Split( TriVertex &, bool createNew ); ///< \ru Резка многоугольника вдоль хорды \en Cutting of polygon along a chord + bool GetTriangle( size_t & k0, size_t & k1, size_t & k2 ) const; ///< \ru Получить индексы вершин треугольника (когда вершин больше 2) \en Get indices of triangle vertices (when there are more than 2 vertices) + + template + bool CalculateGab( const SArray & pnts, Gab & rect ) const; + +private: + void Resize(); ///< \ru Обновление размера \en Set size to zero + +OBVIOUS_PRIVATE_COPY( TriPoly ) +}; + + +//------------------------------------------------------------------------------ +// \ru Посчитать габарит цепочки вершин \en Calculate bounding box of vertex chain +// --- +template +bool TriPoly::CalculateGab( const SArray & pnts, Gab & rect ) const +{ + bool isDone = false; + + rect.SetEmpty(); + size_t pntsCnt = pnts.Count(); + + if ( Size() > 0 && pntsCnt > 0 ) { + const TriVertex * v0 = This(); + size_t ind0 = v0->Index(); + + if ( ind0 < pntsCnt ) { + isDone = true; + const Point & pnt0 = pnts[ind0]; + rect |= pnt0; + + TriVertex * v = v0->Next(); + while( v0 != v && isDone ) { + isDone = false; + size_t ind = v->Index(); + if ( ind < pntsCnt ) { + const Point & pnt = pnts[ind]; + rect |= pnt; + v = v->Next(); + isDone = true; + } + } + } + } + + C3D_ASSERT( isDone ); + return isDone; +} + + +/* +//------------------------------------------------------------------------------ +// \ru Треугольник со ссылками на смежные(соседние) с ним треугольники \en Triangle with references to triangles adjacent (neighboring) to it +// --- +class MbLinkedTri : public MbTri { +protected: + MbTri * neighbors[3]; // \ru Соседние треугольники \en Neighboring triangles + // \ru Нумерация соседних треугольников: \en Numeration of neighboring triangles: + // \ru 0 - смежный через ребро на вершинах 0,1 \en 0 - adjacent at edge with vertices 0,1 + // \ru 1 - смежный через ребро на вершинах 1,2 \en 1 - adjacent at edge with vertices 1,2 + // \ru 2 - смедный через ребра на вершинах 2,0 \en 2 - adjacent at edge with vertices 2,0 + +public: + MbLinkedTri() : MbTri() { neighbors[0] = neighbors[1] = neighbors[2] = NULL; }; + ~MbLinkedTri() {}; +public: + MbTri * GetNeighbor( size_t n ) const { return neighbors[n % 3]; } + void SetNeighbor( size_t n, MbTri * neighbor ) { neighbors[n % 3] = neighbor; } + bool IsBoundary() const; // \ru Является ли треугольник граничным \en Whether the triangle is boundary + +OBVIOUS_PRIVATE_COPY( MbLinkedTri ) +}; + + +//------------------------------------------------------------------------------ +// \ru Является ли треугольник граничным \en Whether the triangle is boundary +// --- +inline bool MbLinkedTri::IsBoundary() const +{ + bool isBoundary = (neighbors[0] == NULL) || + (neighbors[1] == NULL) || + (neighbors[2] == NULL); + return isBoundary; +} +// */ + + +//------------------------------------------------------------------------------ +// \ru Аппроксимация плоской области треугольными пластинами \en Approximation of planar region by triangular plates +// \ru Функция удаляет полигионы точек из массива \en The function removes polygons of points from the array +// --- +MATH_FUNC (void) CalculatePlanarGrid( PArray< SArray > & poly, MbPlanarGrid & grid ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Трингуляция двумерного региона + \en Triangulation of a two-dimensional region \~ + \details \ru Трингуляция двумерного региона. + Регион region должен быть корректным (на некорректном работает неправильно) + \en Triangulation of a two-dimensional region. + 'region' region has to be correct (improper handling of incorrect ones) \~ + \ingroup Polygonal_Objects +*/ +// --- +MATH_FUNC (void) TriangulateRegion( const MbRegion & region, double sag, MbPlanarGrid & grid ); + + +//------------------------------------------------------------------------------ +/// \ru Выпуклая триангуляция неупорядоченного массива двумерных точек \en Convex triangulation of unordered array of two-dimensional points +// --- +MATH_FUNC (bool) TriangulateConvexCloud( const SArray & uvPnts, double xEps, double yEps, const MbMatrix3D & from, + SArray & triangles, + ProgressBarWrapper * progBar ); + + +#endif // __PGRID_H diff --git a/C3d/Include/mesh_polygon.h b/C3d/Include/mesh_polygon.h index 0711805..915bfcc 100644 --- a/C3d/Include/mesh_polygon.h +++ b/C3d/Include/mesh_polygon.h @@ -69,7 +69,7 @@ public: virtual void Reserve( size_t cnt ) { points.reserve( points.size() + cnt ); } // \ru Удалить лишнюю память. \en Free the unnecessary memory. virtual void Adjust() { - #ifdef STANDARD_C11 + #ifdef C3D_STANDARD_CXX_11_PARTIAL points.shrink_to_fit(); #endif } @@ -195,7 +195,7 @@ public: virtual void Reserve( size_t cnt ) { points.reserve( points.size() + cnt ); } // \ru Удалить лишнюю память. \en Free the unnecessary memory. virtual void Adjust() { - #ifdef STANDARD_C11 + #ifdef C3D_STANDARD_CXX_11_PARTIAL points.shrink_to_fit(); #endif } diff --git a/C3d/Include/mesh_primitive.h b/C3d/Include/mesh_primitive.h index 4180359..2dfc6f2 100644 --- a/C3d/Include/mesh_primitive.h +++ b/C3d/Include/mesh_primitive.h @@ -88,7 +88,7 @@ enum MbePrimitiveType { \ingroup Polygonal_Objects */ //////////////////////////////////////////////////////////////////////////////// -class MATH_CLASS MbPrimitive : public MbAttributeContainer, public MbRefItem { +class MATH_CLASS MbPrimitive : public MbAttributeContainer, public MbRefItem, public MbNestSyncItem { protected: SimpleName name; ///< \ru Имя примитива. \en Name of primitive. const MbRefItem * parentItem; ///< \ru Породивший объект (не владеем). \en Begetter object (don't own). @@ -743,6 +743,14 @@ public: /// \ru Добавить в коллекцию данных. \en Add scores to collection. virtual void AddEscorts( const std::vector & scores ) = 0; + /** \brief \ru Добавить цвет как дополнительную информацию в точке (0 <= r,g,b,a <= 1). + \en Add color as an additional information of point (0 <= r,g,b,a <= 1). \~ + \details + \warning \ru Значения компонент цвета должны лежать в диапазоне [ 0; 1 ]. + \en Values of color components should belong to the range [ 0; 1 ]. \~ + \ingroup Polygonal_Objects +*/ + virtual void AddColor( float r, float g, float b, float a ) = 0; /// \ru Выдать точку по её номеру. \en Get point by its index. virtual void GetPoint ( size_t i, MbCartPoint3D & p ) const = 0; diff --git a/C3d/Include/mesh_triangle.h b/C3d/Include/mesh_triangle.h index f3fccde..9dbcaab 100644 --- a/C3d/Include/mesh_triangle.h +++ b/C3d/Include/mesh_triangle.h @@ -1,483 +1,501 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Структуры данных триангуляции. - \en Triangulation data structures. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MESH_TRIANGLE_H -#define __MESH_TRIANGLE_H - - -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -/// \ru Направление движения \en Motion direction -/** - \ingroup Polygonal_Objects -*/ -// --- -enum MbeMoveType { - mt_Forward = 0, ///< \ru Вперед. \en Forward. - mt_Backward = 1, ///< \ru Назад. \en Backward. -}; - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Tреугольник. - \en Triangle. \~ - \details \ru Tреугольник определен, как тройка точек, заданных индексами - вершин триангуляции MbGrid. \n - \en Triangle is defined as a triple of points defined by indices - of vertices of MbGrid triangulation. \n \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbTriangle { -protected : - uint pIndex[3]; ///< \ru Номера вершин треугольника в массиве точек. \en Indices of triangle vertices in the array of points. - -public : - /// \ru Конструктор. \en Constructor. - MbTriangle() { pIndex[0] = pIndex[1] = pIndex[2] = SYS_MAX_UINT; } - /// \ru Конструктор. \en Constructor. - MbTriangle( uint j0, uint j1, uint j2, bool orientation ); - /// \ru Конструктор копирования. \en The copy-constructor. - MbTriangle( const MbTriangle & init ) { - pIndex[0] = init.pIndex[0]; - pIndex[1] = init.pIndex[1]; - pIndex[2] = init.pIndex[2]; - } - /// \ru Деструктор. \en Destructor. - ~MbTriangle(); - /// \ru Оператора присваивания. \en The assignment operator. - MbTriangle & operator = ( const MbTriangle & init ) { - pIndex[0] = init.pIndex[0]; - pIndex[1] = init.pIndex[1]; - pIndex[2] = init.pIndex[2]; - return *this; - } -public : - - /// \ru Инициализация. \en Initialization. - void Init( uint j0, uint j1, uint j2, bool orientation ); - /// \ru Выдать номера вершин треугольника в массиве точек. \en Get indices of triangle vertices in the array of points. - bool GetTriangle ( uint & i0, uint & i1, uint & i2 ) const; - /// \ru Выдать номер вершины n треугольника в массиве точек. \en Get index of n-th triangle vertex in the array of points. - uint GetIndex( size_t n ) const { return pIndex[n % 3]; } - /// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. - void Reverse(); - - /// \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с присланным прямоугольником. \en Determine whether the projection of the triangle to the global XY-plane intersects the given rectangle. - template - bool IntersectRect( const MbRect & rect, const ParamPoints & points ) const - { - if ( points.size() < 3 ) - return false; - - double x1 = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, points[pIndex[2]].x ) ); - double x2 = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, points[pIndex[2]].x ) ); - - double y1 = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, points[pIndex[2]].y ) ); - double y2 = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, points[pIndex[2]].y ) ); - - return std_max( x1, rect.left ) <= std_min( x2, rect.right ) && - std_max( y1, rect.bottom ) <= std_min( y2, rect.top ); - } - - /// \ru Рассчитать габаритный прямоугольник проекции на глобальную плоскость XY треугольника. \en Calculate bounding rectangle of the projection of the triangle to the global XY-plane. - template - void GetGabRect ( MbRect & rect, const ParamPoints & points ) const - { - if ( points.size() < 3 ) - return; - - rect.left = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, points[pIndex[2]].x ) ); - rect.right = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, points[pIndex[2]].x ) ); - - rect.bottom = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, points[pIndex[2]].y ) ); - rect.top = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, points[pIndex[2]].y ) ); - } - - /// \ru Принадлежит ли ребро треугольнику. \en Is triangle's edge? - bool IsTriangleEdge( uint k0, uint k1, size_t & eInd ) const - { - eInd = SYS_MAX_T; - - if ( k0 == pIndex[0] && k1 == pIndex[1] ) - eInd = 0; - else if ( k0 == pIndex[1] && k1 == pIndex[2] ) - eInd = 1; - else if ( k0 == pIndex[2] && k1 == pIndex[0] ) - eInd = 2; - - return (eInd != SYS_MAX_T); - } - - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & properties ); - /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties & properties ); - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbTriangle, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbTriangle, MATH_FUNC_EX ); -}; // MbTriangle - - -//------------------------------------------------------------------------------ -// \ru Инициализация \en Initialization -// --- -inline void MbTriangle::Init( uint j0, uint j1, uint j2, bool orientation ) -{ - if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides - pIndex[0] = j0; - pIndex[1] = j1; - pIndex[2] = j2; - } - else { - pIndex[1] = j1; - pIndex[2] = j0; - pIndex[0] = j2; - } -} - - -//------------------------------------------------------------------------------ -// \ru Получить индексы треугольной пластины \en Get indices of triangle plate -// --- -inline bool MbTriangle::GetTriangle ( uint & i0, uint & i1, uint & i2 ) const -{ - i0 = pIndex[0]; - i1 = pIndex[1]; - i2 = pIndex[2]; - return true; -} - - -//------------------------------------------------------------------------------ -// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. -// --- -inline void MbTriangle::Reverse() -{ - uint ind = pIndex[1]; - pIndex[1] = pIndex[2]; - pIndex[2] = ind; -} - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Четырёхугольник. - \en Quadrangle. \~ - \details \ru Четырёхугольник задан, как четверка индексов элементов из массива - вершин триангуляции MbGrid. \n - \en Quadrangle defined as a quadruple of elements' indices form the array - of vertices of MbGrid triangulation. \n \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbQuadrangle { -protected : - uint pIndex[4]; ///< \ru Номера вершин четырёхугольника в массиве точек. //-V112 \en Indices of quadrangle vertices in the array of points. //-V112 - -public : - /// \ru Конструктор. \en Constructor. - MbQuadrangle(); - /// \ru Конструктор. \en Constructor. - MbQuadrangle( uint j0, uint j1, uint j2, uint j3, bool orientation ); - /// \ru Конструктор копирования. \en The copy-constructor. - MbQuadrangle( const MbQuadrangle & init ) { - pIndex[0] = init.pIndex[0]; - pIndex[1] = init.pIndex[1]; - pIndex[2] = init.pIndex[2]; - pIndex[3] = init.pIndex[3]; - } - /// \ru Деструктор. \en Destructor. - ~MbQuadrangle(); - /// \ru Оператора присваивания. \en The assignment operator. - MbQuadrangle & operator = ( const MbQuadrangle & init ) { - pIndex[0] = init.pIndex[0]; - pIndex[1] = init.pIndex[1]; - pIndex[2] = init.pIndex[2]; - pIndex[3] = init.pIndex[3]; - return *this; - } -public : - - /// \ru Инициализация. \en Initialization. - void Init( uint j0, uint j1, uint j2, uint j3, bool orientation ); - /// \ru Выдать номера вершин четырёхугольника в массиве точек. \en Get indices of quadrangle vertices in the array of points. - bool GetQuadrangle ( uint & i0, uint & i1, uint & i2, uint & i3 ) const; - /// \ru Выдать номер вершины n четырёхугольника в массиве точек. \en Get index of n-th quadrangle vertex in the array of points. - uint GetIndex( size_t n ) const { return pIndex[n % 4]; } //-V112 - /// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. - void Reverse(); - - /// \ru Определить, пересекается ли проекция на глобальную плоскость XY четырёхугольника с присланным прямоугольником. \en Determine whether the projection of the quadrangle to the global XY-plane intersects the given rectangle. - template - bool IntersectRect( const MbRect & rect, const ParamPoints & points ) const - { - if ( points.size() < 4 ) //-V112 - return false; - - double x1 = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, std_min( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); - double x2 = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, std_max( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); - - double y1 = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, std_min( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); - double y2 = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, std_max( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); - - return std_max( x1, rect.left ) <= std_min( x2, rect.right ) && - std_max( y1, rect.bottom ) <= std_min( y2, rect.top ); - } - - /// \ru Рассчитать габаритный прямоугольник проекции на глобальную плоскость XY четырёхугольника. \en Calculate bounding rectangle of the projection of quadrangle to the global XY-plane. - template - void GetGabRect ( MbRect & rect, const ParamPoints & points ) const - { - if ( points.size() < 4 ) //-V112 - return; - - rect.left = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, std_min( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); - rect.right = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, std_max( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); - - rect.bottom = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, std_min( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); - rect.top = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, std_max( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); - } - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties &properties ); - /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties &properties ); - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbQuadrangle, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbQuadrangle, MATH_FUNC_EX ); -}; // MbQuadrangle - - -//------------------------------------------------------------------------------ -// \ru Инициализация \en Initialization -// --- -inline void MbQuadrangle::Init( uint j0, uint j1, uint j2, uint j3, bool orientation ) -{ - if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides - pIndex[0] = j0; - pIndex[1] = j1; - pIndex[2] = j2; - pIndex[3] = j3; - } - else { - pIndex[2] = j1; - pIndex[3] = j0; - pIndex[0] = j3; - pIndex[1] = j2; - } -} - - -//------------------------------------------------------------------------------ -/// \ru Получить индексы четырехугольной пластины \en Get indices of quadrangle plate -// --- -inline bool MbQuadrangle::GetQuadrangle ( uint & i0, uint & i1, uint & i2, uint & i3 ) const -{ - i0 = pIndex[0]; - i1 = pIndex[1]; - i2 = pIndex[2]; - i3 = pIndex[3]; - return true; -} - - -//------------------------------------------------------------------------------ -// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. -// --- -inline void MbQuadrangle::Reverse() -{ - uint ind = pIndex[1]; - pIndex[1] = pIndex[3]; - pIndex[3] = ind; -} - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Объемный элемент. - \en Element of tesselation of solid volume. \~ - \details \ru Элемент задан, как восемь индексов точек из массива вершин объекта MbGrid. \n - \en Element defined as an elements' indices form the array of vertices of MbGrid. \n \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbElement { -protected : - uint pIndex[8]; ///< \ru Номера вершин елемента в массиве точек. \en Indices of element vertices in the array of points. - size_t estate; ///< \ru Свойство элемента. \en Estate of element. - double props; ///< \ru Характеристика элемента. \en Property of element. - -public : - /// \ru Конструктор. \en Constructor. - MbElement(); - /// \ru Конструктор. \en Constructor. - MbElement( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbElement( const MbElement & ); - /// \ru Деструктор. \en Destructor. - ~MbElement(); - // \ru Оператор присваивания. \en Assignment operator. - MbElement & operator = ( const MbElement & ); - -public : - - /// \ru Инициализация. \en Initialization. - void Init( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ); - /// \ru Выдать номера вершин четырёхугольника в массиве точек. \en Get indices of quadrangle vertices in the array of points. - bool GetElement ( uint & i0, uint & i1, uint & i2, uint & i3, uint & i4, uint & i5, uint & i6, uint & i7 ) const; - /// \ru Выдать номер вершины n четырёхугольника в массиве точек. \en Get index of n-th quadrangle vertex in the array of points. - uint GetIndex( size_t n ) const { return pIndex[n % 8]; } - /// \ru Дать свойство элемента. \en Get estate of element. - size_t GetEstate() const { return estate; } - /// \ru Изменить свойство элемента. \en Set estate of element. - void SetEstate( uint32 e ) { estate = e; } - /// \ru Дать характеристику элемента. \en Get property of element. - double GetProps() const { return props; } - /// \ru Изменить характеристику элемента. \en Get property of element. - void SetProps( double p ) { props = p; } - - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties &properties ); - /// \ru Записать свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties &properties ); - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbElement, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbElement, MATH_FUNC_EX ); -}; // MbElement - - -//------------------------------------------------------------------------------ -// \ru Инициализация \en Initialization -// --- -inline void MbElement::Init( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ) -{ - pIndex[0] = j0; - pIndex[1] = j1; - pIndex[2] = j2; - pIndex[3] = j3; - pIndex[4] = j4; - pIndex[5] = j5; - pIndex[6] = j6; - pIndex[7] = j7; -} - - -//------------------------------------------------------------------------------ -/// \ru Получить индексы четырехугольной пластины \en Get indices of quadrangle plate -// --- -inline bool MbElement::GetElement ( uint & i0, uint & i1, uint & i2, uint & i3, uint & i4, uint & i5, uint & i6, uint & i7 ) const -{ - i0 = pIndex[0]; - i1 = pIndex[1]; - i2 = pIndex[2]; - i3 = pIndex[3]; - i4 = pIndex[4]; - i5 = pIndex[5]; - i6 = pIndex[6]; - i7 = pIndex[7]; - return true; -} - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Граница триангуляции. - \en Border of triangulation. \~ - \details \ru Граница триангуляции используется для описания набора ребер грани оболочки. \n - Граница триангуляции содержит номера последовательности вершины. - \en Border of triangulation is used to describe edge sequence of shell's face. \n - Border of triangulation contains indices of vertex sequence. \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbGridLoop { -private: - std::vector pIndices; ///< \ru Номера вершин в массиве точек. \en Indices of vertices in the array of points. - -public: - /// \ru Конструктор. \en Constructor. - MbGridLoop( size_t n = 0 ) : pIndices() { if ( n > 0 ) pIndices.reserve( n ); } - /// \ru Конструктор. \en Constructor. - template - explicit MbGridLoop( const UintVector & init ) : pIndices() { - pIndices.reserve( init.size() ); - for ( size_t i = 0, iCount = init.size(); i < iCount; i++ ) - pIndices.push_back( init[i] ); - } - /// \ru Деструктор. \en Destructor. - ~MbGridLoop() {} - -public: - /// \ru Инициализация. \en Initialization. - template - void Init( const UintVector & init ) { - pIndices.clear(); pIndices.reserve( init.size() ); - for ( size_t i = 0, iCount = init.size(); i < iCount; i++ ) - pIndices.push_back( init[i] ); - } - /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. - size_t Count() const { return pIndices.size(); } - /// \ru Добавить номер вершины. \en Add vertex number. - void Add( uint n ) { pIndices.push_back(n); } - /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. - uint GetIndex( size_t i ) const { return pIndices[i]; } - /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. - uint & SetIndex( size_t i ) { return pIndices[i]; } - /// \ru Очистить полосу. \en Clear the strip. - void Flush() { pIndices.clear(); } - /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - const uint * GetIndicesAddr() const { return &(pIndices[0]); } - /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - const std::vector & GetIndices() const { return pIndices; } - /// \ru Выдать контейнер номеров вершин. \en Get the container of vertex numbers. - template - void GetIndices( IndicesVector & iVector ) const { - iVector.reserve( iVector.size() + pIndices.size() ); - for ( size_t i = 0, iCount = pIndices.size(); i < iCount; i++ ) - iVector.push_back( pIndices[i] ); - } - /// \ru Есть ли такой индекс в цикле? \en Is exist index n in the loop? - bool IsExist( uint n ) const { return ( std::find(pIndices.begin(), pIndices.end(), n) != pIndices.end() ); } - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbGridLoop, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbGridLoop, MATH_FUNC_EX ); - OBVIOUS_PRIVATE_COPY( MbGridLoop ) -}; - - -//////////////////////////////////////////////////////////////////////////////// -/** \brief \ru Сегмент(результат сегментации) полигональной сетки. - \en A polygonal mesh segment (segmentation result). \~ - \details \ru Сегмент определен множеством треугольников полигональной сетки. \n - \en Segment is defined as a set of triangles of polygonal mesh. \n \~ - \ingroup Polygonal_Objects -*/ -// --- -class MATH_CLASS MbGridSegment { -private: - std::vector faces; ///< \ru Вектор индексов треугольников сегмента. \en A vector of segment triangles indicies. - -public: - /// \ru Конструктор. \en Constructor. - MbGridSegment() : faces() {} - /// \ru Конструктор. \en Constructor. - MbGridSegment( const std::vector & initFaces ) : faces( initFaces ) {} - /// \ru Выдать вектор индексов треугольников сегмента. \en Get the vector of segment triangles indicies. - const std::vector & GetFaces() const { return faces; } - /// \ru Выдать количество треугольников сегмента. \en Get the count of of segment triangles. - size_t GetFaceCount() const { return faces.size(); } - /// \ru Выдать индекс треугольника сегмента. \en Get the index of segment triangle. - size_t GetFace( size_t idx ) const { return faces[idx]; } - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbGridSegment, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbGridSegment, MATH_FUNC_EX ); -}; - -#endif // __MESH_TRIANGLE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Структуры данных триангуляции. + \en Triangulation data structures. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MESH_TRIANGLE_H +#define __MESH_TRIANGLE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbTriangle; + +namespace c3d // namespace C3D +{ + typedef MbTriangle MeshTriangle; ///< \ru Треугольник. \en Triangles vector. + typedef std::vector MeshTrianglesVector; ///< \ru Вектор треугольников. \en Mesh triangles vector. +} + + +//------------------------------------------------------------------------------ +/// \ru Направление движения. \en Motion direction. +/** + \ingroup Polygonal_Objects +*/ +// --- +enum MbeMoveType { + mt_Forward = 0, ///< \ru Вперед. \en Forward. + mt_Backward = 1, ///< \ru Назад. \en Backward. +}; + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Tреугольник. + \en Triangle. \~ + \details \ru Tреугольник определен, как тройка точек, заданных индексами + вершин триангуляции MbGrid. \n + \en Triangle is defined as a triple of points defined by indices + of vertices of MbGrid triangulation. \n \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbTriangle { +protected : + uint pIndex[3]; ///< \ru Номера вершин треугольника в массиве точек. \en Indices of triangle vertices in the array of points. + +public : + /// \ru Конструктор. \en Constructor. + MbTriangle() { pIndex[0] = pIndex[1] = pIndex[2] = SYS_MAX_UINT; } + /// \ru Конструктор. \en Constructor. + MbTriangle( uint j0, uint j1, uint j2, bool orientation ); + /// \ru Конструктор копирования. \en The copy-constructor. + MbTriangle( const MbTriangle & init ) { + pIndex[0] = init.pIndex[0]; + pIndex[1] = init.pIndex[1]; + pIndex[2] = init.pIndex[2]; + } + /// \ru Деструктор. \en Destructor. + ~MbTriangle(); + /// \ru Оператора присваивания. \en The assignment operator. + MbTriangle & operator = ( const MbTriangle & init ) { + pIndex[0] = init.pIndex[0]; + pIndex[1] = init.pIndex[1]; + pIndex[2] = init.pIndex[2]; + return *this; + } +public : + + /// \ru Инициализация. \en Initialization. + void Init( uint j0, uint j1, uint j2, bool orientation ); + /// \ru Выдать номера вершин треугольника в массиве точек. \en Get indices of triangle vertices in the array of points. + bool GetTriangle ( uint & i0, uint & i1, uint & i2 ) const; + /// \ru Выдать номер вершины n треугольника в массиве точек. \en Get index of n-th triangle vertex in the array of points. + uint GetIndex( size_t n ) const { return pIndex[n % 3]; } + /// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. + void Reverse(); + + /// \ru Определить, пересекается ли проекция на глобальную плоскость XY треугольника с присланным прямоугольником. \en Determine whether the projection of the triangle to the global XY-plane intersects the given rectangle. + template + bool IntersectRect( const MbRect & rect, const ParamPoints & points ) const + { + if ( points.size() < 3 ) + return false; + + double x1 = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, points[pIndex[2]].x ) ); + double x2 = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, points[pIndex[2]].x ) ); + + double y1 = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, points[pIndex[2]].y ) ); + double y2 = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, points[pIndex[2]].y ) ); + + return std_max( x1, rect.left ) <= std_min( x2, rect.right ) && + std_max( y1, rect.bottom ) <= std_min( y2, rect.top ); + } + + /// \ru Рассчитать габаритный прямоугольник проекции на глобальную плоскость XY треугольника. \en Calculate bounding rectangle of the projection of the triangle to the global XY-plane. + template + void GetGabRect ( MbRect & rect, const ParamPoints & points ) const + { + if ( points.size() < 3 ) + return; + + rect.left = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, points[pIndex[2]].x ) ); + rect.right = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, points[pIndex[2]].x ) ); + + rect.bottom = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, points[pIndex[2]].y ) ); + rect.top = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, points[pIndex[2]].y ) ); + } + + /// \ru Принадлежит ли ребро треугольнику. \en Is triangle's edge? + bool IsTriangleEdge( uint k0, uint k1, size_t & eInd ) const + { + eInd = SYS_MAX_T; + + if ( k0 == pIndex[0] && k1 == pIndex[1] ) + eInd = 0; + else if ( k0 == pIndex[1] && k1 == pIndex[2] ) + eInd = 1; + else if ( k0 == pIndex[2] && k1 == pIndex[0] ) + eInd = 2; + + return (eInd != SYS_MAX_T); + } + + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties & properties ); + /// \ru Записать свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties & properties ); + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbTriangle, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbTriangle, MATH_FUNC_EX ); +}; // MbTriangle + + +//------------------------------------------------------------------------------ +// \ru Инициализация \en Initialization +// --- +inline void MbTriangle::Init( uint j0, uint j1, uint j2, bool orientation ) +{ + if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides + pIndex[0] = j0; + pIndex[1] = j1; + pIndex[2] = j2; + } + else { + pIndex[1] = j1; + pIndex[2] = j0; + pIndex[0] = j2; + } +} + + +//------------------------------------------------------------------------------ +// \ru Получить индексы треугольной пластины \en Get indices of triangle plate +// --- +inline bool MbTriangle::GetTriangle ( uint & i0, uint & i1, uint & i2 ) const +{ + i0 = pIndex[0]; + i1 = pIndex[1]; + i2 = pIndex[2]; + return true; +} + + +//------------------------------------------------------------------------------ +// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. +// --- +inline void MbTriangle::Reverse() +{ + uint ind = pIndex[1]; + pIndex[1] = pIndex[2]; + pIndex[2] = ind; +} + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Четырёхугольник. + \en Quadrangle. \~ + \details \ru Четырёхугольник задан, как четверка индексов элементов из массива + вершин триангуляции MbGrid. \n + \en Quadrangle defined as a quadruple of elements' indices form the array + of vertices of MbGrid triangulation. \n \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbQuadrangle { +protected : + uint pIndex[4]; ///< \ru Номера вершин четырёхугольника в массиве точек. //-V112 \en Indices of quadrangle vertices in the array of points. //-V112 + +public : + /// \ru Конструктор. \en Constructor. + MbQuadrangle(); + /// \ru Конструктор. \en Constructor. + MbQuadrangle( uint j0, uint j1, uint j2, uint j3, bool orientation ); + /// \ru Конструктор копирования. \en The copy-constructor. + MbQuadrangle( const MbQuadrangle & init ) { + pIndex[0] = init.pIndex[0]; + pIndex[1] = init.pIndex[1]; + pIndex[2] = init.pIndex[2]; + pIndex[3] = init.pIndex[3]; + } + /// \ru Деструктор. \en Destructor. + ~MbQuadrangle(); + /// \ru Оператора присваивания. \en The assignment operator. + MbQuadrangle & operator = ( const MbQuadrangle & init ) { + pIndex[0] = init.pIndex[0]; + pIndex[1] = init.pIndex[1]; + pIndex[2] = init.pIndex[2]; + pIndex[3] = init.pIndex[3]; + return *this; + } +public : + + /// \ru Инициализация. \en Initialization. + void Init( uint j0, uint j1, uint j2, uint j3, bool orientation ); + /// \ru Выдать номера вершин четырёхугольника в массиве точек. \en Get indices of quadrangle vertices in the array of points. + bool GetQuadrangle ( uint & i0, uint & i1, uint & i2, uint & i3 ) const; + /// \ru Выдать пару треугольников, составляющих четырехугольник. \en Get a pair of triangles consisting the quadrangle. + void GetTriangles( MbTriangle &, MbTriangle & ) const; + /// \ru Выдать номер вершины n четырёхугольника в массиве точек. \en Get index of n-th quadrangle vertex in the array of points. + uint GetIndex( size_t n ) const { return pIndex[n % 4]; } //-V112 + /// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. + void Reverse(); + /// \ru Определить, пересекается ли проекция на глобальную плоскость XY четырёхугольника с присланным прямоугольником. \en Determine whether the projection of the quadrangle to the global XY-plane intersects the given rectangle. + template + bool IntersectRect( const MbRect & rect, const ParamPoints & points ) const + { + if ( points.size() < 4 ) //-V112 + return false; + + double x1 = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, std_min( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); + double x2 = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, std_max( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); + + double y1 = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, std_min( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); + double y2 = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, std_max( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); + + return std_max( x1, rect.left ) <= std_min( x2, rect.right ) && + std_max( y1, rect.bottom ) <= std_min( y2, rect.top ); + } + + /// \ru Рассчитать габаритный прямоугольник проекции на глобальную плоскость XY четырёхугольника. \en Calculate bounding rectangle of the projection of quadrangle to the global XY-plane. + template + void GetGabRect ( MbRect & rect, const ParamPoints & points ) const + { + if ( points.size() < 4 ) //-V112 + return; + + rect.left = std_min( points[pIndex[0]].x, std_min( points[pIndex[1]].x, std_min( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); + rect.right = std_max( points[pIndex[0]].x, std_max( points[pIndex[1]].x, std_max( points[pIndex[2]].x, points[pIndex[3]].x ) ) ); + + rect.bottom = std_min( points[pIndex[0]].y, std_min( points[pIndex[1]].y, std_min( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); + rect.top = std_max( points[pIndex[0]].y, std_max( points[pIndex[1]].y, std_max( points[pIndex[2]].y, points[pIndex[3]].y ) ) ); + } + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties &properties ); + /// \ru Записать свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties &properties ); + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbQuadrangle, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbQuadrangle, MATH_FUNC_EX ); +}; // MbQuadrangle + + +//------------------------------------------------------------------------------ +// \ru Инициализация \en Initialization +// --- +inline void MbQuadrangle::Init( uint j0, uint j1, uint j2, uint j3, bool orientation ) +{ + if ( orientation ) { // \ru Совпадает направление обхода \en Traverse direction coincides + pIndex[0] = j0; + pIndex[1] = j1; + pIndex[2] = j2; + pIndex[3] = j3; + } + else { + pIndex[2] = j1; + pIndex[3] = j0; + pIndex[0] = j3; + pIndex[1] = j2; + } +} + + +//------------------------------------------------------------------------------ +/// \ru Получить индексы четырехугольной пластины \en Get indices of quadrangle plate +// --- +inline bool MbQuadrangle::GetQuadrangle ( uint & i0, uint & i1, uint & i2, uint & i3 ) const +{ + i0 = pIndex[0]; + i1 = pIndex[1]; + i2 = pIndex[2]; + i3 = pIndex[3]; + return true; +} + +//------------------------------------------------------------------------------ +// \ru Выдать пару треугольников, составляющих четырехугольник. \en Get a pair of triangles consisting the quadrangle. +//--- +inline void MbQuadrangle::GetTriangles( MbTriangle & fTri, MbTriangle & sTri ) const +{ + fTri.Init( pIndex[0], pIndex[1], pIndex[2], true ); + sTri.Init( pIndex[2], pIndex[3], pIndex[0], true ); +} + +//------------------------------------------------------------------------------ +// \ru Инвертировать последовательность вершин. \en Reverse the sequence of vertices. +// --- +inline void MbQuadrangle::Reverse() +{ + uint ind = pIndex[1]; + pIndex[1] = pIndex[3]; + pIndex[3] = ind; +} + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Объемный элемент. + \en Element of tesselation of solid volume. \~ + \details \ru Элемент задан, как восемь индексов точек из массива вершин объекта MbGrid. \n + \en Element defined as an elements' indices form the array of vertices of MbGrid. \n \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbElement { +protected : + uint pIndex[8]; ///< \ru Номера вершин елемента в массиве точек. \en Indices of element vertices in the array of points. + size_t estate; ///< \ru Свойство элемента. \en Estate of element. + double props; ///< \ru Характеристика элемента. \en Property of element. + +public : + /// \ru Конструктор. \en Constructor. + MbElement(); + /// \ru Конструктор. \en Constructor. + MbElement( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbElement( const MbElement & ); + /// \ru Деструктор. \en Destructor. + ~MbElement(); + // \ru Оператор присваивания. \en Assignment operator. + MbElement & operator = ( const MbElement & ); + +public : + + /// \ru Инициализация. \en Initialization. + void Init( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ); + /// \ru Выдать номера вершин четырёхугольника в массиве точек. \en Get indices of quadrangle vertices in the array of points. + bool GetElement ( uint & i0, uint & i1, uint & i2, uint & i3, uint & i4, uint & i5, uint & i6, uint & i7 ) const; + /// \ru Выдать номер вершины n четырёхугольника в массиве точек. \en Get index of n-th quadrangle vertex in the array of points. + uint GetIndex( size_t n ) const { return pIndex[n % 8]; } + /// \ru Дать свойство элемента. \en Get estate of element. + size_t GetEstate() const { return estate; } + /// \ru Изменить свойство элемента. \en Set estate of element. + void SetEstate( uint32 e ) { estate = e; } + /// \ru Дать характеристику элемента. \en Get property of element. + double GetProps() const { return props; } + /// \ru Изменить характеристику элемента. \en Get property of element. + void SetProps( double p ) { props = p; } + + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties &properties ); + /// \ru Записать свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties &properties ); + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbElement, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbElement, MATH_FUNC_EX ); +}; // MbElement + + +//------------------------------------------------------------------------------ +// \ru Инициализация \en Initialization +// --- +inline void MbElement::Init( uint j0, uint j1, uint j2, uint j3, uint j4, uint j5, uint j6, uint j7 ) +{ + pIndex[0] = j0; + pIndex[1] = j1; + pIndex[2] = j2; + pIndex[3] = j3; + pIndex[4] = j4; + pIndex[5] = j5; + pIndex[6] = j6; + pIndex[7] = j7; +} + + +//------------------------------------------------------------------------------ +/// \ru Получить индексы четырехугольной пластины \en Get indices of quadrangle plate +// --- +inline bool MbElement::GetElement ( uint & i0, uint & i1, uint & i2, uint & i3, uint & i4, uint & i5, uint & i6, uint & i7 ) const +{ + i0 = pIndex[0]; + i1 = pIndex[1]; + i2 = pIndex[2]; + i3 = pIndex[3]; + i4 = pIndex[4]; + i5 = pIndex[5]; + i6 = pIndex[6]; + i7 = pIndex[7]; + return true; +} + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Граница триангуляции. + \en Border of triangulation. \~ + \details \ru Граница триангуляции используется для описания набора ребер грани оболочки. \n + Граница триангуляции содержит номера последовательности вершины. + \en Border of triangulation is used to describe edge sequence of shell's face. \n + Border of triangulation contains indices of vertex sequence. \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbGridLoop { +private: + std::vector pIndices; ///< \ru Номера вершин в массиве точек. \en Indices of vertices in the array of points. + +public: + /// \ru Конструктор. \en Constructor. + MbGridLoop( size_t n = 0 ) : pIndices() { if ( n > 0 ) pIndices.reserve( n ); } + /// \ru Конструктор. \en Constructor. + template + explicit MbGridLoop( const UintVector & init ) : pIndices() { + pIndices.reserve( init.size() ); + for ( size_t i = 0, iCount = init.size(); i < iCount; i++ ) + pIndices.push_back( init[i] ); + } + /// \ru Деструктор. \en Destructor. + ~MbGridLoop() {} + +public: + /// \ru Инициализация. \en Initialization. + template + void Init( const UintVector & init ) { + pIndices.clear(); pIndices.reserve( init.size() ); + for ( size_t i = 0, iCount = init.size(); i < iCount; i++ ) + pIndices.push_back( init[i] ); + } + /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. + size_t Count() const { return pIndices.size(); } + /// \ru Добавить номер вершины. \en Add vertex number. + void Add( uint n ) { pIndices.push_back(n); } + /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. + uint GetIndex( size_t i ) const { return pIndices[i]; } + /// \ru Выдать количество вершин полосы. \en Get the count of strip vertices. + uint & SetIndex( size_t i ) { return pIndices[i]; } + /// \ru Очистить полосу. \en Clear the strip. + void Flush() { pIndices.clear(); } + /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. + const uint * GetIndicesAddr() const { return &(pIndices[0]); } + /// \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. + const std::vector & GetIndices() const { return pIndices; } + /// \ru Выдать контейнер номеров вершин. \en Get the container of vertex numbers. + template + void GetIndices( IndicesVector & iVector ) const { + iVector.reserve( iVector.size() + pIndices.size() ); + for ( size_t i = 0, iCount = pIndices.size(); i < iCount; i++ ) + iVector.push_back( pIndices[i] ); + } + /// \ru Есть ли такой индекс в цикле? \en Is exist index n in the loop? + bool IsExist( uint n ) const { return ( std::find(pIndices.begin(), pIndices.end(), n) != pIndices.end() ); } + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbGridLoop, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbGridLoop, MATH_FUNC_EX ); + OBVIOUS_PRIVATE_COPY( MbGridLoop ) +}; + + +//////////////////////////////////////////////////////////////////////////////// +/** \brief \ru Сегмент(результат сегментации) полигональной сетки. + \en A polygonal mesh segment (segmentation result). \~ + \details \ru Сегмент определен множеством треугольников полигональной сетки. \n + \en Segment is defined as a set of triangles of polygonal mesh. \n \~ + \ingroup Polygonal_Objects +*/ +// --- +class MATH_CLASS MbGridSegment { +private: + std::vector faces; ///< \ru Вектор индексов треугольников сегмента. \en A vector of segment triangles indicies. + +public: + /// \ru Конструктор. \en Constructor. + MbGridSegment() : faces() {} + /// \ru Конструктор. \en Constructor. + MbGridSegment( const std::vector & initFaces ) : faces( initFaces ) {} + /// \ru Выдать вектор индексов треугольников сегмента. \en Get the vector of segment triangles indicies. + const std::vector & GetFaces() const { return faces; } + /// \ru Выдать количество треугольников сегмента. \en Get the count of of segment triangles. + size_t GetFaceCount() const { return faces.size(); } + /// \ru Выдать индекс треугольника сегмента. \en Get the index of segment triangle. + size_t GetFace( size_t idx ) const { return faces[idx]; } + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbGridSegment, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbGridSegment, MATH_FUNC_EX ); +}; + +#endif // __MESH_TRIANGLE_H diff --git a/C3d/Include/mip_solid_mass_inertia.h b/C3d/Include/mip_solid_mass_inertia.h index 095d5f2..066d60c 100644 --- a/C3d/Include/mip_solid_mass_inertia.h +++ b/C3d/Include/mip_solid_mass_inertia.h @@ -20,14 +20,14 @@ struct IfProgressIndicator; /// \ru Неинициализированное значение double. \en Uninitialized value of double. -#define NOT_INITIAL_DBL -DETERMINANT_MAX +const_expr double NOT_INITIAL_DBL = -DETERMINANT_MAX; //------------------------------------------------------------------------------ /** \brief \ru Инерционные характеристики тела. \en Inertial properties of solid. \~ \details \ru Инерционные характеристики тела.\n - Векторы direction дают направления главных осей инерции. \n + Векторы direction дают направления главных осей инерции. \n Если все главные моменты инерции general[i] i=1,2,3 разные, то все векторы direction[i] i=1,2,3 не равны нулю. \n Если все главные моменты инерции general[i] i=1,2,3 одинаковые, diff --git a/C3d/Include/model.h b/C3d/Include/model.h index cda4e12..32062f1 100644 --- a/C3d/Include/model.h +++ b/C3d/Include/model.h @@ -1,669 +1,669 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** \file - \brief \ru Геометрическая модель. - \en Geometric model. \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __MODEL_H -#define __MODEL_H - - -#include -#include - -struct ItModelVisitor; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Геометрическая модель. - \en Geometric model. \~ - \details \ru Геометрическая модель - контейнер геометрических объектов. \n - Модель состоит из массивов указателей на объекты геометрической модели MbItem. - Модель может содержать вспомогательные объекты MbAssistingItem, - точки MbPointFrame, каркасы MbWireFrame, - твердые тела MbSolid, полигональные объекты MbMesh, - объекты MbSpaceInstance и MbPlaneInstance.\n - Модель используется для описания геометрических свойств реальных и - воображаемых объектов, визуализации моделируемых объектов, - вычисления геометрических характеристик моделируемых объектов.\n - Имя объекта геометрической модели представляет собой контейнер простых имён. - В начале контейнера содержится простое имя SimpleName, - которое совпадает с первым полем std::multimap геометрической модели. \n - Если объект не держит в себе других объектов, то контейнер содержит одно простое имя SimpleName. - Ели объект держит в себе другие объекты (MbAssembly или MbInstance), - то имя внутренних объектов представляет собой контейнер, содержащий как минимум два простых имени. - Количество элементов имени объекта отражают количество уровней вложенности объект относительно модели. - \en Geometric model is a container of geometric objects. \n - The model consists of arrays of pointers to geometric model objects MbItem. - The model can contain MbAssistingItem assisting items, - MbPointFrame points, MbWireFrame frames, - MbSolid solids, polygonal objects MbMesh, - MbSpaceInstance and MbPlaneInstance objects.\n - Model is used to describe geometric properties of real and - imaginary objects, to visualize modeled objects, - to calculate geometric properties of modeled objects.\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 - which coincides with the first field std::multimap of the 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 -*/ -//--- -class MATH_CLASS MbModel : public TapeBase, - public MbRefItem, - public MbTransactions, - public MbAttributeContainer -{ -public: - typedef std::map NameItemArray; - -private: - NameItemArray modelItems; ///< \ru Множество объектов модели. \en Set of the model objects. - SimpleName name; ///< \ru Имя объекта. \en A name of an object. - -protected: - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbModel( const MbModel &, MbRegDuplicate * ); - -public: - /// \ru Конструктор по имени объекта. \en Constructor by object's name. - MbModel( SimpleName n = 0 ); - /// \ru Деструктор \en Destructor - virtual ~MbModel(); - -public : - - /** \ru \name Общие функции геометрического объекта - \en \name Common functions of a geometric object - \{ */ - /// \ru Тип контейнера атрибутов - классификатор наследников. \en Type of an attribute container is a classifier of inheritors. - virtual MbeImplicationType ImplicationType() const; - - /// \ru Создать копию. \en Create a copy. - MbModel & Duplicate( MbRegDuplicate * = NULL ) const; - /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. - void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); - /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. - void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); - /// \ru Повернуть вокруг оси. \en Rotate about an axis. - void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); - /// \ru Вычислить расстояние до точки. \en Calculate the distance to a point. - double DistanceToPoint ( const MbCartPoint3D & ) const; - /// \ru Добавь свой габарит в габаритный куб. \en Include your own bounding box into bounding box. - void AddYourGabaritTo( MbCube & ) const; - - /// \ru Создать собственное свойство с заданием его имени. \en Create your own property with specified name. - MbProperty & CreateProperty( MbePrompt ) const; - /// \ru Выдать свойства объекта. \en Get properties of the object. - void GetProperties( MbProperties & ); - /// \ru Установить свойства объекта. \en Set properties of the object. - void SetProperties( const MbProperties & ); - /** \} */ - - /// \ru Выдать имя модели. \en Get name of a model. - SimpleName GetModelName() const { return name; } - /// \ru Установить имя модели. \en Set name of a model. - void SetModelName( SimpleName n ) { name = n; } - - /** \brief \ru Добавить объект в модель. - \en Add object to the model. \~ - \details \ru Добавить объект в модель с указанным именем. - \en Add object to the model with a given name. \~ - \param[in] item - \ru Объект модели. - \en A model object. \~ - \param[in] n - \ru Имя объекта. Если указанное имя равно нулю, то модель именует объект своим уникальным именем. - \en A name of an object. If a given name is equal to zero, then the model names an object with its unique name. \~ - \return \ru Добавленный объект. - \en Added object. \~ - */ - MbItem * AddItem( MbItem & item, SimpleName n = UNDEFINED_SNAME ); - /// \ru Добавить объекты модели item в модель. \en Add item objects of to the model. \~ - bool AddModel( const MbModel & ); - - // \ru Выдать объект модели по индексу. \en Get item of model by index. - const MbItem * GetItem( size_t ind ) const; - // \ru Выдать непосредственный объект модели по идентификатору. \en Get the immediate item of model by identifier. - const MbItem * SubItem( SimpleName n ) const; - - /** \brief \ru Заменить объект. - \en Replace the object. \~ - \details \ru Заменить объект новым. - \en Replace the object by a new one. \~ - \param[in] item - \ru Заменяемый объект. - \en An object to replace. \~ - \param[in] newItem - \ru Новый объект. - \en A new object. \~ - \return \ru Возвращает true, если замена была выполнена. - \en Returns true if the replacement has been done. \~ - */ - bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); - - /// \ru Дать все объекты. \en Get all the objects. - template - void GetItems( Items & ) const; - /// \ru Отцепить объект, если он есть в модели. \en Detach an object if it is in the model. - bool DetachItem ( MbItem *, bool resetName = true ); - /// \ru Отцепить все объекты. \en Detach all the objects. - template - void DetachItems( Items & ); - - /// \ru Удалить объект, если он есть в модели. \en Delete an object if it is in the model. - bool DeleteItem ( MbItem *, bool resetName = true ); - /// \ru Удалить все объекты модели. \en Delete all the model objects. - void DeleteItems(); - - /// \ru Разрушить сборки с подсборками на составляющие. \en Decompose assemblies with subassemblies into components. - bool DecomposeAssemblies(); - - /** \brief \ru Наполнить присланную модель полигональными копиями объектов модели. - \en Fill the given model with polygonal copies of the model objects. \~ - \details \ru Наполнить присланную модель полигональными копиями объектов оригинальной модели. - Присланная модель опустошается и наполняется полигональными копиями объектов оригинальной модели. - Присланная модель заполняется аналогично оригинальной модели с той разницей, что вместо - тел, проволочных каркасов, точечных каркасов и других конечных объектов модели - присланную модель заполняют соответствующие полигональные копии объектов (MbMesh). - Сборки и вставки в присланной модели сохраняются аналогичными оригинальной модели. - Присланная модель может использоваться для визуализации модели и расчетов. - \en Fill the given model with polygonal copies of the original model objects. - Given model is being cleared and filled with polygonal copies of objects of the original model. - Given model is to be filled similarly to original model, but instead of - solids, wire-frames, point-frames and other finite objects of model - the given model is filled by the corresponding polygonal copies of objects (MbMesh). - Assemblies and instances in the given model remains similar to the original model. - Given model can be used for calculations and visualization of the model. \~ - \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ - - \param[in] stepData - \ru Данные для вычисления шага при триангуляции. - \en Data for step calculation during triangulation. \~ - \param[in] note - \ru Способ построения полигонального объекта. - \en Way for polygonal object constructing. \~ - \param[out] meshModel - \ru Присланная модель для наполнения. - \en Given model to be filled. \~ - \return \ru Не было ошибок во время построения - true, были ошибки - false. - \en If there were no errors during construction, then true, otherwise false. \~ - */ - bool FillMeshModel( const MbStepData & stepData, const MbFormNote & note, MbModel & meshModel ) const; - - /** \brief \ru Добавить полигональный объект. - \en Add polygonal object. \~ - \details \ru Добавить полигональную копию модели в присланный полигональный объект (MbMesh). - Все объекты модели, её сборки и вставки помещаются в единый плоскогранный полигональный объект. - Один и тот же объект, вставленный несколько раз в сборки и вставки модели, получает несколько копий, - так как каждая копия трансформируется по матрице локальной системы координат cjjndtncnde.otq сборки и вставки. - \en Add polygonal copy of the model to the given polygonal object (MbMesh). - All the objects, assemblies and instances of the model are placed in a unified planar polygonal object. - The same object inserted several times in assemblies and instances of the model gets several copies - because each copy is transformed by the matrix of local coordinate system of the corresponding assembly and instance. \~ - \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. \~ - */ - bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; - - /** \brief \ru Разрезать модель полигональных объектов одной или двумя параллельными плоскостями. - \en Cut model of polygonal objects by one or two parallel planes. \~ - \details \ru Создать новую модель полигональных объектов и наполнить её частями исходной модели, - лежащими под плоскостью XY локальной системы координат на заданном расстоянии.\n - Функция "режет" только модель полигональных объектов MbMesh. - Функция "режет" модель двумя плоскостями: - плоскостью XY локальной системы координат place и плоскостью, параллельной ей и - расположенной на расстоянии distance ниже неё. - Если distance<=0, то функция "режет" объект только одной плоскостью XY локальной системы.\n - Содержимое исходных полигональных объектов, - необходимое для построения разрезанного объекта и не затронутое режущими плоскостями, - добавляется в возвращаемый разрезанный объект без копирования.\n - \en Create new model of polygonal objects and fill it by the source model parts - lying under XY plane of the local coordinate system at the given distance.\n - Function "cuts" only MbMesh model of polygonal objects. - Function "cuts" the model 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 the source polygonal objects - 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 a new model of polygonal objects that lies under XY plane of local coordinate system at given distance. \~ - */ - MbModel * CutMeshModel( 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. \~ - \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ - \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] 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 Path to the object in 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. \~ - */ - bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, - const MbAxis3D & axis, double maxDistance, bool gridPriority, - 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[out] items - \ru Множество найденных объектов. - \en Found objects. \~ - \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. - \en Transformation matrix of found objects to the global coordinate system. \~ - \ingroup Model_Items - */ - virtual void GetItems( MbeSpaceType type, RPArray & items, SArray & matrs ); - - /** \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[out] items - \ru Множество найденных объектов. - \en Found objects. \~ - \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. - \en Transformation matrix of found objects to the global coordinate system. \~ - \ingroup Model_Items - */ - virtual void GetItems( MbeSpaceType type, RPArray & items, SArray & matrs ) const; - - /** \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. \~ - \ingroup Model_Items - */ - virtual void GetUniqItems( MbeSpaceType type, CSSArray & items ) const; - - /** \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 to the object in 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. \~ - */ - bool MakePath( const MbItem & obj, MbPath & path, MbMatrix3D & from ) 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 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. \~ - */ - const MbItem * GetItemByPath( const MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Найти объект по геометрическому объекту. - \en Find object by geometric object. \~ - \details \ru Найти объект по геометрическому объекту, а также получить путь к - объекту в модели и матрицу преобразования в глобальную систему координат. - \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. \~ - \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. \~ - */ - 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. \~ - */ - 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. \~ - */ - 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. \~ - */ - const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; - - /** \brief \ru Найти объект по имени для редактирования. - \en Find object by name for editing. \~ - \details \ru Найти объект по имени для редактирования, а также получить путь к объекту в модели - и матрицу преобразования в глобальную систему координат. \n - \en Find object by name for editing 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. \~ - */ - MbItem * SetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ); - /** \brief \ru Алгоритм общего назначения для обхода дерева модели в глубину. - \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 ); - /// \ru Сдвинуть выбранные объекты. \en Move selected objects. - void MoveSelected( const MbVector3D &, MbRegTransform * = NULL ); - /// \ru Повернуть выбранные объекты вокруг оси. \en Rotate selected objects around an axis. - void RotateSelected( const MbAxis3D &, double angle, MbRegTransform * = NULL ); - - /** \brief \ru Отцепить все выбранные объекты. - \en Detach all selected objects. \~ - \details \ru Отцепить все выбранные объекты модели, в том числе и - содержащиеся в сложных составных объектах, таких как сборка. \n - \en Detach all selected objects of model including ones - contained in complex composite objects such as assembly. \n \~ - \param[out] items - \ru Отцепленные объекты. - \en Detach the objects. \~ - \param[out] matrs - \ru Матрицы преобразования отцепленных объектов в глобальную систему координат. - \en Transformation matrices of detached objects to global coordinate system. \~ - */ - void DetachSelected( RPArray & , SArray & , bool selected, bool resetName = true ); - /// \ru Отцепить все видимые или невидимые объекты. \en Detach all visible or invisible objects. \~ - void DetachInvisible( RPArray & , SArray & , bool invisible, bool resetName = true ); - - /// \ru Выдать количество объектов модели. \en Get the count of objects of model. - size_t ItemsCount() const { return modelItems.size(); } - - /// \ru Содержится ли объект в модели? \en Whether the object is contained in model. - bool ContainsItem( const MbItem * ) const; - /// \ru Добавить в модель объекты другой модели. \en Add objects of other model to the model. - bool AddModelItems( const MbModel & ); - /// \ru Добавить в массив выбранные объекты модели без поиска в сложных составных объектах. \en Add selected objects of model to array without search in complex composite objects. - size_t GetSelected( RPArray & ) const; - - /// \ru Вычислить габарит по всем объектам модели. \en Calculate bounding box for all the objects of model. - void CalculateGabarit( MbCube & ) const; - - private: - // Отдать все объекты с указанным свойством. - void DetachByAttribute( RPArray & items, SArray & matrs, int attribute, bool resetName ); - -public: - /// \ru Простой итератор по объектам модели. \en Simple iterator on objects of model. - class ItemIterator { - private: - NameItemArray::iterator currIter; - - private: - ItemIterator( const NameItemArray::iterator & iter ) : currIter( iter ) {} - - public: - MbItem * operator * () { return currIter->second; } - MbItem * operator -> () { return currIter->second; } - ItemIterator & operator ++ () { ++currIter; return *this; } - ItemIterator operator ++ ( int ) { return ItemIterator(currIter++); } - - bool operator == ( const ItemIterator & other) const { return currIter == other.currIter; } - bool operator != ( const ItemIterator & other) const { return currIter != other.currIter; } - - friend class MbModel; - }; // ItemIterator - - - /// \ru Константный итератор по объектам модели. \en Constant iterator on objects of the model. - class ItemConstIterator { - private: - NameItemArray::const_iterator currIter; - - private: - ItemConstIterator( const NameItemArray::const_iterator & iter ) : currIter( iter ) {} - -// public: -// ItemConstIterator( const ItemIterator& iIter ) : currIter( iIter.currIter ) {} - - public: - const MbItem * operator * () const { return currIter->second; } - const MbItem * operator -> () const { return currIter->second; } - ItemConstIterator & operator ++ () { ++currIter; return *this; } - ItemConstIterator operator ++ ( int ) { return ItemConstIterator(currIter++); } - - bool operator == ( const ItemConstIterator & other) const { return currIter == other.currIter; } - bool operator != ( const ItemConstIterator & other) const { return currIter != other.currIter; } - - friend class MbModel; - }; // ItemConstIterator - -public: - /// \ru Выдать константный итератор по всем объектам с указанием на начало. \en Get constant iterator on all objects pointing to the first element. - ItemConstIterator CBegin() const { return ItemConstIterator( modelItems.begin() ); } - /// \ru Выдать константный итератор по всем объектам с указанием за конец. \en Get constant iterator on all objects pointing to the past-the-end element. - ItemConstIterator CEnd() const { return ItemConstIterator( modelItems.end() ); } - /// \ru Выдать константный итератор для указанного имени с указанием на начало. \en Get constant iterator by the given name pointing to the first element. - ItemConstIterator CBegin( SimpleName n ) const { return ItemConstIterator( modelItems.lower_bound(n) ); } - /// \ru Выдать константный итератор для указанного имени с указанием на конец. \en Get constant iterator by the given name pointing to the past-the-end element. - ItemConstIterator CEnd( SimpleName n ) const { return ItemConstIterator( modelItems.upper_bound(n) ); } - /// \ru Выдать не константный итератор по всем объектам с указанием на начало. \en Get non-constant iterator on all the objects pointing to the first element. - ItemIterator Begin() { return ItemIterator( modelItems.begin() ); } - /// \ru Выдать не константный итератор по всем объектам с указанием за конец. \en Get non-constant iterator on all the objects pointing to the past-the-end element. - ItemIterator End() { return ItemIterator( modelItems.end() ); } - /// \ru Выдать не константный итератор для указанного имени с указанием на начало. \en Get non-constant iterator by the given name pointing to the first element. - ItemIterator Begin( SimpleName n ) { return ItemIterator( modelItems.lower_bound(n) ); } - /// \ru Выдать не константный итератор для указанного имени с указанием на конец. \en Get non-constant iterator by the given name pointing to the past-the-end element. - ItemIterator End( SimpleName n ) { return ItemIterator( modelItems.upper_bound(n) ); } - -private: - void CreateItemsMeshes( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * ) const; - - -private: // Устаревшие методы. // Deprecated methods (it will be deleted in future revisions) - /// \ru Установить первое простое имя существующему объекту модели. \en Set the first simple name for existing object of model. - bool SetItemMainName( MbItem *, SimpleName ); - // The function is deprecated. Use ItemIterator instead indexed access. - const MbItem * GetModelItem( size_t i ) const; - -private: // \ru Закрытые методы. // \en Internal use methods. - // \ru Выдать имя последнего объекта в контейнере. \en Get name of the last object in container. - SimpleName _LastItemName() const { return modelItems.empty() ? 0 : modelItems.rbegin()->first; } - // \ru Выдать имя для следующего за последним объекта. \en Get name of past-the-end object (next object to the last one). - SimpleName _NextItemName() const; - // \ru Генерация имени для нового элемента. \en Generate identifier for a new item. - SimpleName _NewItemName( SimpleName & startName ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbModel ); - OBVIOUS_PRIVATE_COPY( MbModel ); -}; // MbModel - -IMPL_PERSISTENT_OPS( MbModel ) - -//---------------------------------------------------------------------------------------- -// \ru Дать все объекты. \en Get all the objects. -// --- -template -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 ) - items.push_back( iter->second ); - } -} - -//---------------------------------------------------------------------------------------- -// \ru Отцепить все объекты. \en Detach all the objects. -// --- -template -void MbModel::DetachItems( Items & items ) -{ - items.reserve( modelItems.size() ); - NameItemArray::iterator iter = modelItems.begin(); - NameItemArray::const_iterator endItem = modelItems.end(); - for ( ; iter != endItem; ++iter ) { - MbItem * item = iter->second; - if ( item != NULL ) { - item->DecRef(); - items.push_back( item ); - } - } - modelItems.clear(); - AttributesChange(); -} - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Чтение модели MbModel из потока #reader. - \en Read MbModel model from #reader stream. \~ - \details \ru Чтение модели MbModel из потока #reader. \n - \en Read MbModel model from #reader stream. \n \~ - \ingroup Model -*/ -// --- -MATH_FUNC (bool) ReadModelItems( reader &, MbModel & ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Чтение из потока объектов, определенных в данном дереве модели. - \en Read items, defined in the given model tree, from a stream. - \details \ru Чтение из потока всех объектов, определенных в данном дереве модели, включая его корень (корни). - \en Read items, defined in the given model tree including its root(s), from a stream. - \param[in] in - \ru Поток для чтения. \en Stream to read from. \~ - \param[in] tree - \ru Дерево модели. \en Model tree. \~ - \param[out] items - \ru Прочитанные объекты. \en Read objects. \~ -*/ -// --- -MATH_FUNC (void) ReadModelItemsFromTree( reader & in, const c3d::IModelTree * tree, std::vector< SPtr > & items ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Чтение из потока объектов, определенных в поддереве с корнем в данном узле. - \en Read items, defined in a subtree with a root at the given node, from a stream. - \details \ru Чтение из потока объектов, определенных в поддереве с корнем в данном узле, исключая сам узел. - Если определено флагом (addAttr == true), то из объекта, определенного заданным узлом, читаются атрибуты и добавляются в модель. - \en Read items, defined in a subtree with a root at the given node, from a stream, excluding the node itself. - If defined by the flag (addAttr == true), attributes are read from an object defined by the given node and added to the model. - \param[in] in - \ru Поток для чтения. \en Stream to read from. \~ - \param[in] node - \ru Узел дерева модели. \en Node of Model tree. \~ - \param[out] model - \ru Модель, куда добавлять прочитанные объекты. \en Model where to add read objects. \~ - \param[in] addAttr - \ru Флаг чтения атрибутов. \en Attributes read flag. \~ -*/ -// --- -MATH_FUNC (void) ReadModelItemsFromTree( reader & in, const c3d::IModelTreeNode * node, MbModel & model, bool addAttr = false ); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Запись модели MbModel в поток #writer. - \en Write MbModel model to #writer stream. \~ - \details \ru Запись модели MbModel в поток #writer. \n - \en Write MbModel model to #writer stream. \n \~ - \ingroup Model -*/ -// --- -MATH_FUNC (void) WriteModelItems( writer &, const MbModel & ); - - -#endif // __MODEL_H +////////////////////////////////////////////////////////////////////////////////////////// +/** \file + \brief \ru Геометрическая модель. + \en Geometric model. \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __MODEL_H +#define __MODEL_H + + +#include +#include + +struct ItModelVisitor; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Геометрическая модель. + \en Geometric model. \~ + \details \ru Геометрическая модель - контейнер геометрических объектов. \n + Модель состоит из массивов указателей на объекты геометрической модели MbItem. + Модель может содержать вспомогательные объекты MbAssistingItem, + точки MbPointFrame, каркасы MbWireFrame, + твердые тела MbSolid, полигональные объекты MbMesh, + объекты MbSpaceInstance и MbPlaneInstance.\n + Модель используется для описания геометрических свойств реальных и + воображаемых объектов, визуализации моделируемых объектов, + вычисления геометрических характеристик моделируемых объектов.\n + Имя объекта геометрической модели представляет собой контейнер простых имён. + В начале контейнера содержится простое имя SimpleName, + которое совпадает с первым полем std::multimap геометрической модели. \n + Если объект не держит в себе других объектов, то контейнер содержит одно простое имя SimpleName. + Ели объект держит в себе другие объекты (MbAssembly или MbInstance), + то имя внутренних объектов представляет собой контейнер, содержащий как минимум два простых имени. + Количество элементов имени объекта отражают количество уровней вложенности объект относительно модели. + \en Geometric model is a container of geometric objects. \n + The model consists of arrays of pointers to geometric model objects MbItem. + The model can contain MbAssistingItem assisting items, + MbPointFrame points, MbWireFrame frames, + MbSolid solids, polygonal objects MbMesh, + MbSpaceInstance and MbPlaneInstance objects.\n + Model is used to describe geometric properties of real and + imaginary objects, to visualize modeled objects, + to calculate geometric properties of modeled objects.\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 + which coincides with the first field std::multimap of the 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 +*/ +//--- +class MATH_CLASS MbModel : public TapeBase, + public MbRefItem, + public MbTransactions, + public MbAttributeContainer +{ +public: + typedef std::map NameItemArray; + +private: + NameItemArray modelItems; ///< \ru Множество объектов модели. \en Set of the model objects. + SimpleName name; ///< \ru Имя объекта. \en A name of an object. + +protected: + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbModel( const MbModel &, MbRegDuplicate * ); + +public: + /// \ru Конструктор по имени объекта. \en Constructor by object's name. + MbModel( SimpleName n = 0 ); + /// \ru Деструктор \en Destructor + virtual ~MbModel(); + +public : + + /** \ru \name Общие функции геометрического объекта + \en \name Common functions of a geometric object + \{ */ + /// \ru Тип контейнера атрибутов - классификатор наследников. \en Type of an attribute container is a classifier of inheritors. + virtual MbeImplicationType ImplicationType() const; + + /// \ru Создать копию. \en Create a copy. + MbModel & Duplicate( MbRegDuplicate * = NULL ) const; + /// \ru Преобразовать согласно матрице. \en Transform according to the matrix. + void Transform( const MbMatrix3D &, MbRegTransform * iReg = NULL ); + /// \ru Сдвинуть вдоль вектора. \en Translate along a vector. + void Move ( const MbVector3D &, MbRegTransform * iReg = NULL ); + /// \ru Повернуть вокруг оси. \en Rotate about an axis. + void Rotate ( const MbAxis3D &, double angle, MbRegTransform * iReg = NULL ); + /// \ru Вычислить расстояние до точки. \en Calculate the distance to a point. + double DistanceToPoint ( const MbCartPoint3D & ) const; + /// \ru Добавь свой габарит в габаритный куб. \en Include your own bounding box into bounding box. + void AddYourGabaritTo( MbCube & ) const; + + /// \ru Создать собственное свойство с заданием его имени. \en Create your own property with specified name. + MbProperty & CreateProperty( MbePrompt ) const; + /// \ru Выдать свойства объекта. \en Get properties of the object. + void GetProperties( MbProperties & ); + /// \ru Установить свойства объекта. \en Set properties of the object. + void SetProperties( const MbProperties & ); + /** \} */ + + /// \ru Выдать имя модели. \en Get name of a model. + SimpleName GetModelName() const { return name; } + /// \ru Установить имя модели. \en Set name of a model. + void SetModelName( SimpleName n ) { name = n; } + + /** \brief \ru Добавить объект в модель. + \en Add object to the model. \~ + \details \ru Добавить объект в модель с указанным именем. + \en Add object to the model with a given name. \~ + \param[in] item - \ru Объект модели. + \en A model object. \~ + \param[in] n - \ru Имя объекта. Если указанное имя равно нулю, то модель именует объект своим уникальным именем. + \en A name of an object. If a given name is equal to zero, then the model names an object with its unique name. \~ + \return \ru Добавленный объект. + \en Added object. \~ + */ + MbItem * AddItem( MbItem & item, SimpleName n = c3d::UNDEFINED_SNAME ); + /// \ru Добавить объекты модели item в модель. \en Add item objects of to the model. \~ + bool AddModel( const MbModel & ); + + // \ru Выдать объект модели по индексу. \en Get item of model by index. + const MbItem * GetItem( size_t ind ) const; + // \ru Выдать непосредственный объект модели по идентификатору. \en Get the immediate item of model by identifier. + const MbItem * SubItem( SimpleName n ) const; + + /** \brief \ru Заменить объект. + \en Replace the object. \~ + \details \ru Заменить объект новым. + \en Replace the object by a new one. \~ + \param[in] item - \ru Заменяемый объект. + \en An object to replace. \~ + \param[in] newItem - \ru Новый объект. + \en A new object. \~ + \return \ru Возвращает true, если замена была выполнена. + \en Returns true if the replacement has been done. \~ + */ + bool ReplaceItem( const MbItem & item, MbItem & newItem, bool saveName = false ); + + /// \ru Дать все объекты. \en Get all the objects. + template + void GetItems( Items & ) const; + /// \ru Отцепить объект, если он есть в модели. \en Detach an object if it is in the model. + bool DetachItem ( MbItem *, bool resetName = true ); + /// \ru Отцепить все объекты. \en Detach all the objects. + template + void DetachItems( Items & ); + + /// \ru Удалить объект, если он есть в модели. \en Delete an object if it is in the model. + bool DeleteItem ( MbItem *, bool resetName = true ); + /// \ru Удалить все объекты модели. \en Delete all the model objects. + void DeleteItems(); + + /// \ru Разрушить сборки с подсборками на составляющие. \en Decompose assemblies with subassemblies into components. + bool DecomposeAssemblies(); + + /** \brief \ru Наполнить присланную модель полигональными копиями объектов модели. + \en Fill the given model with polygonal copies of the model objects. \~ + \details \ru Наполнить присланную модель полигональными копиями объектов оригинальной модели. + Присланная модель опустошается и наполняется полигональными копиями объектов оригинальной модели. + Присланная модель заполняется аналогично оригинальной модели с той разницей, что вместо + тел, проволочных каркасов, точечных каркасов и других конечных объектов модели + присланную модель заполняют соответствующие полигональные копии объектов (MbMesh). + Сборки и вставки в присланной модели сохраняются аналогичными оригинальной модели. + Присланная модель может использоваться для визуализации модели и расчетов. + \en Fill the given model with polygonal copies of the original model objects. + Given model is being cleared and filled with polygonal copies of objects of the original model. + Given model is to be filled similarly to original model, but instead of + solids, wire-frames, point-frames and other finite objects of model + the given model is filled by the corresponding polygonal copies of objects (MbMesh). + Assemblies and instances in the given model remains similar to the original model. + Given model can be used for calculations and visualization of the model. \~ + \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ + + \param[in] stepData - \ru Данные для вычисления шага при триангуляции. + \en Data for step calculation during triangulation. \~ + \param[in] note - \ru Способ построения полигонального объекта. + \en Way for polygonal object constructing. \~ + \param[out] meshModel - \ru Присланная модель для наполнения. + \en Given model to be filled. \~ + \return \ru Не было ошибок во время построения - true, были ошибки - false. + \en If there were no errors during construction, then true, otherwise false. \~ + */ + bool FillMeshModel( const MbStepData & stepData, const MbFormNote & note, MbModel & meshModel ) const; + + /** \brief \ru Добавить полигональный объект. + \en Add polygonal object. \~ + \details \ru Добавить полигональную копию модели в присланный полигональный объект (MbMesh). + Все объекты модели, её сборки и вставки помещаются в единый плоскогранный полигональный объект. + Один и тот же объект, вставленный несколько раз в сборки и вставки модели, получает несколько копий, + так как каждая копия трансформируется по матрице локальной системы координат cjjndtncnde.otq сборки и вставки. + \en Add polygonal copy of the model to the given polygonal object (MbMesh). + All the objects, assemblies and instances of the model are placed in a unified planar polygonal object. + The same object inserted several times in assemblies and instances of the model gets several copies + because each copy is transformed by the matrix of local coordinate system of the corresponding assembly and instance. \~ + \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. \~ + */ + bool AddYourMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; + + /** \brief \ru Разрезать модель полигональных объектов одной или двумя параллельными плоскостями. + \en Cut model of polygonal objects by one or two parallel planes. \~ + \details \ru Создать новую модель полигональных объектов и наполнить её частями исходной модели, + лежащими под плоскостью XY локальной системы координат на заданном расстоянии.\n + Функция "режет" только модель полигональных объектов MbMesh. + Функция "режет" модель двумя плоскостями: + плоскостью XY локальной системы координат place и плоскостью, параллельной ей и + расположенной на расстоянии distance ниже неё. + Если distance<=0, то функция "режет" объект только одной плоскостью XY локальной системы.\n + Содержимое исходных полигональных объектов, + необходимое для построения разрезанного объекта и не затронутое режущими плоскостями, + добавляется в возвращаемый разрезанный объект без копирования.\n + \en Create new model of polygonal objects and fill it by the source model parts + lying under XY plane of the local coordinate system at the given distance.\n + Function "cuts" only MbMesh model of polygonal objects. + Function "cuts" the model 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 the source polygonal objects + 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 a new model of polygonal objects that lies under XY plane of local coordinate system at given distance. \~ + */ + MbModel * CutMeshModel( 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. \~ + \note \ru В многопоточном режиме выполняется параллельно. \en In multithreaded mode runs in parallel. \~ + \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] 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 Path to the object in 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. \~ + */ + bool NearestMesh( MbeSpaceType sType, MbeTopologyType tType, MbePlaneType pType, + const MbAxis3D & axis, double maxDistance, bool gridPriority, + 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[out] items - \ru Множество найденных объектов. + \en Found objects. \~ + \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. + \en Transformation matrix of found objects to the global coordinate system. \~ + \ingroup Model_Items + */ + virtual void GetItems( MbeSpaceType type, RPArray & items, SArray & matrs ); + + /** \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[out] items - \ru Множество найденных объектов. + \en Found objects. \~ + \param[out] matrs - \ru Матрицы преобразования найденных объектов в глобальную систему координат. + \en Transformation matrix of found objects to the global coordinate system. \~ + \ingroup Model_Items + */ + virtual void GetItems( MbeSpaceType type, RPArray & items, SArray & matrs ) const; + + /** \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. \~ + \ingroup Model_Items + */ + virtual void GetUniqItems( MbeSpaceType type, CSSArray & items ) const; + + /** \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 to the object in 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. \~ + */ + bool MakePath( const MbItem & obj, MbPath & path, MbMatrix3D & from ) 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 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. \~ + */ + const MbItem * GetItemByPath( const MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Найти объект по геометрическому объекту. + \en Find object by geometric object. \~ + \details \ru Найти объект по геометрическому объекту, а также получить путь к + объекту в модели и матрицу преобразования в глобальную систему координат. + \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. \~ + \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. \~ + */ + 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. \~ + */ + 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. \~ + */ + 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. \~ + */ + const MbItem * GetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ) const; + + /** \brief \ru Найти объект по имени для редактирования. + \en Find object by name for editing. \~ + \details \ru Найти объект по имени для редактирования, а также получить путь к объекту в модели + и матрицу преобразования в глобальную систему координат. \n + \en Find object by name for editing 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. \~ + */ + MbItem * SetItemByName( SimpleName n, MbPath & path, MbMatrix3D & from ); + /** \brief \ru Алгоритм общего назначения для обхода дерева модели в глубину. + \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 ); + /// \ru Сдвинуть выбранные объекты. \en Move selected objects. + void MoveSelected( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Повернуть выбранные объекты вокруг оси. \en Rotate selected objects around an axis. + void RotateSelected( const MbAxis3D &, double angle, MbRegTransform * = NULL ); + + /** \brief \ru Отцепить все выбранные объекты. + \en Detach all selected objects. \~ + \details \ru Отцепить все выбранные объекты модели, в том числе и + содержащиеся в сложных составных объектах, таких как сборка. \n + \en Detach all selected objects of model including ones + contained in complex composite objects such as assembly. \n \~ + \param[out] items - \ru Отцепленные объекты. + \en Detach the objects. \~ + \param[out] matrs - \ru Матрицы преобразования отцепленных объектов в глобальную систему координат. + \en Transformation matrices of detached objects to global coordinate system. \~ + */ + void DetachSelected( RPArray & , SArray & , bool selected, bool resetName = true ); + /// \ru Отцепить все видимые или невидимые объекты. \en Detach all visible or invisible objects. \~ + void DetachInvisible( RPArray & , SArray & , bool invisible, bool resetName = true ); + + /// \ru Выдать количество объектов модели. \en Get the count of objects of model. + size_t ItemsCount() const { return modelItems.size(); } + + /// \ru Содержится ли объект в модели? \en Whether the object is contained in model. + bool ContainsItem( const MbItem * ) const; + /// \ru Добавить в модель объекты другой модели. \en Add objects of other model to the model. + bool AddModelItems( const MbModel & ); + /// \ru Добавить в массив выбранные объекты модели без поиска в сложных составных объектах. \en Add selected objects of model to array without search in complex composite objects. + size_t GetSelected( RPArray & ) const; + + /// \ru Вычислить габарит по всем объектам модели. \en Calculate bounding box for all the objects of model. + void CalculateGabarit( MbCube & ) const; + + private: + // Отдать все объекты с указанным свойством. + void DetachByAttribute( RPArray & items, SArray & matrs, int attribute, bool resetName ); + +public: + /// \ru Простой итератор по объектам модели. \en Simple iterator on objects of model. + class ItemIterator { + private: + NameItemArray::iterator currIter; + + private: + ItemIterator( const NameItemArray::iterator & iter ) : currIter( iter ) {} + + public: + MbItem * operator * () { return currIter->second; } + MbItem * operator -> () { return currIter->second; } + ItemIterator & operator ++ () { ++currIter; return *this; } + ItemIterator operator ++ ( int ) { return ItemIterator(currIter++); } + + bool operator == ( const ItemIterator & other) const { return currIter == other.currIter; } + bool operator != ( const ItemIterator & other) const { return currIter != other.currIter; } + + friend class MbModel; + }; // ItemIterator + + + /// \ru Константный итератор по объектам модели. \en Constant iterator on objects of the model. + class ItemConstIterator { + private: + NameItemArray::const_iterator currIter; + + private: + ItemConstIterator( const NameItemArray::const_iterator & iter ) : currIter( iter ) {} + +// public: +// ItemConstIterator( const ItemIterator& iIter ) : currIter( iIter.currIter ) {} + + public: + const MbItem * operator * () const { return currIter->second; } + const MbItem * operator -> () const { return currIter->second; } + ItemConstIterator & operator ++ () { ++currIter; return *this; } + ItemConstIterator operator ++ ( int ) { return ItemConstIterator(currIter++); } + + bool operator == ( const ItemConstIterator & other) const { return currIter == other.currIter; } + bool operator != ( const ItemConstIterator & other) const { return currIter != other.currIter; } + + friend class MbModel; + }; // ItemConstIterator + +public: + /// \ru Выдать константный итератор по всем объектам с указанием на начало. \en Get constant iterator on all objects pointing to the first element. + ItemConstIterator CBegin() const { return ItemConstIterator( modelItems.begin() ); } + /// \ru Выдать константный итератор по всем объектам с указанием за конец. \en Get constant iterator on all objects pointing to the past-the-end element. + ItemConstIterator CEnd() const { return ItemConstIterator( modelItems.end() ); } + /// \ru Выдать константный итератор для указанного имени с указанием на начало. \en Get constant iterator by the given name pointing to the first element. + ItemConstIterator CBegin( SimpleName n ) const { return ItemConstIterator( modelItems.lower_bound(n) ); } + /// \ru Выдать константный итератор для указанного имени с указанием на конец. \en Get constant iterator by the given name pointing to the past-the-end element. + ItemConstIterator CEnd( SimpleName n ) const { return ItemConstIterator( modelItems.upper_bound(n) ); } + /// \ru Выдать не константный итератор по всем объектам с указанием на начало. \en Get non-constant iterator on all the objects pointing to the first element. + ItemIterator Begin() { return ItemIterator( modelItems.begin() ); } + /// \ru Выдать не константный итератор по всем объектам с указанием за конец. \en Get non-constant iterator on all the objects pointing to the past-the-end element. + ItemIterator End() { return ItemIterator( modelItems.end() ); } + /// \ru Выдать не константный итератор для указанного имени с указанием на начало. \en Get non-constant iterator by the given name pointing to the first element. + ItemIterator Begin( SimpleName n ) { return ItemIterator( modelItems.lower_bound(n) ); } + /// \ru Выдать не константный итератор для указанного имени с указанием на конец. \en Get non-constant iterator by the given name pointing to the past-the-end element. + ItemIterator End( SimpleName n ) { return ItemIterator( modelItems.upper_bound(n) ); } + +private: + void CreateItemsMeshes( const MbStepData & stepData, const MbFormNote & note, MbRegDuplicate * ) const; + + +private: // Устаревшие методы. // Deprecated methods (it will be deleted in future revisions) + /// \ru Установить первое простое имя существующему объекту модели. \en Set the first simple name for existing object of model. + bool SetItemMainName( MbItem *, SimpleName ); + // The function is deprecated. Use ItemIterator instead indexed access. + const MbItem * GetModelItem( size_t i ) const; + +private: // \ru Закрытые методы. // \en Internal use methods. + // \ru Выдать имя последнего объекта в контейнере. \en Get name of the last object in container. + SimpleName _LastItemName() const { return modelItems.empty() ? 0 : modelItems.rbegin()->first; } + // \ru Выдать имя для следующего за последним объекта. \en Get name of past-the-end object (next object to the last one). + SimpleName _NextItemName() const; + // \ru Генерация имени для нового элемента. \en Generate identifier for a new item. + SimpleName _NewItemName( SimpleName & startName ) const; + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbModel ) +OBVIOUS_PRIVATE_COPY( MbModel ) +}; // MbModel + +IMPL_PERSISTENT_OPS( MbModel ) + +//---------------------------------------------------------------------------------------- +// \ru Дать все объекты. \en Get all the objects. +// --- +template +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 ) + items.push_back( iter->second ); + } +} + +//---------------------------------------------------------------------------------------- +// \ru Отцепить все объекты. \en Detach all the objects. +// --- +template +void MbModel::DetachItems( Items & items ) +{ + items.reserve( modelItems.size() ); + NameItemArray::iterator iter = modelItems.begin(); + NameItemArray::const_iterator endItem = modelItems.end(); + for ( ; iter != endItem; ++iter ) { + MbItem * item = iter->second; + if ( item != NULL ) { + item->DecRef(); + items.push_back( item ); + } + } + modelItems.clear(); + AttributesChange(); +} + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Чтение модели MbModel из потока #reader. + \en Read MbModel model from #reader stream. \~ + \details \ru Чтение модели MbModel из потока #reader. \n + \en Read MbModel model from #reader stream. \n \~ + \ingroup Model +*/ +// --- +MATH_FUNC (bool) ReadModelItems( reader &, MbModel & ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Чтение из потока объектов, определенных в данном дереве модели. + \en Read items, defined in the given model tree, from a stream. + \details \ru Чтение из потока всех объектов, определенных в данном дереве модели, включая его корень (корни). + \en Read items, defined in the given model tree including its root(s), from a stream. + \param[in] in - \ru Поток для чтения. \en Stream to read from. \~ + \param[in] tree - \ru Дерево модели. \en Model tree. \~ + \param[out] items - \ru Прочитанные объекты. \en Read objects. \~ +*/ +// --- +MATH_FUNC (void) ReadModelItemsFromTree( reader & in, const c3d::IModelTree * tree, std::vector< SPtr > & items ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Чтение из потока объектов, определенных в поддереве с корнем в данном узле. + \en Read items, defined in a subtree with a root at the given node, from a stream. + \details \ru Чтение из потока объектов, определенных в поддереве с корнем в данном узле, исключая сам узел. + Если определено флагом (addAttr == true), то из объекта, определенного заданным узлом, читаются атрибуты и добавляются в модель. + \en Read items, defined in a subtree with a root at the given node, from a stream, excluding the node itself. + If defined by the flag (addAttr == true), attributes are read from an object defined by the given node and added to the model. + \param[in] in - \ru Поток для чтения. \en Stream to read from. \~ + \param[in] node - \ru Узел дерева модели. \en Node of Model tree. \~ + \param[out] model - \ru Модель, куда добавлять прочитанные объекты. \en Model where to add read objects. \~ + \param[in] addAttr - \ru Флаг чтения атрибутов. \en Attributes read flag. \~ +*/ +// --- +MATH_FUNC (void) ReadModelItemsFromTree( reader & in, const c3d::IModelTreeNode * node, MbModel & model, bool addAttr = false ); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Запись модели MbModel в поток #writer. + \en Write MbModel model to #writer stream. \~ + \details \ru Запись модели MbModel в поток #writer. \n + \en Write MbModel model to #writer stream. \n \~ + \ingroup Model +*/ +// --- +MATH_FUNC (void) WriteModelItems( writer &, const MbModel & ); + + +#endif // __MODEL_H diff --git a/C3d/Include/model_item.h b/C3d/Include/model_item.h index 908bfae..5306ff7 100644 --- a/C3d/Include/model_item.h +++ b/C3d/Include/model_item.h @@ -1,545 +1,545 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \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(); - } -}; - - -#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 * = 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(); + } +}; + + +#endif // __MODEL_ITEM_H diff --git a/C3d/Include/model_tree.h b/C3d/Include/model_tree.h index eadb623..51430ba 100644 --- a/C3d/Include/model_tree.h +++ b/C3d/Include/model_tree.h @@ -1,309 +1,309 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** \file - \brief \ru Реализация дерева модели - \en Implementation of Model Tree classes \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __MODEL_TREE_H -#define __MODEL_TREE_H - - -#include -#include -#include -#include -#include -#include -#include -#include - -//---------------------------------------------------------------------------------------- -// \ru Реализация интерфейсов дерева модели. \en Implementation of Model Tree interfaces. -//---------------------------------------------------------------------------------------- - -namespace c3d // namespace C3D -{ -//---------------------------------------------------------------------------------------- -/** \brief \ru Узел дерева. - \en Tree node. \~ - \details \ru Узел дерева (может иметь несколько потомков). \n - \en Tree node (can have several children). \n \~ - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS MbTreeNode : public IModelTreeNode -{ - // \ru Временное хранилище для индексов потомков узла (используется при чтении узла). - // \en Temporary storage for indices of child nodes (used while reading the node). - std::vector m_childrenIndices; - // \ru Данные узла \en The node data. - MbItemData m_data; - // \ru Флаг, указывающий, открыт ли узел при проходе вглубь по дереву. - // \en Flag which indicates whether the node is entered during traversing into depth over the tree. - mutable bool m_open; - // \ru Флаг, указывающий, читать ли только часть узла. - // \en Flag which indicates whether to read only a part of the node. - mutable bool m_partial; -public: - MbTreeNode() : m_open(false), m_partial(false) {} - MbTreeNode ( const MbItemData& data ) : m_data(data), m_open(false), m_partial(false) {} - MbTreeNode ( const MbTreeNode& node ) : m_data(node.m_data), m_childrenIndices(node.m_childrenIndices), - m_open(node.m_open), m_partial(node.m_partial) { GetChildren() = node.GetChildren(); GetParents() = node.GetParents(); } - - ///--------- - /// \ru Методы IModelTreeNode. \en IModelTreeNode methods. - - /// \ru Доступ к данным узла. \en Access to the node data. - virtual MbItemData& GetData() { return m_data; } - virtual const MbItemData& GetData() const { return m_data; } - - /// \ru Доступ к позиции чтения/записм узла. \en Access to the node read/write position. - virtual ClusterReference& GetPosition() { return m_data.position; } - virtual const ClusterReference& GetPosition() const { return m_data.position; } - - /// \ru Узнать, читать ли только часть узла. - /// \en Check whether to read the node partially. - virtual bool PartialRead() const { return m_partial; }; - - /// \ru Установить признак частичного или полного чтения узла. - /// \en Set indication of full or partial node reading. - virtual void SetPartialRead ( bool partial ) const { m_partial = partial; }; - - /// \ru Записать узел. \en Write the node. - virtual writer & operator >> ( writer & ); - - /// \ru Прочитать узел. \en Read the node. - virtual reader & operator << ( reader & ); - - /// \ru Доступ ко все потомкам узла. \en Access to the all descendants of the node. - void GetAllDescendants ( std::set& nodes ) const; - - /// \ru Создать узел с данными текущего узла и добавить его в дерево. - /// Рекурсивно скопировать в дерево всех предков текущего узла с сохранением иерархии. - /// \en Create a node with data from the current node. - /// Copy recursively all parents of the node to the tree preserving the hierarchy. - MbTreeNode* CopyToTreeWithParents ( c3d::IModelTree* tree, bool partial ) const; - - /// \ru Создать узел с данными текущего узла и добавить его в дерево. - /// Рекурсивно скопировать в дерево всех потомков текущего узла с сохранением иерархии. - /// \en Create a node with data from the current node. - /// Copy recursively all children of the node to the tree preserving the hierarchy. - MbTreeNode* CopyToTreeWithChildren ( c3d::IModelTree* tree, bool partial ) const; - - /// \ru Доступ к флагу, который указывет, открыт ли узел при проходе вглубь по дереву - /// (false означает, что узел и его потомки уже пройдены или еще не обнаружены). - /// \en Access to the flag which indicates whether the node is entered during traversing into depth over the tree - /// (false - means that the node and its children are already leaved or are not met yet). - bool IsOpen() const { return m_open; } - void SetOpen ( bool open ) { m_open = open; } - void SetOpen ( bool open ) const { m_open = open; } - - // \ru Равенство определяется по id объекта MbItemData. - // \en Equality is defined by id field of MbItemData object. - bool operator == ( const MbTreeNode& node2 ) const - { - if ( !( GetData() == node2.GetData() ) || - GetData().id != node2.GetData().id ) - return false; - return true; - } - - // \ru Сравнение по полям объектов MbItemData. - // \en Comparison of filtering fields of MbItemData objects. - bool operator < ( const MbTreeNode& node2 ) const - { - return m_data < node2.m_data; - } - - friend class MbModelTree; - -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Узел дерева исполнений. - \en Embodiments tree node. \~ - \details \ru Узел дерева исполнений (может иметь несколько потомков). - \en Embodiments tree node (can have several children). - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS MbEmbodimentNode : public IEmbodimentNode -{ - const MbTreeNode * m_subtree; -public: - MbEmbodimentNode( const MbTreeNode* node ) : IEmbodimentNode(), m_subtree( node ) {} - ~MbEmbodimentNode() {} - - // \ru Выдать узел дерева модели, соответствующий данному исполнению. - // \en Get a model tree node which corresponds to a given embodiment. - 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(); } - - // \ru Построить дерево модели, которое содержится в данном исполнении. - // \en Build a tree of a model which is contained in a given embodiment. - virtual std_unique_ptr GetEmbodiment() const; - -private: - MbEmbodimentNode(); -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Дерево геометрической модели. - \en Tree of geometric model. \~ - \details \ru Дерево геометрической модели. (может иметь несколько корней). - \en Tree of geometric model (can have several roots). \n \~ - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS MbModelTree : public IModelTree -{ -private: - // \ru Временное хранилище для индексов корней дерева (используется при чтении дерева). - // \en Temporary storage for indices of the tree roots (used while reading the tree). - std::vector m_rootsIndices; - // \ru Все узлы дерева, упорядоченные по данным. - // \en All nodes of the tree, ordered by data. - std::set m_filteredNodes; - // \ru Стек узлов, открытых при чтении/записи дерева. - // \en Stack of nodes opened during reading/writing the tree. - std::stack m_nestedNodesStack; - // \ru Все узлы дерева, упорядоченные по ID. - // \en All nodes of the tree, ordered by ID. - std::map m_indexToNode; // \ru Вспомогательный массив. \en Auxiliary map. - VERSION m_currentVersion; - IEmbodimentTree m_embTree; // \ru Дерево исполнений. \en Embodiment tree. -public: - - // \ru Конструктор. \en Constructor. - MbModelTree(); - - // \ru Деструктор. \en Destructor. - virtual ~MbModelTree(); - - ///--------- - /// \ru Методы IModelTreeNode. \en IModelTreeNode methods. - - /// \ru Создать узел по данными и добавить в дерево. \en Create a node by data and add to the tree. - virtual void AddNode ( const TapeBase* mem, const ClusterReference& ref ); - - /// \ru Закрыть узел (удалить узел из стека, так что родительский узел станет текущим). - /// \en Close the node (remove it from the stack so that its parent becomes the current node). - virtual void CloseNode ( const TapeBase* mem ); - - // \ru Построить дерево из узлов, выбранных по фильтрам. В случае дерева исполнений, функция работает с первым исполнением. - // \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). - 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 Версия дерева. \en Tree version. - virtual VERSION GetVersion() { return m_currentVersion; } - virtual void SetVersion( VERSION version ) { m_currentVersion = version; } - - /// \ru Записать дерево. \en Write the tree. - virtual writer & operator >> ( writer & ); - - /// \ru Прочитать дерево. \en Read the tree. - virtual reader & operator << ( reader & ); - - ///--------- - - /// \ru Добавить узел с данными из указанного узла, если узел с такими данными не существует. - /// \param node - узел с данными. - /// \param added - заполняется, если ненулевой (true - узел добавлен, false - узел уже существует). - /// \return - возвращает указатель на узел дерева. - /// \en Add a node with the data from the given node if a node with such data does not exist. - /// \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 ); - - /// \ru Добавить узел с указанными данными, если узел с такими данными не существует. - /// \param node - данные. - /// \param added - заполняется, если ненулевой (true - узел добавлен, false - узел уже существует). - /// \return - возвращает указатель на узел дерева. - /// \en Add a node with the given if a node with such data does not exist. - /// \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 ); - - /// \ru Доступ к узлам дерева, упорядоченным по данным. - /// \en Access to nodes of the tree, ordered by data. - std::set& GetFilteredNodes() { return m_filteredNodes; } - const std::set& GetFilteredNodes() const { return m_filteredNodes; } - - // \ru Добавить в корень текущего дерева указанное поддерево. \en Add a given subtree to the current tree root. - const void AddSubtree( IModelTree* tree, const IModelTreeNode* node ) const; - - /// \ru Заполнить массив корней дерева. - /// \en Fill the tree roots. - void FillRoots(); - -protected: - /// \ru Добавить ветвь в дерево: - /// \param branch - листовой узел с ветвью дерева, ведущей к нему, начиная с корневого узла дерева; - /// \param partial - определяет тип чтения листового узла (частичное или полное). - /// \en Add a branch to the tree: - /// \param branch - a leaf node with the tree branch, leading to it; - /// \param partial - defines partial or full read of the leaf node. - void AddBranch( const NodeBranch& branch, bool partial ); - - /// \ru Получить уникальные узлы для данного набора узлов. Проходятся все заданные узлы и исключаются те, - /// которые являются потомками заданных узлов (и будут прочитаны, как их часть). - /// Таким образом, результат будет содержать узлы поддеревьев, содержащих все заданные узлы. - /// \en Get unique nodes for given set of nodes. Walk through the given nodes and exclude nodes, - /// which are children of other given nodes (and will be read as a part of them). - /// Thus, the result set of nodes will represent the roots of subtrees containing all given nodes. - std::vector GetUniqueNodes ( std::vector& nodes ) const; - - - // \ru Построить дерево по заданным узлам без проверки типа. - // \en Build a tree for given nodes without type check. - const IModelTree* GetFilteredTreeEx( std::vector& nodes ) const; - - /// \ru Построить дерево по индексам (используется при чтении дерева). - /// \en Build the tree using indices (used during reading the tree). - void BuildTree(); - -private: - OBVIOUS_PRIVATE_COPY(MbModelTree) -}; - -//---------------------------------------------------------------------------------------- -/// \ru Операторы для записи дерева в xml формате. -/// \en Operators for outputing a tree to xml. -// --- - -//---------------------------------------------------------------------------------------- -/// \ru Запись узла дерева в xml формате. \en Tree node writing to xml. -// --- -MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, const IModelTreeNode& node ); - -//---------------------------------------------------------------------------------------- -/// \ru Запись узла дерева в xml формате. \en Tree node writing to xml. -// --- -MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, IModelTreeNode& node ); - -//---------------------------------------------------------------------------------------- -/// \ru Запись дерева в xml формате. \en Tree writing to xml. -// --- -MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, const IModelTree& tree ); - -//---------------------------------------------------------------------------------------- -/// \ru Запись дерева в xml формате. \en Tree writing to xml. -// --- -MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, IModelTree& tree ); - -} //namespace c3d - -#endif // __MODEL_TREE_H +////////////////////////////////////////////////////////////////////////////////////////// +/** \file + \brief \ru Реализация дерева модели + \en Implementation of Model Tree classes \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __MODEL_TREE_H +#define __MODEL_TREE_H + + +#include +#include +#include +#include +#include +#include +#include +#include + +//---------------------------------------------------------------------------------------- +// \ru Реализация интерфейсов дерева модели. \en Implementation of Model Tree interfaces. +//---------------------------------------------------------------------------------------- + +namespace c3d // namespace C3D +{ +//---------------------------------------------------------------------------------------- +/** \brief \ru Узел дерева. + \en Tree node. \~ + \details \ru Узел дерева (может иметь несколько потомков). \n + \en Tree node (can have several children). \n \~ + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS MbTreeNode : public IModelTreeNode +{ + // \ru Временное хранилище для индексов потомков узла (используется при чтении узла). + // \en Temporary storage for indices of child nodes (used while reading the node). + std::vector m_childrenIndices; + // \ru Данные узла \en The node data. + MbItemData m_data; + // \ru Флаг, указывающий, открыт ли узел при проходе вглубь по дереву. + // \en Flag which indicates whether the node is entered during traversing into depth over the tree. + mutable bool m_open; + // \ru Флаг, указывающий, читать ли только часть узла. + // \en Flag which indicates whether to read only a part of the node. + mutable bool m_partial; +public: + MbTreeNode() : m_open(false), m_partial(false) {} + MbTreeNode ( const MbItemData& data ) : m_data(data), m_open(false), m_partial(false) {} + MbTreeNode ( const MbTreeNode& node ) : m_data(node.m_data), m_childrenIndices(node.m_childrenIndices), + m_open(node.m_open), m_partial(node.m_partial) { GetChildren() = node.GetChildren(); GetParents() = node.GetParents(); } + + ///--------- + /// \ru Методы IModelTreeNode. \en IModelTreeNode methods. + + /// \ru Доступ к данным узла. \en Access to the node data. + virtual MbItemData& GetData() { return m_data; } + virtual const MbItemData& GetData() const { return m_data; } + + /// \ru Доступ к позиции чтения/записм узла. \en Access to the node read/write position. + virtual ClusterReference& GetPosition() { return m_data.position; } + virtual const ClusterReference& GetPosition() const { return m_data.position; } + + /// \ru Узнать, читать ли только часть узла. + /// \en Check whether to read the node partially. + virtual bool PartialRead() const { return m_partial; }; + + /// \ru Установить признак частичного или полного чтения узла. + /// \en Set indication of full or partial node reading. + virtual void SetPartialRead ( bool partial ) const { m_partial = partial; }; + + /// \ru Записать узел. \en Write the node. + virtual writer & operator >> ( writer & ); + + /// \ru Прочитать узел. \en Read the node. + virtual reader & operator << ( reader & ); + + /// \ru Доступ ко все потомкам узла. \en Access to the all descendants of the node. + void GetAllDescendants ( std::set& nodes ) const; + + /// \ru Создать узел с данными текущего узла и добавить его в дерево. + /// Рекурсивно скопировать в дерево всех предков текущего узла с сохранением иерархии. + /// \en Create a node with data from the current node. + /// Copy recursively all parents of the node to the tree preserving the hierarchy. + MbTreeNode* CopyToTreeWithParents ( c3d::IModelTree* tree, bool partial ) const; + + /// \ru Создать узел с данными текущего узла и добавить его в дерево. + /// Рекурсивно скопировать в дерево всех потомков текущего узла с сохранением иерархии. + /// \en Create a node with data from the current node. + /// Copy recursively all children of the node to the tree preserving the hierarchy. + MbTreeNode* CopyToTreeWithChildren ( c3d::IModelTree* tree, bool partial ) const; + + /// \ru Доступ к флагу, который указывет, открыт ли узел при проходе вглубь по дереву + /// (false означает, что узел и его потомки уже пройдены или еще не обнаружены). + /// \en Access to the flag which indicates whether the node is entered during traversing into depth over the tree + /// (false - means that the node and its children are already leaved or are not met yet). + bool IsOpen() const { return m_open; } + void SetOpen ( bool open ) { m_open = open; } + void SetOpen ( bool open ) const { m_open = open; } + + // \ru Равенство определяется по id объекта MbItemData. + // \en Equality is defined by id field of MbItemData object. + bool operator == ( const MbTreeNode& node2 ) const + { + if ( !( GetData() == node2.GetData() ) || + GetData().id != node2.GetData().id ) + return false; + return true; + } + + // \ru Сравнение по полям объектов MbItemData. + // \en Comparison of filtering fields of MbItemData objects. + bool operator < ( const MbTreeNode& node2 ) const + { + return m_data < node2.m_data; + } + + friend class MbModelTree; + +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Узел дерева исполнений. + \en Embodiments tree node. \~ + \details \ru Узел дерева исполнений (может иметь несколько потомков). + \en Embodiments tree node (can have several children). + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS MbEmbodimentNode : public IEmbodimentNode +{ + const MbTreeNode * m_subtree; +public: + MbEmbodimentNode( const MbTreeNode* node ) : IEmbodimentNode(), m_subtree( node ) {} + ~MbEmbodimentNode() {} + + // \ru Выдать узел дерева модели, соответствующий данному исполнению. + // \en Get a model tree node which corresponds to a given embodiment. + 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(); } + + // \ru Построить дерево модели, которое содержится в данном исполнении. + // \en Build a tree of a model which is contained in a given embodiment. + virtual std_unique_ptr GetEmbodiment() const; + +private: + MbEmbodimentNode(); +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Дерево геометрической модели. + \en Tree of geometric model. \~ + \details \ru Дерево геометрической модели. (может иметь несколько корней). + \en Tree of geometric model (can have several roots). \n \~ + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS MbModelTree : public IModelTree +{ +private: + // \ru Временное хранилище для индексов корней дерева (используется при чтении дерева). + // \en Temporary storage for indices of the tree roots (used while reading the tree). + std::vector m_rootsIndices; + // \ru Все узлы дерева, упорядоченные по данным. + // \en All nodes of the tree, ordered by data. + std::set m_filteredNodes; + // \ru Стек узлов, открытых при чтении/записи дерева. + // \en Stack of nodes opened during reading/writing the tree. + std::stack m_nestedNodesStack; + // \ru Все узлы дерева, упорядоченные по ID. + // \en All nodes of the tree, ordered by ID. + std::map m_indexToNode; // \ru Вспомогательный массив. \en Auxiliary map. + VERSION m_currentVersion; + IEmbodimentTree m_embTree; // \ru Дерево исполнений. \en Embodiment tree. +public: + + // \ru Конструктор. \en Constructor. + MbModelTree(); + + // \ru Деструктор. \en Destructor. + virtual ~MbModelTree(); + + ///--------- + /// \ru Методы IModelTreeNode. \en IModelTreeNode methods. + + /// \ru Создать узел по данными и добавить в дерево. \en Create a node by data and add to the tree. + virtual void AddNode ( const TapeBase* mem, const ClusterReference& ref ); + + /// \ru Закрыть узел (удалить узел из стека, так что родительский узел станет текущим). + /// \en Close the node (remove it from the stack so that its parent becomes the current node). + virtual void CloseNode ( const TapeBase* mem ); + + // \ru Построить дерево из узлов, выбранных по фильтрам. В случае дерева исполнений, функция работает с первым исполнением. + // \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). + 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 Версия дерева. \en Tree version. + virtual VERSION GetVersion() { return m_currentVersion; } + virtual void SetVersion( VERSION version ) { m_currentVersion = version; } + + /// \ru Записать дерево. \en Write the tree. + virtual writer & operator >> ( writer & ); + + /// \ru Прочитать дерево. \en Read the tree. + virtual reader & operator << ( reader & ); + + ///--------- + + /// \ru Добавить узел с данными из указанного узла, если узел с такими данными не существует. + /// \param node - узел с данными. + /// \param added - заполняется, если ненулевой (true - узел добавлен, false - узел уже существует). + /// \return - возвращает указатель на узел дерева. + /// \en Add a node with the data from the given node if a node with such data does not exist. + /// \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 ); + + /// \ru Добавить узел с указанными данными, если узел с такими данными не существует. + /// \param node - данные. + /// \param added - заполняется, если ненулевой (true - узел добавлен, false - узел уже существует). + /// \return - возвращает указатель на узел дерева. + /// \en Add a node with the given if a node with such data does not exist. + /// \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 ); + + /// \ru Доступ к узлам дерева, упорядоченным по данным. + /// \en Access to nodes of the tree, ordered by data. + std::set& GetFilteredNodes() { return m_filteredNodes; } + const std::set& GetFilteredNodes() const { return m_filteredNodes; } + + // \ru Добавить в корень текущего дерева указанное поддерево. \en Add a given subtree to the current tree root. + const void AddSubtree( IModelTree* tree, const IModelTreeNode* node ) const; + + /// \ru Заполнить массив корней дерева. + /// \en Fill the tree roots. + void FillRoots(); + +protected: + /// \ru Добавить ветвь в дерево: + /// \param branch - листовой узел с ветвью дерева, ведущей к нему, начиная с корневого узла дерева; + /// \param partial - определяет тип чтения листового узла (частичное или полное). + /// \en Add a branch to the tree: + /// \param branch - a leaf node with the tree branch, leading to it; + /// \param partial - defines partial or full read of the leaf node. + void AddBranch( const NodeBranch& branch, bool partial ); + + /// \ru Получить уникальные узлы для данного набора узлов. Проходятся все заданные узлы и исключаются те, + /// которые являются потомками заданных узлов (и будут прочитаны, как их часть). + /// Таким образом, результат будет содержать узлы поддеревьев, содержащих все заданные узлы. + /// \en Get unique nodes for given set of nodes. Walk through the given nodes and exclude nodes, + /// which are children of other given nodes (and will be read as a part of them). + /// Thus, the result set of nodes will represent the roots of subtrees containing all given nodes. + std::vector GetUniqueNodes ( std::vector& nodes ) const; + + + // \ru Построить дерево по заданным узлам без проверки типа. + // \en Build a tree for given nodes without type check. + const IModelTree* GetFilteredTreeEx( std::vector& nodes ) const; + + /// \ru Построить дерево по индексам (используется при чтении дерева). + /// \en Build the tree using indices (used during reading the tree). + void BuildTree(); + +private: + OBVIOUS_PRIVATE_COPY(MbModelTree) +}; + +//---------------------------------------------------------------------------------------- +/// \ru Операторы для записи дерева в xml формате. +/// \en Operators for outputing a tree to xml. +// --- + +//---------------------------------------------------------------------------------------- +/// \ru Запись узла дерева в xml формате. \en Tree node writing to xml. +// --- +MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, const IModelTreeNode& node ); + +//---------------------------------------------------------------------------------------- +/// \ru Запись узла дерева в xml формате. \en Tree node writing to xml. +// --- +MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, IModelTreeNode& node ); + +//---------------------------------------------------------------------------------------- +/// \ru Запись дерева в xml формате. \en Tree writing to xml. +// --- +MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, const IModelTree& tree ); + +//---------------------------------------------------------------------------------------- +/// \ru Запись дерева в xml формате. \en Tree writing to xml. +// --- +MATH_FUNC( c3d::t_ofstream& ) operator << ( c3d::t_ofstream& file, IModelTree& tree ); + +} //namespace c3d + +#endif // __MODEL_TREE_H diff --git a/C3d/Include/model_tree_data.h b/C3d/Include/model_tree_data.h index cfbd831..5907391 100644 --- a/C3d/Include/model_tree_data.h +++ b/C3d/Include/model_tree_data.h @@ -1,809 +1,822 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** \file - \brief \ru Реализация данных узла дерева модели - \en Implementation of data of Model Tree node \~ -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __MODEL_TREE_DATA_H -#define __MODEL_TREE_DATA_H - - -#include -#include -#include -#include -#include -#include -#include -#include - -//---------------------------------------------------------------------------------------- -// \ru Реализация пользовательских данных узла дерева модели. -// \en Implementation of user data of the model tree node. -//---------------------------------------------------------------------------------------- - -namespace c3d // namespace C3D -{ -//---------------------------------------------------------------------------------------- -/** \brief \ru Тип пользовательских данных узла дерева модели. - \en A type of user data of the model tree node. \~ - \details \ru \ru Тип пользовательских данных узла дерева модели. - \en A type of user data of the model tree node. \~ - \ingroup Base_Tools_IO -*/ -// --- -enum MbeItemDataType -{ - idtBool, // bool - idtInteger, // int - idtDouble, // double - idtString, // c3d::string_t - - // \ru Данные атрибутов, для которых хранится тип и значение атрибута. - // \en Attributes data which keeps attribute type and value. - idtAttrBool, // MbBoolAttribute (bool) - idtAttrInt, // MbIntAttribute (int) - idtAttrDouble, // MbDoubleAttribute (double) - idtAttrString, // MbStringAttribute (c3d::string_t) - idtAttrInt64, // MbInt64Attribute (int64) - idtAttrIdentifier, // MbIdentifier (int32) - idtAttrColor, // MbColor (uint32) - idtAttrWidth, // MbWidth (int) - idtAttrStyle, // MbStyle (int) - idtAttrSelected, // MbSelected (bool) - idtAttrVisible, // MbVisible (bool) - idtAttrChanged, // MbChanged (bool) - idtAttrDencity, // MbDencity (double) - idtAttrUpdateStamp, // MbUpdateStamp (uint32) - idtAttrAnchor, // MbAnchorAttribute (uint8) - - // \ru Данные сложных атрибутов, для которых хранится только тип. - // \en Complex attributes data which keeps attribute type only. - idtAttrVisual, // MbVisual - idtAttrWireCount, // MbWireCount - idtAttrName, // MbNameAttribute - idtAttrGeom, // MbGeomAttribute - idtAttrStampRib, // MbStampRibAttribute - idtAttrModelInfo, // MbModelInfo - idtAttrPersonOrganizationInfo, // MbPersonOrganizationInfo - - // \ru Специальная обработка атрибута - хранится свойство Идентификатор (Обозначение). - // \en Special processing of attribute - keep property Identifier. - idtAttrProductInfo, // MbProductInfo - - // \ru Данные сложных атрибутов, для которых хранится только тип (продолжение). - // \en Complex attributes data which keeps attribute type only (continuation). - idtAttrSTEPTextDescription, // MbSTEPTextDescription - idtAttrSTEPReferenceHolder, // MbSTEPReferenceHolder - idtAttrBinary, // MbBinaryAttribute - - // \ru Атрибут исполнения (хранится тип и пара значений). - // \en Attribute of embodiment (keeps type and values pair). - idtAttrEmbodiment, // MbEmbodimentAttribute - - // \ru Новый тип должен добавляться непосредственно перед idtCount (после всех определенных ранее типов). - // \en New type should be added just before idtCount (after all types defined before). - idtCount // \ru Число поддерживаемых типов данных. \en Number of supported data types -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Базовый класс для пользовательских данных узла дерева. - \en A base class for user data of a tree node. \~ - \details \ru Базовый класс для пользовательских данных узла дерева. - \en A base class for user data of a tree node. \~ - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS ItemDataBase -{ -// \ru Приведение объекта 'item' к типу данных 'Type' (тип проверен заранее). -// \en Cast object 'item' to the data type 'Type' (type already verified). -#define CAST(Type, item) dynamic_cast(const_cast(item)) - -protected: - bool m_filterByType; // \ru Фильтр только по типу (значение данных игнорируется). \en Filter by type only (ignore data value). - -public: - - ItemDataBase() : m_filterByType(false) {} - virtual ~ItemDataBase() {} - - // \ru Тип данных. \en The data type. - virtual MbeItemDataType Type() const = 0; - - // \ru Размер записи данных в поток. \en The data size in the stream. - virtual size_t Size( writer& ) const = 0; - - // \ru Создать данные заданного типа. \en Create data of the given type. - static ItemDataBase* Create( MbeItemDataType type ); - - // \ru Создать копию данных. \en Create data copy. - static ItemDataBase* Create( ItemDataBase* item ); - - // \ru Прочитать данные. \en Read data. - reader& operator << ( reader& in ); - - // \ru Записать данные. \en Write data. - writer& operator >> ( writer& out ) const; - - // \ru Сравнить данные. \en Compare data. - bool operator == ( ItemDataBase* item2 ) const; - - /// \ru Сравнить данные. \en Compare data. - bool operator < ( ItemDataBase* item2 ) const; - - // \ru Выдать/установить флаг сравнения только по типу (значение игнорируется). - // \en Get/set flag for comparing by type only (value ignored). - bool IgnoreValue() const { return m_filterByType; } - void SetIgnoreValue( bool ignore ) { m_filterByType = ignore; } -}; - - -//---------------------------------------------------------------------------------------- -/// \ru Создать объект пользовательских данных для атрибута. Возвращает NULL, если данный атрибут не поддерживается деревом модели. -/// \en Create user data object for the attribute. Return NULL if this attribute is not supported in the model tree. -//--- -MATH_FUNC( ItemDataBase* ) CreateAttributeData( MbAttribute* attr ); - -//---------------------------------------------------------------------------------------- -/// \ru Прочитать атрибуты для узла дерева. -/// \en Read attributes for the model tree node. -//--- -MATH_FUNC( std_unique_ptr ) GetTreeNodeAttributes( const IModelTreeNode * node, reader& in ); - - -//---------------------------------------------------------------------------------------- -// \ru Функции чтения и записи для пользовательских данных атрибута. -// \en Functions of reading and writing for attribute user data. -//--- -#define MTREE_PERSISTENT_DATA_OBJ(Class) \ - public: \ - static void Read(reader& in, Class* item) { in >> item->m_value; } \ - static void Write(writer& out, const Class* item) { out << item->m_value; } - -//---------------------------------------------------------------------------------------- -// \ru Определение типа для пользовательских данных атрибута. -// \en Type definition for attribute user data. -//--- -#define MTREE_DEFINE_DATA_TYPE(type) \ - public: \ - virtual MbeItemDataType Type() const { return type; } - -//---------------------------------------------------------------------------------------- -/// \ru Определение размера записи пользовательских данных атрибута в поток, как sizeof. -/// \en Definition of data size of attribute user data in the stream as sizeof. -//--- -#define MTREE_DEFINE_DATA_SIZE_STD(data) \ - public: \ - virtual size_t Size(writer&) const { return sizeof(data); } - -//---------------------------------------------------------------------------------------- -// \ru Макрос для объявления класса без данных (dataless) для атрибута. -// \en Macro for defining attribute dataless class. -//--- -#define MTREE_ATTR_DATALESS_CLASS(Class,ClassType) \ -class Class : public ItemDataBase { \ -public: \ - virtual ~Class() {} \ - virtual size_t Size( writer& ) const { return 0; } \ - virtual MbeItemDataType Type() const { return ClassType; } \ - static void Read( reader&, Class* ) {} \ - static void Write( writer&, const Class* ) {} \ -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Свойство типа bool. - \en Bool property. \~ - \details \ru Свойство типа bool. - \en Bool property. \~ - \ingroup Base_Tools_IO -*/ -// --- -class ItemDataBool : public ItemDataBase -{ -public: - bool m_value; - - ItemDataBool() : m_value( false ) {} - ItemDataBool( bool value ) : m_value( value ) {} - virtual ~ItemDataBool() {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtBool) - MTREE_PERSISTENT_DATA_OBJ(ItemDataBool) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Свойство типа integer. - \en Integer property. \~ - \details \ru Свойство типа integer. - \en Integer property. \~ - \ingroup Base_Tools_IO -*/ -// --- -class ItemDataInteger : public ItemDataBase -{ -public: - int m_value; - - ItemDataInteger() : m_value( 0 ) {} - ItemDataInteger( int value ) : m_value( value ) {} - virtual ~ItemDataInteger() {} - - MTREE_DEFINE_DATA_SIZE_STD(int32) - MTREE_DEFINE_DATA_TYPE(idtInteger) - MTREE_PERSISTENT_DATA_OBJ(ItemDataInteger) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Свойство типа double. - \en Double property. \~ - \details \ru Свойство типа double. - \en Double property. \~ - \ingroup Base_Tools_IO -*/ -// --- -class ItemDataDouble : public ItemDataBase -{ -public: - double m_value; - - ItemDataDouble() : m_value( 0 ) {} - ItemDataDouble( double value ) : m_value( value ) {} - virtual ~ItemDataDouble() {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtDouble) - MTREE_PERSISTENT_DATA_OBJ(ItemDataDouble) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Свойство типа string. - \en String property. \~ - \details \ru Свойство типа string. - \en String property. \~ - \ingroup Base_Tools_IO -*/ -// --- -class ItemDataString : public ItemDataBase -{ -public: - c3d::string_t m_value; - - ItemDataString() {} - ItemDataString( c3d::string_t value ) : m_value( value ) {} - virtual ~ItemDataString() {} - - /// \ru Размер записи данных в поток. \en The data size in the stream. - virtual size_t Size( writer& out ) const { return out.__lenWchar( m_value.c_str() ); } - - MTREE_DEFINE_DATA_TYPE(idtString) - MTREE_PERSISTENT_DATA_OBJ(ItemDataString) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута bool. - \en Data of Bool attribute. \~ - \details \ru Данные атрибута bool. - \en Data of Bool attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrBool : public ItemDataBool -{ -public: - ItemAttrBool() : ItemDataBool() {} - ItemAttrBool( bool value ) : ItemDataBool( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrBool) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrBool) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута integer. - \en Data of Integer attribute. \~ - \details \ru Данные атрибута integer. - \en Data of Integer attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrInteger : public ItemDataInteger -{ -public: - ItemAttrInteger() : ItemDataInteger() {} - ItemAttrInteger( int value ) : ItemDataInteger( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrInt) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrInteger) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута double. - \en Data of Double attribute. \~ - \details \ru Данные атрибута double. - \en Data of Double attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrDouble : public ItemDataDouble -{ -public: - ItemAttrDouble() : ItemDataDouble() {} - ItemAttrDouble( double value ) : ItemDataDouble( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrDouble) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrDouble) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута string. - \en Data of String attribute. \~ - \details \ru Данные атрибута string. - \en Data of String attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrString : public ItemDataString -{ -public: - ItemAttrString() : ItemDataString() {} - ItemAttrString( c3d::string_t value ) : ItemDataString( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrString) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrString) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута MbProductInfo. - \en Data of MbProductInfo attribute. \~ - \details \ru Данные атрибута MbProductInfo. - \en Data of MbProductInfo attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrProductInfo : public ItemDataString -{ -public: - ItemAttrProductInfo() : ItemDataString() {} - ItemAttrProductInfo( c3d::string_t value ) : ItemDataString( value ) {} - - MTREE_DEFINE_DATA_TYPE( idtAttrProductInfo ) - - static void Read( reader &, ItemAttrProductInfo * ) {} - static void Write( writer &, const ItemAttrProductInfo * ) {} -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута int64. - \en Data of int64 attribute. \~ - \details \ru Данные атрибута int64. - \en Data of int64 attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrInt64 : public ItemDataBase -{ -public: - int64 m_value; - - ItemAttrInt64() : m_value( 0 ) {} - ItemAttrInt64( int64 value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtAttrInt64) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrInt64) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Идентификатор. - \en Data of Identifier attribute. \~ - \details \ru Данные атрибута Идентификатор. - \en Data of Identifier attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrIdentifier : public ItemDataBase -{ -public: - int32 m_value; - - ItemAttrIdentifier() : m_value( 0 ) {} - ItemAttrIdentifier( int32 value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtAttrIdentifier) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrIdentifier) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Цвет. - \en Data of Color attribute. \~ - \details \ru Данные атрибута Цвет. - \en Data of Color attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrColor : public ItemDataBase -{ -public: - uint32 m_value; - - ItemAttrColor() : m_value( 0 ) {} - ItemAttrColor( uint32 value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtAttrColor) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrColor) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Толщина. - \en Data of Width attribute. \~ - \details \ru Данные атрибута Толщина. - \en Data of Width attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrWidth : public ItemDataInteger -{ -public: - ItemAttrWidth() : ItemDataInteger() {} - ItemAttrWidth( int value ) : ItemDataInteger( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrWidth) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrWidth) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Стиль. - \en Data of Style attribute. \~ - \details \ru Данные атрибута Стиль. - \en Data of Style attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrStyle : public ItemDataInteger -{ -public: - ItemAttrStyle() : ItemDataInteger() {} - ItemAttrStyle( int value ) : ItemDataInteger( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrStyle) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrStyle) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Селектированность. - \en Data of Selection attribute. \~ - \details \ru Данные атрибута Селектированность. - \en Data of Selection attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrSelected : public ItemDataBool -{ -public: - ItemAttrSelected() : ItemDataBool() {} - ItemAttrSelected( bool value ) : ItemDataBool( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrSelected) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrSelected) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Видимость. - \en Data of Visibility attribute. \~ - \details \ru Данные атрибута Видимость. - \en Data of Visibility attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrVisible : public ItemDataBool -{ -public: - ItemAttrVisible() : ItemDataBool() {} - ItemAttrVisible( bool value ) : ItemDataBool( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrVisible) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrVisible) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Изменённость. - \en Data of Modification attribute. \~ - \details \ru Данные атрибута Изменённость. - \en Data of Modification attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrChanged : public ItemDataBool -{ -public: - ItemAttrChanged() : ItemDataBool() {} - ItemAttrChanged( bool value ) : ItemDataBool( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrChanged) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrChanged) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Плотность. - \en Data of Dencity attribute. \~ - \details \ru Данные атрибута Плотность. - \en Data of Dencity attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrDencity : public ItemDataDouble -{ -public: - ItemAttrDencity() : ItemDataDouble( 0 ) {} - ItemAttrDencity( double value ) : ItemDataDouble( value ) {} - - MTREE_DEFINE_DATA_TYPE(idtAttrDencity) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrDencity) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Метка времени обновления. - \en Data of Update timestamp attribute. \~ - \details \ru Данные атрибута Метка времени обновления. - \en Data of Update timestamp attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrUpdateStamp : public ItemDataBase -{ -public: - uint32 m_value; - - ItemAttrUpdateStamp() : m_value( 0 ) {} - ItemAttrUpdateStamp( uint32 value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtAttrUpdateStamp) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrUpdateStamp) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута Якорь. - \en Data of Anchor attribute. \~ - \details \ru Данные атрибута Якорь. - \en Data of Anchor attribute. \~ -\ingroup Base_Tools_IO -*/ -// --- -class ItemAttrAnchor : public ItemDataBase -{ -public: - uint8 m_value; - - ItemAttrAnchor() : m_value( 0 ) {} - ItemAttrAnchor( uint8 value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD(m_value) - MTREE_DEFINE_DATA_TYPE(idtAttrAnchor) - MTREE_PERSISTENT_DATA_OBJ(ItemAttrAnchor) -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные атрибута исполнения. - \en Data of embodiment attribute. \~ - \details \ru Данные атрибута исполнения. - \en Data of embodiment attribute. \~ - \ingroup Base_Tools_IO -*/ -// --- -class ItemAttrEmbodiment : public ItemDataBase -{ -public: - typedef std::pair, bool> EmbData; - EmbData m_value; - - ItemAttrEmbodiment() : m_value( std::pair(0, 0),false ) {} - ItemAttrEmbodiment( const EmbData& value ) : m_value( value ) {} - - MTREE_DEFINE_DATA_SIZE_STD( m_value ) - MTREE_DEFINE_DATA_TYPE( idtAttrEmbodiment ) - static void Read( reader& in, ItemAttrEmbodiment* item ) { - in >> item->m_value.first.first; - in >> item->m_value.first.second; - if ( in.MathVersion() >= 0x13000010L ) - in >> item->m_value.second; - } - static void Write( writer& out, const ItemAttrEmbodiment* item ) { - out << item->m_value.first.first; - out << item->m_value.first.second; - if ( out.MathVersion() >= 0x13000010L ) - out << item->m_value.second; - } -}; - -//---------------------------------------------------------------------------------------- -/// \ru Объявление классов без данных для атрибутов. -/// \en Definition of attribute dataless classes. -//--- -MTREE_ATTR_DATALESS_CLASS(ItemAttrVisual, idtAttrVisual); -MTREE_ATTR_DATALESS_CLASS(ItemAttrWireCount, idtAttrWireCount); -MTREE_ATTR_DATALESS_CLASS(ItemAttrName, idtAttrName); -MTREE_ATTR_DATALESS_CLASS(ItemAttrGeom, idtAttrGeom); -MTREE_ATTR_DATALESS_CLASS(ItemAttrStampRib, idtAttrStampRib); -MTREE_ATTR_DATALESS_CLASS(ItemAttrModelInfo, idtAttrModelInfo); -MTREE_ATTR_DATALESS_CLASS(ItemAttrPersonOrganizationInfo, idtAttrPersonOrganizationInfo); -MTREE_ATTR_DATALESS_CLASS(ItemAttrSTEPTextDescription, idtAttrSTEPTextDescription); -MTREE_ATTR_DATALESS_CLASS(ItemAttrSTEPReferenceHolder, idtAttrSTEPReferenceHolder); -MTREE_ATTR_DATALESS_CLASS(ItemAttrBinary, idtAttrBinary); - -//---------------------------------------------------------------------------------------- -/** \brief \ru Контейнер для пользовательских данных узла дерева. - \en A container for user data of a tree node. \~ - \details \ru Контейнер для пользовательских данных узла дерева (владеет данными). - \en A container for user data of a tree node (owns the data). \~ - \ingroup Base_Tools_IO -*/ -// --- -class MATH_CLASS UserDataMap : public MultiMap -{ -public: - UserDataMap() {} - UserDataMap( const UserDataMap& other ); - - ~UserDataMap(); // \ru Владеет данными. \en Owns the data. - - /// \ru Оператор ==. \en Operator ==. - bool operator == ( const UserDataMap& other ) const; - - /// \ru Оператор <. \en Operator <. - bool operator < ( const UserDataMap& other ) const; - - /// \ru Оператор =. \en Operator =. - UserDataMap& operator = ( const UserDataMap& other ); -}; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Данные узла дерева. -\en Tree node data. \~ -\details \ru Данные узла дерева. \n -\en Tree node data. \n \~ -\ingroup Base_Tools_IO -*/ -// --- -struct MATH_CLASS MbItemData -{ - // \ru Признак наличия локальной системы координат. - // \en Token of local coordinate system presence. - enum PlacementPresenceToken - { - ppt_No = 0x01, - ppt_Yes = 0x02 - }; - - // \ru Уникальный ID узла в дереве модели. \en Unique id in the model tree. - // \ru Не учитывается при сравнении. \en Not considered during comparison. - mutable size_t id; - // \ru Тип объекта. \en Object type. - // \ru type==st_Undefined означает, что фильтр по типу не определен. - // \en type==st_Undefined means that filter is undefined. - MbeSpaceType type; - // \ru иИмя объекта. \en Object name. - // \ru name==SYS_MAX_UINT32 означает, что фильтр по имени не определен. - // \en name==SYS_MAX_UINT32 means that filter is undefined. - SimpleName name; - // \ru gabarit.IsEmpty()==true означает, что фильтр по габариту не определен. - // \en gabarit.IsEmpty()==true means that filter is undefined. - MbCube gabarit; - // \ru Позиция записи/чтения узла. \en Position for the node writing/reading. - // \ru position.IsValid()==false означает, что это поле не учитывается при сравнении. - // \en position.IsValid()==false means that this field is not considered during comparison. - ClusterReference position; - // \ru Локальная система координат объекта. \en Local coordinate system for the object. - // \ru Не учитывается при сравнении. \en Not considered during comparison. - MbPlacement3D placement; - - // \ru Кроме обязательных данных узла, описанных выше, можно задать пользовательские данные, - // которые содержатся в контейнере 'properties'. - // \en In addition to the mandatory node data, described above, it is possible to define user data, - // which is kept in the 'properties' container. - // \ru Контейнер для пользовательских данных узла. - // \en Container for user data of a node. - UserDataMap properties; - - - // \ru Конструкторы. \en Constructors. - MbItemData() : id( SYS_MAX_T ), type( st_Undefined ), name( SYS_MAX_UINT32 ) {} - MbItemData( MbeSpaceType t, SimpleName n, const MbCube& c, ClusterReference& pos ) : id( SYS_MAX_T ), type( t ), name( n ), gabarit( c ), position( pos ) {} - MbItemData( MbeSpaceType t, SimpleName n, const MbCube& c, ClusterReference& pos, const UserDataMap& prop ) : - id( SYS_MAX_T ), type( t ), name( n ), gabarit( c ), position( pos ), properties( prop ) {} - MbItemData( const MbItemData& data ) : id( data.id ), type( data.type ), - name( data.name ), gabarit( data.gabarit ), position( data.position ), - placement( data.placement ), properties( data.properties ) {} - - // \ru Признак пустых (неинициализированных) данных. \en Indicator of empty (uninitialized) data. - bool IsEmpty() const; - - // \ru Идентичность полей-фильтров (id не важен). - // \en Equality of filtering fields (id is irrelevant). - bool operator == ( const MbItemData& rt ) const; - - // \ru Сравнение полей-фильтров (id не важен). - // \en Comparison of filtering fields (id is irrelevant). - bool operator < ( const MbItemData& rt ) const; - - // \ru Специальное сравнение габаритов для сортировки объектов. - // \en Special comparison of bounding boxes for object sorting. - static bool CompareGabarits( const MbCube& a, const MbCube& b ); - - // \ru Запись и чтение. - // \en Writing and reading. - writer& operator >> ( writer & out ); - reader& operator << ( reader & out ); -}; - -//---------------------------------------------------------------------------------------- -/// \ru Чтение UserDataMap. \en UserDataMap reading. -// --- -inline reader& operator >> ( reader & in, UserDataMap& itemmap ) -{ - size_t typeCount = ::ReadCOUNT( in ); // \ru Количество типов данных в наборе. \en A number of types in the map. - - if ( in.good() ) { - for ( size_t i = 0; i < typeCount; i++ ) { - int t; - in >> t; - size_t typeSize = ::ReadCOUNT( in ); - C3D_ASSERT( t < (int)idtCount ); - if ( t < (int)idtCount ) { - MbeItemDataType type = (MbeItemDataType)t; // \ru Тип данных. \en A data type. - ItemDataBase* item = ItemDataBase::Create( type ); - *item << in; - itemmap.Associate( type, item ); - } - else { // skip unknown data - char* buff = new char[typeSize]; - in.readBytes( buff, typeSize ); - delete[] buff; - } - - if ( !in.good() ) { - in.setState( io::fail ); - break; - } - } - } - return in; -} - -//---------------------------------------------------------------------------------------- -/// \ru Запись UserDataMap. \en UserDataMap writing. -// --- -inline writer& operator << ( writer & out, const UserDataMap& itemmap ) -{ - size_t mapCount = itemmap.Count(); - ::WriteCOUNT( out, mapCount ); // \ru Количество типов данных в наборе. \en A number of types in the map. - - if ( out.good() && mapCount ) { - UserDataMap::Iterator curIter = itemmap.First(); - while ( !curIter.Empty() ) { - MbeItemDataType type = curIter.Key(); - ItemDataBase* item = curIter.Value(); - C3D_ASSERT( type < idtCount && item != NULL ); - if ( type < idtCount && item != NULL ) { - out << (int)type; // \ru Тип данных. \en A data type. - size_t dataSize = item->Size( out ); - ::WriteCOUNT( out, dataSize );// \ru Размер данных. \en Data size. - *item >> out; - } - if ( !out.good() ) { - out.setState( io::fail ); - break; - } - curIter++; - } - } - return out; -} - -} //namespace c3d - -#endif // __MODEL_TREE_DATA_H +////////////////////////////////////////////////////////////////////////////////////////// +/** \file + \brief \ru Реализация данных узла дерева модели + \en Implementation of data of Model Tree node \~ +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __MODEL_TREE_DATA_H +#define __MODEL_TREE_DATA_H + + +#include +#include +#include +#include +#include +#include +#include +#include + +//---------------------------------------------------------------------------------------- +// \ru Реализация пользовательских данных узла дерева модели. +// \en Implementation of user data of the model tree node. +//---------------------------------------------------------------------------------------- + +namespace c3d // namespace C3D +{ +//---------------------------------------------------------------------------------------- +/** \brief \ru Тип пользовательских данных узла дерева модели. + \en A type of user data of the model tree node. \~ + \details \ru \ru Тип пользовательских данных узла дерева модели. + \en A type of user data of the model tree node. \~ + \ingroup Base_Tools_IO +*/ +// --- +enum MbeItemDataType +{ + // \ru Простые пользовательские данные. \en Simple user data. + idtBool, // bool + idtInteger, // int + idtDouble, // double + idtString, // c3d::string_t + + // \ru Данные атрибутов. \en Attributes data. + + // \ru Данные атрибутов, для которых хранится тип и значение атрибута. + // \en Attributes data which keeps attribute type and value. + idtAttrBool, // MbBoolAttribute (bool) at_BoolAttribute + idtAttrInt, // MbIntAttribute (int) at_IntAttribute + idtAttrDouble, // MbDoubleAttribute (double) at_DoubleAttribute + idtAttrString, // MbStringAttribute (c3d::string_t) at_StringAttribute + idtAttrInt64, // MbInt64Attribute (int64) at_Int64Attribute + idtAttrIdentifier, // MbIdentifier (int32) at_Identifier + idtAttrColor, // MbColor (uint32) at_Color + idtAttrWidth, // MbWidth (int) at_Width + idtAttrStyle, // MbStyle (int) at_Style + idtAttrSelected, // MbSelected (bool) at_Selected + idtAttrVisible, // MbVisible (bool) at_Visible + idtAttrChanged, // MbChanged (bool) at_Changed + idtAttrDencity, // MbDencity (double) at_Dencity + idtAttrUpdateStamp, // MbUpdateStamp (uint32) at_UpdateStamp + idtAttrAnchor, // MbAnchorAttribute (uint8) at_AnchorAttribute + + // \ru Данные сложных атрибутов, для которых хранится только тип. + // \en Complex attributes data which keeps attribute type only. + idtAttrVisual, // MbVisual at_Visual + idtAttrWireCount, // MbWireCount at_WireCount + idtAttrName, // MbNameAttribute at_NameAttribute + idtAttrGeom, // MbGeomAttribute at_GeomAttribute + idtAttrStampRib, // MbStampRibAttribute at_StampRibAttribute + idtAttrModelInfo, // MbModelInfo at_ModelInfo + idtAttrPersonOrganizationInfo, // MbPersonOrganizationInfo at_PersonOrganizationInfo + + // \ru Специальная обработка атрибута - хранится свойство Идентификатор (Обозначение). + // \en Special processing of attribute - keep property Identifier. + idtAttrProductInfo, // MbProductInfo at_ProductInfo + + // \ru Данные сложных атрибутов, для которых хранится только тип (продолжение 1). + // \en Complex attributes data which keeps attribute type only (continuation 1). + idtAttrSTEPTextDescription, // MbSTEPTextDescription at_STEPTextDescription + idtAttrSTEPReferenceHolder, // MbSTEPReferenceHolder at_STEPReferenceHolder + idtAttrBinary, // MbBinaryAttribute at_BinaryAttribute + + // \ru Специальный атрибут исполнения (хранится тип и пара значений). + // \en Special attribute of embodiment (keeps type and values pair). + idtAttrEmbodiment, // MbEmbodimentAttribute at_Embodiment + + // \ru Данные сложных атрибутов, для которых хранится только тип (продолжение 2). + // \en Complex attributes data which keeps attribute type only (continuation 2). + idtAttrStrains, // MbStrains at_Strains + idtAttrElasticity, // MbElasticity at_Elasticity + idtAttrSheetFlanging, // MbSheetFlangingAttribute at_SweptFlangeAttribute + + + // \ru Новый тип должен добавляться непосредственно перед idtCount (после всех определенных ранее типов). + // \en New type should be added just before idtCount (after all types defined before). + idtCount // \ru Число поддерживаемых типов данных. \en Number of supported data types +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Базовый класс для пользовательских данных узла дерева. + \en A base class for user data of a tree node. \~ + \details \ru Базовый класс для пользовательских данных узла дерева. + \en A base class for user data of a tree node. \~ + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS ItemDataBase +{ +// \ru Приведение объекта 'item' к типу данных 'Type' (тип проверен заранее). +// \en Cast object 'item' to the data type 'Type' (type already verified). +#define CAST(Type, item) dynamic_cast(const_cast(item)) + +protected: + bool m_filterByType; // \ru Фильтр только по типу (значение данных игнорируется). \en Filter by type only (ignore data value). + +public: + + ItemDataBase() : m_filterByType(false) {} + virtual ~ItemDataBase() {} + + // \ru Тип данных. \en The data type. + virtual MbeItemDataType Type() const = 0; + + // \ru Размер записи данных в поток. \en The data size in the stream. + virtual size_t Size( writer& ) const = 0; + + // \ru Создать данные заданного типа. \en Create data of the given type. + static ItemDataBase* Create( MbeItemDataType type ); + + // \ru Создать копию данных. \en Create data copy. + static ItemDataBase* Create( ItemDataBase* item ); + + // \ru Прочитать данные. \en Read data. + reader& operator << ( reader& in ); + + // \ru Записать данные. \en Write data. + writer& operator >> ( writer& out ) const; + + // \ru Сравнить данные. \en Compare data. + bool operator == ( ItemDataBase* item2 ) const; + + /// \ru Сравнить данные. \en Compare data. + bool operator < ( ItemDataBase* item2 ) const; + + // \ru Выдать/установить флаг сравнения только по типу (значение игнорируется). + // \en Get/set flag for comparing by type only (value ignored). + bool IgnoreValue() const { return m_filterByType; } + void SetIgnoreValue( bool ignore ) { m_filterByType = ignore; } +}; + + +//---------------------------------------------------------------------------------------- +/// \ru Создать объект пользовательских данных для атрибута. Возвращает NULL, если данный атрибут не поддерживается деревом модели. +/// \en Create user data object for the attribute. Return NULL if this attribute is not supported in the model tree. +//--- +MATH_FUNC( ItemDataBase* ) CreateAttributeData( MbAttribute* attr ); + +//---------------------------------------------------------------------------------------- +/// \ru Прочитать атрибуты для узла дерева. +/// \en Read attributes for the model tree node. +//--- +MATH_FUNC( std_unique_ptr ) GetTreeNodeAttributes( const IModelTreeNode * node, reader& in ); + + +//---------------------------------------------------------------------------------------- +// \ru Функции чтения и записи для пользовательских данных атрибута. +// \en Functions of reading and writing for attribute user data. +//--- +#define MTREE_PERSISTENT_DATA_OBJ(Class) \ + public: \ + static void Read(reader& in, Class* item) { in >> item->m_value; } \ + static void Write(writer& out, const Class* item) { out << item->m_value; } + +//---------------------------------------------------------------------------------------- +// \ru Определение типа для пользовательских данных атрибута. +// \en Type definition for attribute user data. +//--- +#define MTREE_DEFINE_DATA_TYPE(type) \ + public: \ + virtual MbeItemDataType Type() const { return type; } + +//---------------------------------------------------------------------------------------- +/// \ru Определение размера записи пользовательских данных атрибута в поток, как sizeof. +/// \en Definition of data size of attribute user data in the stream as sizeof. +//--- +#define MTREE_DEFINE_DATA_SIZE_STD(data) \ + public: \ + virtual size_t Size(writer&) const { return sizeof(data); } + +//---------------------------------------------------------------------------------------- +// \ru Макрос для объявления класса без данных (dataless) для атрибута. +// \en Macro for defining attribute dataless class. +//--- +#define MTREE_ATTR_DATALESS_CLASS(Class,ClassType) \ +class Class : public ItemDataBase { \ +public: \ + virtual ~Class() {} \ + virtual size_t Size( writer& ) const { return 0; } \ + virtual MbeItemDataType Type() const { return ClassType; } \ + static void Read( reader&, Class* ) {} \ + static void Write( writer&, const Class* ) {} \ +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Свойство типа bool. + \en Bool property. \~ + \details \ru Свойство типа bool. + \en Bool property. \~ + \ingroup Base_Tools_IO +*/ +// --- +class ItemDataBool : public ItemDataBase +{ +public: + bool m_value; + + ItemDataBool() : m_value( false ) {} + ItemDataBool( bool value ) : m_value( value ) {} + virtual ~ItemDataBool() {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtBool) + MTREE_PERSISTENT_DATA_OBJ(ItemDataBool) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Свойство типа integer. + \en Integer property. \~ + \details \ru Свойство типа integer. + \en Integer property. \~ + \ingroup Base_Tools_IO +*/ +// --- +class ItemDataInteger : public ItemDataBase +{ +public: + int m_value; + + ItemDataInteger() : m_value( 0 ) {} + ItemDataInteger( int value ) : m_value( value ) {} + virtual ~ItemDataInteger() {} + + MTREE_DEFINE_DATA_SIZE_STD(int32) + MTREE_DEFINE_DATA_TYPE(idtInteger) + MTREE_PERSISTENT_DATA_OBJ(ItemDataInteger) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Свойство типа double. + \en Double property. \~ + \details \ru Свойство типа double. + \en Double property. \~ + \ingroup Base_Tools_IO +*/ +// --- +class ItemDataDouble : public ItemDataBase +{ +public: + double m_value; + + ItemDataDouble() : m_value( 0 ) {} + ItemDataDouble( double value ) : m_value( value ) {} + virtual ~ItemDataDouble() {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtDouble) + MTREE_PERSISTENT_DATA_OBJ(ItemDataDouble) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Свойство типа string. + \en String property. \~ + \details \ru Свойство типа string. + \en String property. \~ + \ingroup Base_Tools_IO +*/ +// --- +class ItemDataString : public ItemDataBase +{ +public: + c3d::string_t m_value; + + ItemDataString() {} + ItemDataString( c3d::string_t value ) : m_value( value ) {} + virtual ~ItemDataString() {} + + /// \ru Размер записи данных в поток. \en The data size in the stream. + virtual size_t Size( writer& out ) const { return out.__lenWchar( m_value.c_str() ); } + + MTREE_DEFINE_DATA_TYPE(idtString) + MTREE_PERSISTENT_DATA_OBJ(ItemDataString) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута bool. + \en Data of Bool attribute. \~ + \details \ru Данные атрибута bool. + \en Data of Bool attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrBool : public ItemDataBool +{ +public: + ItemAttrBool() : ItemDataBool() {} + ItemAttrBool( bool value ) : ItemDataBool( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrBool) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrBool) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута integer. + \en Data of Integer attribute. \~ + \details \ru Данные атрибута integer. + \en Data of Integer attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrInteger : public ItemDataInteger +{ +public: + ItemAttrInteger() : ItemDataInteger() {} + ItemAttrInteger( int value ) : ItemDataInteger( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrInt) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrInteger) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута double. + \en Data of Double attribute. \~ + \details \ru Данные атрибута double. + \en Data of Double attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrDouble : public ItemDataDouble +{ +public: + ItemAttrDouble() : ItemDataDouble() {} + ItemAttrDouble( double value ) : ItemDataDouble( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrDouble) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrDouble) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута string. + \en Data of String attribute. \~ + \details \ru Данные атрибута string. + \en Data of String attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrString : public ItemDataString +{ +public: + ItemAttrString() : ItemDataString() {} + ItemAttrString( c3d::string_t value ) : ItemDataString( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrString) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrString) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута MbProductInfo. + \en Data of MbProductInfo attribute. \~ + \details \ru Данные атрибута MbProductInfo. + \en Data of MbProductInfo attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrProductInfo : public ItemDataString +{ +public: + ItemAttrProductInfo() : ItemDataString() {} + ItemAttrProductInfo( c3d::string_t value ) : ItemDataString( value ) {} + + MTREE_DEFINE_DATA_TYPE( idtAttrProductInfo ) + + static void Read( reader &, ItemAttrProductInfo * ) {} + static void Write( writer &, const ItemAttrProductInfo * ) {} +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута int64. + \en Data of int64 attribute. \~ + \details \ru Данные атрибута int64. + \en Data of int64 attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrInt64 : public ItemDataBase +{ +public: + int64 m_value; + + ItemAttrInt64() : m_value( 0 ) {} + ItemAttrInt64( int64 value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtAttrInt64) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrInt64) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Идентификатор. + \en Data of Identifier attribute. \~ + \details \ru Данные атрибута Идентификатор. + \en Data of Identifier attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrIdentifier : public ItemDataBase +{ +public: + int32 m_value; + + ItemAttrIdentifier() : m_value( 0 ) {} + ItemAttrIdentifier( int32 value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtAttrIdentifier) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrIdentifier) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Цвет. + \en Data of Color attribute. \~ + \details \ru Данные атрибута Цвет. + \en Data of Color attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrColor : public ItemDataBase +{ +public: + uint32 m_value; + + ItemAttrColor() : m_value( 0 ) {} + ItemAttrColor( uint32 value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtAttrColor) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrColor) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Толщина. + \en Data of Width attribute. \~ + \details \ru Данные атрибута Толщина. + \en Data of Width attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrWidth : public ItemDataInteger +{ +public: + ItemAttrWidth() : ItemDataInteger() {} + ItemAttrWidth( int value ) : ItemDataInteger( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrWidth) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrWidth) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Стиль. + \en Data of Style attribute. \~ + \details \ru Данные атрибута Стиль. + \en Data of Style attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrStyle : public ItemDataInteger +{ +public: + ItemAttrStyle() : ItemDataInteger() {} + ItemAttrStyle( int value ) : ItemDataInteger( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrStyle) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrStyle) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Селектированность. + \en Data of Selection attribute. \~ + \details \ru Данные атрибута Селектированность. + \en Data of Selection attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrSelected : public ItemDataBool +{ +public: + ItemAttrSelected() : ItemDataBool() {} + ItemAttrSelected( bool value ) : ItemDataBool( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrSelected) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrSelected) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Видимость. + \en Data of Visibility attribute. \~ + \details \ru Данные атрибута Видимость. + \en Data of Visibility attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrVisible : public ItemDataBool +{ +public: + ItemAttrVisible() : ItemDataBool() {} + ItemAttrVisible( bool value ) : ItemDataBool( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrVisible) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrVisible) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Изменённость. + \en Data of Modification attribute. \~ + \details \ru Данные атрибута Изменённость. + \en Data of Modification attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrChanged : public ItemDataBool +{ +public: + ItemAttrChanged() : ItemDataBool() {} + ItemAttrChanged( bool value ) : ItemDataBool( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrChanged) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrChanged) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Плотность. + \en Data of Dencity attribute. \~ + \details \ru Данные атрибута Плотность. + \en Data of Dencity attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrDencity : public ItemDataDouble +{ +public: + ItemAttrDencity() : ItemDataDouble( 0 ) {} + ItemAttrDencity( double value ) : ItemDataDouble( value ) {} + + MTREE_DEFINE_DATA_TYPE(idtAttrDencity) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrDencity) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Метка времени обновления. + \en Data of Update timestamp attribute. \~ + \details \ru Данные атрибута Метка времени обновления. + \en Data of Update timestamp attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrUpdateStamp : public ItemDataBase +{ +public: + uint32 m_value; + + ItemAttrUpdateStamp() : m_value( 0 ) {} + ItemAttrUpdateStamp( uint32 value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtAttrUpdateStamp) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrUpdateStamp) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута Якорь. + \en Data of Anchor attribute. \~ + \details \ru Данные атрибута Якорь. + \en Data of Anchor attribute. \~ +\ingroup Base_Tools_IO +*/ +// --- +class ItemAttrAnchor : public ItemDataBase +{ +public: + uint8 m_value; + + ItemAttrAnchor() : m_value( 0 ) {} + ItemAttrAnchor( uint8 value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD(m_value) + MTREE_DEFINE_DATA_TYPE(idtAttrAnchor) + MTREE_PERSISTENT_DATA_OBJ(ItemAttrAnchor) +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные атрибута исполнения. + \en Data of embodiment attribute. \~ + \details \ru Данные атрибута исполнения. + \en Data of embodiment attribute. \~ + \ingroup Base_Tools_IO +*/ +// --- +class ItemAttrEmbodiment : public ItemDataBase +{ +public: + typedef std::pair, bool> EmbData; + EmbData m_value; + + ItemAttrEmbodiment() : m_value( std::pair(0, 0),false ) {} + ItemAttrEmbodiment( const EmbData& value ) : m_value( value ) {} + + MTREE_DEFINE_DATA_SIZE_STD( m_value ) + MTREE_DEFINE_DATA_TYPE( idtAttrEmbodiment ) + static void Read( reader& in, ItemAttrEmbodiment* item ) { + item->m_value.first.first = ::ReadSimpleName( in ); // in >> item->m_value.first.first; + item->m_value.first.second = ::ReadSimpleName( in ); // in >> item->m_value.first.second; + if ( in.MathVersion() >= 0x13000010L ) + in >> item->m_value.second; + } + static void Write( writer& out, const ItemAttrEmbodiment* item ) { + ::WriteSimpleName( out, item->m_value.first.first ); // out << item->m_value.first.first; + ::WriteSimpleName( out, item->m_value.first.second ); // out << item->m_value.first.second; + if ( out.MathVersion() >= 0x13000010L ) + out << item->m_value.second; + } +}; + +//---------------------------------------------------------------------------------------- +/// \ru Объявление классов без данных для атрибутов. +/// \en Definition of attribute dataless classes. +//--- +MTREE_ATTR_DATALESS_CLASS(ItemAttrVisual, idtAttrVisual); +MTREE_ATTR_DATALESS_CLASS(ItemAttrWireCount, idtAttrWireCount); +MTREE_ATTR_DATALESS_CLASS(ItemAttrName, idtAttrName); +MTREE_ATTR_DATALESS_CLASS(ItemAttrGeom, idtAttrGeom); +MTREE_ATTR_DATALESS_CLASS(ItemAttrStampRib, idtAttrStampRib); +MTREE_ATTR_DATALESS_CLASS(ItemAttrModelInfo, idtAttrModelInfo); +MTREE_ATTR_DATALESS_CLASS(ItemAttrPersonOrganizationInfo, idtAttrPersonOrganizationInfo); +MTREE_ATTR_DATALESS_CLASS(ItemAttrSTEPTextDescription, idtAttrSTEPTextDescription); +MTREE_ATTR_DATALESS_CLASS(ItemAttrSTEPReferenceHolder, idtAttrSTEPReferenceHolder); +MTREE_ATTR_DATALESS_CLASS(ItemAttrBinary, idtAttrBinary); +MTREE_ATTR_DATALESS_CLASS(ItemAttrStrains, idtAttrStrains); +MTREE_ATTR_DATALESS_CLASS(ItemAttrElasticity, idtAttrElasticity); +MTREE_ATTR_DATALESS_CLASS(ItemAttrSheetFlanging, idtAttrSheetFlanging); + +//---------------------------------------------------------------------------------------- +/** \brief \ru Контейнер для пользовательских данных узла дерева. + \en A container for user data of a tree node. \~ + \details \ru Контейнер для пользовательских данных узла дерева (владеет данными). + \en A container for user data of a tree node (owns the data). \~ + \ingroup Base_Tools_IO +*/ +// --- +class MATH_CLASS UserDataMap : public MultiMap +{ +public: + UserDataMap() {} + UserDataMap( const UserDataMap& other ); + + ~UserDataMap(); // \ru Владеет данными. \en Owns the data. + + /// \ru Оператор ==. \en Operator ==. + bool operator == ( const UserDataMap& other ) const; + + /// \ru Оператор <. \en Operator <. + bool operator < ( const UserDataMap& other ) const; + + /// \ru Оператор =. \en Operator =. + UserDataMap& operator = ( const UserDataMap& other ); +}; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Данные узла дерева. +\en Tree node data. \~ +\details \ru Данные узла дерева. \n +\en Tree node data. \n \~ +\ingroup Base_Tools_IO +*/ +// --- +struct MATH_CLASS MbItemData +{ + // \ru Признак наличия локальной системы координат. + // \en Token of local coordinate system presence. + enum PlacementPresenceToken + { + ppt_No = 0x01, + ppt_Yes = 0x02 + }; + + // \ru Уникальный ID узла в дереве модели. \en Unique id in the model tree. + // \ru Не учитывается при сравнении. \en Not considered during comparison. + mutable size_t id; + // \ru Тип объекта. \en Object type. + // \ru type==st_Undefined означает, что фильтр по типу не определен. + // \en type==st_Undefined means that filter is undefined. + MbeSpaceType type; + // \ru иИмя объекта. \en Object name. + // \ru name==SYS_MAX_UINT32 означает, что фильтр по имени не определен. + // \en name==SYS_MAX_UINT32 means that filter is undefined. + SimpleName name; + // \ru gabarit.IsEmpty()==true означает, что фильтр по габариту не определен. + // \en gabarit.IsEmpty()==true means that filter is undefined. + MbCube gabarit; + // \ru Позиция записи/чтения узла. \en Position for the node writing/reading. + // \ru position.IsValid()==false означает, что это поле не учитывается при сравнении. + // \en position.IsValid()==false means that this field is not considered during comparison. + ClusterReference position; + // \ru Локальная система координат объекта. \en Local coordinate system for the object. + // \ru Не учитывается при сравнении. \en Not considered during comparison. + MbPlacement3D placement; + + // \ru Кроме обязательных данных узла, описанных выше, можно задать пользовательские данные, + // которые содержатся в контейнере 'properties'. + // \en In addition to the mandatory node data, described above, it is possible to define user data, + // which is kept in the 'properties' container. + // \ru Контейнер для пользовательских данных узла. + // \en Container for user data of a node. + UserDataMap properties; + + + // \ru Конструкторы. \en Constructors. + MbItemData() : id( SYS_MAX_T ), type( st_Undefined ), name( SYS_MAX_UINT32 ) {} + MbItemData( MbeSpaceType t, SimpleName n, const MbCube& c, ClusterReference& pos ) : id( SYS_MAX_T ), type( t ), name( n ), gabarit( c ), position( pos ) {} + MbItemData( MbeSpaceType t, SimpleName n, const MbCube& c, ClusterReference& pos, const UserDataMap& prop ) : + id( SYS_MAX_T ), type( t ), name( n ), gabarit( c ), position( pos ), properties( prop ) {} + MbItemData( const MbItemData& data ) : id( data.id ), type( data.type ), + name( data.name ), gabarit( data.gabarit ), position( data.position ), + placement( data.placement ), properties( data.properties ) {} + + // \ru Признак пустых (неинициализированных) данных. \en Indicator of empty (uninitialized) data. + bool IsEmpty() const; + + // \ru Идентичность полей-фильтров (id не важен). + // \en Equality of filtering fields (id is irrelevant). + bool operator == ( const MbItemData& rt ) const; + + // \ru Сравнение полей-фильтров (id не важен). + // \en Comparison of filtering fields (id is irrelevant). + bool operator < ( const MbItemData& rt ) const; + + // \ru Специальное сравнение габаритов для сортировки объектов. + // \en Special comparison of bounding boxes for object sorting. + static bool CompareGabarits( const MbCube& a, const MbCube& b ); + + // \ru Запись и чтение. + // \en Writing and reading. + writer& operator >> ( writer & out ); + reader& operator << ( reader & out ); +}; + +//---------------------------------------------------------------------------------------- +/// \ru Чтение UserDataMap. \en UserDataMap reading. +// --- +inline reader& operator >> ( reader & in, UserDataMap& itemmap ) +{ + size_t typeCount = ::ReadCOUNT( in ); // \ru Количество типов данных в наборе. \en A number of types in the map. + + if ( in.good() ) { + for ( size_t i = 0; i < typeCount; i++ ) { + int t; + in >> t; + size_t typeSize = ::ReadCOUNT( in ); + C3D_ASSERT( t < (int)idtCount ); + if ( t < (int)idtCount ) { + MbeItemDataType type = (MbeItemDataType)t; // \ru Тип данных. \en A data type. + ItemDataBase* item = ItemDataBase::Create( type ); + *item << in; + itemmap.Associate( type, item ); + } + else { // skip unknown data + char* buff = new char[typeSize]; + in.readBytes( buff, typeSize ); + delete[] buff; + } + + if ( !in.good() ) { + in.setState( io::fail ); + break; + } + } + } + return in; +} + +//---------------------------------------------------------------------------------------- +/// \ru Запись UserDataMap. \en UserDataMap writing. +// --- +inline writer& operator << ( writer & out, const UserDataMap& itemmap ) +{ + size_t mapCount = itemmap.Count(); + ::WriteCOUNT( out, mapCount ); // \ru Количество типов данных в наборе. \en A number of types in the map. + + if ( out.good() && mapCount ) { + UserDataMap::Iterator curIter = itemmap.First(); + while ( !curIter.Empty() ) { + MbeItemDataType type = curIter.Key(); + ItemDataBase* item = curIter.Value(); + C3D_ASSERT( type < idtCount && item != NULL ); + if ( type < idtCount && item != NULL ) { + out << (int)type; // \ru Тип данных. \en A data type. + size_t dataSize = item->Size( out ); + ::WriteCOUNT( out, dataSize );// \ru Размер данных. \en Data size. + *item >> out; + } + if ( !out.good() ) { + out.setState( io::fail ); + break; + } + curIter++; + } + } + return out; +} + +} //namespace c3d + +#endif // __MODEL_TREE_DATA_H diff --git a/C3d/Include/multiline.h b/C3d/Include/multiline.h index f2b55f5..cb8e0b8 100644 --- a/C3d/Include/multiline.h +++ b/C3d/Include/multiline.h @@ -1,1816 +1,1816 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Мультилиния. - \en Multiline. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// \ru Заголовочный файл мультилинии cодержит следующие разделы. \en Header file of multiline contains the following sections. -// \ru _1_ EnMLVertexTracingType - тип обхода углов в вершине мультилинии \en _1_ EnMLVertexTracingType - type of traverse of corners at a vertex of multiline -// \ru _2_ EnMLInnerTipType - тип внутренней законцовки мультилинии \en _2_ EnMLInnerTipType - type of inner tip of multiline -// \ru _3_ EnMLTipType - тип законцовки мультилинии \en _3_ EnMLTipType - type of tip of multiline -// \ru _4_ StMLTipParams - структура параметров законцовки мультилинии \en _4_ StMLTipParams - tip of multiline parameters structure -// \ru _5_ StVertexOfMultilineInfo - информация о вершине мультилинии \en _5_ StVertexOfMultilineInfo - information about vertex of multiline -// \ru _6_ MbMultiline - класс мультилиния \en _6_ MbMultiline - multiline class -// \ru _7_ Функция построения скругления базовой кривой мультилинии \en _7_ Function for multiline base curve fillet construction -// \ru _8_ Функция построения фаски базовой кривой мультилинии \en _8_ Function for multiline base curve chamfer construction -// \ru _9_ Внеклассные функции расчета/учета радиусов кривизны \en _9_ Out-of-class functions for curvature radii calculation/consideration -// \ru _10_ Внеклассная функция гладкого стыка двух последовательных кривых \en _10_ Out-of-class function for smooth joint of two consecutive curves -// \ru _11_ Разбить мультилинию на две части \en _11_ Split multiline into two pieces -// \ru _12_ Разбить мультилинию на N равных частей \en _12_ Split multiline into N equal pieces -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MULTILINE_H -#define __MULTILINE_H - - -#include -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -// _1_ -/** \brief \ru Тип обхода углов. - \en Type of traverse of corners. \~ - \details \ru Тип обхода углов в вершине мультилинии.\n - \en Type of traverse of corners at a vertex of multiline.\n \~ - \ingroup Algorithms_2D -*/ // --- -enum EnMLVertexTracingType { - mvt_ShearType, ///< \ru Обход срезом. \en Traverse by shear. - mvt_FilletType, ///< \ru Обход со скруглением. \en Traverse by fillet. - mvt_SpecFilletType, ///< \ru Обход со скруглением заданным радиусом. \en Traverse by fillet with a given radius. - // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! -}; - - -//------------------------------------------------------------------------------ -// _2_ -/** \brief \ru Тип внутренней законцовки. - \en Type of inner tip. \~ - \details \ru Тип внутренней законцовки мультилинии.\n - \en Type of inner tip of multiline.\n \~ - \ingroup Algorithms_2D -*/ // --- -enum EnMLInnerTipType { - mit_UndefTip, ///< \ru Законцовки нет. \en No tip. - mit_VerticesTip, ///< \ru Законцовка между соответствующими вершинами. \en Tip between corresponding vertices. - mit_LinearTip, ///< \ru Линейная законцовка. \en Linear tip. - mit_ArcTip, ///< \ru Дуговая законцовка. \en Arc tip. - // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! -}; - - -//------------------------------------------------------------------------------ -// _3_ -/** \brief \ru Тип законцовки. - \en Type of tip. \~ - \details \ru Тип законцовки мультилинии.\n - \en Type of tip of multiline.\n \~ - \ingroup Algorithms_2D -*/ // --- -enum EnMLTipType { - mtt_UndefTip, ///< \ru Законцовки нет. \en No tip. - mtt_LinearTip, ///< \ru Линейная законцовка. \en Linear tip. - mtt_ArcTip, ///< \ru Дуговая законцовка. \en Arc tip. - mtt_PolylineTip, ///< \ru Ломаная законцовка. \en Polyline tip. - mtt_ObliqueTip, ///< \ru Наклонная законцовка. \en Inclined tip. - // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! -}; - - -//------------------------------------------------------------------------------ -// _4_ -/** \brief \ru Cтруктура параметров законцовки. - \en Tip parameters structure. \~ - \details \ru Cтруктура параметров законцовки мультилинии.\n - Изменять данные объекта можно только из MbMultiline. - \en Multiline tip parameters structure.\n - Object data can be changed only from MbMultiline. \~ - \ingroup Algorithms_2D -*/ -struct MATH_CLASS StMLTipParams { -friend class MbMultiline; -private: - EnMLTipType tipType; ///< \ru Тип законцовки. \en Type of tip. - - /** \brief \ru Параметр законцовки. - \en Parameter of tip. \~ - \details \ru Для mtt_UndefTip неопределен,\n - для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n - для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n - для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n - для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). - \en Undefined for mtt_UndefTip,\n - for mtt_LinearTip - distance from the end of multiline to the tip,\n - for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n - for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n - for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians).\~ - */ - double tipParam; - -public: - StMLTipParams(); ///< \ru Умолчательный конструктор. \en Default constructor. - StMLTipParams( const StMLTipParams & other ); ///< \ru Копирующий конструктор. \en Copy-constructor. - - /** \brief \ru Конструктор по типу законцовки и параметру законцовки. - \en Constructor by type of tip and parameter of tip. \~ - \details \ru Конструктор по типу законцовки и параметру законцовки.\n - \en Constructor by type of tip and parameter of tip.\n \~ - \param[in] _tipType - \ru Тип законцовки. - \en Type of tip. \~ - \param[in] _tipParam - \ru Параметр законцовки, зависит от типа законцовки:\n - для mtt_UndefTip неопределен,\n - для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n - для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n - для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n - для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). - \en Parameter of tip, depends on type of tip:\n - for mtt_UndefTip is undefined,\n - for mtt_LinearTip - distance from the end of multiline to the tip,\n - for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n - for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n - for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians). \~ - */ - StMLTipParams( EnMLTipType _tipType, double _tipParam ); - -public: - - /**\ru \name Функции доступа к данным - \en \name Functions for access to data - \{ */ - /// \ru Тип законцовки. \en Type of tip. - EnMLTipType GetTipType () const { return tipType; } - /// \ru Параметр законцовки. \en Parameter of tip. - double GetTipParam() const { return tipParam; } - /** \} */ - /**\ru \name Операторы сравнения - \en \name Comparison operators - \{ */ - /// \ru Оператор сравнения. \en Comparison operator. - bool operator ==( const StMLTipParams & ) const; - /// \ru Оператор сравнения. \en Comparison operator. - bool operator !=( const StMLTipParams & ) const; - /** \} */ - -protected: - - /**\ru \name Функции инициализации - \en \name Initialization functions - \{ */ - - /// \ru Инициализация по структуре параметров законцовки. \en Initialization by tip parameters structure. - void Init ( const StMLTipParams & other ); - - /** \brief \ru Инициализация по типу законцовки и параметру законцовки. - \en Initialization by type of tip and parameter of tip. \~ - \details \ru Инициализация по типу законцовки и параметру законцовки.\n - \en Initialization by type of tip and parameter of tip.\n \~ - \param[in] _tipType - \ru Тип законцовки. - \en Type of tip. \~ - \param[in] _tipParam - \ru Параметр законцовки, зависит от типа законцовки:\n - для mtt_UndefTip неопределен,\n - для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n - для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n - для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n - для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). - \en Parameter of tip, depends on type of tip:\n - for mtt_UndefTip is undefined,\n - for mtt_LinearTip - distance from the end of multiline to the tip,\n - for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n - for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n - for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians). \~ - */ - void Init ( EnMLTipType _tipType, double _tipParam ); - - /** \} */ - /**\ru \name Функции изменения данных - \en \name Functions for changing data - \{ */ - - /** \brief \ru Изменить тип законцовки. - \en Change type of tip. \~ - \details \ru Изменить тип законцовки мультилинии.\ n - \en Change type of tip of multiline.\n \~ - \param[in] othTipType - \ru Новый тип законцовки. - \en New type of tip. \~ - \return \ru false, если старое значение типа совпадает со значением othTipType. - \en False if the old value of type coincides with the value of othTipType. \~ - */ - bool ChangeTipType ( EnMLTipType othTipType ); - - /** \brief \ru Изменить параметр законцовки. - \en Change parameter of tip. \~ - \details \ru Изменить параметр законцовки мультилинии.\n - \en Change parameter of tip of multiline.\n \~ - \param[in] othTipParam - \ru Новый параметр законцовки. - \en New parameter of tip. \~ - \return \ru false, если старое значение параметра совпадает со значением othTipParam. - \en False if the old value of parameter coincides with the value of othTipParam. \~ - */ - bool ChangeTipParam( double othTipParam ); - - /** \brief \ru Трансформация. - \en Transformation. \~ - \details \ru Преобразование объекта согласно матрице.\n - \en Transform object according to the matrix.\n \~ - \param[in] matr - \ru Матрица трансформации. - \en Transformation matrix. \~ - */ - void Transform ( const MbMatrix & matr ); - /** \} */ - -private: - /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const StMLTipParams & ); - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( StMLTipParams, MATH_FUNC_EX ) -}; // StMLTipParams - - -//------------------------------------------------------------------------------ -// _5_ -/** \brief \ru Информация о вершине. - \en Information about a vertex. \~ - \details \ru Информация о вершине мультилинии.\n - Изменять данные объекта можно только из MbMultiline. - \en Information about a vertex of multiline.\n - Object data can be changed only from MbMultiline. \~ - \ingroup Algorithms_2D -*/ -struct MATH_CLASS StVertexOfMultilineInfo { -friend class MbMultiline; -private: - bool smoothJoint; ///< \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии \en Flag of multiline base line segments smooth joint at a vertex - ///< \ru (только для сплайнов). \en (only for splines). - EnMLVertexTracingType tracingType; ///< \ru Тип обхода углов в вершине мультилинии. \en Type of traverse of corners at a vertex of multiline. - double specFilletRad; ///< \ru Радиус особого скругления на линии мультилинии (если tracingType == mvt_SpecFilletType). \en Radius of a special fillet on a line of multiline (if tracingType == mvt_SpecFilletType). - // \ru Параметры законцовки в вершине (внутренней) \en Parameters of (inner) tip at a vertex - EnMLInnerTipType tipType; ///< \ru Тип внутренней законцовки. \en Type of inner tip. - bool firstSegTip; ///< \ru Законцовка для первого сегмента вершины. \en Tip for the first segment of a vertex. - -public: - StVertexOfMultilineInfo(); ///< \ru Умолчательный конструктор. \en Default constructor. - StVertexOfMultilineInfo( const StVertexOfMultilineInfo & other ); ///< \ru Копирующий конструктор. \en Copy-constructor. - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор.\n - \en Constructor.\n \~ - \param[in] _smoothJoint - \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии,\n - используется только для сплайнов. - \en Flag of multiline base line segments smooth joint at a vertex,\n - used only for splines. \~ - \param[in] _tracingType - \ru Тип обхода углов в вершине мультилинии. - \en Type of traverse of corners at a vertex of multiline. \~ - \param[in] _specFilletRad - \ru Радиус особого скругления на линии мультилинии,\n - если tracingType == mvt_SpecFilletType. - \en Radius of a special fillet on line of multiline,\n - if tracingType == mvt_SpecFilletType. \~ - \param[in] _tipType - \ru Тип внутренней законцовки. - \en Type of inner tip. \~ - \param[in] _firstSegTip - \ru Законцовка для первого сегмента вершины. - \en Tip for the first segment of a vertex. \~ - */ - StVertexOfMultilineInfo( bool _smoothJoint, EnMLVertexTracingType _tracingType, - double _specFilletRad, EnMLInnerTipType _tipType, bool _firstSegTip ); - -public: - - /**\ru \name Функции доступа к данным - \en \name Functions for access to data - \{ */ - /// \ru Тип обхода углов в вершине мультилинии. \en Type of traverse of corners at a vertex of multiline. - EnMLVertexTracingType GetTracingType () const { return tracingType; } - /// \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии. \en Flag of multiline base line segments smooth joint at a vertex. - bool IsSmoothJoint () const { return smoothJoint; } - /// \ru Радиус особого скругления на линии мультилинии. \en Radius of special fillet on base line of multiline. - double GetSpecFilletRad() const { return specFilletRad; } - /// \ru Тип внутренней законцовки. \en Type of inner tip. - EnMLInnerTipType GetTipType () const { return tipType; } - /// \ru Законцовка для первого сегмента вершины. \en Tip for the first segment of a vertex. - bool IsFirstSegTip () const { return firstSegTip; } - /// \ru Обход скруглением. \en Traverse by fillet. - bool IsFilletTracing () const; - -public: - - /** \} */ - /**\ru \name Операторы сравнения и присваивания - \en \name Comparison operators and assignment - \{ */ - /// \ru Оператор сравнения. \en Comparison operator. - bool operator == ( const StVertexOfMultilineInfo & ) const; - /// \ru Оператор сравнения. \en Comparison operator. - bool operator != ( const StVertexOfMultilineInfo & ) const; - /// \ru Оператор присваивания. \en Assignment operator. - StVertexOfMultilineInfo & operator = ( const StVertexOfMultilineInfo & other ) - { - Init( other ); - return *this; - } - - /** \} */ - - -protected: - - /**\ru \name Функции инициализации - \en \name Initialization functions - \{ */ - - /// \ru Инициализация по информации о вершине мультилинии. \en Initialization by an information about a vertex of multiline. - void Init( const StVertexOfMultilineInfo & other ); - - /** \brief \ru Инициализация. - \en Initialization. \~ - \details \ru Инициализация.\n - \en Initialization.\n \~ - \param[in] _smoothJoint - \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии,\n - используется только для сплайнов. - \en Flag of multiline base line segments smooth joint at a vertex,\n - used only for splines. \~ - \param[in] _tracingType - \ru Тип обхода углов в вершине мультилинии. - \en Type of traverse of corners at a vertex of multiline. \~ - \param[in] _specFilletRad - \ru Радиус особого скругления на линии мультилинии,\n - если tracingType == mvt_SpecFilletType. - \en Radius of a special fillet on line of multiline,\n - if tracingType == mvt_SpecFilletType. \~ - \param[in] _tipType - \ru Тип внутренней законцовки. - \en Type of inner tip. \~ - \param[in] _firstSegTip - \ru Законцовка для первого сегмента вершины. - \en Tip for the first segment of a vertex. \~ - */ - void Init ( bool _smoothJoint, EnMLVertexTracingType _tracingType, - double _specFilletRad, EnMLInnerTipType _tipType, - bool _firstSegTip ); - /** \} */ - /**\ru \name Функции изменения данных - \en \name Functions for changing data - \{ */ - /// \ru Изменить флаг гладкого стыка в вершине сегментов базовой линии мультилинии. \en Change flag of multiline base line segments smooth joint at a vertex. - bool ChangeSmoothJoint ( bool othSmoothJoint ); - /// \ru Изменить тип обхода углов в вершине мультилинии. \en Change type of traverse of corners at a vertex of multiline. - bool ChangeTracingType ( EnMLVertexTracingType othTracingType ); - /// \ru Изменить радиус особого скругления на линии мультилинии. \en Change radius of special fillet on base line of multiline. - bool ChangeSpecFilletRad( double othSpecFilletRad ); - /// \ru Изменить тип внутренней законцовки. \en Change type of inner tip. - bool ChangeTipType ( EnMLInnerTipType othTipType ); - /// \ru Изменить флаг законцовки для первого сегмента вершины. \en Change flag of tip for the first segment of a vertex. - bool ChangeFirstSegTip ( bool othFirstSegTip ); - - /** \brief \ru Трансформация. - \en Transformation. \~ - \details \ru Преобразование объекта согласно матрице.\n - \en Transform object according to the matrix.\n \~ - \param[in] matr - \ru Матрица трансформации. - \en Transformation matrix. \~ - */ - void Transform ( const MbMatrix & matr ); - /** \} */ - -private: - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( StVertexOfMultilineInfo, MATH_FUNC_EX ) -}; // StVertexOfMultilineInfo - - -//------------------------------------------------------------------------------ -/** \brief \ru Класс для перестроения разрывов. - \en Class for breaks rebuilding. \~ - \details \ru Класс для перестроения разрывов. Содержит номера сегментов базовой кривой.\n - \en Class for breaks rebuilding. Contains indices of the base curve segments.\n \~ - \ingroup Algorithms_2D -*/ -// --- -class MATH_CLASS MbBreaksRebuild { - -public: - SArray baseNumbers; ///< \ru Номера сегментов базовой кривой для сегментов линии мультилинии. \en Indices of the base curve segments for line segments of multiline. - -public: - /// \ru Конструктор по массиву номеров. \en Constructor by array of indices. - MbBreaksRebuild( const SArray & bNumbers ) - :baseNumbers( bNumbers ) - { - } - ~MbBreaksRebuild() {} -}; - - -//------------------------------------------------------------------------------ -// _6_ -/** \brief \ru Мультилиния. - \en Multiline. \~ - \details \ru Мультилиния - составной геометрический объект, состоящий из\n - 1) кривых curves, построенных эквидистантно к базовой кривой мультилинии basisCurve - с радиусами equidRadii. При этом способ обхода углов для каждой вершины - basisCurve определяется отдельно (с помощью vertices.tracingType и vertices.specFilletRad).\n - 2) массива законцовок tipCurves в вершинах мультилинии, тип которых определяется - соответствующим vertices[i].tipParams.tipType.\n - 3) законцовок begTipCurve и endTipCurve на концах мультилинии, тип которых определяется - с помощью begTipParams и endTipParams.\n - При создании линии мультилинии (добавлении радиуса эквидистанты) создается контур, - который будет жить (меняться только внутри) до того момента, пока в массиве equidRadii - есть соответствующий ему в начале элемент.\n - Контур законцовки живет до тех пор, пока соответствующий тип законцовки не равен m_t_UndefTip.\n - За существованием и удалением законцовок должны следить функции SetTipType.\n - При построении кривых мультилинии вырожденные участки исключаются только в вершинах (перехлесты). - \en Multiline is a composite geometric object consisting of\n - 1) 'curves' curves constructed to be equidistant to base line 'basisCurve' of the multiline - with 'equidRadii' radii. The method of traverse of corners for each vertex of - 'basisCurve' is defined separately (with the help of vertices.tracingType and vertices.specFilletRad).\n - 2) 'tipCurves' array of tips at vertices of multiline, which type is defined - by corresponding vertices[i].tipParams.tipType.\n - 3) 'begTipCurve' and 'endTipCurve' tips at the ends of multiline, which type is defined - with the help of 'begTipParams' and 'endTipParams'.\n - While creating line of multiline (adding equidistance radius) the contour is created - which will be alive (can be changed only internally) while the 'equidRadii' array - contains element at the beginning corresponding to it.\n - The contour of a tip will be alive while the corresponding type of the tip isn't equal to m_t_UndefTip.\n - SetTipType functions care about the existence and removal of tips.\n - Degenerated regions are excluded only at vertices (overlaps) while constructing the curves of a multiline. \~ - \ingroup Region_2D -*/ -// --- -class MATH_CLASS MbMultiline : public MbPlaneItem { -private: - MbContour * basisCurve; ///< \ru Базовая кривая (БК) (всегда не NULL). \en Base curve (BC) (always not 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). - StMLTipParams endTipParams; ///< \ru Параметры законцовки в конце мультилинии (конце БК). \en Parameters of a tip at the end of a multiline (end of the base curve). - bool processClosed; ///< \ru Обрабатывать ли замкнутость БК (доп. вершина). \en Whether to process the closedness of the base curve (additional vertex). - 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 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). - - mutable double maxPosRadius; ///< \ru Максимально возможный для невывернутого построения положительный радиус. \en Maximum possible positive radius for non-everted construction. - mutable double minNegRadius; ///< \ru Минимально возможный для невывернутого построения отрицательный радиус. \en Minimum possible negative radius for non-everted construction. - mutable size_t minNotDegInd; ///< \ru Индекс невырожденного элемента curves с минимальным радиусом. \en Index of non-everted element of 'curves' with minimal radius. - mutable size_t maxNotDegInd; ///< \ru Индекс невырожденного элемента curves с максимальным радиусом. \en Index of non-everted element of 'curves' with maximal radius. - -public: - MbMultiline(); ///< \ru Конструктор пустой мультилинии. \en Constructor of an empty multiline. - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор.\n - \en Constructor.\n \~ - \param[in] _basisCurve - \ru Базовая кривая. - \en Base curve. \~ - \param[in] vertInfo - \ru Информация о вершине мультилинии (применяется ко всем вершинам). - \en Information about a vertex of the multiline (applied to all vertices). \~ - \param[in] _equidRadii - \ru Сортированный массив радиусов эквидистантных кривых. - \en Sorted array of radii of equidistant curves. \~ - \param[in] _begTipParams - \ru Параметры законцовки в начале мультилинии. - \en Parameters of tip at the beginning of multiline. \~ - \param[in] _endTipParams - \ru Параметры законцовки в конце мультилинии. - \en Parameters of a tip at the end of a multiline. \~ - \param[in] _processClosed - \ru Обрабатывать ли замкнутость базовой кривой. - \en Whether to process the closedness of the base curve. \~ - \param[in] _isTransparent - \ru "Прозрачная" ли мультилиния\n - параметр не используется, мультилиния считается прозрачной. - \en Whether the multiline is "transparent"\n - parameter isn't used, multiline is considered to be transparent. \~ - */ - MbMultiline( const MbContour & _basisCurve, const StVertexOfMultilineInfo & vertInfo, - const SArray & _equidRadii, - const StMLTipParams & _begTipParams, const StMLTipParams & _endTipParams, - bool _processClosed, bool _isTransparent ); - -protected: - /// \ru Копирующий конструктор. \en Copy-constructor. - MbMultiline( const MbMultiline & ); - -private: - MbMultiline( const MbContour & _basisCurve, const SArray & _vertices, - const SArray & _equidRadii, - const StMLTipParams & _begTipParams, const StMLTipParams & _endTipParams, - bool _processClosed, bool _isTransparent, bool & error ); - -public: - virtual ~MbMultiline(); - -public: - - /**\ru \name Общие функции геометрического объекта - \en \name Common functions of a geometric object - \{ */ - virtual MbePlaneType IsA () const; // \ru Тип объекта. \en A type of an object. - virtual MbePlaneType Type () const; // \ru Групповой тип объекта. \en Group type of an object. - virtual MbePlaneType Family () const; // \ru Семейство объекта. \en Family of an object. - 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 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. - virtual double DistanceToPoint ( const MbCartPoint & toP ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. - virtual bool DistanceToPointIfLess( const MbCartPoint & to, double &distance) const; // \ru Вычислить расстояние до точки, если оно меньше d. \en Calculate the distance to the point if it is less than d. - - virtual MbProperty& CreateProperty( MbePrompt name ) 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( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - - /** \} */ - /**\ru \name Функции доступа к данным - \en \name Functions for access to data - \{ */ - - /// \ru Базовая кривая. \en Base curve. - const MbContour & GetBasisCurve () const { return *basisCurve; } - /// \ru Дать базовую кривую для изменения. \en Get base curve for editing. - MbContour & SetBasisCurve () { return *basisCurve; } - /// \ru Количество вершин. \en Count of vertices. - size_t GetVerticesCount () const { return vertices.Count(); } - /// \ru Вершина по номеру. Номер должен быть меньше количества вершин. \en Vertex by an index. Index must be less than count of vertices. - const StVertexOfMultilineInfo & GetVertex ( size_t i ) const { return vertices[i]; } - /// \ru Количество радиусов эквидистант. \en Count of radii of equidistant curves. - size_t GetEquidRadiiCount() const { return equidRadii.Count(); } - /// \ru Радиус эквидистанты по номеру. Номер должен быть меньше количества радиусов. \en Radius of equidistant curve by an index. Index must be less than count of radii. - double GetEquidRadius ( size_t i ) const { return equidRadii[i]; } - /// \ru Параметры законцовки в начале мультилинии. \en Parameters of tip at the beginning of multiline. - const StMLTipParams & GetBegTipParams () const { return begTipParams; } - /// \ru Параметры законцовки в конце мультилинии. \en Parameters of a tip at the end of a multiline. - const StMLTipParams & GetEndTipParams () const { return endTipParams; } - /// \ru Признак обрабатывания замкнутости базовой кривой. \en An attribute of the base curve closedness processing. - bool IsProcessClosed () const { return processClosed; } - /// \ru Прозрачность мультилинии. \en Transparency of multiline. - bool IsTransparent () const { return isTransparent; } - // \ru Функции доступа к объектам мультилинии \en Functions for access to objects of multiline - // \ru ЭТИ ОБЪЕКТЫ НЕЛЬЗЯ МЕНЯТЬ СНАРУЖИ!!! \en THESE OBJECTS CAN'T BE CHANGED OUTSIDE!!! - - /// \ru Количество кривых мультилинии. \en Count of curves of a multiline. - size_t GetCurvesCount () const { return curves.Count(); } - /// \ru Кривая мультилинии по номеру. Номер должен быть меньше количества кривых. \en Curve of multiline by an index. Index must be less than count of curves. - const MbContourWithBreaks* GetCurve ( size_t i ) const { return curves[i]; } - - /// \ru Количество кривых - законцовок в вершинах мультилинии. \en Count of tip-curves at vertices of multiline. - size_t GetTipCurvesCount () const { return tipCurves.Count(); } - /// \ru Кривая - законцовка по номеру. Номер должен быть меньше количества законцовок. \en Tip-curve by an index. Index must be less than the count of tips. - const MbContour * GetTipCurve ( size_t i ) const { return tipCurves[i]; } - - /// \ru Законцовка в начале мультилинии. \en Tip at the beginning of a multiline. - const MbContour * GetBegTipCurve () const { return begTipCurve; } - /// \ru Законцовка в конце мультилинии. \en Tip at the end of a multiline. - const MbContour * GetEndTipCurve () const { return endTipCurve; } - - /// \ru Максимально возможный для невывернутого построения положительный радиус. \en Maximum possible positive radius for non-everted construction. - double GetMaxPosRadius () const { return maxPosRadius; } - /// \ru Минимально возможный для невывернутого построения отрицательный радиус. \en Minimum possible negative radius for non-everted construction. - double GetMinNegRadius () const { return minNegRadius; } - - /// \ru Индекс невырожденной кривой мультилинии с минимальным радиусом \en Index of non-degenerated curve of a multiline with minimal radius - size_t GetMinNotDegInd () const { return minNotDegInd; } - /// \ru Индекс невырожденной кривой мультилинии с максимальным радиусом \en Index of non-degenerated curve of a multiline with maximal radius - size_t GetMaxNotDegInd () const { return maxNotDegInd; } - - /** \} */ - /**\ru \name Функции изменения данных: изменение базовой кривой мультилинии - \en \name Functions for changing data: changing the base curve of a multiline - \{ */ - - /// \ru Очистить базовую кривую. \en Clear the base curve. - void ClearBasisCurve (); - - /** \brief \ru Заменить базовую кривую. - \en Replace the base curve. \~ - \details \ru Заменить базовую кривую.\n - При замене базовой кривой мультилинии в ней удаляются все разрывы. - \en Replace the base curve.\n - When replacing the base curve of multiline all of its breaks are removed. \~ - \param[in] _basisCurve - \ru Новая базовая кривая. - \en New base curve. \~ - \param[in] vertInfo - \ru Новая информация о вершинах мультилинии. - \en New information about vertices of multiline. \~ - */ - void ReplaceBasisCurve ( const MbContour & _basisCurve, - const StVertexOfMultilineInfo & vertInfo ); - - /** \brief \ru Добавить сегмент в базовую кривую. - \en Add a segment to a base curve. \~ - \details \ru Добавить сегмент в базовую кривую.\n - \en Add a segment to a base curve.\n \~ - \param[in] segment - \ru Добавляемый сегмент,\n - если является ломаной или контуром, то в мультилинию добавляются только составляющие сегменты. - \en Segment to add,\n - if it is polyline or contour, then only component segments are added to the multiline. \~ - \param[in] vertInfo - \ru Информация присваивается всем добавленным или измененным вершинам. - \en Information is assigned to all added or changed vertices. \~ - \return \ru true, если сегмент был добавлен. - \en True if a segment has been added. \~ - */ - bool AddBasisSegment ( MbCurve * segment, - const StVertexOfMultilineInfo & vertInfo ); - - /// \ru Удалить последний сегмент базовой кривой. \en Delete the last segment of the base curve. - void DeleteLastBasisSegment (); - - /** \brief \ru Вставить вершину. - \en Insert a vertex. \~ - \details \ru Вставить вершину. Сегмент разбивается на два.\n - \en Insert a vertex. Segment is split into two segments.\n \~ - \param[in] t - \ru Параметр на базовой кривой. - \en Parameter on the base curve. \~ - \param[in] vertInfo - \ru Информация о новой вершине мультилинии. - \en Information about new vertex of a multiline. \~ - \return \ru Индекс разбитого сегмента. - \en Index of split segment. \~ - */ - size_t InsertVertex ( double t, - const StVertexOfMultilineInfo & vertInfo ); - - /** \brief \ru Удалить вершину мультилинии. - \en Delete a vertex of multiline. \~ - \details \ru Удалить вершину мультилинии.\n - Пара сегментов, примыкающих к вершине, заменяется отрезком.\n - Разрывы на прилегающих сегментах исчезают. - Разрывы, лежащие на прямолинейных прилегающих сегментах, - остаются, привязываясь к вершинам нового отрезка. - \en Delete a vertex of multiline.\n - Pair of segments adjoining the vertex is replaced by a segment.\n - Breaks on adjacent segments are disappeared. - Breaks on straight adjacent segments - are remained by binding to the vertices of a new segment. \~ - \param[in] i - \ru Индекс вершины. - \en An index of a vertex. \~ - \return \ru true, если вершина была удалена. - \en True if a vertex is deleted. \~ - */ - bool RemoveVertex ( size_t i ); - - /** \brief \ru Сместить геометрическую hot-точку. - \en Shift a geometric hot-point. \~ - \details \ru Сместить геометрическую hot-точку базовой кривой.\n - При перемещении точки разрывы контуров, соответствующих прилегающим прямолинейным - сегментам привязываются к соседним неподвижным вершинам базовой кривой. - \en Shift a geometric hot-point of the base curve.\n - While shifting point, the contour breaks corresponding to adjacent straight - segments are bound to the neighboring fixed vertices of the base curve. \~ - \param[in] segInd - \ru Номер сегмента. - \en An index of a segment. \~ - \param[in] subInd - \ru Номер точки на сегменте:\n - если subInd = 0 - общая точка между двумя сегментами (может быть задана для любого сегмента),\n - если subInd = 1 - средняя точкой отрезка, средняя точкой дуги, базовая точка сплайнов pt_Nurbs и pt_Bezier,\n - если subInd > 1 - базовая точка сплайнов pt_Nurbs и pt_Bezier. - \en An index of a point on the segment:\n - if subInd = 0 - common point between two segments (can be specified for any segment),\n - if subInd = 1 - middle point of a segment, middle point of an arc, the base point of pt_Nurbs and pt_Bezier splines,\n - if subInd > 1 - base point of pt_Nurbs and pt_Bezier splines. \~ - \param[in] newPoint - \ru Новое положение точки. - \en New position of the point. \~ - \return \ru Точка была смещена. - \en Point has been shifted. \~ - */ - bool SetBasisCurvesGeoHotPoint( size_t segInd, size_t subInd, - const MbCartPoint & newPoint ); - - /** \brief \ru Удалить геометрическую hot-точку. - \en Delete a geometric hot-point. \~ - \details \ru Удалить геометрическую hot-точку базовой кривой.\n - \en Delete a geometric hot-point of the base curve.\n \~ - \param[in] segInd - \ru Номер сегмента. - \en An index of a segment. \~ - \param[in] subInd - \ru Номер точки на сегменте:\n - если subInd = 0 - результат аналогичен удалению вершины мультилинии RemoveVertex,\n - если subInd = 1 - удаление средней точки дуги (дуга заменяется отрезком), - удаление базовой точки сплайнов pt_Nurbs и pt_Bezier (изменение формы),\n - если subInd > 1 - удаление базовой точки сплайнов pt_Nurbs и pt_Bezier (изменение формы). - \en An index of a point on the segment:\n - if subInd = 0 - result is similar to deletion of the 'RemoveVertex' vertex of a multiline,\n - if subInd = 1 - deletion of the middle point of an arc (the arc is replaced by segment), - deletion of the base point of pt_Nurbs and pt_Bezier splines (changing of shape),\n - if subInd > 1 - deletion of the base point of pt_Nurbs and pt_Bezier splines (changing of shape). \~ - \return \ru true, если hot-точка была удалена. - \en True if hot-point has been deleted. \~ - */ - bool DelBasisCurvesGeoHotPoint( size_t segInd, size_t subInd ); - - /** \} */ - /**\ru \name Функции изменения данных: скругления и фаски базовой кривой - \en \name Functions for changing data: fillet and chamfer of the base curve - \{ */ - - /** \brief \ru Скруглить два соседних сегмента. - \en Fillet two neighboring segments. \~ - \details \ru Скруглить два соседних сегмента базовой кривой.\n - \en Fillet two neighboring segments of base curve.\n \~ - \param[in] index - \ru Индекс первого скругляемого сегмента. - \en Index of the first segment to fillet. \~ - \param[in] rad - \ru Радиус скругления. - \en The radius of fillet. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \return \ru true в случае успеха операции. - \en Returns true if the operation succeeded. \~ - */ - bool FilletTwoBasisSegments ( ptrdiff_t & index, double rad, - const StVertexOfMultilineInfo & vertInfo ); - - /** \brief \ru Скруглить базовую кривую. - \en Fillet the base curve. \~ - \details \ru Скруглить все углы базовой кривой.\n - \en Fillet all corners of the base curve.\n \~ - \param[in] rad - \ru Радиус скругления. - \en The radius of fillet. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \return \ru true, если добавилось хотя бы одно скругление. - \en True if at least one fillet is added. \~ - */ - bool FilletBasisCurve ( double rad, - const StVertexOfMultilineInfo & vertInfo ); - - /** \brief \ru Вставить фаску между двумя соседними сегментами базовой кривой мультилинии. - \en Insert a chamfer between two neighboring segments of the base curve of a multiline. \~ - \details \ru Вставить фаску между двумя соседними сегментами базовой кривой мультилинии.\n - \en Insert a chamfer between two neighboring segments of the base curve of a multiline.\n \~ - \param[in] index - \ru Индекс первого скругляемого сегмента. - \en Index of the first segment to fillet. \~ - \param[in] len - \ru Длина фаски. - \en Length of chamfer. \~ - \param[in] par - \ru Параметр в зависимости от типа type:\n - если type = true, par - угол\n - если type = false, par - размер. - \en Parameter depending on 'type' type:\n - if type = true, par is a corner\n - if type = false, par is a size. \~ - \param[in] type - \ru Тип задания фаски:\n - true - фаска задана как размер + угол,\n - false - фаска задана как размер + размер. - \en The type of a chamfer specification:\n - true - chamfer specified as size + angle,\n - false - chamfer specified as size + size. \~ - \param[in] firstSeg - \ru true, если параметр par относится к первому сегменту. - \en True if 'par' parameter is related to the first segment. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \return \ru true в случае успеха операции. - \en Returns true if the operation succeeded. \~ - */ - bool ChamferTwoBasisSegments ( ptrdiff_t & index, double len, double par, - bool type, bool firstSeg, - const StVertexOfMultilineInfo & vertInfo ); - - /** \brief \ru Вставить фаску между каждыми двумя соседними сегментами базовой кривой мультилинии. - \en Insert a chamfer between each two neighboring segments of the base curve of a multiline. \~ - \details \ru Вставить фаску между каждыми двумя соседними сегментами базовой кривой мультилинии.\n - Параметр par относится к первому сегменту из каждой пары. - \en Insert a chamfer between each two neighboring segments of the base curve of a multiline.\n - 'par' parameter is related to the first segment of each pair. \~ - \param[in] len - \ru Длина фаски. - \en Length of chamfer. \~ - \param[in] par - \ru Параметр в зависимости от типа type:\n - если type = true, par - угол,\n - если type = false, par - размер. - \en Parameter depending on 'type' type:\n - if type = true, par is a corner,\n - if type = false, par is a size. \~ - \param[in] type - \ru Тип задания фаски:\n - true - фаска задана как размер + угол,\n - false - фаска задана как размер + размер. - \en The type of a chamfer specification:\n - true - chamfer specified as size + angle,\n - false - chamfer specified as size + size. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \return \ru true, если добавилась хотя бы одна фаска. - \en True if at least one chamfer is added. \~ - */ - bool ChamferBasisCurve ( double len, double par, bool type, - const StVertexOfMultilineInfo & vertInfo ); ///< \ru Вставить фаску БК \en Insert chamfer of the base curve - - /** \} */ - /**\ru \name Функции изменения данных: изменение параметров вершины мультилинии - \en \name Functions for changing data: changing the parameters of a vertex of a multiline - \{ */ - - /** \brief \ru Установить флаг гладкого стыка. - \en Set the flag of smooth joint. \~ - \details \ru Установить флаг гладкого стыка в вершине.\n - \en Set the flag of smooth joint at a vertex.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] othSmoothJoint - \ru Флаг гладкого стыка. - \en Flag of smooth joint. \~ - */ - void SetSmoothJoint ( size_t i, bool othSmoothJoint ); - - /** \brief \ru Установить тип обхода. - \en Set the type of traverse. \~ - \details \ru Установить тип обхода вершины.\n - \en Set the type of traverse of the vertex.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] othTracingType - \ru Тип обхода. - \en Type of traverse. \~ - */ - void SetTracingType ( size_t i, EnMLVertexTracingType othTracingType ); - - /** \brief \ru Установить радиус специального скругления. - \en Set the radius of a special fillet. \~ - \details \ru Установить радиус специального скругления вершины мультилинии.\n - \en Set the radius of special fillet of a vertex of the multiline.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] othSpecFilletRad - \ru Радиус. - \en Radius. \~ - */ - void SetSpecFilletRad ( size_t i, double othSpecFilletRad ); - - /** \brief \ru Установить тип законцовки. - \en Set the type of a tip. \~ - \details \ru Установить тип законцовки (разделителя) в вершине.\n - \en Set the type of tip (splitter) at the vertex.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] othTipType - \ru Тип законцовки. - \en Type of tip. \~ - */ - void SetTipType ( size_t i, EnMLInnerTipType othTipType ); - - /** \brief \ru Установить направление законцовки. - \en Set the direction of a tip. \~ - \details \ru Установить направление законцовки в вершине мультилинии.\n - \en Set the direction of a tip at a vertex of multiline.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] othFirstSegTip - \ru Направление законцовки, если true - от первого сегмента. - \en Direction of tip, if true - from the first segment. \~ - */ - void SetTipDirection ( size_t i, bool othFirstSegTip ); - - /** \brief \ru Установить информацию о вершине. - \en Set the information about a vertex. \~ - \details \ru Установить информацию о вершине мультилинии.\n - \en Set the information about a vertex of multiline.\n \~ - \param[in] i - \ru Индекс вершины мультилинии. - \en An index of a vertex of a multiline. \~ - \param[in] vertInfo - \ru Информация о вершине. - \en Information about a vertex. \~ - */ - void SetVertexOfMultilineInfo ( size_t i, - const StVertexOfMultilineInfo & vertInfo ); - - /** \} */ - /**\ru \name Функции изменения данных: изменение радиусов эквидистант - \en \name Functions for changing data: changing the radii of equidistant curves - \{ */ - - /** \brief \ru Установить значение радиуса кривой. - \en Set the value of radius of curve. \~ - \details \ru Установить значение радиуса кривой.\n - \en Set the value of radius of curve.\n \~ - \param[in] i - \ru Индекс кривой мультилинии. - \en An index of curve of multiline. \~ - \param[in] radius - \ru Новое значение радиуса. - \en New value of the radius. \~ - \param[out] newIndex - \ru Новый индекс кривой. - \en New index of curve. \~ - \return \ru true, если радиус был изменен. - \en True if a radius has been changed. \~ - */ - bool SetRadius ( size_t i, double radius, size_t & newIndex ); - - /** \brief \ru Изменение всех радиусов кривых. - \en Changing all radii of curves. \~ - \details \ru Изменение одновременно всех радиусов кривых.\n - Значения радиусов будут изменены, если их количество в newRadii совпадает с количеством кривых. - \en Simultaneous changing all radii of curves.\n - Values of radii will be changed if their count in 'newRadii' is coincident to the count of curves. \~ - \param[in] newRadii - \ru Новые значения радиусов кривых. - \en New values of radii of curves. \~ - \return \ru true, если радиусы были изменены. - \en True if radii has been changed. \~ - */ - bool SetRadii ( const CSSArray & newRadii ); - - /** \brief \ru Изменение радиуса. - \en Change the radius. \~ - \details \ru Изменение радиуса кривой мультилинии.\n - \en Change the radius of a curve of multiline.\n \~ - \param[in] oldRadius - \ru Старое значение радиуса. - \en Old value of the radius. \~ - \param[in] radius - \ru Новое значение радиуса. - \en New value of the radius. \~ - */ - void ChangeRadius ( double oldRadius, double radius ); - - /** \brief \ru Добавление радиуса кривой мультилинии. - \en Add the radius of a curve of multiline. \~ - \details \ru Добавление радиуса кривой мультилинии.\n - Фактически, добавление кривой мультилинии. - \en Add the radius of a curve of multiline.\n - Actually, addition of a curve of multiline. \~ - \param[in] radius - \ru Значение радиуса. - \en Value of radius. \~ - \return \ru Значение индекса новой кривой\n - если кривая не была добавлена, индекс равен SYS_MAX_T. - \en Value of an index of the new curve.\n - if curve was not added, then the index is equal to SYS_MAX_T. \~ - */ - size_t AddRadius ( double radius ); - - /** \brief \ru Удаление кривой. - \en Delete a curve. \~ - \details \ru Удаление кривой мультилинии.\n - \en Delete a curve of multiline.\n \~ - \param[in] i - \ru Индекс кривой. - \en A curve index. \~ - \return \ru true, если кривая была удалена. - \en True if curve has been deleted. \~ - */ - bool RemoveRadius ( size_t i ); - - /** \brief \ru Удаление кривой. - \en Delete a curve. \~ - \details \ru Удаление кривой мультилинии.\n - \en Delete a curve of multiline.\n \~ - \param[in] oldRadius - \ru Радиус кривой. - \en Radius of a curve. \~ - \return \ru true, если кривая была удалена. - \en True if curve has been deleted. \~ - */ - bool RemoveRadius ( double oldRadius ); - - /** \} */ - /**\ru \name Функции изменения данных: изменение параметров законцовок - \en \name Functions for changing data: change the parameters of tips - \{ */ - - /** \brief \ru Изменение типа законцовки в начале. - \en Change the type of a tip at the beginning. \~ - \details \ru Изменение типа законцовки мультилинии в начале.\n - \en Change the type of a tip of multiline at the beginning.\n \~ - \param[in] othTipType - \ru Новый тип законцовки. - \en New type of tip. \~ - */ - void SetBegTipType ( EnMLTipType othTipType ); - - /** \brief \ru Изменение параметра законцовки в начале. - \en Change the parameter of a tip at the beginning. \~ - \details \ru Изменение параметра законцовки мультилинии в начале.\n - \en Change the parameter of a tip of multiline at the beginning.\n \~ - \param[in] othTipParam - \ru Новый параметр законцовки. - \en New parameter of tip. \~ - */ - void SetBegTipParam ( double othTipParam ); - - /** \brief \ru Изменение типа законцовки в конце. - \en Change the type of a tip at the end. \~ - \details \ru Изменение типа законцовки мультилинии в конце.\n - \en Change the type of a tip of multiline at the end.\n \~ - \param[in] othTipType - \ru Новый тип законцовки. - \en New type of tip. \~ - */ - void SetEndTipType ( EnMLTipType othTipType ); - - /** \brief \ru Изменение параметра законцовки в конце. - \en Change the parameter of a tip at the end. \~ - \details \ru Изменение параметра законцовки мультилинии в конце.\n - \en Change the parameter of a tip of multiline at the end.\n \~ - \param[in] othTipParam - \ru Новый параметр законцовки. - \en New parameter of tip. \~ - */ - void SetEndTipParam ( double othTipParam ); - - /** \} */ - /**\ru \name Функции изменения данных - \en \name Functions for changing data - \{ */ - - /** \brief \ru Изменение обработки замкнутости. - \en Change the closedness processing. \~ - \details \ru Изменение флага обработки замкнутости.\n - \en Change the flag of the closedness processing.\n \~ - \param[in] othProcessClosed - \ru Флаг обработки замкнутости. - \en Flag of the closedness processing. \~ - */ - void SetProcessClosed ( bool othProcessClosed ); - - /** \brief \ru Изменение прозрачности мультилинии. - \en Change the transparency of multiline. \~ - \details \ru Изменение флага прозрачности мультилинии.\n - \en Change the flag of transparency of multiline.\n \~ - \param[in] othTransparent - \ru Флаг прозрачности. - \en Transparency flag. \~ - */ - void SetTransparent ( bool othTransparent ); - - /** \} */ - /**\ru \name Работа с разрывами: добавление разрывов - \en \name Working with breaks: addition of breaks - \{ */ - - /** \brief \ru Усечение части кривой мультилинии между точками. - \en Trimming of a piece of a curve of multiline between points. \~ - \details \ru Усечение части кривой мультилинии между точками.\n - Добавление разрыва. - \en Trimming of a piece of a curve of multiline between points.\n - Add a break. \~ - \param[in] contour - \ru Кривая мультилинии для добавления разрыва. - \en Curve of multiline for addition of a break. \~ - \param[in] point1 - \ru Первая граница разрыва. - \en The first boundary of the break. \~ - \param[in] point2 - \ru Вторая граница разрыва. - \en The second boundary of the break. \~ - \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n - в случае разомкнутого контура она игнорируется. - \en The point indicating the piece of a closed contour to be deleted,\n - ignored in case of the opened contour. \~ - \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. - \en If 'true', then the break is applied to the opposite piece of the contour. \~ - \return \ru true, если разрыв был добавлен. - \en True if a break has been added. \~ - */ - bool DeletePartP1P2 ( MbContourWithBreaks * contour, - const MbCartPoint & point1, - const MbCartPoint & point2, - const MbCartPoint & point3, - bool invertBreak = false ); - - /** \brief \ru Усечение части кривой мультилинии между точками. - \en Trimming of a piece of a curve of multiline between points. \~ - \details \ru Усечение части кривой мультилинии между точками.\n - Добавление разрыва. - \en Trimming of a piece of a curve of multiline between points.\n - Add a break. \~ - \param[in] cNumber - \ru Номер кривой мультилинии для добавления разрыва. - \en Index of curve of multiline for addition of a break. \~ - \param[in] point1 - \ru Первая граница разрыва. - \en The first boundary of the break. \~ - \param[in] point2 - \ru Вторая граница разрыва. - \en The second boundary of the break. \~ - \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n - в случае разомкнутого контура она игнорируется. - \en The point indicating the piece of a closed contour to be deleted,\n - ignored in case of the opened contour. \~ - \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. - \en If 'true', then the break is applied to the opposite piece of the contour. \~ - \return \ru true, если разрыв был добавлен. - \en True if a break has been added. \~ - */ - bool DeletePartP1P2 ( size_t cNumber, - const MbCartPoint & point1, - const MbCartPoint & point2, - const MbCartPoint & point3, - bool invertBreak = false ); - - /** \brief \ru Усечение части кривой мультилинии между параметрами контура. - \en Trimming of a piece of a curve of multiline between parameters of contour. \~ - \details \ru Усечение части кривой мультилинии между параметрами контура.\n - Добавление разрыва. - \en Trimming of a piece of a curve of multiline between parameters of contour.\n - Add a break. \~ - \param[in] cNumber - \ru Номер кривой мультилинии для добавления разрыва. - \en Index of curve of multiline for addition of a break. \~ - \param[in] t1 - \ru Первая граница разрыва. - \en The first boundary of the break. \~ - \param[in] t2 - \ru Вторая граница разрыва. - \en The second boundary of the break. \~ - \param[in] t3 - \ru Параметр, который показывает удаляемую часть замкнутого контура,\n - в случае разомкнутого контура он игнорируется. - \en A parameter which indicates a removable part of the closed contour, \n - ignored in case of opened contour. \~ - \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. - \en If 'true', then the break is applied to the opposite piece of the contour. \~ - \return \ru true, если разрыв был добавлен. - \en True if a break has been added. \~ - */ - bool DeletePartP1P2 ( size_t cNumber, - double t1, double t2, double t3, - bool invertBreak = false ); - - /** \} */ - /**\ru \name Работа с разрывами: удаление разрывов - \en \name Working with breaks: deletion of breaks - \{ */ - - /** \brief \ru Удалить разрывы. - \en Remove breaks. \~ - \details \ru Удалить все разрывы мультилинии.\n - \en Delete all breaks of multiline.\n \~ - \return \ru true, если хотя бы один разрыв был удален. - \en true, if at least one break has been deleted. \~ - */ - bool DeleteBreaks ( ); - - /** \brief \ru Удалить разрывы кривой. - \en Remove breaks of curve. \~ - \details \ru Удалить все разрывы кривой мультилинии.\n - \en Delete all breaks of curve of multiline.\n \~ - \param[in] cNumber - \ru Номер кривой. - \en Index of curve. \~ - \return \ru true, если хотя бы один разрыв был удален. - \en true, if at least one break has been deleted. \~ - */ - bool DeleteBreaks ( size_t cNumber ); - - /** \brief \ru Удалить разрыв кривой. - \en Delete a break of curve. \~ - \details \ru Удалить разрыв по параметру на кривой.\n - \en Delete a break by a parameter on the curve.\n \~ - \param[in] cNumber - \ru Номер кривой. - \en Index of curve. \~ - \param[in] t - \ru Параметр на кривой. - \en A parameter on the curve. \~ - \return \ru true, если разрыв был удален. - \en True if a break has been deleted. \~ - */ - bool DeleteBreak ( size_t cNumber, double t ); - - /** \brief \ru Удалить разрыв. - \en Delete a break. \~ - \details \ru Удалить разрыв по номеру.\n - \en Delete a break by an index.\n \~ - \param[in] cNumber - \ru Номер кривой. - \en Index of curve. \~ - \param[in] brNumber - \ru Номер разрыва на кривой. - \en Index of a break on the curve. \~ - \return \ru true, если разрыв был удален. - \en True if a break has been deleted. \~ - */ - bool DeleteBreakAtNumber ( size_t cNumber, size_t brNumber ); - - /** \brief \ru Удалить разрывы малой длины. - \en Delete breaks of small length. \~ - \details \ru Удалить разрывы малой метрической длины у кривой мультилинии.\n - В случае успеха линия мультилинии перестраивается соответственно разрывам. - \en Delete breaks of small length of a curve of multiline.\n - In case of success the line of multiline is rebuilt according to breaks. \~ - \param[in] cNumber - \ru Номер кривой мультилинии. - \en Index of a curve of multiline. \~ - \param[in] length - \ru Минимальная длина невидимой части. - \en Minimal length of invisible piece. \~ - \return \ru true, если хотя бы один разрыв кривой был удален. - \en True if at least one break of the curve has been deleted. \~ - */ - bool DeleteSmallBreaks ( size_t cNumber, double length ); - - /** \brief \ru Удалить малые видимые части. - \en Delete small visible pieces. \~ - \details \ru Удалить видимые части малой метрической длины у кривой мультилинии.\n - Соответствует объединению близких разрывов в один. - В случае успеха видимые контуры кривой перестраиваются соответственно разрывам. - \en Delete small visible pieces of a curve of multiline with small metric length.\n - Corresponds to union of close breaks into one. - In case of success the visible contours of the line is rebuilt according to breaks. \~ - \param[in] cNumber - \ru Номер кривой мультилинии. - \en Index of a curve of multiline. \~ - \param[in] length - \ru Минимальная длина видимой части. - \en Minimal length of visible piece. \~ - \return \ru true, если разрывы кривой были изменены. - \en True if breaks has been changed. \~ - */ - bool DeleteSmallVisContours ( size_t cNumber, double length ); - - /** \} */ - /**\ru \name Работа с разрывами - \en \name Working with breaks - \{ */ - - /** \brief \ru Находится ли интервал на разрыве. - \en Whether the interval is on a break. \~ - \details \ru Находится ли интервал параметров на разрыве кривой.\n - \en Whether the interval of parameters is on a break of a curve.\n \~ - \param[in] cNumber - \ru Номер кривой мультилинии. - \en Index of a curve of multiline. \~ - \param[in] rect - \ru Интервал для проверки. - \en Interval to check. \~ - \return \ru true, если интервал полностью находится на разрыве или совпадает с ним. - \en True if interval entirely is on the break or coincides with it. \~ - */ - bool IsRectInBreak ( size_t cNumber, const MbRect1D & rect ); - - /** \brief \ru Запомнить разрывы. - \en Memorize the breaks. \~ - \details \ru Запомнить разрывы невидимыми контурами.\n - Для использования в паре с AddBreaksByInvisContours.\n - Удаляет все разрывы мультилинии.\n - Все контуры invisContours имеют счетчик ссылок = 1 (вызван AddRef()). - \en Memorize the breaks as invisible contours.\n - For using together with AddBreaksByInvisContours.\n - Deletes all breaks of multiline.\n - All 'invisContours' contours has a reference counter = 1 (called AddRef()). \~ - \param[out] invisContours - \ru Набор невидимых контуров всех кривых мультилинии. - \en Set of invisible contours of all curves of multiline. \~ - */ - void GetBreaksInInvisContours( RPArray & invisContours ); - - /** \brief \ru Добавить разрывы. - \en Add breaks. \~ - \details \ru Добавить разрывы невидимыми контурами.\n - Для использования в паре с GetBreaksInInvisContours.\n - Контуры invisContours удаляются (вызывается Release()).\n - Данной функцией можно наложить разрывы на мультилинию, - если они были получены методом GetBreaksInInvisContours у этой мультилинии - и форма мультилинии не была изменена. - \en Add the breaks as invisible contours.\n - For using together with GetBreaksInInvisContours.\n - 'invisContours' contours are deleted (called Release()).\n - It is possible to apply breaks to multiline by this function, - if they were obtained by GetBreaksInInvisContours method from this multiline - and shape of multiline wasn't changed. \~ - \param[in] invisContours - \ru Набор невидимых контуров всех кривых мультилинии. - \en Set of invisible contours of all curves of multiline. \~ - */ - void AddBreaksByInvisContours( RPArray & invisContours ); - - /** \brief \ru Номера контуров, пересекаемых отрезком. - \en Indices of contours intersected with a segment. \~ - \details \ru Номера контуров, которые пересекаются с отрезком по двум точкам.\n - \en Indices of contours which are intersected with segment by two points.\n \~ - \param[in] p1 - \ru Первая точка отрезка. - \en The first point of a segment. \~ - \param[in] p2 - \ru Вторая точка отрезка. - \en The second point of a segment. \~ - \param[out] cNumbers - \ru Номера контуров. - \en Indices of contours. \~ - */ - void CurvesIntersectNumbers ( const MbCartPoint & p1, const MbCartPoint & p2, SArray & cNumbers ) const; - - /** \} */ - /**\ru \name Информация о мультилинии - \en \name Information about multiline. - \{ */ - - /// \ru Вырождена ли мультилиния. \en Whether the multiline is degenerate. - bool IsDegenerate( double lenEps = Math::LengthEps ) const; - /// \ru Замкнутая ли мультилиния. \en Whether the multiline is closed. - bool IsClosed () const; - /// \ru Получить ширину мультилинии. \en Get width of multiline. - double GetWidth () const; - /// \ru Лежит ли данная точка на мультилинии. \en Whether the given point is on multiline. - bool IsPointOn ( const MbCartPoint & point ) const; - - /** \brief \ru Найти индекс кривой мультилинии. - \en Find an index of a curve of multiline. \~ - \details \ru Найти индекс кривой мультилинии.\n - \en Find an index of a curve of multiline.\n \~ - \param[in] radius - \ru Радиус нужной кривой. - \en Radius of the required curve. \~ - \return \ru Индекс кривой. - \en A curve index. \~ - */ - size_t FindRadius ( double radius ); - - /** \} */ - /**\ru \name Операции с мультилинией - \en \name Operations with multiline - \{ */ - - /** \brief \ru Усечь мультилинию. - \en Truncate multiline. \~ - \details \ru Усечь мультилинию.\n - Вернуть мультилинию, базовая кривая которой - - копия участка между параметрами t1 и t2 базовой данной мультилинии. - \en Truncate multiline.\n - Return multiline which base curve is - a copy of piece between parameters t1 and t2 of the base curve of a given multiline. \~ - \param[in] t1 - \ru Начальный параметр усечения. - \en Start parameter of trimming. \~ - \param[in] t2 - \ru Конечный параметр усечения. - \en End parameter of trimming. \~ - \param[in] sense - \ru Направление усеченной базовой кривой. - \en Direction of the trimmed base curve. \~ - \return \ru Новую мультилинию. - \en New multiline. \~ - */ - MbMultiline * Trimmed( double t1, double t2, int sense ) const; - - /** \} */ -private: - /**\ru \name Внутренние функции мультилинии - \en \name Internal functions of multiline - \{ */ - - // \ru Все внутренние функции реализованы в MltLine_.cpp (кроме тех, для которых указан другой файл) \en All internal functions implemented in MltLine_.cpp (except ones for which the other file is specified) - // \ru Насчет объектов \en Calculation of objects - /// \ru Насчитать кривую мультилинии c радиусом эквидистанты rad. \en Calculate curve of multiline with 'rad' equidistant radius. - void CalculateCurve ( double rad, MbContourWithBreaks & contour ); - /// \ru Насчитать кривую мультилинии c радиусом эквидистанты rad c заполнением информации. \en Calculate curve of multiline with equidistant radius 'rad' and filling the information. - void CalculateCurveWithInfo ( double rad, MbContourWithBreaks & contour, - SArray & baseIndexes ); - /// \ru Насчитать все кривые (с определением minNotDegInd и maxNotDegInd). \en Calculate all the curves (with determination of minNotDegInd and maxNotDegInd). - void CalculateCurves (); - /// \ru Насчитать все кривые с информацией для граничных невырожденных кривых. \en Calculate all the curves with information for non-degenerate boundary curves. - bool CalculateCurvesWithInfo ( SArray & minInfo, SArray & maxInfo ); - /// \ru Насчитать все законцовки в вершинах. \en Calculate all tips at vertices. - void CalculateTipCurves ( const SArray & minInfo, const SArray & maxInfo ); - /// \ru Насчитать все законцовки в вершинах. \en Calculate all tips at vertices. - void CalculateTipCurves (); - /// \ru Насчитать все кривые и все законцовки в вершинах. \en Calculate all curves and all tips at vertices. - void CalculateCurvesAndTipCurves(); - /// \ru Насчитать законцовку в начале. \en Calculate tip at the beginning. - void CalculateBegTipCurve ( SArray * changeCurvesNumbers = NULL ); - /// \ru Насчитать законцовку в конце. \en Calculate tip at the end. - void CalculateEndTipCurve (); - - // \ru Отцепление объектов \en Detach the objects - - /// \ru Отцепить все кривые. \en Detach all curves. - void DeleteCurves (); - /// \ru Отцепить кривую с индексом i. \en Detach i-th curve. - void DeleteCurve ( size_t i ); - /// \ru Отцепить все законцовки в вершинах. \en Detach all tips at vertices. - void DeleteTipCurves (); - /// \ru Отцепить законцовку в вершине с индексом i. \en Detach i-th tip at vertex. - void DeleteTipCurve ( size_t i ); - /// \ru Отцепить законцовку в начале. \en Detach tip at the beginning. - void DeleteBegTipCurve (); - /// \ru Отцепить законцовку в конце. \en Detach tip at the end. - void DeleteEndTipCurve (); - /// \ru Отцепить все объекты. \en Detach all the objects. - void DeleteAllObjects (); - - // \ru Пересчет объектов \en Recalculation of objects - - /// \ru Перестроить все объекты. \en Rebuild all objects. - void RebuildAllObjects (); - - // \ru Обработки изменения vertices (без перестроения) \en Processing of 'vertices' changing (without rebuilding) - void AddVert ( const StVertexOfMultilineInfo & vertInfo ); - void InsertVert ( size_t i, const StVertexOfMultilineInfo & vertInfo ); - void ChangeVert ( size_t i, const StVertexOfMultilineInfo & vertInfo ); - void RemoveVert ( size_t i ); - - // \ru Вспомогательные функции \en Auxiliary functions - - /// \ru Обработать изменение i-ого сегмента БК. \en Process change of i-th segment of base curve. - void CalculateChangeOfSegment ( size_t i ); - /// \ru Продлить кривую до законцовок. \en Extend curve to the tips. - void ProlongCurveToTips ( size_t i ); - /// \ru Рассчитать удаление i-ой кривой (обработка). \en Calculate removal of i-th curve (processing). - void CalculateRemovalOfCurve ( size_t i ); - - // \ru Скругление/фаска двух соседних сегментов БК (реализация в MLOper.cpp) \en Fillet/chamfer of two neighboring segments of the base curve (implementation in MLOper.cpp) - bool FilletOrChamferTwoBasisSegs( ptrdiff_t & index, const StVertexOfMultilineInfo & vertInfo, - bool fillet, bool recalcCrvRadii, - double param, - double par = 0.0, bool type = false, bool firstSeg = true ); - - // \ru Работа с разрывами \en Working with breaks - // \ru Работа с разрывами при редактировании (сохранение фиксированной точки и длины) \en Working with breaks while editing (preserving of fixed point and length) - void SetBreaksFixedVars ( size_t segInd, size_t subInd, const MbCartPoint & newPoint ); - void TransformBreaks ( const MbMatrix & matr ); - - // \ru Удалить разрывы на сегментах контура, с соотв. базовым номером \en Delete breaks on segments of contour with corresponding base index - void DeleteBreaksAtBaseNumber ( size_t baseNumber, bool delTracingBreaks, bool delEquidBreaks, - bool delInLineSeg = true/*\ru Удалять ли разрывы с прямолинейных сегментов - \en Whether to remove breaks from straight segments \~*/ ); - - // \ru Функции восстановления разрывов по невидимым контурам \en Functions for recovering breaks by invisible contours - void GetBreaksInInvisContours( bool allBreaks, // \ru Удалять все разырвы \en Delete all breaks - size_t i, // \ru Номер вершины, специально для изменения типа обхода \en Index of vertex, specially for changing the type of traverse \~ - bool addContWbr, // \ru Набирать контуры с разрывами \en Collect contours with breaks - RPArray & breaksContours, - RPArray & invisContours ); - void AddBreaksByInvisContours( RPArray & breaksContours, - RPArray & invisContours ); - // \ru Для перестроения разрывов \en For breaks rebuilding - void GetBreaks ( RPArray & baseNumbers ); - void RebuildBreaks ( RPArray & baseNumbers ); - - /** \} */ -private: - void operator =( const MbMultiline & ); ///< \ru Не реализован \en Not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMultiline ) -}; // MbMultiline - -IMPL_PERSISTENT_OPS( MbMultiline ) - -//------------------------------------------------------------------------------ -// _7_ -/** \brief \ru Построить скругления мультилинии. - \en Construct a fillet of multiline. \~ - \details \ru Построить скругления базовой кривой мультилинии.\n - \en Construct a fillet of the base curve of multiline.\n \~ - \param[in] multiline - \ru Изменяемая мультилиния. - \en A multiline to be modified. \~ - \param[in] rad - \ru Радиус скругления. - \en The radius of fillet. \~ - \param[in] nodeFlag - \ru Флаг выбора скругляемых вершин:\n - true - скругление всех вершин мультилинии,\n - false - скругление ближайшей вершины к точке pnt. - \en Flag of selection of vertices to fillet:\n - true - fillet of all vertices of multiline,\n - false - fillet of the vertex nearest to 'pnt' point. \~ - \param[in] pnt - \ru Точка для указания нужной вершины. - \en Point for indication the required vertex. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \ingroup Algorithms_2D -*/ // --- -MATH_FUNC (bool) FilletMultiline ( MbMultiline & multiline, double rad, - bool nodeFlag, MbCartPoint & pnt, - const StVertexOfMultilineInfo & vertInfo ); - - -//------------------------------------------------------------------------------ -// _8_ -/** \brief \ru Построить фаски мультилинии. - \en Construct a chamfer of multiline. \~ - \details \ru Построить фаски базовой кривой мультилинии.\n - \en Construct a chamfer of the base curve of multiline.\n \~ - \param[in] multiline - \ru Изменяема мультилиния. - \en A multiline to be modified. \~ - \param[in] len - \ru Длина фаски. - \en Length of chamfer. \~ - \param[in] par - \ru Параметр в зависимости от типа type:\n - если type = true, par - угол,\n - если type = false, par - размер. - \en Parameter depending on 'type' type:\n - if type = true, par is a corner,\n - if type = false, par is a size. \~ - \param[in] type - \ru Тип задания фаски:\n - true - фаска задана как размер + угол,\n - false - фаска задана как размер + размер. - \en The type of a chamfer specification:\n - true - chamfer specified as size + angle,\n - false - chamfer specified as size + size. \~ - \param[in] nodeFlag - \ru Флаг выбора обрабатываемых вершин:\n - true - фаска между каждыми двумя соседними сегментами мультилинии,\n - false - фаска между двумя соседними сегментами мультилинии, примыкающими к ближайшей к точке pnt вершине. - \en Flag of selection of vertices to process:\n - true - chamfer between each two neighboring segments of multiline,\n - false - chamfer between two neighboring multiline segments joining at the vertex nearest to 'pnt' point. \~ - \param[in] pnt - \ru Точка для указания нужной пары сегментов. - \en Point for indication the required pair of segments. \~ - \param[in] vertInfo - \ru Информация для новых вершин мультилинии. - \en Information for new vertices of a multiline. \~ - \ingroup Algorithms_2D -*/ // --- -MATH_FUNC (bool) ChamferMultiline( MbMultiline & multiline, double len, double par, bool type, - bool nodeFlag, MbCartPoint & pnt, - const StVertexOfMultilineInfo & vertInfo ); - - -//////////////////////////////////////////////////////////////////////////////// -// -// _9_ -/// \ru Внеклассные функции расчета/учета радиусов кривизны (реализация в MltLine.cpp) \en Out-of-class functions for curvature radii calculation/consideration (implementation in MltLine.cpp) -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -/** \brief \ru Учесть радиусы кривизны кривой. - \en Consider the curve curvature radii. \~ - \details \ru Учесть минимальный положительный и максимальный отрицательный радиусы кривизны кривой.\n - Для внутреннего использования. - \en Consider the curve curvature minimum positive and maximum negative radii.\n - For internal use only. \~ - \param[in] curve - \ru Кривая мультилинии. - \en A curve of multiline. \~ - \param[in] angle - \ru Угловая толерантность. - \en An angular tolerance. \~ - \param[in, out] minPos - \ru Радиус кривой, если он меньше текущего значения переменной minPos. - \en Curve radius if it is less than current value of 'minPos' variable. \~ - \param[in, out] maxNeg - \ru Радиус кривой, если он больше текущего значения переменной minPos. - \en Curve radius if it is greater than current value of 'minPos' variable. \~ - \ingroup Algorithms_2D -*/ // --- -void ToTakeIntoCurvesCrvRadii( MbCurve & curve, double angle, double & minPos, double & maxNeg ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Получить радиусы кривизны контура. - \en Get the contour curvatures radii. \~ - \details \ru Получить минимальный положительный и максимальный отрицательный радиусы кривизны контура.\n - Для внутреннего использования. - \en Get the contour curvature minimum positive and maximum negative radii.\n - For internal use only. \~ - \param[in] contour - \ru Контур. - \en A contour. \~ - \param[in] angle - \ru Угловая толерантность. - \en An angular tolerance. \~ - \param[out] minPos - \ru Минимальный радиус сегмента контура. - \en Minimal contour segment radius. \~ - \param[out] maxNeg - \ru Максимальный радиус сегмента контура. - \en Maximal contour segment radius. \~ - \ingroup Algorithms_2D -*/ // --- -void GetContoursCrvRadii( MbContour & contour, double angle, double & minPos, double & maxNeg ); - - -//------------------------------------------------------------------------------ -// _10_ -/** \brief \ru Состыковать две кривые. - \en Join two curves. \~ - \details \ru Гладко состыковать две последовательные кривые.\n - Для внутреннего использования. - \en Smoothly join two consecutive curves.\n - For internal use only. \~ - \param[in] curve1 - \ru Первая кривая. - \en The first curve. \~ - \param[in] curve2 - \ru Вторая кривая. - \en The second curve. \~ - \return \ru true, если хотя бы одна кривая была изменена. - \en True if at least one curve has been changed. \~ - \ingroup Algorithms_2D -*/ // --- -bool SmoothJointSuccessiveCurves( MbCurve & curve1, MbCurve & curve2 ); - - -//------------------------------------------------------------------------------ -// _11_ -/** \brief \ru Разбить мультилинию. - \en Split multiline. \~ - \details \ru Разбить мультилинию на две части. - \en Split multiline into two pieces. \~ - \param[in] multiline - \ru Разбиваемая мультилиния. - \en A multiline to be split. \~ - \param[in] p1 - \ru Точка разбиения или, если мультилиния замкнута, начальная точка для новой мультилинии. - \en Splitting point or start point of a new multiline if the multiline is closed. \~ - \param[in] p2 - \ru Если мультилиния замкнута, то конечная точка для новой мультилинии. - \en End point of a new multiline if the multiline is closed. \~ - \param[out] parts - \ru Массив полученных участков (2 элемента). - \en The array of obtained pieces (two elements). \~ - \ingroup Algorithms_2D -*/ // --- -MATH_FUNC (bool) BreakMultiline( const MbMultiline & multiline, - const MbCartPoint & p1, const MbCartPoint & p2, - PArray & parts ); - - -//------------------------------------------------------------------------------ -// _12_ -/** \brief \ru Разбить мультилинию. - \en Split multiline. \~ - \details \ru Разбить мультилинию на N равных частей. - \en Split multiline into N equal pieces. \~ - \param[in] multiline - \ru Разбиваемая мультилиния. - \en A multiline to be split. \~ - \param[in] partsCount - \ru Количество частей. - \en The count of pieces. \~ - \param[in] point - \ru Ограничивающая точка для замкнутой мультилинии. - \en Bounding point for closed multiline. \~ - \param[out] parts - \ru Массив полученных участков (partsCount элементов). - \en The array of obtained pieces (partsCount elements). \~ - \ingroup Algorithms_2D -*/ // --- -MATH_FUNC (bool) BreakMultilineNParts( const MbMultiline & multiline, size_t partsCount, - const MbCartPoint & point, PArray & parts ); - -// \ru LF-Linux: inline-функции следует помещать в заголовочный файл, а не cpp! \en LF-Linux: inline-functions should be placed in the header file instead of cpp! -//------------------------------------------------------------------------------- -/// \ru Вырождена ли мультилиния \en Whether the multiline is degenerate -// --- -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)) ); -} - - -//------------------------------------------------------------------------------- -/// \ru Замкнутая ли мультилиния \en Whether the multiline is closed -// --- -inline bool MbMultiline::IsClosed() const { - return ( basisCurve->IsClosed() && processClosed && basisCurve->GetSegmentsCount() > 1 ); -} - - -//------------------------------------------------------------------------------- -/// \ru Получить ширину мультилинии \en Get width of multiline -// --- -inline double MbMultiline::GetWidth() const -{ - if ( minNotDegInd == maxNotDegInd ) - return 0.0; - else - return ( equidRadii[maxNotDegInd] - equidRadii[minNotDegInd] ); -} - -//------------------------------------------------------------------------------- -/// \ru Обход скруглением (одним из) \en Traverse by fillet (one of) -// --- -inline bool StVertexOfMultilineInfo::IsFilletTracing() const -{ - return ( tracingType == mvt_FilletType || tracingType == mvt_SpecFilletType ); -} - - -//------------------------------------------------------------------------------- -/// -// --- -inline bool StVertexOfMultilineInfo::operator ==( const StVertexOfMultilineInfo & with ) const -{ - return smoothJoint == with.smoothJoint && - tracingType == with.tracingType && - ::fabs(specFilletRad - with.specFilletRad) < EXTENT_REGION && - tipType == with.tipType && - firstSegTip == with.firstSegTip; -} - - -//------------------------------------------------------------------------------- -/// -// --- -inline bool StVertexOfMultilineInfo::operator !=( const StVertexOfMultilineInfo & with ) const -{ - return !(*this == with); -} - - -//------------------------------------------------------------------------------- -/// \ru Инициализация по объекту \en Initialization by object -// --- -inline void StVertexOfMultilineInfo::Init( const StVertexOfMultilineInfo & other ) -{ - smoothJoint = other.smoothJoint; - tracingType = other.tracingType; - specFilletRad = other.specFilletRad; - tipType = other.tipType; - firstSegTip = other.firstSegTip; -} - - -//------------------------------------------------------------------------------- -/// \ru Инициализация по параметрам \en Initialize by parameters -// --- -inline void StVertexOfMultilineInfo::Init( bool _smoothJoint, EnMLVertexTracingType _tracingType, - double _specFilletRad, EnMLInnerTipType _tipType, - bool _firstSegTip ) -{ - smoothJoint = _smoothJoint; - tracingType = _tracingType; - specFilletRad = _specFilletRad; - tipType = _tipType; - firstSegTip = _firstSegTip; -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить флаг "гладкий стык" (smoothJoint) \en Change flag "smooth joint" (smoothJoint) -// --- -inline bool StVertexOfMultilineInfo::ChangeSmoothJoint( bool othSmoothJoint ) -{ - if ( smoothJoint == othSmoothJoint ) - return false; - else { - smoothJoint = othSmoothJoint; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить тип обхода углов в вершине (tracingType) \en Change type of traverse of corners at a vertex (tracingType) -// --- -inline bool StVertexOfMultilineInfo::ChangeTracingType( EnMLVertexTracingType othTracingType ) -{ - if ( tracingType == othTracingType ) - return false; - else { - tracingType = othTracingType; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить радиус особого скругления (specFilletRad) \en Change radius of special fillet (specFilletRad) -// --- -inline bool StVertexOfMultilineInfo::ChangeSpecFilletRad( double othSpecFilletRad ) -{ - if ( ::fabs(specFilletRad - othSpecFilletRad) < Math::LengthEps ) - return false; - else { - specFilletRad = othSpecFilletRad; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить тип законцовки (tipType) \en Change type of tip (tipType) -// --- -inline bool StVertexOfMultilineInfo::ChangeTipType( EnMLInnerTipType othTipType ) -{ - if ( tipType == othTipType ) - return false; - else { - tipType = othTipType; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить флаг сегмента законцовки (isFirstSegTip) \en Change flag of segment of tip (isFirstSegTip) -// --- -inline bool StVertexOfMultilineInfo::ChangeFirstSegTip( bool othFirstSegTip ) -{ - if ( firstSegTip == othFirstSegTip ) - return false; - else { - firstSegTip = othFirstSegTip; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Преобразовать объект согласно матрице \en Transform an object according to the matrix -// --- -inline void StVertexOfMultilineInfo::Transform( const MbMatrix & matr ) -{ - matr.TransformScalarX( specFilletRad ); // \ru Преобразовать радиус \en Transform radius -} - - -//------------------------------------------------------------------------------- -/// -// --- -inline bool StMLTipParams::operator ==( const StMLTipParams & with ) const -{ - return (tipType == with.tipType ) && - ::fabs(tipParam - with.tipParam) < EXTENT_REGION; -} - - -//------------------------------------------------------------------------------- -/// -// --- -inline bool StMLTipParams::operator !=( const StMLTipParams & with ) const -{ - return !(*this == with); -} - - -//------------------------------------------------------------------------------- -/// \ru Инициализация \en Initialization -// --- -inline void StMLTipParams::Init( const StMLTipParams & other ) -{ - tipType = other.tipType; - tipParam = other.tipParam; -} - - -//------------------------------------------------------------------------------- -/// \ru Инициализация \en Initialization -// --- -inline void StMLTipParams::Init( EnMLTipType _tipType, double _tipParam ) -{ - tipType = _tipType; - tipParam = _tipParam; -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить тип законцовки (tipType) \en Change type of tip (tipType) -// --- -inline bool StMLTipParams::ChangeTipType( EnMLTipType othTipType ) -{ - if ( tipType == othTipType ) - return false; - else { - tipType = othTipType; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Изменить параметр законцовки (tipParam) \en Change parameter of tip (tipParam) -// --- -inline bool StMLTipParams::ChangeTipParam( double othTipParam ) -{ - if ( ::fabs(tipParam - othTipParam) < Math::LengthEps ) - return false; - else { - tipParam = othTipParam; - return true; - } -} - - -//------------------------------------------------------------------------------- -/// \ru Преобразовать объект согласно матрице \en Transform an object according to the matrix -// --- -inline void StMLTipParams::Transform( const MbMatrix & matr ) -{ - matr.TransformScalarX( tipParam ); // \ru Преобразовать расстояние \en Transform distance -} - - -#endif // __MULTILINE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Мультилиния. + \en Multiline. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// \ru Заголовочный файл мультилинии cодержит следующие разделы. \en Header file of multiline contains the following sections. +// \ru _1_ EnMLVertexTracingType - тип обхода углов в вершине мультилинии \en _1_ EnMLVertexTracingType - type of traverse of corners at a vertex of multiline +// \ru _2_ EnMLInnerTipType - тип внутренней законцовки мультилинии \en _2_ EnMLInnerTipType - type of inner tip of multiline +// \ru _3_ EnMLTipType - тип законцовки мультилинии \en _3_ EnMLTipType - type of tip of multiline +// \ru _4_ StMLTipParams - структура параметров законцовки мультилинии \en _4_ StMLTipParams - tip of multiline parameters structure +// \ru _5_ StVertexOfMultilineInfo - информация о вершине мультилинии \en _5_ StVertexOfMultilineInfo - information about vertex of multiline +// \ru _6_ MbMultiline - класс мультилиния \en _6_ MbMultiline - multiline class +// \ru _7_ Функция построения скругления базовой кривой мультилинии \en _7_ Function for multiline base curve fillet construction +// \ru _8_ Функция построения фаски базовой кривой мультилинии \en _8_ Function for multiline base curve chamfer construction +// \ru _9_ Внеклассные функции расчета/учета радиусов кривизны \en _9_ Out-of-class functions for curvature radii calculation/consideration +// \ru _10_ Внеклассная функция гладкого стыка двух последовательных кривых \en _10_ Out-of-class function for smooth joint of two consecutive curves +// \ru _11_ Разбить мультилинию на две части \en _11_ Split multiline into two pieces +// \ru _12_ Разбить мультилинию на N равных частей \en _12_ Split multiline into N equal pieces +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MULTILINE_H +#define __MULTILINE_H + + +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +// _1_ +/** \brief \ru Тип обхода углов. + \en Type of traverse of corners. \~ + \details \ru Тип обхода углов в вершине мультилинии.\n + \en Type of traverse of corners at a vertex of multiline.\n \~ + \ingroup Algorithms_2D +*/ // --- +enum EnMLVertexTracingType { + mvt_ShearType, ///< \ru Обход срезом. \en Traverse by shear. + mvt_FilletType, ///< \ru Обход со скруглением. \en Traverse by fillet. + mvt_SpecFilletType, ///< \ru Обход со скруглением заданным радиусом. \en Traverse by fillet with a given radius. + // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! +}; + + +//------------------------------------------------------------------------------ +// _2_ +/** \brief \ru Тип внутренней законцовки. + \en Type of inner tip. \~ + \details \ru Тип внутренней законцовки мультилинии.\n + \en Type of inner tip of multiline.\n \~ + \ingroup Algorithms_2D +*/ // --- +enum EnMLInnerTipType { + mit_UndefTip, ///< \ru Законцовки нет. \en No tip. + mit_VerticesTip, ///< \ru Законцовка между соответствующими вершинами. \en Tip between corresponding vertices. + mit_LinearTip, ///< \ru Линейная законцовка. \en Linear tip. + mit_ArcTip, ///< \ru Дуговая законцовка. \en Arc tip. + // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! +}; + + +//------------------------------------------------------------------------------ +// _3_ +/** \brief \ru Тип законцовки. + \en Type of tip. \~ + \details \ru Тип законцовки мультилинии.\n + \en Type of tip of multiline.\n \~ + \ingroup Algorithms_2D +*/ // --- +enum EnMLTipType { + mtt_UndefTip, ///< \ru Законцовки нет. \en No tip. + mtt_LinearTip, ///< \ru Линейная законцовка. \en Linear tip. + mtt_ArcTip, ///< \ru Дуговая законцовка. \en Arc tip. + mtt_PolylineTip, ///< \ru Ломаная законцовка. \en Polyline tip. + mtt_ObliqueTip, ///< \ru Наклонная законцовка. \en Inclined tip. + // \ru ДОБАВЛЕНИЕ ТОЛЬКО В КОНЕЦ!!! \en ADDITION ONLY TO THE END!!! +}; + + +//------------------------------------------------------------------------------ +// _4_ +/** \brief \ru Cтруктура параметров законцовки. + \en Tip parameters structure. \~ + \details \ru Cтруктура параметров законцовки мультилинии.\n + Изменять данные объекта можно только из MbMultiline. + \en Multiline tip parameters structure.\n + Object data can be changed only from MbMultiline. \~ + \ingroup Algorithms_2D +*/ +struct MATH_CLASS StMLTipParams { +friend class MbMultiline; +private: + EnMLTipType tipType; ///< \ru Тип законцовки. \en Type of tip. + + /** \brief \ru Параметр законцовки. + \en Parameter of tip. \~ + \details \ru Для mtt_UndefTip неопределен,\n + для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n + для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n + для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n + для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). + \en Undefined for mtt_UndefTip,\n + for mtt_LinearTip - distance from the end of multiline to the tip,\n + for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n + for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n + for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians).\~ + */ + double tipParam; + +public: + StMLTipParams(); ///< \ru Умолчательный конструктор. \en Default constructor. + StMLTipParams( const StMLTipParams & other ); ///< \ru Копирующий конструктор. \en Copy-constructor. + + /** \brief \ru Конструктор по типу законцовки и параметру законцовки. + \en Constructor by type of tip and parameter of tip. \~ + \details \ru Конструктор по типу законцовки и параметру законцовки.\n + \en Constructor by type of tip and parameter of tip.\n \~ + \param[in] _tipType - \ru Тип законцовки. + \en Type of tip. \~ + \param[in] _tipParam - \ru Параметр законцовки, зависит от типа законцовки:\n + для mtt_UndefTip неопределен,\n + для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n + для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n + для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n + для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). + \en Parameter of tip, depends on type of tip:\n + for mtt_UndefTip is undefined,\n + for mtt_LinearTip - distance from the end of multiline to the tip,\n + for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n + for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n + for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians). \~ + */ + StMLTipParams( EnMLTipType _tipType, double _tipParam ); + +public: + + /**\ru \name Функции доступа к данным + \en \name Functions for access to data + \{ */ + /// \ru Тип законцовки. \en Type of tip. + EnMLTipType GetTipType () const { return tipType; } + /// \ru Параметр законцовки. \en Parameter of tip. + double GetTipParam() const { return tipParam; } + /** \} */ + /**\ru \name Операторы сравнения + \en \name Comparison operators + \{ */ + /// \ru Оператор сравнения. \en Comparison operator. + bool operator ==( const StMLTipParams & ) const; + /// \ru Оператор сравнения. \en Comparison operator. + bool operator !=( const StMLTipParams & ) const; + /** \} */ + +protected: + + /**\ru \name Функции инициализации + \en \name Initialization functions + \{ */ + + /// \ru Инициализация по структуре параметров законцовки. \en Initialization by tip parameters structure. + void Init ( const StMLTipParams & other ); + + /** \brief \ru Инициализация по типу законцовки и параметру законцовки. + \en Initialization by type of tip and parameter of tip. \~ + \details \ru Инициализация по типу законцовки и параметру законцовки.\n + \en Initialization by type of tip and parameter of tip.\n \~ + \param[in] _tipType - \ru Тип законцовки. + \en Type of tip. \~ + \param[in] _tipParam - \ru Параметр законцовки, зависит от типа законцовки:\n + для mtt_UndefTip неопределен,\n + для mtt_LinearTip - расстояние от конца ЛМ до законцовки,\n + для mtt_ArcTip - расстояние от конца ЛМ до вершины дуги законцовки,\n + для mtt_PolylineTip - расстояние от конца ЛМ до вершины угла законцовки,\n + для mtt_ObliqueTip - угол поворота нормали от конца мультилинии (в радианах). + \en Parameter of tip, depends on type of tip:\n + for mtt_UndefTip is undefined,\n + for mtt_LinearTip - distance from the end of multiline to the tip,\n + for mtt_ArcTip - distance from the end of multiline to the vertex of arc of tip,\n + for mtt_PolylineTip - distance from the end of multiline to the vertex of corner of tip,\n + for mtt_ObliqueTip - angle of rotation of normal from the end of multiline (in radians). \~ + */ + void Init ( EnMLTipType _tipType, double _tipParam ); + + /** \} */ + /**\ru \name Функции изменения данных + \en \name Functions for changing data + \{ */ + + /** \brief \ru Изменить тип законцовки. + \en Change type of tip. \~ + \details \ru Изменить тип законцовки мультилинии.\ n + \en Change type of tip of multiline.\n \~ + \param[in] othTipType - \ru Новый тип законцовки. + \en New type of tip. \~ + \return \ru false, если старое значение типа совпадает со значением othTipType. + \en False if the old value of type coincides with the value of othTipType. \~ + */ + bool ChangeTipType ( EnMLTipType othTipType ); + + /** \brief \ru Изменить параметр законцовки. + \en Change parameter of tip. \~ + \details \ru Изменить параметр законцовки мультилинии.\n + \en Change parameter of tip of multiline.\n \~ + \param[in] othTipParam - \ru Новый параметр законцовки. + \en New parameter of tip. \~ + \return \ru false, если старое значение параметра совпадает со значением othTipParam. + \en False if the old value of parameter coincides with the value of othTipParam. \~ + */ + bool ChangeTipParam( double othTipParam ); + + /** \brief \ru Трансформация. + \en Transformation. \~ + \details \ru Преобразование объекта согласно матрице.\n + \en Transform object according to the matrix.\n \~ + \param[in] matr - \ru Матрица трансформации. + \en Transformation matrix. \~ + */ + void Transform ( const MbMatrix & matr ); + /** \} */ + +private: + /// \ru Оператор присваивания. \en Assignment operator. + void operator = ( const StMLTipParams & ); + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( StMLTipParams, MATH_FUNC_EX ) +}; // StMLTipParams + + +//------------------------------------------------------------------------------ +// _5_ +/** \brief \ru Информация о вершине. + \en Information about a vertex. \~ + \details \ru Информация о вершине мультилинии.\n + Изменять данные объекта можно только из MbMultiline. + \en Information about a vertex of multiline.\n + Object data can be changed only from MbMultiline. \~ + \ingroup Algorithms_2D +*/ +struct MATH_CLASS StVertexOfMultilineInfo { +friend class MbMultiline; +private: + bool smoothJoint; ///< \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии \en Flag of multiline base line segments smooth joint at a vertex + ///< \ru (только для сплайнов). \en (only for splines). + EnMLVertexTracingType tracingType; ///< \ru Тип обхода углов в вершине мультилинии. \en Type of traverse of corners at a vertex of multiline. + double specFilletRad; ///< \ru Радиус особого скругления на линии мультилинии (если tracingType == mvt_SpecFilletType). \en Radius of a special fillet on a line of multiline (if tracingType == mvt_SpecFilletType). + // \ru Параметры законцовки в вершине (внутренней) \en Parameters of (inner) tip at a vertex + EnMLInnerTipType tipType; ///< \ru Тип внутренней законцовки. \en Type of inner tip. + bool firstSegTip; ///< \ru Законцовка для первого сегмента вершины. \en Tip for the first segment of a vertex. + +public: + StVertexOfMultilineInfo(); ///< \ru Умолчательный конструктор. \en Default constructor. + StVertexOfMultilineInfo( const StVertexOfMultilineInfo & other ); ///< \ru Копирующий конструктор. \en Copy-constructor. + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор.\n + \en Constructor.\n \~ + \param[in] _smoothJoint - \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии,\n + используется только для сплайнов. + \en Flag of multiline base line segments smooth joint at a vertex,\n + used only for splines. \~ + \param[in] _tracingType - \ru Тип обхода углов в вершине мультилинии. + \en Type of traverse of corners at a vertex of multiline. \~ + \param[in] _specFilletRad - \ru Радиус особого скругления на линии мультилинии,\n + если tracingType == mvt_SpecFilletType. + \en Radius of a special fillet on line of multiline,\n + if tracingType == mvt_SpecFilletType. \~ + \param[in] _tipType - \ru Тип внутренней законцовки. + \en Type of inner tip. \~ + \param[in] _firstSegTip - \ru Законцовка для первого сегмента вершины. + \en Tip for the first segment of a vertex. \~ + */ + StVertexOfMultilineInfo( bool _smoothJoint, EnMLVertexTracingType _tracingType, + double _specFilletRad, EnMLInnerTipType _tipType, bool _firstSegTip ); + +public: + + /**\ru \name Функции доступа к данным + \en \name Functions for access to data + \{ */ + /// \ru Тип обхода углов в вершине мультилинии. \en Type of traverse of corners at a vertex of multiline. + EnMLVertexTracingType GetTracingType () const { return tracingType; } + /// \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии. \en Flag of multiline base line segments smooth joint at a vertex. + bool IsSmoothJoint () const { return smoothJoint; } + /// \ru Радиус особого скругления на линии мультилинии. \en Radius of special fillet on base line of multiline. + double GetSpecFilletRad() const { return specFilletRad; } + /// \ru Тип внутренней законцовки. \en Type of inner tip. + EnMLInnerTipType GetTipType () const { return tipType; } + /// \ru Законцовка для первого сегмента вершины. \en Tip for the first segment of a vertex. + bool IsFirstSegTip () const { return firstSegTip; } + /// \ru Обход скруглением. \en Traverse by fillet. + bool IsFilletTracing () const; + +public: + + /** \} */ + /**\ru \name Операторы сравнения и присваивания + \en \name Comparison operators and assignment + \{ */ + /// \ru Оператор сравнения. \en Comparison operator. + bool operator == ( const StVertexOfMultilineInfo & ) const; + /// \ru Оператор сравнения. \en Comparison operator. + bool operator != ( const StVertexOfMultilineInfo & ) const; + /// \ru Оператор присваивания. \en Assignment operator. + StVertexOfMultilineInfo & operator = ( const StVertexOfMultilineInfo & other ) + { + Init( other ); + return *this; + } + + /** \} */ + + +protected: + + /**\ru \name Функции инициализации + \en \name Initialization functions + \{ */ + + /// \ru Инициализация по информации о вершине мультилинии. \en Initialization by an information about a vertex of multiline. + void Init( const StVertexOfMultilineInfo & other ); + + /** \brief \ru Инициализация. + \en Initialization. \~ + \details \ru Инициализация.\n + \en Initialization.\n \~ + \param[in] _smoothJoint - \ru Флаг гладкого стыка в вершине сегментов базовой линии мультилинии,\n + используется только для сплайнов. + \en Flag of multiline base line segments smooth joint at a vertex,\n + used only for splines. \~ + \param[in] _tracingType - \ru Тип обхода углов в вершине мультилинии. + \en Type of traverse of corners at a vertex of multiline. \~ + \param[in] _specFilletRad - \ru Радиус особого скругления на линии мультилинии,\n + если tracingType == mvt_SpecFilletType. + \en Radius of a special fillet on line of multiline,\n + if tracingType == mvt_SpecFilletType. \~ + \param[in] _tipType - \ru Тип внутренней законцовки. + \en Type of inner tip. \~ + \param[in] _firstSegTip - \ru Законцовка для первого сегмента вершины. + \en Tip for the first segment of a vertex. \~ + */ + void Init ( bool _smoothJoint, EnMLVertexTracingType _tracingType, + double _specFilletRad, EnMLInnerTipType _tipType, + bool _firstSegTip ); + /** \} */ + /**\ru \name Функции изменения данных + \en \name Functions for changing data + \{ */ + /// \ru Изменить флаг гладкого стыка в вершине сегментов базовой линии мультилинии. \en Change flag of multiline base line segments smooth joint at a vertex. + bool ChangeSmoothJoint ( bool othSmoothJoint ); + /// \ru Изменить тип обхода углов в вершине мультилинии. \en Change type of traverse of corners at a vertex of multiline. + bool ChangeTracingType ( EnMLVertexTracingType othTracingType ); + /// \ru Изменить радиус особого скругления на линии мультилинии. \en Change radius of special fillet on base line of multiline. + bool ChangeSpecFilletRad( double othSpecFilletRad ); + /// \ru Изменить тип внутренней законцовки. \en Change type of inner tip. + bool ChangeTipType ( EnMLInnerTipType othTipType ); + /// \ru Изменить флаг законцовки для первого сегмента вершины. \en Change flag of tip for the first segment of a vertex. + bool ChangeFirstSegTip ( bool othFirstSegTip ); + + /** \brief \ru Трансформация. + \en Transformation. \~ + \details \ru Преобразование объекта согласно матрице.\n + \en Transform object according to the matrix.\n \~ + \param[in] matr - \ru Матрица трансформации. + \en Transformation matrix. \~ + */ + void Transform ( const MbMatrix & matr ); + /** \} */ + +private: + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( StVertexOfMultilineInfo, MATH_FUNC_EX ) +}; // StVertexOfMultilineInfo + + +//------------------------------------------------------------------------------ +/** \brief \ru Класс для перестроения разрывов. + \en Class for breaks rebuilding. \~ + \details \ru Класс для перестроения разрывов. Содержит номера сегментов базовой кривой.\n + \en Class for breaks rebuilding. Contains indices of the base curve segments.\n \~ + \ingroup Algorithms_2D +*/ +// --- +class MATH_CLASS MbBreaksRebuild { + +public: + SArray baseNumbers; ///< \ru Номера сегментов базовой кривой для сегментов линии мультилинии. \en Indices of the base curve segments for line segments of multiline. + +public: + /// \ru Конструктор по массиву номеров. \en Constructor by array of indices. + MbBreaksRebuild( const SArray & bNumbers ) + :baseNumbers( bNumbers ) + { + } + ~MbBreaksRebuild() {} +}; + + +//------------------------------------------------------------------------------ +// _6_ +/** \brief \ru Мультилиния. + \en Multiline. \~ + \details \ru Мультилиния - составной геометрический объект, состоящий из\n + 1) кривых curves, построенных эквидистантно к базовой кривой мультилинии basisCurve + с радиусами equidRadii. При этом способ обхода углов для каждой вершины + basisCurve определяется отдельно (с помощью vertices.tracingType и vertices.specFilletRad).\n + 2) массива законцовок tipCurves в вершинах мультилинии, тип которых определяется + соответствующим vertices[i].tipParams.tipType.\n + 3) законцовок begTipCurve и endTipCurve на концах мультилинии, тип которых определяется + с помощью begTipParams и endTipParams.\n + При создании линии мультилинии (добавлении радиуса эквидистанты) создается контур, + который будет жить (меняться только внутри) до того момента, пока в массиве equidRadii + есть соответствующий ему в начале элемент.\n + Контур законцовки живет до тех пор, пока соответствующий тип законцовки не равен m_t_UndefTip.\n + За существованием и удалением законцовок должны следить функции SetTipType.\n + При построении кривых мультилинии вырожденные участки исключаются только в вершинах (перехлесты). + \en Multiline is a composite geometric object consisting of\n + 1) 'curves' curves constructed to be equidistant to base line 'basisCurve' of the multiline + with 'equidRadii' radii. The method of traverse of corners for each vertex of + 'basisCurve' is defined separately (with the help of vertices.tracingType and vertices.specFilletRad).\n + 2) 'tipCurves' array of tips at vertices of multiline, which type is defined + by corresponding vertices[i].tipParams.tipType.\n + 3) 'begTipCurve' and 'endTipCurve' tips at the ends of multiline, which type is defined + with the help of 'begTipParams' and 'endTipParams'.\n + While creating line of multiline (adding equidistance radius) the contour is created + which will be alive (can be changed only internally) while the 'equidRadii' array + contains element at the beginning corresponding to it.\n + The contour of a tip will be alive while the corresponding type of the tip isn't equal to m_t_UndefTip.\n + SetTipType functions care about the existence and removal of tips.\n + Degenerated regions are excluded only at vertices (overlaps) while constructing the curves of a multiline. \~ + \ingroup Region_2D +*/ +// --- +class MATH_CLASS MbMultiline : public MbPlaneItem { +private: + MbContour * basisCurve; ///< \ru Базовая кривая (БК) (всегда не NULL). \en Base curve (BC) (always not 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). + StMLTipParams endTipParams; ///< \ru Параметры законцовки в конце мультилинии (конце БК). \en Parameters of a tip at the end of a multiline (end of the base curve). + bool processClosed; ///< \ru Обрабатывать ли замкнутость БК (доп. вершина). \en Whether to process the closedness of the base curve (additional vertex). + 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 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). + + mutable double maxPosRadius; ///< \ru Максимально возможный для невывернутого построения положительный радиус. \en Maximum possible positive radius for non-everted construction. + mutable double minNegRadius; ///< \ru Минимально возможный для невывернутого построения отрицательный радиус. \en Minimum possible negative radius for non-everted construction. + mutable size_t minNotDegInd; ///< \ru Индекс невырожденного элемента curves с минимальным радиусом. \en Index of non-everted element of 'curves' with minimal radius. + mutable size_t maxNotDegInd; ///< \ru Индекс невырожденного элемента curves с максимальным радиусом. \en Index of non-everted element of 'curves' with maximal radius. + +public: + MbMultiline(); ///< \ru Конструктор пустой мультилинии. \en Constructor of an empty multiline. + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор.\n + \en Constructor.\n \~ + \param[in] _basisCurve - \ru Базовая кривая. + \en Base curve. \~ + \param[in] vertInfo - \ru Информация о вершине мультилинии (применяется ко всем вершинам). + \en Information about a vertex of the multiline (applied to all vertices). \~ + \param[in] _equidRadii - \ru Сортированный массив радиусов эквидистантных кривых. + \en Sorted array of radii of equidistant curves. \~ + \param[in] _begTipParams - \ru Параметры законцовки в начале мультилинии. + \en Parameters of tip at the beginning of multiline. \~ + \param[in] _endTipParams - \ru Параметры законцовки в конце мультилинии. + \en Parameters of a tip at the end of a multiline. \~ + \param[in] _processClosed - \ru Обрабатывать ли замкнутость базовой кривой. + \en Whether to process the closedness of the base curve. \~ + \param[in] _isTransparent - \ru "Прозрачная" ли мультилиния\n + параметр не используется, мультилиния считается прозрачной. + \en Whether the multiline is "transparent"\n + parameter isn't used, multiline is considered to be transparent. \~ + */ + MbMultiline( const MbContour & _basisCurve, const StVertexOfMultilineInfo & vertInfo, + const SArray & _equidRadii, + const StMLTipParams & _begTipParams, const StMLTipParams & _endTipParams, + bool _processClosed, bool _isTransparent ); + +protected: + /// \ru Копирующий конструктор. \en Copy-constructor. + MbMultiline( const MbMultiline & ); + +private: + MbMultiline( const MbContour & _basisCurve, const SArray & _vertices, + const SArray & _equidRadii, + const StMLTipParams & _begTipParams, const StMLTipParams & _endTipParams, + bool _processClosed, bool _isTransparent, bool & error ); + +public: + virtual ~MbMultiline(); + +public: + + /**\ru \name Общие функции геометрического объекта + \en \name Common functions of a geometric object + \{ */ + virtual MbePlaneType IsA () const; // \ru Тип объекта. \en A type of an object. + virtual MbePlaneType Type () const; // \ru Групповой тип объекта. \en Group type of an object. + virtual MbePlaneType Family () const; // \ru Семейство объекта. \en Family of an object. + 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 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. + virtual double DistanceToPoint ( const MbCartPoint & toP ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. + virtual bool DistanceToPointIfLess( const MbCartPoint & to, double &distance) const; // \ru Вычислить расстояние до точки, если оно меньше d. \en Calculate the distance to the point if it is less than d. + + virtual MbProperty& CreateProperty( MbePrompt name ) 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( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + + /** \} */ + /**\ru \name Функции доступа к данным + \en \name Functions for access to data + \{ */ + + /// \ru Базовая кривая. \en Base curve. + const MbContour & GetBasisCurve () const { return *basisCurve; } + /// \ru Дать базовую кривую для изменения. \en Get base curve for editing. + MbContour & SetBasisCurve () { return *basisCurve; } + /// \ru Количество вершин. \en Count of vertices. + size_t GetVerticesCount () const { return vertices.Count(); } + /// \ru Вершина по номеру. Номер должен быть меньше количества вершин. \en Vertex by an index. Index must be less than count of vertices. + const StVertexOfMultilineInfo & GetVertex ( size_t i ) const { return vertices[i]; } + /// \ru Количество радиусов эквидистант. \en Count of radii of equidistant curves. + size_t GetEquidRadiiCount() const { return equidRadii.Count(); } + /// \ru Радиус эквидистанты по номеру. Номер должен быть меньше количества радиусов. \en Radius of equidistant curve by an index. Index must be less than count of radii. + double GetEquidRadius ( size_t i ) const { return equidRadii[i]; } + /// \ru Параметры законцовки в начале мультилинии. \en Parameters of tip at the beginning of multiline. + const StMLTipParams & GetBegTipParams () const { return begTipParams; } + /// \ru Параметры законцовки в конце мультилинии. \en Parameters of a tip at the end of a multiline. + const StMLTipParams & GetEndTipParams () const { return endTipParams; } + /// \ru Признак обрабатывания замкнутости базовой кривой. \en An attribute of the base curve closedness processing. + bool IsProcessClosed () const { return processClosed; } + /// \ru Прозрачность мультилинии. \en Transparency of multiline. + bool IsTransparent () const { return isTransparent; } + // \ru Функции доступа к объектам мультилинии \en Functions for access to objects of multiline + // \ru ЭТИ ОБЪЕКТЫ НЕЛЬЗЯ МЕНЯТЬ СНАРУЖИ!!! \en THESE OBJECTS CAN'T BE CHANGED OUTSIDE!!! + + /// \ru Количество кривых мультилинии. \en Count of curves of a multiline. + size_t GetCurvesCount () const { return curves.Count(); } + /// \ru Кривая мультилинии по номеру. Номер должен быть меньше количества кривых. \en Curve of multiline by an index. Index must be less than count of curves. + const MbContourWithBreaks* GetCurve ( size_t i ) const { return curves[i]; } + + /// \ru Количество кривых - законцовок в вершинах мультилинии. \en Count of tip-curves at vertices of multiline. + size_t GetTipCurvesCount () const { return tipCurves.Count(); } + /// \ru Кривая - законцовка по номеру. Номер должен быть меньше количества законцовок. \en Tip-curve by an index. Index must be less than the count of tips. + const MbContour * GetTipCurve ( size_t i ) const { return tipCurves[i]; } + + /// \ru Законцовка в начале мультилинии. \en Tip at the beginning of a multiline. + const MbContour * GetBegTipCurve () const { return begTipCurve; } + /// \ru Законцовка в конце мультилинии. \en Tip at the end of a multiline. + const MbContour * GetEndTipCurve () const { return endTipCurve; } + + /// \ru Максимально возможный для невывернутого построения положительный радиус. \en Maximum possible positive radius for non-everted construction. + double GetMaxPosRadius () const { return maxPosRadius; } + /// \ru Минимально возможный для невывернутого построения отрицательный радиус. \en Minimum possible negative radius for non-everted construction. + double GetMinNegRadius () const { return minNegRadius; } + + /// \ru Индекс невырожденной кривой мультилинии с минимальным радиусом \en Index of non-degenerated curve of a multiline with minimal radius + size_t GetMinNotDegInd () const { return minNotDegInd; } + /// \ru Индекс невырожденной кривой мультилинии с максимальным радиусом \en Index of non-degenerated curve of a multiline with maximal radius + size_t GetMaxNotDegInd () const { return maxNotDegInd; } + + /** \} */ + /**\ru \name Функции изменения данных: изменение базовой кривой мультилинии + \en \name Functions for changing data: changing the base curve of a multiline + \{ */ + + /// \ru Очистить базовую кривую. \en Clear the base curve. + void ClearBasisCurve (); + + /** \brief \ru Заменить базовую кривую. + \en Replace the base curve. \~ + \details \ru Заменить базовую кривую.\n + При замене базовой кривой мультилинии в ней удаляются все разрывы. + \en Replace the base curve.\n + When replacing the base curve of multiline all of its breaks are removed. \~ + \param[in] _basisCurve - \ru Новая базовая кривая. + \en New base curve. \~ + \param[in] vertInfo - \ru Новая информация о вершинах мультилинии. + \en New information about vertices of multiline. \~ + */ + void ReplaceBasisCurve ( const MbContour & _basisCurve, + const StVertexOfMultilineInfo & vertInfo ); + + /** \brief \ru Добавить сегмент в базовую кривую. + \en Add a segment to a base curve. \~ + \details \ru Добавить сегмент в базовую кривую.\n + \en Add a segment to a base curve.\n \~ + \param[in] segment - \ru Добавляемый сегмент,\n + если является ломаной или контуром, то в мультилинию добавляются только составляющие сегменты. + \en Segment to add,\n + if it is polyline or contour, then only component segments are added to the multiline. \~ + \param[in] vertInfo - \ru Информация присваивается всем добавленным или измененным вершинам. + \en Information is assigned to all added or changed vertices. \~ + \return \ru true, если сегмент был добавлен. + \en True if a segment has been added. \~ + */ + bool AddBasisSegment ( MbCurve * segment, + const StVertexOfMultilineInfo & vertInfo ); + + /// \ru Удалить последний сегмент базовой кривой. \en Delete the last segment of the base curve. + void DeleteLastBasisSegment (); + + /** \brief \ru Вставить вершину. + \en Insert a vertex. \~ + \details \ru Вставить вершину. Сегмент разбивается на два.\n + \en Insert a vertex. Segment is split into two segments.\n \~ + \param[in] t - \ru Параметр на базовой кривой. + \en Parameter on the base curve. \~ + \param[in] vertInfo - \ru Информация о новой вершине мультилинии. + \en Information about new vertex of a multiline. \~ + \return \ru Индекс разбитого сегмента. + \en Index of split segment. \~ + */ + size_t InsertVertex ( double t, + const StVertexOfMultilineInfo & vertInfo ); + + /** \brief \ru Удалить вершину мультилинии. + \en Delete a vertex of multiline. \~ + \details \ru Удалить вершину мультилинии.\n + Пара сегментов, примыкающих к вершине, заменяется отрезком.\n + Разрывы на прилегающих сегментах исчезают. + Разрывы, лежащие на прямолинейных прилегающих сегментах, + остаются, привязываясь к вершинам нового отрезка. + \en Delete a vertex of multiline.\n + Pair of segments adjoining the vertex is replaced by a segment.\n + Breaks on adjacent segments are disappeared. + Breaks on straight adjacent segments + are remained by binding to the vertices of a new segment. \~ + \param[in] i - \ru Индекс вершины. + \en An index of a vertex. \~ + \return \ru true, если вершина была удалена. + \en True if a vertex is deleted. \~ + */ + bool RemoveVertex ( size_t i ); + + /** \brief \ru Сместить геометрическую hot-точку. + \en Shift a geometric hot-point. \~ + \details \ru Сместить геометрическую hot-точку базовой кривой.\n + При перемещении точки разрывы контуров, соответствующих прилегающим прямолинейным + сегментам привязываются к соседним неподвижным вершинам базовой кривой. + \en Shift a geometric hot-point of the base curve.\n + While shifting point, the contour breaks corresponding to adjacent straight + segments are bound to the neighboring fixed vertices of the base curve. \~ + \param[in] segInd - \ru Номер сегмента. + \en An index of a segment. \~ + \param[in] subInd - \ru Номер точки на сегменте:\n + если subInd = 0 - общая точка между двумя сегментами (может быть задана для любого сегмента),\n + если subInd = 1 - средняя точкой отрезка, средняя точкой дуги, базовая точка сплайнов pt_Nurbs и pt_Bezier,\n + если subInd > 1 - базовая точка сплайнов pt_Nurbs и pt_Bezier. + \en An index of a point on the segment:\n + if subInd = 0 - common point between two segments (can be specified for any segment),\n + if subInd = 1 - middle point of a segment, middle point of an arc, the base point of pt_Nurbs and pt_Bezier splines,\n + if subInd > 1 - base point of pt_Nurbs and pt_Bezier splines. \~ + \param[in] newPoint - \ru Новое положение точки. + \en New position of the point. \~ + \return \ru Точка была смещена. + \en Point has been shifted. \~ + */ + bool SetBasisCurvesGeoHotPoint( size_t segInd, size_t subInd, + const MbCartPoint & newPoint ); + + /** \brief \ru Удалить геометрическую hot-точку. + \en Delete a geometric hot-point. \~ + \details \ru Удалить геометрическую hot-точку базовой кривой.\n + \en Delete a geometric hot-point of the base curve.\n \~ + \param[in] segInd - \ru Номер сегмента. + \en An index of a segment. \~ + \param[in] subInd - \ru Номер точки на сегменте:\n + если subInd = 0 - результат аналогичен удалению вершины мультилинии RemoveVertex,\n + если subInd = 1 - удаление средней точки дуги (дуга заменяется отрезком), + удаление базовой точки сплайнов pt_Nurbs и pt_Bezier (изменение формы),\n + если subInd > 1 - удаление базовой точки сплайнов pt_Nurbs и pt_Bezier (изменение формы). + \en An index of a point on the segment:\n + if subInd = 0 - result is similar to deletion of the 'RemoveVertex' vertex of a multiline,\n + if subInd = 1 - deletion of the middle point of an arc (the arc is replaced by segment), + deletion of the base point of pt_Nurbs and pt_Bezier splines (changing of shape),\n + if subInd > 1 - deletion of the base point of pt_Nurbs and pt_Bezier splines (changing of shape). \~ + \return \ru true, если hot-точка была удалена. + \en True if hot-point has been deleted. \~ + */ + bool DelBasisCurvesGeoHotPoint( size_t segInd, size_t subInd ); + + /** \} */ + /**\ru \name Функции изменения данных: скругления и фаски базовой кривой + \en \name Functions for changing data: fillet and chamfer of the base curve + \{ */ + + /** \brief \ru Скруглить два соседних сегмента. + \en Fillet two neighboring segments. \~ + \details \ru Скруглить два соседних сегмента базовой кривой.\n + \en Fillet two neighboring segments of base curve.\n \~ + \param[in] index - \ru Индекс первого скругляемого сегмента. + \en Index of the first segment to fillet. \~ + \param[in] rad - \ru Радиус скругления. + \en The radius of fillet. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \return \ru true в случае успеха операции. + \en Returns true if the operation succeeded. \~ + */ + bool FilletTwoBasisSegments ( ptrdiff_t & index, double rad, + const StVertexOfMultilineInfo & vertInfo ); + + /** \brief \ru Скруглить базовую кривую. + \en Fillet the base curve. \~ + \details \ru Скруглить все углы базовой кривой.\n + \en Fillet all corners of the base curve.\n \~ + \param[in] rad - \ru Радиус скругления. + \en The radius of fillet. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \return \ru true, если добавилось хотя бы одно скругление. + \en True if at least one fillet is added. \~ + */ + bool FilletBasisCurve ( double rad, + const StVertexOfMultilineInfo & vertInfo ); + + /** \brief \ru Вставить фаску между двумя соседними сегментами базовой кривой мультилинии. + \en Insert a chamfer between two neighboring segments of the base curve of a multiline. \~ + \details \ru Вставить фаску между двумя соседними сегментами базовой кривой мультилинии.\n + \en Insert a chamfer between two neighboring segments of the base curve of a multiline.\n \~ + \param[in] index - \ru Индекс первого скругляемого сегмента. + \en Index of the first segment to fillet. \~ + \param[in] len - \ru Длина фаски. + \en Length of chamfer. \~ + \param[in] par - \ru Параметр в зависимости от типа type:\n + если type = true, par - угол\n + если type = false, par - размер. + \en Parameter depending on 'type' type:\n + if type = true, par is a corner\n + if type = false, par is a size. \~ + \param[in] type - \ru Тип задания фаски:\n + true - фаска задана как размер + угол,\n + false - фаска задана как размер + размер. + \en The type of a chamfer specification:\n + true - chamfer specified as size + angle,\n + false - chamfer specified as size + size. \~ + \param[in] firstSeg - \ru true, если параметр par относится к первому сегменту. + \en True if 'par' parameter is related to the first segment. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \return \ru true в случае успеха операции. + \en Returns true if the operation succeeded. \~ + */ + bool ChamferTwoBasisSegments ( ptrdiff_t & index, double len, double par, + bool type, bool firstSeg, + const StVertexOfMultilineInfo & vertInfo ); + + /** \brief \ru Вставить фаску между каждыми двумя соседними сегментами базовой кривой мультилинии. + \en Insert a chamfer between each two neighboring segments of the base curve of a multiline. \~ + \details \ru Вставить фаску между каждыми двумя соседними сегментами базовой кривой мультилинии.\n + Параметр par относится к первому сегменту из каждой пары. + \en Insert a chamfer between each two neighboring segments of the base curve of a multiline.\n + 'par' parameter is related to the first segment of each pair. \~ + \param[in] len - \ru Длина фаски. + \en Length of chamfer. \~ + \param[in] par - \ru Параметр в зависимости от типа type:\n + если type = true, par - угол,\n + если type = false, par - размер. + \en Parameter depending on 'type' type:\n + if type = true, par is a corner,\n + if type = false, par is a size. \~ + \param[in] type - \ru Тип задания фаски:\n + true - фаска задана как размер + угол,\n + false - фаска задана как размер + размер. + \en The type of a chamfer specification:\n + true - chamfer specified as size + angle,\n + false - chamfer specified as size + size. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \return \ru true, если добавилась хотя бы одна фаска. + \en True if at least one chamfer is added. \~ + */ + bool ChamferBasisCurve ( double len, double par, bool type, + const StVertexOfMultilineInfo & vertInfo ); ///< \ru Вставить фаску БК \en Insert chamfer of the base curve + + /** \} */ + /**\ru \name Функции изменения данных: изменение параметров вершины мультилинии + \en \name Functions for changing data: changing the parameters of a vertex of a multiline + \{ */ + + /** \brief \ru Установить флаг гладкого стыка. + \en Set the flag of smooth joint. \~ + \details \ru Установить флаг гладкого стыка в вершине.\n + \en Set the flag of smooth joint at a vertex.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] othSmoothJoint - \ru Флаг гладкого стыка. + \en Flag of smooth joint. \~ + */ + void SetSmoothJoint ( size_t i, bool othSmoothJoint ); + + /** \brief \ru Установить тип обхода. + \en Set the type of traverse. \~ + \details \ru Установить тип обхода вершины.\n + \en Set the type of traverse of the vertex.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] othTracingType - \ru Тип обхода. + \en Type of traverse. \~ + */ + void SetTracingType ( size_t i, EnMLVertexTracingType othTracingType ); + + /** \brief \ru Установить радиус специального скругления. + \en Set the radius of a special fillet. \~ + \details \ru Установить радиус специального скругления вершины мультилинии.\n + \en Set the radius of special fillet of a vertex of the multiline.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] othSpecFilletRad - \ru Радиус. + \en Radius. \~ + */ + void SetSpecFilletRad ( size_t i, double othSpecFilletRad ); + + /** \brief \ru Установить тип законцовки. + \en Set the type of a tip. \~ + \details \ru Установить тип законцовки (разделителя) в вершине.\n + \en Set the type of tip (splitter) at the vertex.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] othTipType - \ru Тип законцовки. + \en Type of tip. \~ + */ + void SetTipType ( size_t i, EnMLInnerTipType othTipType ); + + /** \brief \ru Установить направление законцовки. + \en Set the direction of a tip. \~ + \details \ru Установить направление законцовки в вершине мультилинии.\n + \en Set the direction of a tip at a vertex of multiline.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] othFirstSegTip - \ru Направление законцовки, если true - от первого сегмента. + \en Direction of tip, if true - from the first segment. \~ + */ + void SetTipDirection ( size_t i, bool othFirstSegTip ); + + /** \brief \ru Установить информацию о вершине. + \en Set the information about a vertex. \~ + \details \ru Установить информацию о вершине мультилинии.\n + \en Set the information about a vertex of multiline.\n \~ + \param[in] i - \ru Индекс вершины мультилинии. + \en An index of a vertex of a multiline. \~ + \param[in] vertInfo - \ru Информация о вершине. + \en Information about a vertex. \~ + */ + void SetVertexOfMultilineInfo ( size_t i, + const StVertexOfMultilineInfo & vertInfo ); + + /** \} */ + /**\ru \name Функции изменения данных: изменение радиусов эквидистант + \en \name Functions for changing data: changing the radii of equidistant curves + \{ */ + + /** \brief \ru Установить значение радиуса кривой. + \en Set the value of radius of curve. \~ + \details \ru Установить значение радиуса кривой.\n + \en Set the value of radius of curve.\n \~ + \param[in] i - \ru Индекс кривой мультилинии. + \en An index of curve of multiline. \~ + \param[in] radius - \ru Новое значение радиуса. + \en New value of the radius. \~ + \param[out] newIndex - \ru Новый индекс кривой. + \en New index of curve. \~ + \return \ru true, если радиус был изменен. + \en True if a radius has been changed. \~ + */ + bool SetRadius ( size_t i, double radius, size_t & newIndex ); + + /** \brief \ru Изменение всех радиусов кривых. + \en Changing all radii of curves. \~ + \details \ru Изменение одновременно всех радиусов кривых.\n + Значения радиусов будут изменены, если их количество в newRadii совпадает с количеством кривых. + \en Simultaneous changing all radii of curves.\n + Values of radii will be changed if their count in 'newRadii' is coincident to the count of curves. \~ + \param[in] newRadii - \ru Новые значения радиусов кривых. + \en New values of radii of curves. \~ + \return \ru true, если радиусы были изменены. + \en True if radii has been changed. \~ + */ + bool SetRadii ( const CSSArray & newRadii ); + + /** \brief \ru Изменение радиуса. + \en Change the radius. \~ + \details \ru Изменение радиуса кривой мультилинии.\n + \en Change the radius of a curve of multiline.\n \~ + \param[in] oldRadius - \ru Старое значение радиуса. + \en Old value of the radius. \~ + \param[in] radius - \ru Новое значение радиуса. + \en New value of the radius. \~ + */ + void ChangeRadius ( double oldRadius, double radius ); + + /** \brief \ru Добавление радиуса кривой мультилинии. + \en Add the radius of a curve of multiline. \~ + \details \ru Добавление радиуса кривой мультилинии.\n + Фактически, добавление кривой мультилинии. + \en Add the radius of a curve of multiline.\n + Actually, addition of a curve of multiline. \~ + \param[in] radius - \ru Значение радиуса. + \en Value of radius. \~ + \return \ru Значение индекса новой кривой\n + если кривая не была добавлена, индекс равен SYS_MAX_T. + \en Value of an index of the new curve.\n + if curve was not added, then the index is equal to SYS_MAX_T. \~ + */ + size_t AddRadius ( double radius ); + + /** \brief \ru Удаление кривой. + \en Delete a curve. \~ + \details \ru Удаление кривой мультилинии.\n + \en Delete a curve of multiline.\n \~ + \param[in] i - \ru Индекс кривой. + \en A curve index. \~ + \return \ru true, если кривая была удалена. + \en True if curve has been deleted. \~ + */ + bool RemoveRadius ( size_t i ); + + /** \brief \ru Удаление кривой. + \en Delete a curve. \~ + \details \ru Удаление кривой мультилинии.\n + \en Delete a curve of multiline.\n \~ + \param[in] oldRadius - \ru Радиус кривой. + \en Radius of a curve. \~ + \return \ru true, если кривая была удалена. + \en True if curve has been deleted. \~ + */ + bool RemoveRadius ( double oldRadius ); + + /** \} */ + /**\ru \name Функции изменения данных: изменение параметров законцовок + \en \name Functions for changing data: change the parameters of tips + \{ */ + + /** \brief \ru Изменение типа законцовки в начале. + \en Change the type of a tip at the beginning. \~ + \details \ru Изменение типа законцовки мультилинии в начале.\n + \en Change the type of a tip of multiline at the beginning.\n \~ + \param[in] othTipType - \ru Новый тип законцовки. + \en New type of tip. \~ + */ + void SetBegTipType ( EnMLTipType othTipType ); + + /** \brief \ru Изменение параметра законцовки в начале. + \en Change the parameter of a tip at the beginning. \~ + \details \ru Изменение параметра законцовки мультилинии в начале.\n + \en Change the parameter of a tip of multiline at the beginning.\n \~ + \param[in] othTipParam - \ru Новый параметр законцовки. + \en New parameter of tip. \~ + */ + void SetBegTipParam ( double othTipParam ); + + /** \brief \ru Изменение типа законцовки в конце. + \en Change the type of a tip at the end. \~ + \details \ru Изменение типа законцовки мультилинии в конце.\n + \en Change the type of a tip of multiline at the end.\n \~ + \param[in] othTipType - \ru Новый тип законцовки. + \en New type of tip. \~ + */ + void SetEndTipType ( EnMLTipType othTipType ); + + /** \brief \ru Изменение параметра законцовки в конце. + \en Change the parameter of a tip at the end. \~ + \details \ru Изменение параметра законцовки мультилинии в конце.\n + \en Change the parameter of a tip of multiline at the end.\n \~ + \param[in] othTipParam - \ru Новый параметр законцовки. + \en New parameter of tip. \~ + */ + void SetEndTipParam ( double othTipParam ); + + /** \} */ + /**\ru \name Функции изменения данных + \en \name Functions for changing data + \{ */ + + /** \brief \ru Изменение обработки замкнутости. + \en Change the closedness processing. \~ + \details \ru Изменение флага обработки замкнутости.\n + \en Change the flag of the closedness processing.\n \~ + \param[in] othProcessClosed - \ru Флаг обработки замкнутости. + \en Flag of the closedness processing. \~ + */ + void SetProcessClosed ( bool othProcessClosed ); + + /** \brief \ru Изменение прозрачности мультилинии. + \en Change the transparency of multiline. \~ + \details \ru Изменение флага прозрачности мультилинии.\n + \en Change the flag of transparency of multiline.\n \~ + \param[in] othTransparent - \ru Флаг прозрачности. + \en Transparency flag. \~ + */ + void SetTransparent ( bool othTransparent ); + + /** \} */ + /**\ru \name Работа с разрывами: добавление разрывов + \en \name Working with breaks: addition of breaks + \{ */ + + /** \brief \ru Усечение части кривой мультилинии между точками. + \en Trimming of a piece of a curve of multiline between points. \~ + \details \ru Усечение части кривой мультилинии между точками.\n + Добавление разрыва. + \en Trimming of a piece of a curve of multiline between points.\n + Add a break. \~ + \param[in] contour - \ru Кривая мультилинии для добавления разрыва. + \en Curve of multiline for addition of a break. \~ + \param[in] point1 - \ru Первая граница разрыва. + \en The first boundary of the break. \~ + \param[in] point2 - \ru Вторая граница разрыва. + \en The second boundary of the break. \~ + \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n + в случае разомкнутого контура она игнорируется. + \en The point indicating the piece of a closed contour to be deleted,\n + ignored in case of the opened contour. \~ + \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. + \en If 'true', then the break is applied to the opposite piece of the contour. \~ + \return \ru true, если разрыв был добавлен. + \en True if a break has been added. \~ + */ + bool DeletePartP1P2 ( MbContourWithBreaks * contour, + const MbCartPoint & point1, + const MbCartPoint & point2, + const MbCartPoint & point3, + bool invertBreak = false ); + + /** \brief \ru Усечение части кривой мультилинии между точками. + \en Trimming of a piece of a curve of multiline between points. \~ + \details \ru Усечение части кривой мультилинии между точками.\n + Добавление разрыва. + \en Trimming of a piece of a curve of multiline between points.\n + Add a break. \~ + \param[in] cNumber - \ru Номер кривой мультилинии для добавления разрыва. + \en Index of curve of multiline for addition of a break. \~ + \param[in] point1 - \ru Первая граница разрыва. + \en The first boundary of the break. \~ + \param[in] point2 - \ru Вторая граница разрыва. + \en The second boundary of the break. \~ + \param[in] point3 - \ru Точка, которая показывает удаляемую часть замкнутого контура,\n + в случае разомкнутого контура она игнорируется. + \en The point indicating the piece of a closed contour to be deleted,\n + ignored in case of the opened contour. \~ + \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. + \en If 'true', then the break is applied to the opposite piece of the contour. \~ + \return \ru true, если разрыв был добавлен. + \en True if a break has been added. \~ + */ + bool DeletePartP1P2 ( size_t cNumber, + const MbCartPoint & point1, + const MbCartPoint & point2, + const MbCartPoint & point3, + bool invertBreak = false ); + + /** \brief \ru Усечение части кривой мультилинии между параметрами контура. + \en Trimming of a piece of a curve of multiline between parameters of contour. \~ + \details \ru Усечение части кривой мультилинии между параметрами контура.\n + Добавление разрыва. + \en Trimming of a piece of a curve of multiline between parameters of contour.\n + Add a break. \~ + \param[in] cNumber - \ru Номер кривой мультилинии для добавления разрыва. + \en Index of curve of multiline for addition of a break. \~ + \param[in] t1 - \ru Первая граница разрыва. + \en The first boundary of the break. \~ + \param[in] t2 - \ru Вторая граница разрыва. + \en The second boundary of the break. \~ + \param[in] t3 - \ru Параметр, который показывает удаляемую часть замкнутого контура,\n + в случае разомкнутого контура он игнорируется. + \en A parameter which indicates a removable part of the closed contour, \n + ignored in case of opened contour. \~ + \param[in] invertBreak - \ru Если true, то разрыв накладывается на противоположную часть контура. + \en If 'true', then the break is applied to the opposite piece of the contour. \~ + \return \ru true, если разрыв был добавлен. + \en True if a break has been added. \~ + */ + bool DeletePartP1P2 ( size_t cNumber, + double t1, double t2, double t3, + bool invertBreak = false ); + + /** \} */ + /**\ru \name Работа с разрывами: удаление разрывов + \en \name Working with breaks: deletion of breaks + \{ */ + + /** \brief \ru Удалить разрывы. + \en Remove breaks. \~ + \details \ru Удалить все разрывы мультилинии.\n + \en Delete all breaks of multiline.\n \~ + \return \ru true, если хотя бы один разрыв был удален. + \en true, if at least one break has been deleted. \~ + */ + bool DeleteBreaks ( ); + + /** \brief \ru Удалить разрывы кривой. + \en Remove breaks of curve. \~ + \details \ru Удалить все разрывы кривой мультилинии.\n + \en Delete all breaks of curve of multiline.\n \~ + \param[in] cNumber - \ru Номер кривой. + \en Index of curve. \~ + \return \ru true, если хотя бы один разрыв был удален. + \en true, if at least one break has been deleted. \~ + */ + bool DeleteBreaks ( size_t cNumber ); + + /** \brief \ru Удалить разрыв кривой. + \en Delete a break of curve. \~ + \details \ru Удалить разрыв по параметру на кривой.\n + \en Delete a break by a parameter on the curve.\n \~ + \param[in] cNumber - \ru Номер кривой. + \en Index of curve. \~ + \param[in] t - \ru Параметр на кривой. + \en A parameter on the curve. \~ + \return \ru true, если разрыв был удален. + \en True if a break has been deleted. \~ + */ + bool DeleteBreak ( size_t cNumber, double t ); + + /** \brief \ru Удалить разрыв. + \en Delete a break. \~ + \details \ru Удалить разрыв по номеру.\n + \en Delete a break by an index.\n \~ + \param[in] cNumber - \ru Номер кривой. + \en Index of curve. \~ + \param[in] brNumber - \ru Номер разрыва на кривой. + \en Index of a break on the curve. \~ + \return \ru true, если разрыв был удален. + \en True if a break has been deleted. \~ + */ + bool DeleteBreakAtNumber ( size_t cNumber, size_t brNumber ); + + /** \brief \ru Удалить разрывы малой длины. + \en Delete breaks of small length. \~ + \details \ru Удалить разрывы малой метрической длины у кривой мультилинии.\n + В случае успеха линия мультилинии перестраивается соответственно разрывам. + \en Delete breaks of small length of a curve of multiline.\n + In case of success the line of multiline is rebuilt according to breaks. \~ + \param[in] cNumber - \ru Номер кривой мультилинии. + \en Index of a curve of multiline. \~ + \param[in] length - \ru Минимальная длина невидимой части. + \en Minimal length of invisible piece. \~ + \return \ru true, если хотя бы один разрыв кривой был удален. + \en True if at least one break of the curve has been deleted. \~ + */ + bool DeleteSmallBreaks ( size_t cNumber, double length ); + + /** \brief \ru Удалить малые видимые части. + \en Delete small visible pieces. \~ + \details \ru Удалить видимые части малой метрической длины у кривой мультилинии.\n + Соответствует объединению близких разрывов в один. + В случае успеха видимые контуры кривой перестраиваются соответственно разрывам. + \en Delete small visible pieces of a curve of multiline with small metric length.\n + Corresponds to union of close breaks into one. + In case of success the visible contours of the line is rebuilt according to breaks. \~ + \param[in] cNumber - \ru Номер кривой мультилинии. + \en Index of a curve of multiline. \~ + \param[in] length - \ru Минимальная длина видимой части. + \en Minimal length of visible piece. \~ + \return \ru true, если разрывы кривой были изменены. + \en True if breaks has been changed. \~ + */ + bool DeleteSmallVisContours ( size_t cNumber, double length ); + + /** \} */ + /**\ru \name Работа с разрывами + \en \name Working with breaks + \{ */ + + /** \brief \ru Находится ли интервал на разрыве. + \en Whether the interval is on a break. \~ + \details \ru Находится ли интервал параметров на разрыве кривой.\n + \en Whether the interval of parameters is on a break of a curve.\n \~ + \param[in] cNumber - \ru Номер кривой мультилинии. + \en Index of a curve of multiline. \~ + \param[in] rect - \ru Интервал для проверки. + \en Interval to check. \~ + \return \ru true, если интервал полностью находится на разрыве или совпадает с ним. + \en True if interval entirely is on the break or coincides with it. \~ + */ + bool IsRectInBreak ( size_t cNumber, const MbRect1D & rect ); + + /** \brief \ru Запомнить разрывы. + \en Memorize the breaks. \~ + \details \ru Запомнить разрывы невидимыми контурами.\n + Для использования в паре с AddBreaksByInvisContours.\n + Удаляет все разрывы мультилинии.\n + Все контуры invisContours имеют счетчик ссылок = 1 (вызван AddRef()). + \en Memorize the breaks as invisible contours.\n + For using together with AddBreaksByInvisContours.\n + Deletes all breaks of multiline.\n + All 'invisContours' contours has a reference counter = 1 (called AddRef()). \~ + \param[out] invisContours - \ru Набор невидимых контуров всех кривых мультилинии. + \en Set of invisible contours of all curves of multiline. \~ + */ + void GetBreaksInInvisContours( RPArray & invisContours ); + + /** \brief \ru Добавить разрывы. + \en Add breaks. \~ + \details \ru Добавить разрывы невидимыми контурами.\n + Для использования в паре с GetBreaksInInvisContours.\n + Контуры invisContours удаляются (вызывается Release()).\n + Данной функцией можно наложить разрывы на мультилинию, + если они были получены методом GetBreaksInInvisContours у этой мультилинии + и форма мультилинии не была изменена. + \en Add the breaks as invisible contours.\n + For using together with GetBreaksInInvisContours.\n + 'invisContours' contours are deleted (called Release()).\n + It is possible to apply breaks to multiline by this function, + if they were obtained by GetBreaksInInvisContours method from this multiline + and shape of multiline wasn't changed. \~ + \param[in] invisContours - \ru Набор невидимых контуров всех кривых мультилинии. + \en Set of invisible contours of all curves of multiline. \~ + */ + void AddBreaksByInvisContours( RPArray & invisContours ); + + /** \brief \ru Номера контуров, пересекаемых отрезком. + \en Indices of contours intersected with a segment. \~ + \details \ru Номера контуров, которые пересекаются с отрезком по двум точкам.\n + \en Indices of contours which are intersected with segment by two points.\n \~ + \param[in] p1 - \ru Первая точка отрезка. + \en The first point of a segment. \~ + \param[in] p2 - \ru Вторая точка отрезка. + \en The second point of a segment. \~ + \param[out] cNumbers - \ru Номера контуров. + \en Indices of contours. \~ + */ + void CurvesIntersectNumbers ( const MbCartPoint & p1, const MbCartPoint & p2, SArray & cNumbers ) const; + + /** \} */ + /**\ru \name Информация о мультилинии + \en \name Information about multiline. + \{ */ + + /// \ru Вырождена ли мультилиния. \en Whether the multiline is degenerate. + bool IsDegenerate( double lenEps = Math::LengthEps ) const; + /// \ru Замкнутая ли мультилиния. \en Whether the multiline is closed. + bool IsClosed () const; + /// \ru Получить ширину мультилинии. \en Get width of multiline. + double GetWidth () const; + /// \ru Лежит ли данная точка на мультилинии. \en Whether the given point is on multiline. + bool IsPointOn ( const MbCartPoint & point ) const; + + /** \brief \ru Найти индекс кривой мультилинии. + \en Find an index of a curve of multiline. \~ + \details \ru Найти индекс кривой мультилинии.\n + \en Find an index of a curve of multiline.\n \~ + \param[in] radius - \ru Радиус нужной кривой. + \en Radius of the required curve. \~ + \return \ru Индекс кривой. + \en A curve index. \~ + */ + size_t FindRadius ( double radius ); + + /** \} */ + /**\ru \name Операции с мультилинией + \en \name Operations with multiline + \{ */ + + /** \brief \ru Усечь мультилинию. + \en Truncate multiline. \~ + \details \ru Усечь мультилинию.\n + Вернуть мультилинию, базовая кривая которой - + копия участка между параметрами t1 и t2 базовой данной мультилинии. + \en Truncate multiline.\n + Return multiline which base curve is + a copy of piece between parameters t1 and t2 of the base curve of a given multiline. \~ + \param[in] t1 - \ru Начальный параметр усечения. + \en Start parameter of trimming. \~ + \param[in] t2 - \ru Конечный параметр усечения. + \en End parameter of trimming. \~ + \param[in] sense - \ru Направление усеченной базовой кривой. + \en Direction of the trimmed base curve. \~ + \return \ru Новую мультилинию. + \en New multiline. \~ + */ + MbMultiline * Trimmed( double t1, double t2, int sense ) const; + + /** \} */ +private: + /**\ru \name Внутренние функции мультилинии + \en \name Internal functions of multiline + \{ */ + + // \ru Все внутренние функции реализованы в MltLine_.cpp (кроме тех, для которых указан другой файл) \en All internal functions implemented in MltLine_.cpp (except ones for which the other file is specified) + // \ru Насчет объектов \en Calculation of objects + /// \ru Насчитать кривую мультилинии c радиусом эквидистанты rad. \en Calculate curve of multiline with 'rad' equidistant radius. + void CalculateCurve ( double rad, MbContourWithBreaks & contour ); + /// \ru Насчитать кривую мультилинии c радиусом эквидистанты rad c заполнением информации. \en Calculate curve of multiline with equidistant radius 'rad' and filling the information. + void CalculateCurveWithInfo ( double rad, MbContourWithBreaks & contour, + SArray & baseIndexes ); + /// \ru Насчитать все кривые (с определением minNotDegInd и maxNotDegInd). \en Calculate all the curves (with determination of minNotDegInd and maxNotDegInd). + void CalculateCurves (); + /// \ru Насчитать все кривые с информацией для граничных невырожденных кривых. \en Calculate all the curves with information for non-degenerate boundary curves. + bool CalculateCurvesWithInfo ( SArray & minInfo, SArray & maxInfo ); + /// \ru Насчитать все законцовки в вершинах. \en Calculate all tips at vertices. + void CalculateTipCurves ( const SArray & minInfo, const SArray & maxInfo ); + /// \ru Насчитать все законцовки в вершинах. \en Calculate all tips at vertices. + void CalculateTipCurves (); + /// \ru Насчитать все кривые и все законцовки в вершинах. \en Calculate all curves and all tips at vertices. + void CalculateCurvesAndTipCurves(); + /// \ru Насчитать законцовку в начале. \en Calculate tip at the beginning. + void CalculateBegTipCurve ( SArray * changeCurvesNumbers = NULL ); + /// \ru Насчитать законцовку в конце. \en Calculate tip at the end. + void CalculateEndTipCurve (); + + // \ru Отцепление объектов \en Detach the objects + + /// \ru Отцепить все кривые. \en Detach all curves. + void DeleteCurves (); + /// \ru Отцепить кривую с индексом i. \en Detach i-th curve. + void DeleteCurve ( size_t i ); + /// \ru Отцепить все законцовки в вершинах. \en Detach all tips at vertices. + void DeleteTipCurves (); + /// \ru Отцепить законцовку в вершине с индексом i. \en Detach i-th tip at vertex. + void DeleteTipCurve ( size_t i ); + /// \ru Отцепить законцовку в начале. \en Detach tip at the beginning. + void DeleteBegTipCurve (); + /// \ru Отцепить законцовку в конце. \en Detach tip at the end. + void DeleteEndTipCurve (); + /// \ru Отцепить все объекты. \en Detach all the objects. + void DeleteAllObjects (); + + // \ru Пересчет объектов \en Recalculation of objects + + /// \ru Перестроить все объекты. \en Rebuild all objects. + void RebuildAllObjects (); + + // \ru Обработки изменения vertices (без перестроения) \en Processing of 'vertices' changing (without rebuilding) + void AddVert ( const StVertexOfMultilineInfo & vertInfo ); + void InsertVert ( size_t i, const StVertexOfMultilineInfo & vertInfo ); + void ChangeVert ( size_t i, const StVertexOfMultilineInfo & vertInfo ); + void RemoveVert ( size_t i ); + + // \ru Вспомогательные функции \en Auxiliary functions + + /// \ru Обработать изменение i-ого сегмента БК. \en Process change of i-th segment of base curve. + void CalculateChangeOfSegment ( size_t i ); + /// \ru Продлить кривую до законцовок. \en Extend curve to the tips. + void ProlongCurveToTips ( size_t i ); + /// \ru Рассчитать удаление i-ой кривой (обработка). \en Calculate removal of i-th curve (processing). + void CalculateRemovalOfCurve ( size_t i ); + + // \ru Скругление/фаска двух соседних сегментов БК (реализация в MLOper.cpp) \en Fillet/chamfer of two neighboring segments of the base curve (implementation in MLOper.cpp) + bool FilletOrChamferTwoBasisSegs( ptrdiff_t & index, const StVertexOfMultilineInfo & vertInfo, + bool fillet, bool recalcCrvRadii, + double param, + double par = 0.0, bool type = false, bool firstSeg = true ); + + // \ru Работа с разрывами \en Working with breaks + // \ru Работа с разрывами при редактировании (сохранение фиксированной точки и длины) \en Working with breaks while editing (preserving of fixed point and length) + void SetBreaksFixedVars ( size_t segInd, size_t subInd, const MbCartPoint & newPoint ); + void TransformBreaks ( const MbMatrix & matr ); + + // \ru Удалить разрывы на сегментах контура, с соотв. базовым номером \en Delete breaks on segments of contour with corresponding base index + void DeleteBreaksAtBaseNumber ( size_t baseNumber, bool delTracingBreaks, bool delEquidBreaks, + bool delInLineSeg = true/*\ru Удалять ли разрывы с прямолинейных сегментов + \en Whether to remove breaks from straight segments \~*/ ); + + // \ru Функции восстановления разрывов по невидимым контурам \en Functions for recovering breaks by invisible contours + void GetBreaksInInvisContours( bool allBreaks, // \ru Удалять все разырвы \en Delete all breaks + size_t i, // \ru Номер вершины, специально для изменения типа обхода \en Index of vertex, specially for changing the type of traverse \~ + bool addContWbr, // \ru Набирать контуры с разрывами \en Collect contours with breaks + RPArray & breaksContours, + RPArray & invisContours ); + void AddBreaksByInvisContours( RPArray & breaksContours, + RPArray & invisContours ); + // \ru Для перестроения разрывов \en For breaks rebuilding + void GetBreaks ( RPArray & baseNumbers ); + void RebuildBreaks ( RPArray & baseNumbers ); + + /** \} */ +private: + void operator =( const MbMultiline & ); ///< \ru Не реализован \en Not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMultiline ) +}; // MbMultiline + +IMPL_PERSISTENT_OPS( MbMultiline ) + +//------------------------------------------------------------------------------ +// _7_ +/** \brief \ru Построить скругления мультилинии. + \en Construct a fillet of multiline. \~ + \details \ru Построить скругления базовой кривой мультилинии.\n + \en Construct a fillet of the base curve of multiline.\n \~ + \param[in] multiline - \ru Изменяемая мультилиния. + \en A multiline to be modified. \~ + \param[in] rad - \ru Радиус скругления. + \en The radius of fillet. \~ + \param[in] nodeFlag - \ru Флаг выбора скругляемых вершин:\n + true - скругление всех вершин мультилинии,\n + false - скругление ближайшей вершины к точке pnt. + \en Flag of selection of vertices to fillet:\n + true - fillet of all vertices of multiline,\n + false - fillet of the vertex nearest to 'pnt' point. \~ + \param[in] pnt - \ru Точка для указания нужной вершины. + \en Point for indication the required vertex. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \ingroup Algorithms_2D +*/ // --- +MATH_FUNC (bool) FilletMultiline ( MbMultiline & multiline, double rad, + bool nodeFlag, MbCartPoint & pnt, + const StVertexOfMultilineInfo & vertInfo ); + + +//------------------------------------------------------------------------------ +// _8_ +/** \brief \ru Построить фаски мультилинии. + \en Construct a chamfer of multiline. \~ + \details \ru Построить фаски базовой кривой мультилинии.\n + \en Construct a chamfer of the base curve of multiline.\n \~ + \param[in] multiline - \ru Изменяема мультилиния. + \en A multiline to be modified. \~ + \param[in] len - \ru Длина фаски. + \en Length of chamfer. \~ + \param[in] par - \ru Параметр в зависимости от типа type:\n + если type = true, par - угол,\n + если type = false, par - размер. + \en Parameter depending on 'type' type:\n + if type = true, par is a corner,\n + if type = false, par is a size. \~ + \param[in] type - \ru Тип задания фаски:\n + true - фаска задана как размер + угол,\n + false - фаска задана как размер + размер. + \en The type of a chamfer specification:\n + true - chamfer specified as size + angle,\n + false - chamfer specified as size + size. \~ + \param[in] nodeFlag - \ru Флаг выбора обрабатываемых вершин:\n + true - фаска между каждыми двумя соседними сегментами мультилинии,\n + false - фаска между двумя соседними сегментами мультилинии, примыкающими к ближайшей к точке pnt вершине. + \en Flag of selection of vertices to process:\n + true - chamfer between each two neighboring segments of multiline,\n + false - chamfer between two neighboring multiline segments joining at the vertex nearest to 'pnt' point. \~ + \param[in] pnt - \ru Точка для указания нужной пары сегментов. + \en Point for indication the required pair of segments. \~ + \param[in] vertInfo - \ru Информация для новых вершин мультилинии. + \en Information for new vertices of a multiline. \~ + \ingroup Algorithms_2D +*/ // --- +MATH_FUNC (bool) ChamferMultiline( MbMultiline & multiline, double len, double par, bool type, + bool nodeFlag, MbCartPoint & pnt, + const StVertexOfMultilineInfo & vertInfo ); + + +//////////////////////////////////////////////////////////////////////////////// +// +// _9_ +/// \ru Внеклассные функции расчета/учета радиусов кривизны (реализация в MltLine.cpp) \en Out-of-class functions for curvature radii calculation/consideration (implementation in MltLine.cpp) +// +//////////////////////////////////////////////////////////////////////////////// + + +//------------------------------------------------------------------------------ +/** \brief \ru Учесть радиусы кривизны кривой. + \en Consider the curve curvature radii. \~ + \details \ru Учесть минимальный положительный и максимальный отрицательный радиусы кривизны кривой.\n + Для внутреннего использования. + \en Consider the curve curvature minimum positive and maximum negative radii.\n + For internal use only. \~ + \param[in] curve - \ru Кривая мультилинии. + \en A curve of multiline. \~ + \param[in] angle - \ru Угловая толерантность. + \en An angular tolerance. \~ + \param[in, out] minPos - \ru Радиус кривой, если он меньше текущего значения переменной minPos. + \en Curve radius if it is less than current value of 'minPos' variable. \~ + \param[in, out] maxNeg - \ru Радиус кривой, если он больше текущего значения переменной minPos. + \en Curve radius if it is greater than current value of 'minPos' variable. \~ + \ingroup Algorithms_2D +*/ // --- +void ToTakeIntoCurvesCrvRadii( MbCurve & curve, double angle, double & minPos, double & maxNeg ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Получить радиусы кривизны контура. + \en Get the contour curvatures radii. \~ + \details \ru Получить минимальный положительный и максимальный отрицательный радиусы кривизны контура.\n + Для внутреннего использования. + \en Get the contour curvature minimum positive and maximum negative radii.\n + For internal use only. \~ + \param[in] contour - \ru Контур. + \en A contour. \~ + \param[in] angle - \ru Угловая толерантность. + \en An angular tolerance. \~ + \param[out] minPos - \ru Минимальный радиус сегмента контура. + \en Minimal contour segment radius. \~ + \param[out] maxNeg - \ru Максимальный радиус сегмента контура. + \en Maximal contour segment radius. \~ + \ingroup Algorithms_2D +*/ // --- +void GetContoursCrvRadii( MbContour & contour, double angle, double & minPos, double & maxNeg ); + + +//------------------------------------------------------------------------------ +// _10_ +/** \brief \ru Состыковать две кривые. + \en Join two curves. \~ + \details \ru Гладко состыковать две последовательные кривые.\n + Для внутреннего использования. + \en Smoothly join two consecutive curves.\n + For internal use only. \~ + \param[in] curve1 - \ru Первая кривая. + \en The first curve. \~ + \param[in] curve2 - \ru Вторая кривая. + \en The second curve. \~ + \return \ru true, если хотя бы одна кривая была изменена. + \en True if at least one curve has been changed. \~ + \ingroup Algorithms_2D +*/ // --- +bool SmoothJointSuccessiveCurves( MbCurve & curve1, MbCurve & curve2 ); + + +//------------------------------------------------------------------------------ +// _11_ +/** \brief \ru Разбить мультилинию. + \en Split multiline. \~ + \details \ru Разбить мультилинию на две части. + \en Split multiline into two pieces. \~ + \param[in] multiline - \ru Разбиваемая мультилиния. + \en A multiline to be split. \~ + \param[in] p1 - \ru Точка разбиения или, если мультилиния замкнута, начальная точка для новой мультилинии. + \en Splitting point or start point of a new multiline if the multiline is closed. \~ + \param[in] p2 - \ru Если мультилиния замкнута, то конечная точка для новой мультилинии. + \en End point of a new multiline if the multiline is closed. \~ + \param[out] parts - \ru Массив полученных участков (2 элемента). + \en The array of obtained pieces (two elements). \~ + \ingroup Algorithms_2D +*/ // --- +MATH_FUNC (bool) BreakMultiline( const MbMultiline & multiline, + const MbCartPoint & p1, const MbCartPoint & p2, + PArray & parts ); + + +//------------------------------------------------------------------------------ +// _12_ +/** \brief \ru Разбить мультилинию. + \en Split multiline. \~ + \details \ru Разбить мультилинию на N равных частей. + \en Split multiline into N equal pieces. \~ + \param[in] multiline - \ru Разбиваемая мультилиния. + \en A multiline to be split. \~ + \param[in] partsCount - \ru Количество частей. + \en The count of pieces. \~ + \param[in] point - \ru Ограничивающая точка для замкнутой мультилинии. + \en Bounding point for closed multiline. \~ + \param[out] parts - \ru Массив полученных участков (partsCount элементов). + \en The array of obtained pieces (partsCount elements). \~ + \ingroup Algorithms_2D +*/ // --- +MATH_FUNC (bool) BreakMultilineNParts( const MbMultiline & multiline, size_t partsCount, + const MbCartPoint & point, PArray & parts ); + +// \ru LF-Linux: inline-функции следует помещать в заголовочный файл, а не cpp! \en LF-Linux: inline-functions should be placed in the header file instead of cpp! +//------------------------------------------------------------------------------- +/// \ru Вырождена ли мультилиния \en Whether the multiline is degenerate +// --- +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)) ); +} + + +//------------------------------------------------------------------------------- +/// \ru Замкнутая ли мультилиния \en Whether the multiline is closed +// --- +inline bool MbMultiline::IsClosed() const { + return ( basisCurve->IsClosed() && processClosed && basisCurve->GetSegmentsCount() > 1 ); +} + + +//------------------------------------------------------------------------------- +/// \ru Получить ширину мультилинии \en Get width of multiline +// --- +inline double MbMultiline::GetWidth() const +{ + if ( minNotDegInd == maxNotDegInd ) + return 0.0; + else + return ( equidRadii[maxNotDegInd] - equidRadii[minNotDegInd] ); +} + +//------------------------------------------------------------------------------- +/// \ru Обход скруглением (одним из) \en Traverse by fillet (one of) +// --- +inline bool StVertexOfMultilineInfo::IsFilletTracing() const +{ + return ( tracingType == mvt_FilletType || tracingType == mvt_SpecFilletType ); +} + + +//------------------------------------------------------------------------------- +/// +// --- +inline bool StVertexOfMultilineInfo::operator ==( const StVertexOfMultilineInfo & with ) const +{ + return smoothJoint == with.smoothJoint && + tracingType == with.tracingType && + ::fabs(specFilletRad - with.specFilletRad) < EXTENT_REGION && + tipType == with.tipType && + firstSegTip == with.firstSegTip; +} + + +//------------------------------------------------------------------------------- +/// +// --- +inline bool StVertexOfMultilineInfo::operator !=( const StVertexOfMultilineInfo & with ) const +{ + return !(*this == with); +} + + +//------------------------------------------------------------------------------- +/// \ru Инициализация по объекту \en Initialization by object +// --- +inline void StVertexOfMultilineInfo::Init( const StVertexOfMultilineInfo & other ) +{ + smoothJoint = other.smoothJoint; + tracingType = other.tracingType; + specFilletRad = other.specFilletRad; + tipType = other.tipType; + firstSegTip = other.firstSegTip; +} + + +//------------------------------------------------------------------------------- +/// \ru Инициализация по параметрам \en Initialize by parameters +// --- +inline void StVertexOfMultilineInfo::Init( bool _smoothJoint, EnMLVertexTracingType _tracingType, + double _specFilletRad, EnMLInnerTipType _tipType, + bool _firstSegTip ) +{ + smoothJoint = _smoothJoint; + tracingType = _tracingType; + specFilletRad = _specFilletRad; + tipType = _tipType; + firstSegTip = _firstSegTip; +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить флаг "гладкий стык" (smoothJoint) \en Change flag "smooth joint" (smoothJoint) +// --- +inline bool StVertexOfMultilineInfo::ChangeSmoothJoint( bool othSmoothJoint ) +{ + if ( smoothJoint == othSmoothJoint ) + return false; + else { + smoothJoint = othSmoothJoint; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить тип обхода углов в вершине (tracingType) \en Change type of traverse of corners at a vertex (tracingType) +// --- +inline bool StVertexOfMultilineInfo::ChangeTracingType( EnMLVertexTracingType othTracingType ) +{ + if ( tracingType == othTracingType ) + return false; + else { + tracingType = othTracingType; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить радиус особого скругления (specFilletRad) \en Change radius of special fillet (specFilletRad) +// --- +inline bool StVertexOfMultilineInfo::ChangeSpecFilletRad( double othSpecFilletRad ) +{ + if ( ::fabs(specFilletRad - othSpecFilletRad) < Math::LengthEps ) + return false; + else { + specFilletRad = othSpecFilletRad; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить тип законцовки (tipType) \en Change type of tip (tipType) +// --- +inline bool StVertexOfMultilineInfo::ChangeTipType( EnMLInnerTipType othTipType ) +{ + if ( tipType == othTipType ) + return false; + else { + tipType = othTipType; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить флаг сегмента законцовки (isFirstSegTip) \en Change flag of segment of tip (isFirstSegTip) +// --- +inline bool StVertexOfMultilineInfo::ChangeFirstSegTip( bool othFirstSegTip ) +{ + if ( firstSegTip == othFirstSegTip ) + return false; + else { + firstSegTip = othFirstSegTip; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Преобразовать объект согласно матрице \en Transform an object according to the matrix +// --- +inline void StVertexOfMultilineInfo::Transform( const MbMatrix & matr ) +{ + matr.TransformScalarX( specFilletRad ); // \ru Преобразовать радиус \en Transform radius +} + + +//------------------------------------------------------------------------------- +/// +// --- +inline bool StMLTipParams::operator ==( const StMLTipParams & with ) const +{ + return (tipType == with.tipType ) && + ::fabs(tipParam - with.tipParam) < EXTENT_REGION; +} + + +//------------------------------------------------------------------------------- +/// +// --- +inline bool StMLTipParams::operator !=( const StMLTipParams & with ) const +{ + return !(*this == with); +} + + +//------------------------------------------------------------------------------- +/// \ru Инициализация \en Initialization +// --- +inline void StMLTipParams::Init( const StMLTipParams & other ) +{ + tipType = other.tipType; + tipParam = other.tipParam; +} + + +//------------------------------------------------------------------------------- +/// \ru Инициализация \en Initialization +// --- +inline void StMLTipParams::Init( EnMLTipType _tipType, double _tipParam ) +{ + tipType = _tipType; + tipParam = _tipParam; +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить тип законцовки (tipType) \en Change type of tip (tipType) +// --- +inline bool StMLTipParams::ChangeTipType( EnMLTipType othTipType ) +{ + if ( tipType == othTipType ) + return false; + else { + tipType = othTipType; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Изменить параметр законцовки (tipParam) \en Change parameter of tip (tipParam) +// --- +inline bool StMLTipParams::ChangeTipParam( double othTipParam ) +{ + if ( ::fabs(tipParam - othTipParam) < Math::LengthEps ) + return false; + else { + tipParam = othTipParam; + return true; + } +} + + +//------------------------------------------------------------------------------- +/// \ru Преобразовать объект согласно матрице \en Transform an object according to the matrix +// --- +inline void StMLTipParams::Transform( const MbMatrix & matr ) +{ + matr.TransformScalarX( tipParam ); // \ru Преобразовать расстояние \en Transform distance +} + + +#endif // __MULTILINE_H diff --git a/C3d/Include/name_check.h b/C3d/Include/name_check.h index ce45618..28212ab 100644 --- a/C3d/Include/name_check.h +++ b/C3d/Include/name_check.h @@ -1,22 +1,26 @@ //////////////////////////////////////////////////////////////////////////////// /** \file - \brief \ru Работа с топологическими именами объекта. - \en Treatment of object's topological names. \~ + \brief \ru Работа с именами топологических объектов. + \en The treatment of names of topological objects. \~ */ //////////////////////////////////////////////////////////////////////////////// -#ifndef __NAME_CEHCK_H -#define __NAME_CEHCK_H +#ifndef __NAME_CHECK_H +#define __NAME_CHECK_H #include -#include -#include +#include +#include +#include -class MATH_CLASS MbSNameMaker; +class MATH_CLASS MbFace; +class MATH_CLASS MbCurveEdge; +class MATH_CLASS MbFaceShell; +class MATH_CLASS MbItem; //------------------------------------------------------------------------------ @@ -30,26 +34,29 @@ class MATH_CLASS MbSNameMaker; \en An first point. \~ \param[in] p2 - \ru Множество граней. \en Вторая точка. \~ + \param[in] precision - \ru Точность сравнения. + \en The precision of comparison. \~ \return \ru Возвращает: -1, если p1 < p2; +1, если p1 > p2; 0, если p1 == p2. \en Returns: -1 -if p1 < p2; +1 -if p1 > p2; 0 -if p1 == p2. \~ \ingroup Names */ // --- -inline int PointCompare3D ( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ) +inline +int PointCompare3D ( const MbCartPoint3D & p1, const MbCartPoint3D & p2, double precision = Math::region ) { - if ( p2.x + Math::region < p1.x ) // по X + if ( p2.x + precision < p1.x ) // по X return 1; - else if ( p1.x + Math::region < p2.x ) + else if ( p1.x + precision < p2.x ) return -1; else { - if ( p2.y + Math::region < p1.y ) // по Y + if ( p2.y + precision < p1.y ) // по Y return 1; - else if ( p1.y + Math::region < p2.y ) + else if ( p1.y + precision < p2.y ) return -1; else { - if ( p2.z + Math::region < p1.z ) // по Z + if ( p2.z + precision < p1.z ) // по Z return 1; - else if ( p1.z + Math::region < p2.z ) + else if ( p1.z + precision < p2.z ) return -1; } } @@ -74,10 +81,10 @@ inline int PointCompare3D ( const MbCartPoint3D & p1, const MbCartPoint3D & p2 ) \ingroup Names */ // --- -MATH_FUNC (void) SetShellNames( RPArray & edges, - const RPArray & faces, - const MbSNameMaker & nameMaker, - bool processVertexes ); +MATH_FUNC (void) SetShellNames( RPArray & edges, + const RPArray & faces, + const MbSNameMaker & nameMaker, + bool processVertexes ); //------------------------------------------------------------------------------ @@ -95,8 +102,8 @@ MATH_FUNC (void) SetShellNames( RPArray & edges, */ // --- MATH_FUNC (void) SetFacesNames( const RPArray & faces, - const MbSNameMaker & nameMaker, - bool processVertexes ); + const MbSNameMaker & nameMaker, + bool processVertexes ); //------------------------------------------------------------------------------ @@ -111,18 +118,29 @@ MATH_FUNC (void) SetFacesNames( const RPArray & faces, \ingroup Names */ // --- -inline -void SetShellNames( MbFaceShell & shell, - const MbSNameMaker & nameMaker ) -{ - RPArray edges( 0, 1 ); - RPArray faces( 0, 1 ); +MATH_FUNC (void) SetShellNames( MbFaceShell & shell, + const MbSNameMaker & nameMaker ); - shell.GetEdges( edges ); // \ru Получение массива ребер \en Get an array of edges - shell.GetFaces( faces ); - ::SetShellNames( edges, faces, nameMaker, true ); -} +//------------------------------------------------------------------------------ +/** \brief \ru Установить имена элементам объекта. + \en Set names for elements of object. \~ + \details \ru Установить имена элементам объекта: граням, ребрам и вершинам тела, ребрам и вершинам проволочного каркаса, вершинам точечного каркаса. + \en Set names for elements of object: faces, edges and vertices of an solid, edges and vertices of a wireframe, vertices of a point frame. \~ + \param[in] item - \ru Тело, вставка, проволочный каркас, точечный каркас. + \en A solid, wire frame, point frame, instance. \~ + \param[in] nameMaker - \ru Именователь. + \en An object for naming the new objects. \~ + \param[in] clearNames - \ru Очистить предварительно все имена у элементов объекта. + \en Clear all names of object elements beforehand. \~ + \return \ru Возвращает true, если было выполнено именование. + \en Returns true if naming operation was performed. \~ + \ingroup Names +*/ +// --- +MATH_FUNC (bool) SetItemNames( MbItem & item, + const MbSNameMaker & nameMaker, + bool clearNames ); //------------------------------------------------------------------------------ @@ -155,14 +173,15 @@ struct NameIntersectionInfo { \ingroup Names */ // --- -MATH_FUNC (bool) CheckShellNames( const RPArray & shells, SArray & infos ); +MATH_FUNC (bool) CheckShellNames( const RPArray & shells, + SArray & infos ); //----------------------------------------------------------------------------- /** \brief \ru Выбрать имя объединяемых ребер. \en Select name for united edges. \~ \details \ru Выбрать наиболее подходящее имя при объединении двух ребер, \n - новое имя будет установленно первому ребру. \n + новое имя будет установлено первому ребру. \n \en Select the most suitable name while uniting two edges, \n the new name will be set to the first edge. \n \~ \param[in,out] edge1 - \ru Первое ребро. @@ -174,7 +193,9 @@ MATH_FUNC (bool) CheckShellNames( const RPArray & shells, SAr \ingroup Names */ //--- -MATH_FUNC (void) CombineNames( MbCurveEdge & edge1, const MbCurveEdge & edge2, VERSION version ); +MATH_FUNC (void) CombineNames( MbCurveEdge & edge1, + const MbCurveEdge & edge2, + VERSION version ); -#endif // __NAME_CEHCK_H +#endif // __NAME_CHECK_H diff --git a/C3d/Include/name_item.h b/C3d/Include/name_item.h index 49becf6..a252aaf 100644 --- a/C3d/Include/name_item.h +++ b/C3d/Include/name_item.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -22,11 +23,23 @@ #include #include #include +#include +#include class MATH_CLASS MbProperties; class MATH_CLASS MbName; +namespace c3d // namespace C3D +{ + typedef std::vector NamesVector; + typedef std::vector ConstNamesVector; + + typedef std::set NamesSet; + typedef std::set ConstNamesSet; +} // namespace C3D + + //---------------------------------------------------------------------------------------- /** \brief \ru Поменять местами. \en Swap. \~ @@ -47,7 +60,7 @@ inline void SwapIT( IntegralType & a, IntegralType & b ) { a^=b; b^=a; a^=b; } \ingroup Names */ // --- -const size_t sizeofSimpleName = sizeof( SimpleName ); +const_expr size_t sizeofSimpleName = sizeof( SimpleName ); ////////////////////////////////////////////////////////////////////////////////////////// @@ -141,9 +154,10 @@ reader & operator >> ( reader & in, SimpleNameArray *& nArr ); //---------------------------------------------------------------------------------------- /// \ru Чтение. \en Reading. // --- -inline reader & operator >> ( reader & in, SimpleNameArray & ref ) +inline +reader & operator >> ( reader & in, SimpleNameArray & ref ) { - size_t count = ReadCOUNT( in, true/*uint_val*/ ); + size_t count = ::ReadCOUNT( in, true/*uint_val*/ ); if ( in.good() && count ) { ref.m_array.SetSize( count, true/*clear*/ ); for ( size_t i = 0; i < count && in.good(); ++i ) { @@ -157,7 +171,8 @@ inline reader & operator >> ( reader & in, SimpleNameArray & ref ) //---------------------------------------------------------------------------------------- /// \ru Запись. \en Writing. // --- -inline writer & operator << ( writer & out, const SimpleNameArray & ref ) +inline +writer & operator << ( writer & out, const SimpleNameArray & ref ) { size_t count = ref.Count(); ::WriteCOUNT( out, count ); @@ -169,14 +184,16 @@ inline writer & operator << ( writer & out, const SimpleNameArray & ref ) //---------------------------------------------------------------------------------------- /// Hash32 // --- -inline SimpleName Hash32( const SimpleNameArray & snArr ) { - return (SimpleName)::Hash32( (uint8 *)snArr.GetAddr(), snArr.Count() * sizeofSimpleName ); +inline +SimpleName Hash32( const SimpleNameArray & snArr ) { + return (SimpleName)c3d::Hash32( (uint8 *)snArr.GetAddr(), snArr.Count() * sizeofSimpleName ); } //---------------------------------------------------------------------------------------- /// \ru Оператор конкатенации. \en Concatenation operator. // --- -inline SArray & operator += ( SArray & array, const SimpleNameArray & other ) +inline +SArray & operator += ( SArray & array, const SimpleNameArray & other ) { array += other.m_array; return array; @@ -198,35 +215,34 @@ inline SArray & operator += ( SArray & array, const Simp \ingroup Names */ // --- -struct MATH_CLASS MbIdArr : private LiSArray -{ +struct MATH_CLASS MbIdArr : private LiSArray { friend class MbName; private: uint16 countBase; ///< \ru Количество элементов в базовой части. \en The count of elements in base part. mutable SimpleName hash; ///< \ru Хэш множества простых имен. \en The hash of simple names` set. -protected://public: - MbFlags flags; ///< \ru Флаги. \en Flags. +protected: + MbFlags flags; ///< \ru Флаги. \en Flags. public: /// \ru Конструктор по умолчанию. \en Default constructor. - MbIdArr() : LiSArray(), countBase(0), hash(SIMPLENAME_MAX), flags() {} + MbIdArr() : LiSArray(), countBase(0), hash(c3d::SIMPLENAME_MAX), flags() {} /// \ru Конструктор копирования. \en Copy-constructor. MbIdArr( const MbIdArr & o ) : LiSArray(o), countBase(o.countBase), hash( o.hash ), flags(o.flags) {} public: SimpleName Hash() const; ///< \ru Вычислить хэш себя. \en Calculate hash of itself. - void FlashHash() { hash = SIMPLENAME_MAX; } ///< \ru Сбросить свой хэш. \en Reset hash value. + void FlashHash() { hash = c3d::SIMPLENAME_MAX; } ///< \ru Сбросить свой хэш. \en Reset hash value. size_t CountAll() const { return Count(); } ///< \ru Дать количество элементов массива. \en Get the number of elements in the array. size_t CountBase() const { return countBase; } ///< \ru Дать количество элементов массива в базовой части. \en Get the number of elements in base part. /// \ru Обнулить количество элементов \en Set the number of elements to null - void Flush () { LiSArray::Flush(); countBase = 0; hash = SIMPLENAME_MAX; } + void Flush () { LiSArray::Flush(); countBase = 0; hash = c3d::SIMPLENAME_MAX; } - bool IsEmpty () const; ///< \ru Множество пуст? \en Is the array empty? - bool GetCut ( SimpleName & cutIndex ) const; ///< \ru Получение индекса разрезки. \en Get an index of a cutaway. - void SetCopyIndex( SimpleName ci ); ///< \ru Установка индекса копирования. \en Set an index of copying. - bool GetCopyIndex( SimpleName & ci ) const; ///< \ru Получение индекса копирования. \en Get an index of copying. + bool IsEmpty () const; ///< \ru Множество пустое? \en Is the array empty? + bool GetCut ( SimpleName & ) const; ///< \ru Получение индекса резки. \en Get an index of a cutaway. + void SetCopyIndex( SimpleName ); ///< \ru Установка индекса копирования. \en Set an index of copying. + bool GetCopyIndex( SimpleName & ) const; ///< \ru Получение индекса копирования. \en Get an index of copying. size_t SizeOf() const; ///< \ru Размер в памяти. \en Size in memory. /// \ru Добавить основной элемент в конец массива. \en Add main element to the end of the array. @@ -262,17 +278,19 @@ KNOWN_OBJECTS_RW_REF_OPERATORS( MbIdArr ) //---------------------------------------------------------------------------------------- // \ru Вычислить хэш себя. \en Calculate hash of itself. // --- -inline SimpleName MbIdArr::Hash() const +inline +SimpleName MbIdArr::Hash() const { - if ( hash == SIMPLENAME_MAX ) - hash = ::Hash32( (uint8*)parr, count * sizeofSimpleName/*4*/ ); + if ( hash == c3d::SIMPLENAME_MAX ) + hash = c3d::Hash32( (uint8*)parr, count * sizeofSimpleName/*4*/ ); return hash; } //---------------------------------------------------------------------------------------- -// \ru Размер в памяти \en Size in memory +// \ru Размер в памяти. \en Size in memory. // --- -inline size_t MbIdArr::SizeOf() const +inline +size_t MbIdArr::SizeOf() const { size_t size = sizeof(MbFlags); size += sizeof(LiSArray) + Count() * sizeofSimpleName; //-V119 @@ -281,9 +299,10 @@ inline size_t MbIdArr::SizeOf() const } //---------------------------------------------------------------------------------------- -// +// \ru Оператор добавления. \en Operator for adding. // --- -inline void MbIdArr::operator += ( const MbIdArr & other ) +inline +void MbIdArr::operator += ( const MbIdArr & other ) { C3D_ASSERT( CountAll() == CountBase() ); if ( CountAll() == CountBase() ) { @@ -315,27 +334,27 @@ inline void MbIdArr::operator += ( const MbIdArr & other ) */ // --- class MATH_CLASS MbName { public: - typedef std_unique_ptr UniqueNamePtr; + typedef std_unique_ptr UniqueNamePtr; public : /// \ru Индекс имени. \en A name index. enum EIndexes - { // v e f + { // Index // v e f (vertices|edges|faces, (*) - mandatory, (+) - used, (-) - none ) // i_Main, // * * * // i_First, // * * * // i_Cut, // - + + // i_Copy, // - - + // i_Extra, // - - + - i_Main, ///< \ru Индекс главного имени. \en Main name index. - i_First, ///< \ru Индекс уникального имени, содержащего в себе hash, построенный по жестким правилам. \en Index of unique name which includes hash constructed by strict rules. - i_Cut, ///< \ru Индекс индекса разрезанности. \en Index of index of cutaway. - i_Copy, ///< \ru Индекс индекса копирования. \en Index of index of copying. - i_Extra, ///< \ru Индекс предыдущего hash'a копирования. \en Index of previous hash of copying. + i_Main, ///< \ru Индекс главного имени. \en Main name index. + i_First, ///< \ru Индекс уникального имени, содержащего в себе hash, построенный по жестким правилам. \en Index of unique name which includes hash constructed by strict rules. + i_Cut, ///< \ru Индекс индекса разрезанности. \en Index of index of cutaway. + i_Copy, ///< \ru Индекс индекса копирования. \en Index of index of copying. + i_Extra, ///< \ru Индекс предыдущего hash'a копирования. \en Index of previous hash of copying. i_PseudoCopy = -1, ///< \ru Индекс псевдо копирования. \en Index of pseudo copying. }; /// \ru Основной индекс имени. \en Main index of name. enum BaseNameIndex - { // v e f + { // Index // v e f // bni_Main, // * * * // bni_First, // * * * // bni_Cut, // - + + @@ -346,7 +365,7 @@ public : }; /// \ru Дополнительный индекс имени. \en Additional index of name. enum ExtraNameIndex - { // v e f + { // Index // v e f // eni_Copy, // - - + // eni_Extra, // - - + eni_Copy, ///< \ru Индекс индекса копирования. \en Index of index of copying. @@ -360,42 +379,65 @@ public : rmn_DummyFaceName = -4, ///< \ru Системное имя фиктивной грани. \en Default name of dummy face. rmn_ReservedName = -3, ///< \ru Системное имя резервное. \en Reserved name. rmn_SectionItemName = -2, ///< \ru Системное имя секущего объекта. \en Section item name. - rmn_DefaultName = -1, ///< \ru Системное имя по умолчанию (= SIMPLENAME_MAX). \en Default name (= SIMPLENAME_MAX). + rmn_DefaultName = -1, ///< \ru Системное имя по умолчанию (= c3d::SIMPLENAME_MAX). \en Default name (= c3d::SIMPLENAME_MAX). }; // The name -2 is also reserved for system names in the Kompas CAD. protected: /// \ru Флаги. \en Flags. enum EFlags { - f_Cut = 0x01, ///< \ru Примитив разрезан. \en Primitive is cut. - f_Sheet = 0x02, ///< \ru Примитив является листовым. (Действителен только для граней) \en Primitive is sheet. (Valid only for faces) - f_InnerBend = 0x04, ///< \ru Примитив является внутренней гранью сгиба. (Действителен только для граней) //-V112 \en Primitive is an internal face of bend. (Valid only for faces) //-V112 - f_OuterBend = 0x08, ///< \ru Примитив является внешней гранью сгиба. (Действителен только для граней) \en Primitive is an external face of bend. (Valid only for faces) - f_SideBend = 0x10, ///< \ru Примитив является боковой гранью сгиба. (Действителен только для граней) \en Primitive is a side face of bend. (Valid only for faces) - f_RibBend = 0x20, ///< \ru Примитив является гранью ребра жесткости листового тела. (Действителен только для граней) \en Primitive is a face of reinforcement rib of sheet solid. (Valid only for faces) + f_Cut = 0x01, ///< \ru Примитив разрезан. \en Primitive is cut. + f_Sheet = 0x02, ///< \ru Примитив является листовым. (Действителен только для граней) \en Primitive is sheet. (Valid only for faces) + f_InnerBend = 0x04, ///< \ru Примитив является внутренней гранью сгиба. (Действителен только для граней) //-V112 \en Primitive is an internal face of bend. (Valid only for faces) //-V112 + f_OuterBend = 0x08, ///< \ru Примитив является внешней гранью сгиба. (Действителен только для граней) \en Primitive is an external face of bend. (Valid only for faces) + f_SideBend = 0x10, ///< \ru Примитив является боковой гранью сгиба. (Действителен только для граней) \en Primitive is a side face of bend. (Valid only for faces) + f_RibBend = 0x20, ///< \ru Примитив является гранью ребра жесткости листового тела. (Действителен только для граней) \en Primitive is a face of reinforcement rib of sheet solid. (Valid only for faces) + f_SweptFlange = 0x40, ///< \ru Примитив является гранью отбортовки. (Действителен только для граней) \en Primitive is a face of a swept flange. (Valid only for faces) }; protected: MbIdArr defNames; ///< \ru Множество идентификаторов. \en An array of identifiers. - public: - static const UniqueNamePtr uniqueFaceName; ///< \ru Уникальное имя фиктивной грани. \en Unique name of dummy face. + static const UniqueNamePtr uniqueFaceName; ///< \ru Уникальное имя фиктивной грани. \en Unique name of dummy face. public : - /// \ru Конструктор по умолчанию \en Default constructor + /// \ru Конструктор по умолчанию. \en Default constructor. MbName() : defNames() {} /// \ru Конструктор копирования. \en Copy-constructor. + /** \brief \ru Конструктор копирования. + \en Copy-constructor. \~ + \details \ru Конструктор копирования. \n + \en Copy-constructor. \n \~ + \param[in] other - \ru Другое имя. + \en Other name. \~ + */ MbName( const MbName & other ) : defNames( other.defNames ) {} /// \ru Деструктор. \en Destructor. virtual ~MbName(); -public: +public: /// \ru Получить главное имя. \en Get main name. SimpleName GetMainName() const; - /// \ru Установить главное имя. \en Set main name. - bool SetMainName( SimpleName n ); - /// \ru Установить имя. \en Set name. - void SetName ( const MbName &, bool setFlags = true ); + /** \brief \ru Установить главное имя. + \en Set main name. \~ + \details \ru Установить главное имя. \n + \en Set main name. \n \~ + \param[in] mn - \ru Главное имя. + \en Main name. \~ + \return \ru Возвращает 'true' в случае успешного выполнения. + \en Returns 'true' in case of successful execution. \~ + */ + bool SetMainName( SimpleName mn ); + /** \brief \ru Установить имя. + \en Set name. \~ + \details \ru Установить другое имя. \n + \en Set other name. \n \~ + \param[in] n - \ru Имя. + \en Name. \~ + \param[in] setFlags - \ru Копировать флаги имени. + \en Copy name flags. \~ + */ + void SetName ( const MbName & n, bool setFlags = true ); /// \ru Пуст ли массив идентификаторов имени. \en Whether the array of name identifiers is empty. bool IsEmpty () const { return defNames.IsEmpty(); } @@ -415,10 +457,25 @@ public: /// \ru Дать или сгенерировать дополнительное имя. \en Get or generate the additional name. SimpleName GetNameExtra( size_t i ) const; - ///< \ru Получение индекса разрезки. \en Get an index of a cutaway. + /// \ru Получение индекса резки. \en Get an index of a cutaway. bool IsCutIndex() const; - /// \ru Получение индекса разрезки. \en Get an index of a cutaway. + /** \brief \ru Получить индекс резки. + \en Get an cut index. \~ + \details \ru Получить индекс резки. \n + \en Get an index of a cutaway. \n \~ + \param[out] cutIndex - \ru Индекс резки. + \en Cut index. \~ + \return \ru Возвращает 'true' в случае успешного выполнения. + \en Returns 'true' in case of successful execution. \~ + */ bool GetCutIndex( SimpleName & cutIndex ) const { return defNames.GetCut( cutIndex ); } + /** \brief \ru Установить индекс резки. + \en Set an cut index. \~ + \details \ru Установить индекс резки. \n + \en Set an index of a cutaway. \n \~ + \param[in] cutIndex - \ru Индекс резки. + \en Cut index. \~ + */ /// \ru Установка индекса разрезки. \en Set an index of cutaway. void SetCutIndex( SimpleName cutIndex ); /// \ru Удаление индекса разрезки. \en Delete an index of cutaway. @@ -431,35 +488,39 @@ public: /// \ru Прямой доступ к первому имени. \en Direct access to the first name. void SetFirstNameDirect( SimpleName fi ) { C3D_ASSERT(defNames.CountBase() > (size_t)i_First); defNames.SetValueBase(fi, (size_t)i_First); } - /// \ru Получение значения флага порезанности. \en Get flag of cutaway. - bool IsCutFlag() const; - /// \ru Установление значения флага порезанности. \en Set flag of cutaway. - void SetCutFlag( bool s = true ); + /// \ru Получить значения флага порезанности. \en Get flag of cutaway. + bool IsCutFlag() const { return !!defNames.flags.GetFlagValue( f_Cut ); } + /// \ru Установить значение флага порезанности. \en Set flag of cutaway. + void SetCutFlag( bool s = true ) { defNames.flags.SetFlagValue( f_Cut, s ); } - /// \ru Установление значения флага листового примитива. \en Set flag of sheet primitive. - void SetSheet( bool s ); - /// \ru Установка значения флага внутренней части сгиба. \en Set flag of internal part of bend. - void SetInnerBend( bool s ); - /// \ru Установка значения флага внешней части сгиба. \en Set flag of external part of bend. - void SetOuterBend( bool s ); - /// \ru Установка значения флага боковой грани сгиба. \en Set flag of side part of bend. - void SetSideBend( bool s ); - /// \ru Установка значения флага грани ребра жесткости листового тела. \en Set flag of reinforcement rib part of sheet solid. - void SetStampRibBend( bool s ); - /// \ru Получение значения флага листового примитива. \en Get flag of sheet primitive. - bool IsSheet() const; - /// \ru Получение значения флага внутренней части сгиба. \en Get flag of internal part of bend. - bool IsInnerBend() const; - /// \ru Получение значения флага внешней части сгиба. \en Get flag of external part of bend. - bool IsOuterBend() const; - /// \ru Получение значения флага боковой грани сгиба. \en Get flag of side part of bend. - bool IsSideBend() const; - /// \ru Получение значения флага грани ребра жесткости листового тела. \en Get flag of reinforcement rib part of sheet solid. - bool IsStampRibBend() const; + /// \ru Установить значение флага листового примитива. \en Set flag of sheet primitive. + void SetSheet( bool s ) { defNames.flags.SetFlagValue( f_Sheet, s ); } + /// \ru Установить значение флага внутренней части сгиба. \en Set flag of internal part of bend. + void SetInnerBend( bool s ) { defNames.flags.SetFlagValue( f_InnerBend, s ); } + /// \ru Установить значение флага внешней части сгиба. \en Set flag of external part of bend. + void SetOuterBend( bool s ) { defNames.flags.SetFlagValue( f_OuterBend, s ); } + /// \ru Установить значение флага боковой грани сгиба. \en Set flag of side part of bend. + void SetSideBend( bool s ) { defNames.flags.SetFlagValue( f_SideBend, s ); } + /// \ru Установить значение флага грани ребра жесткости листового тела. \en Set flag of reinforcement rib part of sheet solid. + void SetStampRibBend( bool s ) { defNames.flags.SetFlagValue( f_RibBend, s ); } + /// \ru Установить значение флага грани отбортовки. \en Set flag of a swept flange. + void SetSweptFlange( bool s ) { defNames.flags.SetFlagValue( f_SweptFlange, s ); } + /// \ru Получить значение флага листового примитива. \en Get flag of sheet primitive. + bool IsSheet() const { return !!defNames.flags.GetFlagValue( f_Sheet ); } + /// \ru Получить значение флага внутренней части сгиба. \en Get flag of internal part of bend. + bool IsInnerBend() const { return !!defNames.flags.GetFlagValue( f_InnerBend ); } + /// \ru Получить значение флага внешней части сгиба. \en Get flag of external part of bend. + bool IsOuterBend() const { return !!defNames.flags.GetFlagValue( f_OuterBend ); } + /// \ru Получить значение флага боковой грани сгиба. \en Get flag of side part of bend. + bool IsSideBend() const { return !!defNames.flags.GetFlagValue( f_SideBend ); } + /// \ru Получить значение флага грани ребра жесткости листового тела. \en Get flag of reinforcement rib part of sheet solid. + bool IsStampRibBend() const { return !!defNames.flags.GetFlagValue( f_RibBend ); } + /// \ru Получить значение флага грани отбортовки. \en Get flag of a swept flange. + bool IsSweptFlange() const { return !!defNames.flags.GetFlagValue( f_SweptFlange ); } - /// \ru Установка индекса копирования. \en Set an index of copying. + /// \ru Установить индекс копирования. \en Set an index of copying. void SetCopyIndex( SimpleName ci ) { defNames.SetCopyIndex( ci ); } - /// \ru Получение индекса копирования. \en Get an index of copying. + /// \ru Получить индекс копирования. \en Get an index of copying. bool GetCopyIndex( SimpleName & ci ) const { return defNames.GetCopyIndex( ci ); } /** \brief \ru Установить положение в сетке копирования. @@ -533,7 +594,8 @@ public: void Assign( const MbName & other ) { defNames.Assign( other.defNames ); } /// \ru Сделать из имени шаблон. \en Create template from name. - void MakeTemplate() { + void MakeTemplate() + { C3D_ASSERT( defNames.CountBase() ); if ( defNames.CountBase() > (size_t)i_First ) { SetFirstNameDirect( 0 ); @@ -563,9 +625,10 @@ KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbName, MATH_FUNC_EX ) // \ru Для рабо //---------------------------------------------------------------------------------------- -// +// \ru Множество пустое? \en Is the array empty? // --- -inline bool MbIdArr::IsEmpty() const { +inline +bool MbIdArr::IsEmpty() const { // \ru IsEmpty проверять parr[MbName::i_Main] только для count == 1 \en IsEmpty check parr[MbName::i_Main] only for count == 1 // \ru Если count > 1 - считать не пустым \en If count > 1, then it is considered as non-empty return ( Count() > (size_t)MbName::i_Main ) ? ( (Count() - 1) == (size_t)MbName::i_Main ? !parr[(size_t)MbName::i_Main] : false ) : true; @@ -575,7 +638,8 @@ inline bool MbIdArr::IsEmpty() const { //---------------------------------------------------------------------------------------- // \ru Получение индекса разрезки \en Get an index of a cutaway // --- -inline bool MbIdArr::GetCut( SimpleName & cutIndex ) const +inline +bool MbIdArr::GetCut( SimpleName & cutIndex ) const { if ( Count() > (size_t)MbName::i_Cut ) { cutIndex = parr[(size_t)MbName::i_Cut]; @@ -588,7 +652,8 @@ inline bool MbIdArr::GetCut( SimpleName & cutIndex ) const //---------------------------------------------------------------------------------------- // \ru Получение индекса копирования \en Get an index of copying // --- -inline bool MbIdArr::GetCopyIndex( SimpleName & ci ) const +inline +bool MbIdArr::GetCopyIndex( SimpleName & ci ) const { if ( Count() > (size_t)MbName::i_Copy ) { ci = parr[(size_t)MbName::i_Copy]; @@ -601,7 +666,8 @@ inline bool MbIdArr::GetCopyIndex( SimpleName & ci ) const //------------------------------------------------------------------------------ // \ru Получить главное имя. \en Get main name. // --- -inline SimpleName MbName::GetMainName() const +inline +SimpleName MbName::GetMainName() const { if ( defNames.CountBase() > (size_t)i_Main ) return defNames.GetValueBase( (size_t)i_Main ); @@ -612,7 +678,8 @@ inline SimpleName MbName::GetMainName() const //------------------------------------------------------------------------------ // \ru Установить главное имя. \en Set main name. // --- -inline bool MbName::SetMainName( SimpleName n ) +inline +bool MbName::SetMainName( SimpleName n ) { bool res = true; if ( static_cast(rmn_DummyFaceName) == n ) { // Reserved for unique name of dummy face (-1 = SIMPLENAME_MAX, -2 is already used for Kompas CAD and It's the error on their side) @@ -620,7 +687,6 @@ inline bool MbName::SetMainName( SimpleName n ) C3D_ASSERT_UNCONDITIONAL( false ); res = false; } - if ( defNames.CountBase() > 0 ) defNames.SetValueBase( n, 0 ); else @@ -633,7 +699,8 @@ inline bool MbName::SetMainName( SimpleName n ) //---------------------------------------------------------------------------------------- // \ru Проверка на равенство. \en Check for equality. // --- -inline bool MbName::operator == ( const MbName & n ) const +inline +bool MbName::operator == ( const MbName & n ) const { if ( defNames.CountAll() == n.defNames.CountAll() ) { if ( defNames.CountAll() ) { @@ -649,7 +716,8 @@ inline bool MbName::operator == ( const MbName & n ) const //---------------------------------------------------------------------------------------- // \ru Проверка не неравенство. \en Check for inequality. // --- -inline bool MbName::operator < ( const MbName & n ) const +inline +bool MbName::operator < ( const MbName & n ) const { if ( defNames.CountAll() == n.defNames.CountAll() ) { if ( defNames.CountAll() ) { @@ -666,9 +734,10 @@ inline bool MbName::operator < ( const MbName & n ) const //---------------------------------------------------------------------------------------- -// \ru Получение индекса разрезки. \en Get an index of a cutaway. +// \ru Получение индекса резки. \en Get an index of a cutaway. // --- -inline bool MbName::IsCutIndex() const +inline +bool MbName::IsCutIndex() const { SimpleName cutIndex = 0; if ( GetCutIndex( cutIndex ) ) @@ -677,112 +746,14 @@ inline bool MbName::IsCutIndex() const } -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага порезанности. \en Get flag of cutaway. -// --- -inline bool MbName::IsCutFlag() const { - return !!defNames.flags.GetFlagValue( f_Cut ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага порезанности. \en Set flag of cutaway. -// --- -inline void MbName::SetCutFlag( bool s ) { - defNames.flags.SetFlagValue( f_Cut, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага листового примитива. \en Set flag of sheet primitive. -// --- -inline void MbName::SetSheet( bool s ) { - defNames.flags.SetFlagValue( f_Sheet, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага листового примитива. \en Get flag of sheet primitive. -// --- -inline bool MbName::IsSheet() const { - return !!defNames.flags.GetFlagValue( f_Sheet ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага внутренней части сгиба. \en Set flag of internal part of bend. -// --- -inline void MbName::SetInnerBend( bool s ) { - defNames.flags.SetFlagValue( f_InnerBend, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага внутренней части сгиба. \en Get flag of internal part of bend. -// --- -inline bool MbName::IsInnerBend() const { - return !!defNames.flags.GetFlagValue( f_InnerBend ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага внешней части сгиба. \en Set flag of external part of bend. -// --- -inline void MbName::SetOuterBend( bool s ) { - defNames.flags.SetFlagValue( f_OuterBend, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага внешней части сгиба. \en Get flag of external part of bend. -// --- -inline bool MbName::IsOuterBend() const { - return !!defNames.flags.GetFlagValue( f_OuterBend ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага боковой грани сгиба. \en Set flag of side part of bend. -// --- -inline void MbName::SetSideBend( bool s ) { - defNames.flags.SetFlagValue( f_SideBend, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага боковой грани сгиба. \en Get flag of side part of bend. -// --- -inline bool MbName::IsSideBend() const { - return !!defNames.flags.GetFlagValue( f_SideBend ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установление значения флага грани ребра жесткости листового тела. \en Set flag of reinforcement rib part of sheet solid. -// --- -inline void MbName::SetStampRibBend( bool s ) { - defNames.flags.SetFlagValue( f_RibBend, s ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Получение значения флага грани ребра жесткости листового тела. \en Get flag of reinforcement rib part of sheet solid. -// --- -inline bool MbName::IsStampRibBend() const { - return !!defNames.flags.GetFlagValue( f_RibBend ); -} - - ////////////////////////////////////////////////////////////////////////////////////////// // // \ru Имя объекта и его копии. \en Name of object and its duplicate. // ////////////////////////////////////////////////////////////////////////////////////////// - #define ORIGINAL_MAIN_NAME // \ru Используется для работы с массивами. \en Used for arrays treatment. - #ifdef ORIGINAL_MAIN_NAME //---------------------------------------------------------------------------------------- /** \brief \ru Имя объекта и его копии. @@ -793,26 +764,47 @@ inline bool MbName::IsStampRibBend() const { */ // --- class MATH_CLASS MbNamePair { + friend class MbNamePairList; private: - MbName * gageName; // \ru Имя оригинала. \en A name of original. - MbName * copyName; // \ru Имя копии. \en A name of duplicate. - + const MbName * gageName; ///< \ru Имя оригинала. \en A name of original. + const MbName * copyName; ///< \ru Имя копии. \en A name of duplicate. // могут использоваться для самостоятельного поиска - mutable SimpleName copyHash; // \ru Кэш хеша имени оригинала. \en + mutable SimpleName copyHash; ///< \ru Кэш хеша имени оригинала. \en Hash cache of the original name. public: - /// \ru Конструктор. \en Constructor. - MbNamePair( MbName * orig, MbName * copy ) : gageName( orig ), copyName( copy ), copyHash( SIMPLENAME_MAX ) {} - /// \ru Конструктор для поиска по имени копии. \en Constructor for find by copy name. - MbNamePair( MbName * copy ) : gageName( NULL ), copyName( copy ), copyHash( SIMPLENAME_MAX ) {} - /// \ru Конструктор для поиска по хешу копии. \en Constructor for find by copy hash. - MbNamePair( SimpleName copy ) : gageName( NULL ), copyName( NULL ), copyHash( copy ) {} + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор. \n + \en Constructor. \n \~ + \param[in] orig - \ru Имя оригинала. + \en The name of the original. \~ + \param[in] copy - \ru Имя копии. + \en The name of the copy. \~ + */ + MbNamePair( const MbName * orig, const MbName * copy ) : gageName( orig ), copyName( copy ), copyHash( c3d::SIMPLENAME_MAX ) {} + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор для поиска по имени копии. \n + \en Constructor for find by copy name. \n \~ + \param[in] copy - \ru Имя копии. + \en The name of the copy. \~ + */ + MbNamePair( const MbName * copy ) : gageName( C3D_NULL_PTR ), copyName( copy ), copyHash( c3d::SIMPLENAME_MAX ) {} + /// \ru . \en . + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор для поиска по хешу копии. \n + \en Constructor for find by copy hash. \n \~ + \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 ) {} /// \ru Деструктор. \en Destructor. ~MbNamePair() {} public: /// \ru Обнулить имя оригинала и имя копии. \en Set name of original and of its duplicate to null. - void SetNull() { gageName = NULL; copyName = NULL; copyHash = SIMPLENAME_MAX; } + void SetNull() { gageName = C3D_NULL_PTR; copyName = C3D_NULL_PTR; copyHash = c3d::SIMPLENAME_MAX; } /// \ru Оператор сравнения. \en Comparison operator. bool operator == ( const MbNamePair & other ) const; /// \ru Оператор меньше. \en "Less than" operator. @@ -824,10 +816,21 @@ public: copyHash = Prepare(*copyName).Hash(); return copyHash; } - /// \ru Правило приготовления имен. \en Names prepare rules. - static MbName Prepare( const MbName & name ); - - friend class MATH_CLASS MbNamePairList; + /** \brief \ru Правило приготовления имен. + \en Names prepare rules. \~ + \details \ru Правило приготовления имен. \n + \en Names prepare rules. \n \~ + \param[out] name - \ru Имя заготовки. + \en Workpiece name. \~ + \return \ru Возвращает имя. + \en Returns a name. \~ + */ + static MbName Prepare( const MbName & name ) + { + MbName ret( name ); + ret.SetMainName( c3d::SIMPLENAME_MAX ); + return ret; + } }; @@ -837,7 +840,6 @@ public: // ////////////////////////////////////////////////////////////////////////////////////////// - //---------------------------------------------------------------------------------------- /** \brief \ru Таблица соответствия имён. \en Table of names correspondence. \~ @@ -847,52 +849,69 @@ public: */ // --- class MATH_CLASS MbNamePairList { + friend class MATH_CLASS MbNameMaker; + friend class MATH_CLASS MbSNameMaker; private: - CSSArray checkList; ///< \ru Имена объектов и их копий. \en Names of objects and of its duplicates. - + mutable CSSArray checkList; ///< \ru Имена объектов и их копий. \en Names of objects and of its duplicates. public: /// \ru Конструктор. \en Constructor. - MbNamePairList( size_t count = 0 ) : checkList( count, 1 ) {} + MbNamePairList() : checkList() {} /// \ru Деструктор. \en Destructor. ~MbNamePairList() { DeleteNames(); } public: - /// \ru Добавить имя объекта и имя его копии, имя оригинала и копии должно быть создано по new. \en Store names of object and its duplicate, which are created by new. - void AddNameData( MbName * orig, MbName * copy ) + /** \brief \ru Добавить имя объекта и имя его копии. + \en Add names of object and its duplicate. \~ + \details \ru Добавить имя объекта и имя его копии, имя оригинала и копии должно быть создано по new. \n + \en Add names of object and its duplicate, which have to be created by new. \n \~ + \param[in] orig - \ru Имя оригинала. + \en The name of the original. \~ + \param[in] copy - \ru Имя копии. + \en The name of the copy. \~ + */ + void AddNameData( const MbName * orig, const MbName * copy ) { - C3D_ASSERT( (orig != NULL) && (copy != NULL) ); - if ( (orig != NULL) && (copy != NULL) ) { + C3D_ASSERT( (orig != C3D_NULL_PTR) && (copy != C3D_NULL_PTR) ); + if ( (orig != C3D_NULL_PTR) && (copy != C3D_NULL_PTR) ) { checkList.Add( MbNamePair( orig, copy ) ); } } /// \ru Выделить память под элементы. \en Allocate memory for elements. void Reserve( size_t count ) { checkList.Reserve( count ); } - /// \ru Очистить массив не удаляя память под элементы. \en Erase array without deleting memory for elements. + /// \ru Очистить массив, не удаляя память под элементы. \en Erase array without deleting memory for elements. void Erase() { DeleteNames(); checkList.Flush(); } /// \ru Удалить память под элементы. \en Delete memory for elements. void Free() { DeleteNames(); checkList.HardFlush(); } /// \ru Удалить ненужные элементы по именам копий. \en Clean up unnecessary pairs by name copies. - bool Clean( const std::vector & delNamesCopies ); + bool Clean( const c3d::ConstNamesVector & delNamesCopies ); /// \ru Заменить имена копий. \en Replace names copies. - bool Replace( const MbName & newNameCopies, const std::vector & oldNamesCopies ); + bool Replace( const MbName & newNameCopies, const c3d::ConstNamesVector & oldNamesCopies ); /// \ru Найти имя объекта по имени его копии. \en Find name of object by name of its duplicate. - const MbName * FindOriginalByCopy( const MbName * copy ); + const MbName * FindOriginalByCopy( const MbName * ) const; /// \ru Найти имя копии объекта по имени его оригинала. \en Find name of duplicate object by name of its original. - const MbName * FindCopyByOriginal( const MbName & original ) const; - /// \ru Найти имя объекта по хешу его копии. \en Find name of object by hash of its duplicate. - const MbName * FindOriginalByCopy( const SimpleName & originalHash ); + const MbName * FindCopyByOriginal( const MbName & ) const; + /// \ru Найти имя оригинала объекта по хешу имени копии объекта. \en Find the name of the original object by the hash of the name of the copy of the object. + const MbName * FindOriginalByCopy( const SimpleName & originalHash ) const; const CSSArray & GetCheckList() const { return checkList; } - - friend class MATH_CLASS MbNameMaker; - friend class MATH_CLASS MbSNameMaker; - private: /// \ru Удалить имена в каждом элементе. \en Delete names in each element. - void DeleteNames(); + void DeleteNames() + { + for ( size_t i = 0, cnt = checkList.size(); i < cnt; ++i ) { + MbNamePair & namePair = checkList[i]; + delete namePair.gageName; + delete namePair.copyName; + namePair.SetNull(); + } + } /// \ru Обнулить имя оригинала и имя копии в каждом элементе. \en Set name of original and of its duplicate to null in each element. - void SetNull(); + void SetNull() + { + for ( size_t i = 0, cnt = checkList.size(); i < cnt; ++i ) + checkList[i].SetNull(); + } }; #endif // ORIGINAL_MAIN_NAME @@ -903,6 +922,8 @@ private: // ////////////////////////////////////////////////////////////////////////////////////////// +class MATH_CLASS MbTopologyItem; +class MATH_CLASS MbTopologyProxy; //---------------------------------------------------------------------------------------- /** \brief \ru Генератор имен. @@ -912,13 +933,13 @@ private: \en Generator of names of topological objects by the given template. \n Do not use the main names from the range MbName::ReservedMainNames (exception - MbName::ReservedMainNames::rmn_DefaultName). \n \~ \internal -\ru Надо добиться того, чтобы имена не могли создаваться в обход определенных правил + \ru Надо добиться того, чтобы имена не могли создаваться в обход определенных правил и одновременно предусмотреть возможность создания новых правил!!! Задача противоречивая - попробуем вот так. Если надо создать новое правило генерации имени, то сделайте наследника от этого класса напишите новое правило создающее MbIdArr (LiSArray) (или просто SimpleName) и отдайте на вход MakeName -\en It is necessary to achieve that names can't be created passing over certain rules + \en It is necessary to achieve that names can't be created passing over certain rules and at the same time to provide possibility for creating new rules!!! Task is inconsistent - try so. If it is necessary to create a new rule for generating name, then inherit from this class, @@ -928,7 +949,7 @@ private: \ingroup Names */ //--- -class MATH_CLASS MbNameMaker { +class MATH_CLASS MbNameMaker : public MbRefItem { protected: MbName defName; ///< \ru Шаблон имени. \en Name template. @@ -939,64 +960,212 @@ protected: #endif // ORIGINAL_MAIN_NAME public: - /// \ru Конструктор по главному имени. \en Constructor by main name. - MbNameMaker( SimpleName mn ); - /// \ru Конструктор по имени. \en Constructor by name. - MbNameMaker( const MbName & _name ); - /// \ru Конструктор другому генератору имен. \en Constructor by another generator of names. - MbNameMaker ( const MbNameMaker & o ); + /** \brief \ru Конструктор по главному имени. + \en Constructor by main name. \~ + \details \ru Конструктор по главному имени. \n + \en Constructor by main name. \n \~ + \param[in] mn - \ru Главное имя. + \en Main name. \~ + */ + MbNameMaker( SimpleName mn ) + : MbRefItem() + , defName() + , version() +#ifdef ORIGINAL_MAIN_NAME + , original( c3d::SIMPLENAME_MAX ) + , nameList( C3D_NULL_PTR ) +#endif // ORIGINAL_MAIN_NAME + { + defName.SetMainName( mn ); + defName.MakeTemplate(); + } + /** \brief \ru Конструктор по имени. + \en Constructor by name. \~ + \details \ru Конструктор по имени. \n + \en Constructor by name. \n \~ + \param[in] n - \ru Имя. + \en Name. \~ + */ + MbNameMaker( const MbName & n ) + : MbRefItem() + , defName( n ) + , version() +#ifdef ORIGINAL_MAIN_NAME + , original( c3d::SIMPLENAME_MAX ) + , nameList( C3D_NULL_PTR ) +#endif // ORIGINAL_MAIN_NAME + { + defName.MakeTemplate(); + } + /** \brief \ru Конструктор другому генератору имен. + \en Constructor by another generator of names. \~ + \details \ru Конструктор другому генератору имен. \n + \en Constructor by another generator of names. \n \~ + \param[in] nm - \ru Генератор имен. + \en Names generator. \~ + */ + MbNameMaker ( const MbNameMaker & nm ) + : MbRefItem() + , defName( nm.defName ) + , version( nm.version ) +#ifdef ORIGINAL_MAIN_NAME + , original( nm.original ) + , nameList( nm.nameList ) +#endif // ORIGINAL_MAIN_NAME + {} /// \ru Деструктор. \en Destructor. - ~MbNameMaker() {} + virtual ~MbNameMaker() {} public: - /// \ru Доступ к главному имени. \en Access to main name. - SimpleName GetMainName () const { return defName.GetMainName(); } - /// \ru Установка главного имени. \en Set main name. - void SetMainName ( SimpleName n ) { defName.SetMainName( n ); } - /// \ru Версия изготовления. \en Version of manufacture. - const VersionContainer & GetVersionContainer() const { return version.GetVersionContainer(); } - /// \ru Версия изготовления. \en Version of manufacture. - const MbNameVersion & GetMbNameVersion() const { return version; } - /// \ru Версия изготовления. \en Version of manufacture. - void SetVersion( const MbNameVersion & v ) { version = v; } + /// \ru Получить главное имя. \en Get main name. + SimpleName GetMainName () const { return defName.GetMainName(); } + /** \brief \ru Установить главное имя. + \en Set main name. \~ + \details \ru Установить главное имя. \n + \en Set main name. \n \~ + \param[in] n - \ru Главное имя. + \en Main name. \~ + */ + void SetMainName ( SimpleName n ) { defName.SetMainName( n ); } - /// \ru Получить версию математического ядра. \en Get version of the mathematical kernel. - VERSION GetMathVersion() const { return version.GetVersionContainer().GetMathVersion(); } - /// \ru Установить версию математического ребра. \en Set version of the mathematical kernel. - void SetMathVersion( VERSION v ) { version.SetVersion( 0, v ); } + /// \ru Получить версию изготовления. \en Get a version of manufacture. + const VersionContainer & GetVersionContainer() const { return version.GetVersionContainer(); } + /// \ru Получить версию изготовления. \en Get a version of manufacture. + const MbNameVersion & GetMbNameVersion() const { return version; } + /** \brief \ru Установить версию изготовления. + \en Set version of manufacture. \~ + \details \ru Установить версию изготовления. \n + \en Set version of manufacture. \n \~ + \param[in] v - \ru Версия изготовления. + \en Version of manufacture. \~ + */ + void SetVersion( const MbNameVersion & v ) { version = v; } + /// \ru Получить версию математического ядра. \en Get version of the mathematical kernel. + VERSION GetMathVersion() const { return version.GetVersionContainer().GetMathVersion(); } + /** \brief \ru Установить версию математического ядра. + \en Set version of the mathematical kernel. \~ + \details \ru Установить версию математического ядра. \n + \en Set version of the mathematical kernel. \n \~ + \param[in] v - \ru Версия изготовления. + \en Version of manufacture. \~ + */ + void SetMathVersion( VERSION v ) { version.SetVersion( 0, v ); } + +public: + /** \brief \ru Получить имя топологического объекта. + \en Get topology item name. \~ + \details \ru Получить имя топологического объекта. \n + \en Get topology item name. \n \~ + \param[in] item - \ru Топологический объект. + \en Topology item. \~ + \param[in,out] name - \ru Копия имени топологического объекта. + \en Topology item name copy. \~ + */ + virtual void GetItemName( const MbTopologyItem & item, MbName & name ) const; + /** \brief \ru Установить имя топологическому объекту. + \en Set topology item name. \~ + \details \ru Установить имя топологическому объекту. \n + \en Set topology item name. \n \~ + \param[in] name - \ru Новое имя топологического объекта. + \en Topology item new name. \~ + \param[in,out] item - \ru Топологический объект. + \en Topology item. \~ + */ + virtual void SetItemName( const MbName & name, MbTopologyItem & item ) const; + + /// \ru Является ли именователь родительским для данного топологического элемента? \en Is the name maker a parent for a given topological element?. + virtual bool IsChild( const MbTopologyItem & ) const; + +public: + /** \brief \ru Генерация имени топологического объекта по двум простым именам. + \en Generate name of topological object by two simple names. \~ + \details \ru Генерация имени топологического объекта по двум простым именам. \n + \en Generate name of topological object by by two simple names. \n \~ + \param[in] sn1 - \ru Простое имя #1. + \en Simple name #2. \~ + \param[in] sn2 - \ru Простое имя #1. + \en Simple name #2. \~ + \param[in,out] dstItem - \ru Топологический объект. + \en Topology item. \~ + */ + virtual void MakeName( SimpleName sn1, SimpleName sn2, MbTopologyItem & dstItem ) const; + /** \brief \ru Генерация имени топологического объекта по простому имени. + \en Generate name of topological object by simple name. \~ + \details \ru Генерация имени топологического объекта по простому имени. \n + \en Generate name of topological object by simple name. \n \~ + \param[in] sn - \ru Простое имя. + \en Simple name. \~ + \param[in,out] dstItem - \ru Топологический объект. + \en Topology item. \~ + */ + virtual void MakeName( SimpleName sn, MbTopologyItem & dstItem ) const; + /** \brief \ru Генерация имени для грани скругления. + \en Generate name for fillet face. \~ + \details \ru Генерация имени для грани скругления. \n + \en Generate name for fillet face. \n \~ + \param[in] srcName - \ru Имя источника. + \en Source name. \~ + \param[in,out] dstItem - \ru Топологический объект. + \en Topology item. \~ + */ + virtual void MakeFilletFaceName( const MbName & srcName, MbTopologyItem & dstItem ) const; protected: - /// \ru Генерация имени name по шаблону и двум простым именам. \en Generate 'name' name by template and two simple names. - void MakeNameBy( SimpleName snFirst, SimpleName snCut, MbName & name ) const; - /// \ru Генерация имени name шаблону и источнику для грани скругления. \en Generate 'name' name by template and by source for fillet face. - void MakeNameBy( const MbName & source, MbName & name ) const; + /// \ru Генерация имени по двум простым именам SimpleName. \en Generate name by two simple names. + void MakeName( SimpleName sn1, SimpleName sn2, MbName & dstName ) const; + /// \ru Генерация имени по простому имени SimpleName. \en Generate name by simple name. + void MakeName( SimpleName sn, MbName & dstName ) const; + /// \ru Генерация имени для грани скругления. \en Generate name for fillet face. + void MakeFilletFaceName( const MbName & srcName, MbName & dstName ) const; + +public: + /** \brief \ru Генерация имени топологического объекта по шаблону и простому имени. + \en Generate name of topological object by template and by simple name. \~ + \details \ru Генерация имени топологического объекта по шаблону и простому имени. \n + \en Generate name of topological object by template and by simple name. \n \~ + \param[in] sn - \ru Простое имя. + \en Simple name. \~ + \param[in,out] dstItem - \ru Топологический объект. + \en Topology item. \~ + */ + virtual void MakeNameBy( SimpleName sn, MbTopologyItem & dstItem ) const; +protected: + /// \ru Генерация имени по шаблону и простому имени. \en Generate name by template and by simple name. + void MakeNameBy( SimpleName sn, MbName & dstName ) const; + /// \ru Генерация имени по шаблону и двум простым именам. \en Generate name by template and two simple names. + void MakeNameBy( SimpleName snFirst, SimpleName snCut, MbName & dstName ) const; + /// \ru Генерация имени по шаблону и источнику для грани скругления. \en Generate name by template and by source for fillet face. + void MakeNameBy( const MbName & srcName, MbName & dstName ) const; public: - /// \ru Генерация имени name по шаблону и простому имени. \en Generate 'name' name by template and by simple name. - void MakeNameBy( SimpleName sn, MbName & name ) const; - /// \ru Генерация имени name по двум простым именам SimpleName. \en Generate 'name' name by two SimpleName simple names. - void MakeName( SimpleName sn1, SimpleName sn2, MbName & name ) const; - /// \ru Генерация имени name по простому имени SimpleName. \en Generate 'name' name by SimpleName simple name. - void MakeName( SimpleName sn, MbName & name ) const; - /// \ru Генерация имени name для грани скругления. \en Generate 'name' name for fillet face. - void MakeFilletFaceName( const MbName &, MbName & name ) const; #ifdef ORIGINAL_MAIN_NAME - /// \ru Установить исходное главное имя и таблицу соответствия имён. \en Set original main name and table of name correspondence. - void SetOriginalMainName( SimpleName orig, MbNamePairList * list ) { original = orig; nameList = list; } - /// \ru Исходное главное имя. \en Source main name. - SimpleName GetOriginalMainName() const { return original; } - /// \ru Таблица соответствия имён оригиналов и их копий. \en Table of correspondence of names of originals and of its duplicates. - MbNamePairList * GetNameList() const { return nameList; } - /// \ru Получить генератор имен оригинала, считая, что это именователь копии. \en Get original name maker. - MbNameMaker GetOriginalNameMaker() const; - /// \ru Удалить ненужные элементы по именам копий. \en Clean up unnecessary pairs by name copies. - bool CleanNameList( std::vector & delNamesCopies ) const; - /// \ru Заменить имена копий. \en Replace names copies. - bool ReplaceNameList( const MbName & newNameCopies, const std::vector & oldNamesCopies ) const; + /// \ru Установить исходное главное имя и таблицу соответствия имён. \en Set original main name and table of name correspondence. + void SetOriginalMainName( SimpleName orig, MbNamePairList * list ) { original = orig; nameList = list; } + /// \ru Исходное главное имя. \en Source main name. + SimpleName GetOriginalMainName() const { return original; } + + /// \ru Таблица соответствия имён оригиналов и их копий. \en Table of correspondence of names of originals and of its duplicates. + const MbNamePairList * GetNameList() const { return nameList; } + /// \ru Таблица соответствия имён оригиналов и их копий. \en Table of correspondence of names of originals and of its duplicates. + MbNamePairList * SetNameList() const { return nameList; } + + /// \ru Получить генератор имен оригинала, считая, что это именователь копии. \en Get original name maker. + 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); + } + /// \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); + } #endif // ORIGINAL_MAIN_NAME - /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbNameMaker & ) const; + /// \ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbNameMaker & ) const; +public: + /// \ru Создать заменитель топологического объекта. \en Create topology item proxy. + static MbTopologyProxy & CreateTopologyProxy(); protected: /// \ru Оператор чтения. \en Read operator. @@ -1046,15 +1215,37 @@ private: public: /// \ru Конструктор. \en Constructor. - explicit MbSNameMaker ( SimpleName _mainName = UNDEFINED_SNAME, ESides _sideAdd = MbSNameMaker::i_SideNone, SimpleName _buttAdd = 0 ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSNameMaker ( const MbSNameMaker & other ); + explicit MbSNameMaker ( SimpleName _mainName = c3d::UNDEFINED_SNAME, + ESides _sideAdd = MbSNameMaker::i_SideNone, + SimpleName _buttAdd = 0 ) + : SimpleNameArray( 0, 2 ) + , MbNameMaker ( _mainName ) + , sideAdd ( _sideAdd ) + , buttAdd ( _buttAdd ) + , cpyHist ( true ) + , addParentNamesAttributes( false ) + {} + /// \ru Конструктор по другому именователю (конструктор копирования). \en Constructor by other name-maker (copy-constructor). + MbSNameMaker ( const MbSNameMaker & other ) + : SimpleNameArray( other.Count(), 2 ) + , MbNameMaker ( other ) + , sideAdd ( i_SideNone ) + , buttAdd ( 0 ) + , cpyHist ( true ) + , addParentNamesAttributes( false ) + { + SetNameMaker( other, true ); + } + /// \ru Деструктор. \en Destructor. + virtual ~MbSNameMaker() {} +public: /// \ru Инициализировать по другому именователю. \en Initialize by another name-maker. - void SetName( const MbSNameMaker & other, bool setVersion = false ); - /// \ru Получить простое имя из массива с контролем выхода за границы \en Get simple name from array with control of overruning - SimpleName GetName( size_t i ) const; - /// \ru Инверсия. \en Inversion. + void SetNameMaker( const MbSNameMaker & other, bool setVersion = false ); + + /// \ru Получить простое имя из массива с контролем выхода за границы. \en Get simple name from array with control of overruning. + SimpleName GetSimpleName( size_t i ) const; + /// \ru Инверсия простых имен именователя. \en Inversion of simple names array. void Inverse(); /// \ru Выдать имя в виде условного положения в сетке копирования (для массивов). \en Get name in form of conditional position in grid of copying (for arrays). @@ -1075,32 +1266,34 @@ public: /// \ru Установить количество имен. \en Set count of names. void SetNamesCount( size_t newCount ); - /// \ru Генерация имени name торцевой грани: mainName, +/-defName, знак определяется направлением. \en Generate 'name' name for butt face: mainName, +/-defName, sign is defined by direction. - void SetButtFaceName( MbName & name, MbSNameMaker::ESides side ) const; - /// \ru Генерация имени name грани: mainName, hash( sideName, add ). \en Generate 'name' name for face: mainName, hash( sideName, add ). - void SetFaceName( MbName & name, size_t i, SimpleName add ) const; - /// \ru Генерация имени name каркаса. \en Generate 'name' name for frame. - void SetWireName( MbName & name, size_t i ) const; - /// \ru Генерация имени name ребра из имен граней (sense - направление ребра по отношению к подлежащей кривой). \en Generate 'name' name for edge from names of faces ('sense' is a direction of edge relative to underlined curve). - void CompileEdgeName( MbName & name, - const MbName * f1, - const MbName * f2, - size_t ind, - bool sameSense ) const; - /// \ru Генерация имени name по другому имени, полное совпадение. \en Generate 'name' name by other name, full coincidence. - void CompileEdgeName( MbName & name, const MbName & other ) const; +public: + /// \ru Генерация имени name торцевой грани: mainName, +/-defName, знак определяется направлением. \en Generate name for butt face: mainName, +/-defName, sign is defined by direction. + virtual void MakeButtFaceName( MbTopologyItem & item, MbSNameMaker::ESides side ) const; + /// \ru Генерация имени грани: mainName, hash( sideName, add ). \en Generate name for face: mainName, hash( sideName, add ). + virtual void MakeFaceName( MbTopologyItem & item, size_t i, SimpleName add ) const; + /// \ru Генерация имени на основе главного имени и простого имени из именователя. \en Generate name on the base of main name and simple name from this names generator. + virtual void MakeItemName( MbTopologyItem & item, size_t i ) const; + /// \ru Генерация имени ребра из имен граней (sense - направление ребра по отношению к подлежащей кривой). \en Generate name for edge from names of faces ('sense' is a direction of edge relative to underlined curve). + virtual void CompileEdgeName( MbTopologyItem & item, + const MbName * faceName1, + const MbName * faceName2, + size_t ind, + bool sameSense ) const; + /// \ru Генерация имени по другому имени, полное совпадение. \en Generate name by other name, full coincidence. + virtual void CompileEdgeName( MbTopologyItem & item, const MbName & other ) const; +public: /// \ru Добавить генератор имен. \en Add name generator. - void AddSNameMaker( const MbSNameMaker & other ); + void AddSNameMaker( const MbSNameMaker & other ) { *this += other; } /// \ru Создать с именем индекса iFrom. \en Create with name of iForm index. - MbSNameMaker * GetSNameMakerFrom( size_t iFrom, size_t iTo ); + MbSNameMaker * GetSNameMakerFrom( size_t iFrom, size_t iTo ); #ifdef ORIGINAL_MAIN_NAME /// \ru Получить генератор имен оригинала, считая, что это именователь копии. \en Get original name maker. - MbSNameMaker GetOriginalSNameMaker() const; + MbSNameMaker GetOriginalSNameMaker() const; #endif // ORIGINAL_MAIN_NAME /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbSNameMaker & ) const; + bool IsSame( const MbSNameMaker & ) const; protected: /// \ru Оператор чтения. \en Read operator. @@ -1117,39 +1310,10 @@ private: //---------------------------------------------------------------------------------------- -// \ru Конструктор. \en Constructor. -//--- -inline MbSNameMaker::MbSNameMaker ( SimpleName _mainName, // =-1 - MbSNameMaker::ESides _sideAdd, // = 0 - SimpleName _buttAdd ) // = 0 - : SimpleNameArray( 0, 2 ) - , MbNameMaker ( _mainName ) - , sideAdd ( _sideAdd ) - , buttAdd ( _buttAdd ) - , cpyHist ( true ) - , addParentNamesAttributes( false ) -{} - - -//---------------------------------------------------------------------------------------- -// \ru Конструктор по другому именователю. \en Constructor by other name-maker. +// \ru Инициализировать по другому именователю. \en Initialize by another name-maker. // --- -inline MbSNameMaker::MbSNameMaker ( const MbSNameMaker & other ) - : SimpleNameArray( other.Count(), 2 ) - , MbNameMaker ( other ) - , sideAdd ( i_SideNone ) - , buttAdd ( 0 ) - , cpyHist ( true ) - , addParentNamesAttributes( false ) -{ - SetName( other, true ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Установить имя \en Set name -// --- -inline void MbSNameMaker::SetName( const MbSNameMaker & other, bool setVersion ) +inline +void MbSNameMaker::SetNameMaker( const MbSNameMaker & other, bool setVersion ) { SetMainName( other.GetMainName() ); SimpleNameArray::operator = ( (SimpleNameArray&)other ); @@ -1186,7 +1350,8 @@ inline void MbSNameMaker::SetName( const MbSNameMaker & other, bool setVersion ) +1, if n1 > n2; \n \~ \ingroup Names */ -inline MATH_FUNC (int) MbMemDefNameCompare( const MbName & n1, const MbName & n2 ) +inline +MATH_FUNC (int) MbMemDefNameCompare( const MbName & n1, const MbName & n2 ) { int res = -1; size_t count1 = n1.defNames.CountAll(); @@ -1213,28 +1378,27 @@ inline MATH_FUNC (int) MbMemDefNameCompare( const MbName & n1, const MbName & n2 \ingroup Names */ // --- -inline MATH_FUNC (int) MbDefNameCompare( const MbName & n1, const MbName & n2 ) -{ - SimpleName hash1 = n1.defNames.Hash(); - SimpleName hash2 = n2.defNames.Hash(); - return ::SimpleNameCompare( hash1, hash2 ); +inline +MATH_FUNC (int) MbDefNameCompare( const MbName & n1, const MbName & n2 ) { + return ::SimpleNameCompare( n1.defNames.Hash(), n2.defNames.Hash() ); } //---------------------------------------------------------------------------------------- // \ru часто встречающаяся комбинация - hash от SArray'a \en Frequently occurring combination - hash of SArray // --- -inline SimpleName Hash32( const SArray & arr ) { - return Hash32( (uint8*)arr.GetAddr(), arr.Count() * sizeofSimpleName ); +inline +SimpleName Hash32( const SArray & arr ) { + return c3d::Hash32( (uint8*)arr.GetAddr(), arr.size() * sizeofSimpleName ); } //---------------------------------------------------------------------------------------- // \ru Расчет модификатора имени примитива \en Calculate of modifier of name of primitive // --- -inline SimpleName CalcNameModifier( const MbName & name, const SArray & path ) -{ - return ( (path.Count()) ? ::Hash32SN(name.Hash(), Hash32(path)) : name.Hash() ); +inline +SimpleName CalcNameModifier( const MbName & name, const SArray & path ) { + return ( path.size() ? c3d::Hash32SN( name.Hash(), ::Hash32(path) ) : name.Hash() ); } @@ -1248,8 +1412,18 @@ inline SimpleName CalcNameModifier( const MbName & name, const SArray & path1, - const SArray & path2 ); +template +bool IsEqualPaths( const SimpleNameVector & path1, const SimpleNameVector & path2 ) +{ + const size_t cnt = path1.size(); + if ( cnt != path2.size() ) + return false; + for ( size_t k = 0; k < cnt; ++k ) { + if ( path1[k] != path2[k] ) + return false; + } + return true; +} ////////////////////////////////////////////////////////////////////////////////////////// @@ -1266,20 +1440,21 @@ MATH_FUNC (bool) IsEqualPaths( const SArray & path1, \en Path as array of identifiers (path to component from upper component). \n \~ \ingroup Names */ // --- -class MbPath : public SArray -{ +class MbPath : public SArray { public: /// \ru Конструктор. \en Constructor. MbPath() : SArray ( 0, 1 ) {} /// \ru Конструктор копирования. \en Copy-constructor. MbPath( const MbPath & other ) : SArray ( other ) {} + /// \ru Вычислить хэш себя. \en Calculate hash of itself. - SimpleName Hash() const; + SimpleName Hash() const { return ::Hash32( *this ); } /// \ru Оператор равенства. \en An equality operator. - bool operator == ( const MbPath & ) const; - bool operator != ( const MbPath & ) const; + bool operator == ( const MbPath & other ) const { return IsEqualPaths( *this, other ); } + /// \ru Оператор неравенства. \en An inequality operator. + bool operator != ( const MbPath & other ) const { return !IsEqualPaths( *this, other ); } /// \ru Оператор присваивания. \en An assignment operator. - MbPath & operator = ( const MbPath & o ) { SArray::operator = (o); return *this; } + MbPath & operator = ( const MbPath & p ) { SArray::operator = (p); return *this; } /// \ru Оператор чтения. \en Read operator. friend reader & operator >> ( reader & in, MbPath & ref ); /// \ru Оператор записи. \en Write operator. @@ -1290,18 +1465,20 @@ public: //---------------------------------------------------------------------------------------- -// \ru чтение \en Reading +// \ru Чтение. \en Reading. // --- -inline reader & operator >> ( reader & in, MbPath & ref ) +inline +reader & operator >> ( reader & in, MbPath & ref ) { size_t count = ReadCOUNT( in, true/*uint_val*/ ); + 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 in.setState( io::outOfMemory ); else { - for ( size_t i = 0; i < count && in.good(); i++ ) { + for ( size_t i = 0; i < count && in.good(); ++i ) { SimpleName item = ReadSimpleName( in ); ref.Add( item ); } @@ -1312,39 +1489,19 @@ inline reader & operator >> ( reader & in, MbPath & ref ) //---------------------------------------------------------------------------------------- -// \ru Запись \en Writing +// \ru Запись. \en Writing. // --- -inline writer & operator << ( writer & out, const MbPath & ref ) +inline +writer & operator << ( writer & out, const MbPath & ref ) { - size_t count = ref.Count(); - WriteCOUNT( out, count ); - for( size_t i = 0; i < count && out.good(); i++ ) - WriteSimpleName( out, (SimpleName&)ref[i] ); - + size_t count = ref.size(); + ::WriteCOUNT( out, count ); + + for( size_t i = 0; i < count && out.good(); ++i ) + ::WriteSimpleName( out, (SimpleName&)ref[i] ); + return out; } -//---------------------------------------------------------------------------------------- -// -// --- -inline SimpleName MbPath::Hash() const -{ - return ::Hash32( *this ); -} - - -//---------------------------------------------------------------------------------------- -// \ru Сравнить пути в виде массива идентификаторов \en Compare paths as array of identifiers -// --- -inline bool MbPath::operator == ( const MbPath & other ) const -{ - return IsEqualPaths( *this, other ); -} -inline bool MbPath::operator != ( const MbPath & other ) const -{ - return !IsEqualPaths( *this, other ); -} - - #endif // __NAME_ITEM_H diff --git a/C3d/Include/op_binding_data.h b/C3d/Include/op_binding_data.h index 044a3fd..53b8ec4 100644 --- a/C3d/Include/op_binding_data.h +++ b/C3d/Include/op_binding_data.h @@ -47,14 +47,14 @@ public: MbItemIndex() : itemIndex( SYS_MAX_T ) , point ( -DETERMINANT_MAX, -DETERMINANT_MAX, -DETERMINANT_MAX ) - , itemName ( SIMPLENAME_MAX ) + , itemName ( c3d::SIMPLENAME_MAX ) {} /// \ru Конструктор по индексу без точки привязки. \en Constructor by the index without anchor point. explicit MbItemIndex( size_t i ) : itemIndex( i ) , point ( -DETERMINANT_MAX, -DETERMINANT_MAX, -DETERMINANT_MAX ) - , itemName ( SIMPLENAME_MAX ) + , itemName ( c3d::SIMPLENAME_MAX ) {} /// \ru Конструктор по индексу с точкой привязки. \en Constructor by the index with anchor point. @@ -92,7 +92,7 @@ public: itemIndex = ind; if ( reset ) { point.Init( -DETERMINANT_MAX, -DETERMINANT_MAX, -DETERMINANT_MAX ); - itemName = SIMPLENAME_MAX; + itemName = c3d::SIMPLENAME_MAX; } } /// \ru Функция инициализации. \en Initialization function. @@ -294,7 +294,7 @@ public: , facePIndex( SYS_MAX_T ) , faceMIndex( SYS_MAX_T ) , point ( -DETERMINANT_MAX, -DETERMINANT_MAX, -DETERMINANT_MAX ) - , itemName ( SIMPLENAME_MAX ) + , itemName ( c3d::SIMPLENAME_MAX ) {} /// \ru Конструктор копирования. \en Copy-constructor. @@ -352,6 +352,78 @@ public: }; +//------------------------------------------------------------------------------ +/** \brief \ru Индекс грани и её ребер. + \en Index of face and it edges. \~ + \details \ru Индекс грани и её ребер, предназначенных для обработки. Индекс служит для поиска грани и ребра в оболочке. + Поиск объекта производится по имени, в случае неудаче - по номеру, и проверяется по контрольной точке \n + \en Index of face and it edges for process. Index is used to search for face end edges in the shell. + The face searching is performed by name. In failure case - by index, and checked by the control point \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbExtendedIndex { +public: + MbItemIndex faceIndex; ///< \ru Идентификаторы граней в оболочке. \en Identifier of a shell face. + std::vector edgeIndices; ///< \ru Идентификаторы обрабатываемых ребер грани. \en Identifiers of processed edges of the face. + +public: + /// \ru Конструктор. \en Constructor. + MbExtendedIndex( const MbItemIndex & fIndex, const std::vector & eIndices ) + : faceIndex( fIndex ) + , edgeIndices( eIndices ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbExtendedIndex( const MbExtendedIndex & other ) + : faceIndex( other.faceIndex ) + , edgeIndices( other.edgeIndices ) + {} + /// \ru Деструктор. \en Destructor. + ~MbExtendedIndex() {} + +public: + /// \ru Функция инициализации. \en Initialization function. + void Init( const MbExtendedIndex & other ) { + faceIndex = other.faceIndex; + edgeIndices.clear(); + edgeIndices = other.edgeIndices; + } + /// \ru Оператор присваивания. \en Assignment operator. + MbExtendedIndex & operator = ( const MbExtendedIndex & other ) { + Init( other ); + return *this; + } + + /// \ru Получить индекс грани. \en Get face index. + MbItemIndex & FaceIndex() { return faceIndex; } + const MbItemIndex & GetFaceIndex() const { return faceIndex; } + /// \ru Получить индексы рёбер грани. \en Get edges indices. + std::vector & EdgeIndices() { return edgeIndices; } + const std::vector & GetEdgeIndices() const { return edgeIndices; } + + /// \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 MbExtendedIndex & other, double accuracy ) const; + + /// \ru Функция чтения. \en Read function. + friend MATH_FUNC (reader &) operator >> ( reader & in, MbExtendedIndex & ref ); + /// \ru Функция записи. \en Write function. + friend MATH_FUNC (writer &) operator << ( writer & out, const MbExtendedIndex & ref ); + /// \ru Функция записи. \en Write function. + friend MATH_FUNC (writer &) operator << ( writer & out, MbExtendedIndex & ref ) { + return operator << ( out,(const MbExtendedIndex &)ref ); + } + + DECLARE_NEW_DELETE_CLASS( MbExtendedIndex ) + DECLARE_NEW_DELETE_CLASS_EX( MbExtendedIndex ) +}; + + //////////////////////////////////////////////////////////////////////////////// // // \ru Неклассные функции. \en Out-of-class functions. diff --git a/C3d/Include/op_boolean_flags.h b/C3d/Include/op_boolean_flags.h index dc5cdaf..dce54ea 100644 --- a/C3d/Include/op_boolean_flags.h +++ b/C3d/Include/op_boolean_flags.h @@ -35,8 +35,11 @@ public: public: bool MergeFaces() const { return mergeFaces; } ///< \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). bool MergeEdges() const { return mergeEdges; } ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). + void SetMergingFaces( bool mf ) { mergeFaces = mf; } ///< \ru Сливать подобные грани (true). \en Whether to merge similar faces (true). + void SetMergingEdges( bool me ) { mergeEdges = me; } ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). public: - MbMergingFlags & operator = ( const MbMergingFlags & f ) { mergeFaces = f.mergeFaces; mergeEdges = f.mergeEdges; return *this; } + MbMergingFlags & operator = ( const MbMergingFlags & f ) { mergeFaces = f.mergeFaces; mergeEdges = f.mergeEdges; return *this; } + bool operator == ( const MbMergingFlags & f ) const { return (mergeFaces == f.mergeFaces && mergeEdges == f.mergeEdges); } }; diff --git a/C3d/Include/op_duplication_parameter.h b/C3d/Include/op_duplication_parameter.h index a8413e2..440a802 100644 --- a/C3d/Include/op_duplication_parameter.h +++ b/C3d/Include/op_duplication_parameter.h @@ -1,416 +1,416 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Параметры размножения. - \en Parameters of duplication. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __OP_DUPLICATION_PARAMETERS_H -#define __OP_DUPLICATION_PARAMETERS_H - -#include -#include -#include -#include - - -class MATH_CLASS MbAxis3D; -class MbRegTransform; -class MbRegDuplicate; - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы параметров размножения. - \en Types of parameters of duplication. \~ - \details \ru dt_Grid - Копии располагаются в узлах декартовой сетки, заданной двумя направлениями, - шагами и количеством шагов по каждому направлению, а также сдвигом относительно исходного положения.\n - Исходное тело находится в центре сетки.\n - O---O---O \n - / / / \n - O---O---O \n - / / / \n - [O]--O---O \n - dt_Polar - Копии располагаются в узлах полярной сетки, заданной вектором начального луча, - вектором оси вращения, шагом по лучу, углом поворота, числом шагов по лучу и угловых шагов, - а также сдвигом относительно исходного положения.\n - Исходное тело находится в центре сетки.\n - O O \n - \ / \n - O O \n - \ / \n - O--O-[O]-O--O \n - dt_Matrix - Параметры разложения - массив матриц. Количество копий равно количеству матриц. - Каждая копия получается из исходного тела трансформацией соответствующей матрицей. \n - \en Dt_Grid - Copies locate in the nodes of the Cartesian grid, that define by two directions, - steps and numbers of steps along of each directions, and also by a shift from the initial position.\n - The original solid locate in the center of the grid.\n - O---O---O \n - / / / \n - O---O---O \n - / / / \n - [O]--O---O \n - dt_Polar - Copies locate in the nodes of the polar grid, that define by directions of the initial ray and the axis of rotation, - steps on the ray, angle of rotation and number of steps on the ray and angular step, - and also by a shift from the initial position.\n - The original solid locate in the center of the grid.\n - O O \n - \ / \n - O O \n - \ / \n - O--O-[O]-O--O \n - dt_Matrix - Parameters of duplication is array of matrices. Number of copies equal to number of matrix. - Each copy is obtained by transformation of corresponding matrix. \n \~ - \ingroup Model_Creators - */ -// --- -enum MbeDuplicatesType -{ - dt_Grid = 0 , ///< \ru Копии располагаются в узлах декартовой сетки. \en Copies locate in nodes of Cartesian grid. - dt_Polar = 1 , ///< \ru Копии располагаются в узлах полярной сетки.\en Copies locate in nodes of a polar grid. - dt_Matrix = 2 , ///< \ru Копии трансформируются матрицами. \en Copies are transformed by matrices. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Абстрактный класс параметров размножения. - \en Abstract class of duplication parameters. \~ - \details \ru Родительский класс для всех видов параметров размножения. \n - \en Parent class for all types of parameters of duplication. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS DuplicationValues -{ -protected: - /** \brief \ru Конструктор по умолчанию. - \en Default constructor. \~ - */ - DuplicationValues() {} - -public: - /** \brief \ru Деструктор. - \en Destructor. \~ - */ - virtual ~DuplicationValues() {} - - /** \brief \ru Функция копирования. - \en Copy function. \~ - */ - virtual bool Init( const DuplicationValues & ) = 0; - - /** \brief \ru Тип параметров. - \en Type of parameters \~ - \details \ru Возвращает тип параметров размножения. \n - \en Return type of parameters of duplication. \n \~ - */ - virtual MbeDuplicatesType Type() const = 0; - - /** \brief \ru Преобразовать параметры согласно матрице. - \en Transform parameters according to the matrix. \~ - */ - virtual void Transform( const MbMatrix3D &, MbRegTransform * = 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; - - /** \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; - - /** \brief \ru Выдать свойства объекта. - \en Get properties of the object. \~ - \details \ru Выдать свойства объекта. \n - \en Get properties of the object. \n \~ - */ - virtual void GetProperties( MbProperties & ) = 0; - - /** \brief \ru Записать свойства объекта. - \en Set properties of the object. \~ - \details \ru Записать свойства объекта. \n - \en Set properties of the object. \n \~ - */ - virtual void SetProperties( const MbProperties & ) = 0; - - /** \brief \ru Являются ли объекты равными? - \en Determine whether an object is equal? \~ - \details \ru Являются ли объекты равными? \n - \en Determine whether an object is equal? \n \~ - */ - virtual bool IsSame( const DuplicationValues &, double accuracy ) const = 0; - - /** \brief \ru Построить копию объекта. - \en Create a copy of the object. \~ - \details \ru Построить копию объекта. \n - \en Create a copy of the object. \n \~ - */ - virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const = 0; - - /** \brief \ru Сгенерировать матрицы трансформаций. - \en Generate matrices of transformations. \~ - \details \ru Сгенерировать матрицы трансформаций согласно параметрам. \n - \en Generate matrices of transformations according to parameters. \n \~ - */ - virtual void GenerateTransformMatrices( SArray & ) const = 0; - - /** \brief \ru Количество создаваемых копий. - \en Number of of copies. \~ - \details \ru Количество создаваемых копий. \n - \en Number of of copies. \n \~ - */ - virtual size_t Count() const = 0; - -OBVIOUS_PRIVATE_COPY( DuplicationValues ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Размножение по сетке. - \en Duplication by grid. \~ - \details \ru Параметры размножение по размножение по декартовой сетке или по полярной сетке.\n - Тип сетки определяется флагом 'isPolar':\n - false - dt_Grid, true - dt_Polar.\n - Исходное тело находится в центре сетки. \n - Вектор 'axis1' задает одно из направлений декартовой сетки или направление луча в полярной сетке. \n - Вектор 'axis2' задает другое направление декартовой сетки или ось вращения в полярной сетке, - точка оси не важна т.к. поворачиваются только вектора. \n - 'step1' и step2' задают шаги по направлениям декартовой сетки. \n - 'step1' - задает шаг по лучу полярной сетки, 'step2' задает угол поворота. \n - 'num1' и 'num2' задают кол-во шагов 'step1' и 'step2' соответственно. \n - Ориентация тел на сетке определяется флагом 'isAlongAxis'. \n - Если флаг 'isAlongAxis' = true, то тела ориентированы вдоль радиальной оси, false - параллельно исходному телу. \n - 'center' задает центр локальной системы координат. \n - ВАЖНО! У векторов 'axis1', 'axis2' учитываются только направления, при инициализации или изменении происходит нормирование. \n - \en Parameters of duplication by Cartesian grid or polar grid.\n - Type of grid is determined by flag 'isPolar':\n - false - dt_Grid, true - dt_Polar.\n - The original solid locate in the center of the grid. \n - Vector 'axis1' define one of the directions of the Cartesian grid or direction of the ray in the polar grid. \n - Vector 'axis2' define other directions of the Cartesian grid or the axis of rotation in the polar grid, - point of axis doesn't matter because only vector will be rotated. - 'step1' and 'step2' define steps along the directions. \n - 'step1' define 'step' along the ray of polar grid, step2 define angle of rotation. \n - 'num1 and 'num2' define number of steps 'step1' and 'step2'. \n - Orientation of the bodies on the grid is controlled by 'isAlongAxis' flag. \n - If 'isAlongAxis' = true, then bodies are oriented along radial axis, false - parallel to the origin body. \n - 'center' determines the origin of local coordinate system. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS DuplicationMeshValues: public DuplicationValues -{ -protected: - MbVector3D axis1; ///< \ru Направление размножения (dt_Grid и dt_Polar). \en Direction of duplication (dt_Grid and dt_Polar). - MbVector3D axis2; ///< \ru Направление размножения (dt_Grid), направление оси вращения (dt_Polar). \en Direction of duplication (dt_Grid), direction of axis of rotation (dt_Polar). - double step1; ///< \ru Шаг по направлению axis1 (dt_Grid и dt_Polar). \en Step along of axis1 (dt_Grid and dt_Polar). - double step2; ///< \ru Шаг по направлению axis2 (dt_Grid), угол поворота (dt_Polar). \en Step along of axis1 (dt_Grid), angle of rotation (dt_Polar). - uint num1; ///< \ru Кол-во шагов по направлению axis1 (dt_Grid и dt_Polar). \en Number of steps along of axis1 (dt_Grid and dt_Polar). - uint num2; ///< \ru Кол-во шагов по направлению axis2 (dt_Grid), кол-во угловых шагов (dt_Polar). \en Number of steps along of axis2 (dt_Grid), number of angular steps (dt_Polar). - bool isPolar; ///< \ru Тип сетки, false - dt_Grid, true - dt_Polar. Type of grid, false - dt_Grid, true - dt_Polar. \en . - bool isAlongAxis; ///< \ru true - тела расположены вдоль радиальной оси, false - параллельно исходному телу. \en true - along polar axis, false - parallel to initial body. - MbCartPoint3D center; ///< \ru Центр локальной системы координат (и точка приложения оси вращения в случае полярной системы). \en Origin of the coordinate system. -public: - /** \brief \ru Конструктор по типу. - \en Constructor by a type. \~ - \details \ru Конструктор размножения по сетке.\n - Вектора и значения инициализируются нулевыми, тип сетки инициализируется параметром, по умолчанию 'false'. \n - \en Constructor of duplication by grid. \n - Vectors and values are initialized to zero, type of grid is initialized by parameter, default 'false'. \n \~ - */ - DuplicationMeshValues( bool polar = false ); - - /** \brief \ru Конструктор по параметрам и типу. - \en Constructor by parameters and a type. \~ - \details \ru Конструктор размножения по сетке. \n - Тип сетки, направления осей, шаги и кол-во шагов инициализируются параметрами. \n - \en Constructor of duplication by grid. \n - Type of grid, vectors, steps and numbers of steps are initialized to parameters. \n \~ - */ - DuplicationMeshValues( bool isPolar, const MbVector3D & dir1, const double step1, const unsigned int num1, - const MbVector3D & dir2, const double step2, const unsigned int num2, - const MbCartPoint3D * center = NULL, bool isAlongAxis = false ); - - /// \ru Деструктор. \en Destructor. - virtual ~DuplicationMeshValues(); - - /// \ru Функция копирования. \en Copy function. - void Init( const DuplicationMeshValues & other ); - /// \ru Функция копирования. \en Copy function. - virtual bool Init( const DuplicationValues & other ); - /// \ru Тип параметров. \en Type of parameters. - virtual MbeDuplicatesType Type() const; - /// \ru Преобразовать сетку согласно матрице. \en Transform grid according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); - /// \ru Сдвинуть сетку вдоль вектора. \en Move grid along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL ); - /// \ru Повернуть сетку вокруг оси на заданный угол. \en Rotate grid at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL ); - - /// \ru Выдать свойства объекта \en Get properties of the object - virtual void GetProperties( MbProperties & ); - /// \ru Записать свойства объекта \en Set properties of the object - virtual void SetProperties( const MbProperties & ); - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const DuplicationValues &, double accuracy ) const; - - /// \ru Построить копию объекта. \en Create a copy of the object. - virtual DuplicationValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; - - /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation by. - virtual void GenerateTransformMatrices( SArray & tfMatr ) const; - - /// \ru Количество создаваемых копий. \en Number of copies. - virtual size_t Count() const; - - /** \brief \ru Установить одно из направлений сетки. - \en Set one of the directions of grid. \~ - \details \ru Установить одно из направлений сетки. \n - \en Set one of the directions of grid. \n \~ - */ - void SetDirection( bool first, const MbVector3D & dir ); - - /** \brief \ru Получить одно из направлений сетки. - \en Get one of the directions of grid. \~ - \details \ru Получить одно из направлений сетки. \n - \en Get one of the directions of grid. \n \~ - */ - void GetDirection( bool first, MbVector3D & dir ) const; - - /** \brief \ru Установить шаг по одному из направлений сетки. - \en Set the step along of one of the directions of grid. \~ - \details \ru Установить шаг по одному из направлений сетки. \n - \en Set the step along of one of the directions of grid. \n \~ - */ - void SetStep( bool first, const double step ); - - /** \brief \ru Получить шаг по одному из направлений сетки. - \en Get the step along of one of the directions of grid. \~ - \details \ru Получить шаг по одному из направлений сетки. \n - \en Get the step along of one of the directions of grid. \n \~ - */ - void GetStep( bool first, double & step ) const; - - /** \brief \ru Установить количество шагов по одному из направлений сетки. - \en Set the number of steps along of one of the directions of grid. \~ - \details \ru Установить количество шагов по одному из направлений сетки. \n - \en Set the number of steps along of one of the directions of grid. \n \~ - */ - void SetNumStep( bool first, const uint num ); - - /** \brief \ru Полярная ли сетка? - \en Is mesh polar? \~ - \details \ru Задана ли сетка в полярной системе координат? \n - \en Is local system of mesh polar? \n \~ - */ - bool IsPolar() const { return isPolar; } - - /** \brief \ru Задать тип сетки. - \en Set mesh type. \~ - \details \ru Задать сетку в полярной или декартовой системе координат. \n - \en Set local system of mesh. \n \~ - */ - void SetPolar( bool p ) { isPolar = p; } - - /** \brief \ru Получить количество шагов по одному из направлений сетки. - \en Get the number of steps along of one of the directions of grid. \~ - \details \ru Получить количество шагов по одному из направлений сетки. \n - \en Get the number of steps along of one of the directions of grid. \n \~ - */ - void GetNumStep( bool first, uint & num ) const; - - /** \brief \ru Тело вдоль радиальной оси? - \en Is body along radial axis? \~ - \details \ru Тело вдоль радиальной оси? \n - \en Is body along radial axis? \n \~ - */ - bool IsAlongAxis() const { return isAlongAxis; } - - /** \brief \ru Вернуть центр полярной системы. - \en Return center of the polar system. \~ - \details \ru Вернуть центр полярной системы. \n - \en Return center of the polar system. \n \~ - */ - - MbCartPoint3D GetCenter() const { return center; } - - /** \brief \ru Установить центр полярной системы. - \en Set center of the polar system. \~ - \details \ru Установить центр полярной системы. \n - \en Set center of the polar system. \n \~ - */ - - void SetCenter( MbCartPoint3D & cntr ) { center = cntr; } - -KNOWN_OBJECTS_RW_REF_OPERATORS( DuplicationMeshValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -OBVIOUS_PRIVATE_COPY( DuplicationMeshValues ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Размножение матрицами. - \en Duplication by matrices. \~ - \details \ru Размножение задается набором матриц трансформаций. Каждая копия это трансформация оригинального тела соответствующей матрицей. \n - \en Duplication is defined by set of transform matrices. Each copy is a transformation of original solid by corresponding matrix. \n \~ - \ingroup Build_Parameters -*/ -// --- -class MATH_CLASS DuplicationMatrixValues: public DuplicationValues -{ -public: - SArray matrices; -public: - /// \ru Конструктор по умолчанию. \en Default constructor. - DuplicationMatrixValues(); - /// \ru Конструктор по матрице. \en Constructor by matrix. - DuplicationMatrixValues( const MbMatrix3D & matr ); - /// \ru Конструктор по набору матриц. \en Constructor by set of matrices. - DuplicationMatrixValues( const SArray & matr ); - - /// \ru Деструктор. \en Destructor. - virtual ~DuplicationMatrixValues(); - - /// \ru Функция копирования. \en Copy function. - void Init( const DuplicationMatrixValues & other ); - /// \ru Функция копирования. \en Copy function. - virtual bool Init( const DuplicationValues & other ); - /// \ru Тип параметров. \en Type of parameters. - virtual MbeDuplicatesType Type() const; - /// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix. - virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ); - /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. - virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL ); - /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. - virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL ); - - /// \ru Выдать свойства объекта \en Get properties of the object - virtual void GetProperties( MbProperties & ); - /// \ru Записать свойства объекта \en Set properties of the object - virtual void SetProperties( const MbProperties & ); - - // \ru Являются ли объекты равными? \en Determine whether an object is equal? - virtual bool IsSame( const DuplicationValues &, double accuracy ) const; - - /// \ru Построить копию объекта. \en Create a copy of the object. - virtual DuplicationValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; - - /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation. - virtual void GenerateTransformMatrices( SArray & tfMatr ) const; - - /// \ru Количество создаваемых копий. \en Number of copies. - virtual size_t Count() const; - -KNOWN_OBJECTS_RW_REF_OPERATORS( DuplicationMatrixValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. -OBVIOUS_PRIVATE_COPY( DuplicationMatrixValues ) -}; - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Параметры копирования. + \en Parameters of duplication. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __OP_DUPLICATION_PARAMETERS_H +#define __OP_DUPLICATION_PARAMETERS_H + +#include +#include +#include +#include + + +class MATH_CLASS MbAxis3D; +class MbRegTransform; +class MbRegDuplicate; + + +//------------------------------------------------------------------------------ +/** \brief \ru Способы копирования. + \en Types of parameters of duplication. \~ + \details \ru dt_Grid - Копии располагаются в узлах декартовой сетки, заданной двумя направлениями, + шагами и количеством шагов по каждому направлению, а также сдвигом относительно исходного положения.\n + Исходное тело находится в центре сетки.\n + O---O---O \n + / / / \n + O---O---O \n + / / / \n + [O]--O---O \n + dt_Polar - Копии располагаются в узлах полярной сетки, заданной вектором начального луча, + вектором оси вращения, шагом по лучу, углом поворота, числом шагов по лучу и угловых шагов, + а также сдвигом относительно исходного положения.\n + Исходное тело находится в центре сетки.\n + O O \n + \ / \n + O O \n + \ / \n + O--O-[O]-O--O \n + dt_Matrix - Параметры копирования - массив матриц. Количество копий равно количеству матриц. + Каждая копия получается из исходного тела трансформацией соответствующей матрицей. \n + \en Dt_Grid - Copies locate in the nodes of the Cartesian grid, that define by two directions, + steps and numbers of steps along of each directions, and also by a shift from the initial position.\n + The original solid locate in the center of the grid.\n + O---O---O \n + / / / \n + O---O---O \n + / / / \n + [O]--O---O \n + dt_Polar - Copies locate in the nodes of the polar grid, that define by directions of the initial ray and the axis of rotation, + steps on the ray, angle of rotation and number of steps on the ray and angular step, + and also by a shift from the initial position.\n + The original solid locate in the center of the grid.\n + O O \n + \ / \n + O O \n + \ / \n + O--O-[O]-O--O \n + dt_Matrix - Parameters of duplication is array of matrices. Number of copies equal to number of matrix. + Each copy is obtained by transformation of corresponding matrix. \n \~ + \ingroup Model_Creators + */ +// --- +enum MbeDuplicatesType +{ + dt_Grid = 0 , ///< \ru Копии располагаются в узлах декартовой сетки. \en Copies locate in nodes of Cartesian grid. + dt_Polar = 1 , ///< \ru Копии располагаются в узлах полярной сетки.\en Copies locate in nodes of a polar grid. + dt_Matrix = 2 , ///< \ru Копии трансформируются матрицами. \en Copies are transformed by matrices. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Абстрактный класс параметров копирования. + \en Abstract class of duplication parameters. \~ + \details \ru Родительский класс для всех видов параметров копирования. \n + \en Parent class for all types of parameters of duplication. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS DuplicationValues +{ +protected: + /** \brief \ru Конструктор по умолчанию. + \en Default constructor. \~ + */ + DuplicationValues() {} + +public: + /** \brief \ru Деструктор. + \en Destructor. \~ + */ + virtual ~DuplicationValues() {} + + /** \brief \ru Функция копирования. + \en Copy function. \~ + */ + virtual bool Init( const DuplicationValues & ) = 0; + + /** \brief \ru Тип параметров. + \en Type of parameters \~ + \details \ru Возвращает способ копирования. \n + \en Return type of parameters of duplication. \n \~ + */ + virtual MbeDuplicatesType Type() const = 0; + + /** \brief \ru Преобразовать параметры согласно матрице. + \en Transform parameters according to the matrix. \~ + */ + virtual void Transform( const MbMatrix3D &, MbRegTransform * = 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; + + /** \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; + + /** \brief \ru Выдать свойства объекта. + \en Get properties of the object. \~ + \details \ru Выдать свойства объекта. \n + \en Get properties of the object. \n \~ + */ + virtual void GetProperties( MbProperties & ) = 0; + + /** \brief \ru Записать свойства объекта. + \en Set properties of the object. \~ + \details \ru Записать свойства объекта. \n + \en Set properties of the object. \n \~ + */ + virtual void SetProperties( const MbProperties & ) = 0; + + /** \brief \ru Являются ли объекты равными? + \en Determine whether an object is equal? \~ + \details \ru Являются ли объекты равными? \n + \en Determine whether an object is equal? \n \~ + */ + virtual bool IsSame( const DuplicationValues &, double accuracy ) const = 0; + + /** \brief \ru Построить копию объекта. + \en Create a copy of the object. \~ + \details \ru Построить копию объекта. \n + \en Create a copy of the object. \n \~ + */ + virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const = 0; + + /** \brief \ru Сгенерировать матрицы трансформаций. + \en Generate matrices of transformations. \~ + \details \ru Сгенерировать матрицы трансформаций согласно параметрам. \n + \en Generate matrices of transformations according to parameters. \n \~ + */ + virtual void GenerateTransformMatrices( std::vector & ) const = 0; + + /** \brief \ru Количество создаваемых копий. + \en Number of of copies. \~ + \details \ru Количество создаваемых копий. \n + \en Number of of copies. \n \~ + */ + virtual size_t Count() const = 0; + +OBVIOUS_PRIVATE_COPY( DuplicationValues ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Копирование по сетке. + \en Duplication by grid. \~ + \details \ru Параметры копирования по декартовой сетке или по полярной сетке.\n + Тип сетки определяется флагом 'isPolar':\n + false - dt_Grid, true - dt_Polar.\n + Исходное тело находится в центре сетки. \n + Вектор 'axis1' задает одно из направлений декартовой сетки или направление луча в полярной сетке. \n + Вектор 'axis2' задает другое направление декартовой сетки или ось вращения в полярной сетке, + точка оси не важна т.к. поворачиваются только вектора. \n + 'step1' и step2' задают шаги по направлениям декартовой сетки. \n + 'step1' - задает шаг по лучу полярной сетки, 'step2' задает угол поворота. \n + 'num1' и 'num2' задают кол-во шагов 'step1' и 'step2' соответственно. \n + Ориентация тел на сетке определяется флагом 'isAlongAxis'. \n + Если флаг 'isAlongAxis' = true, то тела ориентированы вдоль радиальной оси, false - параллельно исходному телу. \n + 'center' задает центр локальной системы координат. \n + ВАЖНО! У векторов 'axis1', 'axis2' учитываются только направления, при инициализации или изменении происходит нормирование. \n + \en Parameters of duplication by Cartesian grid or polar grid.\n + Type of grid is determined by flag 'isPolar':\n + false - dt_Grid, true - dt_Polar.\n + The original solid locate in the center of the grid. \n + Vector 'axis1' define one of the directions of the Cartesian grid or direction of the ray in the polar grid. \n + Vector 'axis2' define other directions of the Cartesian grid or the axis of rotation in the polar grid, + point of axis doesn't matter because only vector will be rotated. + 'step1' and 'step2' define steps along the directions. \n + 'step1' define 'step' along the ray of polar grid, step2 define angle of rotation. \n + 'num1 and 'num2' define number of steps 'step1' and 'step2'. \n + Orientation of the bodies on the grid is controlled by 'isAlongAxis' flag. \n + If 'isAlongAxis' = true, then bodies are oriented along radial axis, false - parallel to the origin body. \n + 'center' determines the origin of local coordinate system. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS DuplicationMeshValues: public DuplicationValues +{ +protected: + MbVector3D axis1; ///< \ru Направление копирования (dt_Grid и dt_Polar). \en Direction of duplication (dt_Grid and dt_Polar). + MbVector3D axis2; ///< \ru Направление копирования (dt_Grid), направление оси вращения (dt_Polar). \en Direction of duplication (dt_Grid), direction of axis of rotation (dt_Polar). + double step1; ///< \ru Шаг по направлению axis1 (dt_Grid и dt_Polar). \en Step along of axis1 (dt_Grid and dt_Polar). + double step2; ///< \ru Шаг по направлению axis2 (dt_Grid), угол поворота (dt_Polar). \en Step along of axis1 (dt_Grid), angle of rotation (dt_Polar). + uint num1; ///< \ru Кол-во шагов по направлению axis1 (dt_Grid и dt_Polar). \en Number of steps along of axis1 (dt_Grid and dt_Polar). + uint num2; ///< \ru Кол-во шагов по направлению axis2 (dt_Grid), кол-во угловых шагов (dt_Polar). \en Number of steps along of axis2 (dt_Grid), number of angular steps (dt_Polar). + bool isPolar; ///< \ru Тип сетки, false - dt_Grid, true - dt_Polar. Type of grid, false - dt_Grid, true - dt_Polar. \en . + bool isAlongAxis; ///< \ru true - тела расположены вдоль радиальной оси, false - параллельно исходному телу. \en true - along polar axis, false - parallel to initial body. + MbCartPoint3D center; ///< \ru Центр локальной системы координат (и точка приложения оси вращения в случае полярной системы). \en Origin of the coordinate system. +public: + /** \brief \ru Конструктор по типу. + \en Constructor by a type. \~ + \details \ru Конструктор копирования по сетке.\n + Вектора и значения инициализируются нулевыми, тип сетки инициализируется параметром, по умолчанию 'false'. \n + \en Constructor of duplication by grid. \n + Vectors and values are initialized to zero, type of grid is initialized by parameter, default 'false'. \n \~ + */ + DuplicationMeshValues( bool polar = false ); + + /** \brief \ru Конструктор по параметрам и типу. + \en Constructor by parameters and a type. \~ + \details \ru Конструктор копирования по сетке. \n + Тип сетки, направления осей, шаги и кол-во шагов инициализируются параметрами. \n + \en Constructor of duplication by grid. \n + Type of grid, vectors, steps and numbers of steps are initialized to parameters. \n \~ + */ + 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 ); + + /// \ru Деструктор. \en Destructor. + virtual ~DuplicationMeshValues(); + + /// \ru Функция копирования. \en Copy function. + void Init( const DuplicationMeshValues & ); + /// \ru Функция копирования. \en Copy function. + virtual bool Init( const DuplicationValues & ); + /// \ru Тип параметров. \en Type of parameters. + virtual MbeDuplicatesType Type() const; + /// \ru Преобразовать сетку согласно матрице. \en Transform grid according to the matrix. + virtual void Transform( const MbMatrix3D &, MbRegTransform * = NULL ); + /// \ru Сдвинуть сетку вдоль вектора. \en Move grid along a vector. + virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Повернуть сетку вокруг оси на заданный угол. \en Rotate grid at a given angle around an axis. + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = NULL ); + + /// \ru Выдать свойства объекта \en Get properties of the object + virtual void GetProperties( MbProperties & ); + /// \ru Записать свойства объекта \en Set properties of the object + virtual void SetProperties( const MbProperties & ); + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const DuplicationValues &, double accuracy ) const; + + /// \ru Построить копию объекта. \en Create a copy of the object. + virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const; + + /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation by. + virtual void GenerateTransformMatrices( std::vector & ) const; + + /// \ru Количество создаваемых копий. \en Number of copies. + virtual size_t Count() const; + + /** \brief \ru Установить одно из направлений сетки. + \en Set one of the directions of grid. \~ + \details \ru Установить одно из направлений сетки. \n + \en Set one of the directions of grid. \n \~ + */ + void SetDirection( bool first, const MbVector3D & dir ); + + /** \brief \ru Получить одно из направлений сетки. + \en Get one of the directions of grid. \~ + \details \ru Получить одно из направлений сетки. \n + \en Get one of the directions of grid. \n \~ + */ + void GetDirection( bool first, MbVector3D & dir ) const; + + /** \brief \ru Установить шаг по одному из направлений сетки. + \en Set the step along of one of the directions of grid. \~ + \details \ru Установить шаг по одному из направлений сетки. \n + \en Set the step along of one of the directions of grid. \n \~ + */ + void SetStep( bool first, const double step ); + + /** \brief \ru Получить шаг по одному из направлений сетки. + \en Get the step along of one of the directions of grid. \~ + \details \ru Получить шаг по одному из направлений сетки. \n + \en Get the step along of one of the directions of grid. \n \~ + */ + void GetStep( bool first, double & step ) const; + + /** \brief \ru Установить количество шагов по одному из направлений сетки. + \en Set the number of steps along of one of the directions of grid. \~ + \details \ru Установить количество шагов по одному из направлений сетки. \n + \en Set the number of steps along of one of the directions of grid. \n \~ + */ + void SetNumStep( bool first, const uint num ); + + /** \brief \ru Полярная ли сетка? + \en Is mesh polar? \~ + \details \ru Задана ли сетка в полярной системе координат? \n + \en Is local system of mesh polar? \n \~ + */ + bool IsPolar() const { return isPolar; } + + /** \brief \ru Задать тип сетки. + \en Set mesh type. \~ + \details \ru Задать сетку в полярной или декартовой системе координат. \n + \en Set local system of mesh. \n \~ + */ + void SetPolar( bool p ) { isPolar = p; } + + /** \brief \ru Получить количество шагов по одному из направлений сетки. + \en Get the number of steps along of one of the directions of grid. \~ + \details \ru Получить количество шагов по одному из направлений сетки. \n + \en Get the number of steps along of one of the directions of grid. \n \~ + */ + void GetNumStep( bool first, uint & num ) const; + + /** \brief \ru Тело вдоль радиальной оси? + \en Is body along radial axis? \~ + \details \ru Тело вдоль радиальной оси? \n + \en Is body along radial axis? \n \~ + */ + bool IsAlongAxis() const { return isAlongAxis; } + + /** \brief \ru Вернуть центр полярной системы. + \en Return center of the polar system. \~ + \details \ru Вернуть центр полярной системы. \n + \en Return center of the polar system. \n \~ + */ + MbCartPoint3D GetCenter() const { return center; } + + /** \brief \ru Установить центр полярной системы. + \en Set center of the polar system. \~ + \details \ru Установить центр полярной системы. \n + \en Set center of the polar system. \n \~ + */ + void SetCenter( MbCartPoint3D & cntr ) { center = cntr; } + +KNOWN_OBJECTS_RW_REF_OPERATORS( DuplicationMeshValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +OBVIOUS_PRIVATE_COPY( DuplicationMeshValues ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Копирование с трансформациями по матрицам. + \en Duplication by matrices. \~ + \details \ru Копирование задается набором матриц трансформаций. Каждая копия оригинального тела трансформируется соответствующей матрицей. \n + \en Duplication is defined by set of transform matrices. Each copy of original solid is transforming by corresponding matrix. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS DuplicationMatrixValues: public DuplicationValues +{ +public: + std::vector matrices; +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + DuplicationMatrixValues(); + /// \ru Конструктор по матрице. \en Constructor by matrix. + DuplicationMatrixValues( const MbMatrix3D & ); + /// \ru Конструктор по набору матриц. \en Constructor by set of matrices. + DuplicationMatrixValues( const SArray & ); + /// \ru Конструктор по набору матриц. \en Constructor by set of matrices. + DuplicationMatrixValues( const std::vector & ); + + /// \ru Деструктор. \en Destructor. + virtual ~DuplicationMatrixValues(); + + /// \ru Функция копирования. \en Copy function. + void Init( const DuplicationMatrixValues & ); + /// \ru Функция копирования. \en Copy function. + virtual bool Init( const DuplicationValues & ); + /// \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 ); + /// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector. + virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + /// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis. + virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * = NULL ); + + /// \ru Выдать свойства объекта \en Get properties of the object + virtual void GetProperties( MbProperties & ); + /// \ru Записать свойства объекта \en Set properties of the object + virtual void SetProperties( const MbProperties & ); + + // \ru Являются ли объекты равными? \en Determine whether an object is equal? + virtual bool IsSame( const DuplicationValues &, double accuracy ) const; + + /// \ru Построить копию объекта. \en Create a copy of the object. + virtual DuplicationValues & Duplicate( MbRegDuplicate * = NULL ) const; + + /// \ru Сгенерировать матрицы трансформации. \en Generate matrix of transformation. + virtual void GenerateTransformMatrices( std::vector & ) const; + + /// \ru Количество создаваемых копий. \en Number of copies. + virtual size_t Count() const; + +KNOWN_OBJECTS_RW_REF_OPERATORS( DuplicationMatrixValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. +OBVIOUS_PRIVATE_COPY( DuplicationMatrixValues ) +}; + + #endif // __OP_DUPLICATION_PARAMETERS_H \ No newline at end of file diff --git a/C3d/Include/op_shell_parameter.h b/C3d/Include/op_shell_parameter.h index acb493d..f682aac 100644 --- a/C3d/Include/op_shell_parameter.h +++ b/C3d/Include/op_shell_parameter.h @@ -813,6 +813,47 @@ public: }; +class MbPatchCurveMating; +//------------------------------------------------------------------------------ +/** \brief \ru Сопряжение по кривой заплатки. + \en Patch curve conjugation. \~ + \details \ru Сопряжение по кривой заплатки. \n + \en Patch curve conjugation. \n \~ + \ingroup Build_Parameters +*/ +// --- +class MATH_CLASS MbPatchMating { + +protected: + /// \ru Конструктор. \en Constructor. + MbPatchMating() {} + /// \ru Конструктор. \en Constructor. + MbPatchMating( const MbPatchMating & ) {} +public: + /// \ru Деструктор. \en Destructor. + virtual ~MbPatchMating() {} + +public: + /// \ru Установить тип сопряжения. \en Set conjugation type. + virtual void SetMate( MbePatchMatingType newType, const MbSurface * newSurface ) = 0; + /// \ru Установить тип сопряжения сегмента. \en Set conjugation type of segment. + virtual void SetMate( size_t segInd, MbePatchMatingType newType, const MbSurface * newSurface ) = 0; + + /// \ru Выдать тип сопряжения. \en Get the type of conjugation. + virtual MbePatchMatingType GetMatingType() const = 0; + /// \ru Выдать посверхность. \en Get surface. + virtual const MbSurface * GetSurface() const = 0; + + /// \ru Сопряжение для сегмента номер segInd. \en The conjugation by segment number segInd. + virtual MbPatchCurveMating & GetSegmentMate( size_t segInd ) = 0; + /// \ru Чье сопряжение. \en The conjugation owner type. + virtual MbeSpaceType GetOwnerType() = 0; + +private: + MbPatchMating & operator = ( const MbPatchMating & ); +}; + + //------------------------------------------------------------------------------ /** \brief \ru Параметры заплатки. \en The parameters of patch. \~ @@ -834,11 +875,14 @@ public: ts_tang, ///< \ru По касательной. \en Along the tangent. ts_norm, ///< \ru По нормали. \en Along the normal. ts_none, ///< \ru Не определено. \en Undefined. - ts_plane ///< \ru Плоская заплатка. \en Plane patch. + ts_plane, ///< \ru Плоская заплатка. \en Plane patch. + ts_byCurves, ///< \ru Построение задается сопряжениями по каждой кривой. \en The construction is defined by conjugations on curves. }; private: - SurfaceType type; ///< \ru Тип заплатки. \en Type of patch. - bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods). + SurfaceType type; ///< \ru Тип заплатки. \en Type of patch. + bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods). + bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). + std::vector> curvesMatings; ///< \ru Сопряжения по кривым. Параметр используется при type == ts_byCurves. \en The conjugation by curves. public: /** \brief \ru Конструктор по умолчанию. @@ -849,11 +893,14 @@ public: PatchValues() : type ( ts_none ) , checkSelfInt( false ) + , mergeEdges ( true ) {} /// \ru Конструктор копирования. \en Copy-constructor. PatchValues( const PatchValues & other ) - : type ( other.type ) - , checkSelfInt( other.checkSelfInt ) + : type ( other.type ) + , checkSelfInt ( other.checkSelfInt ) + , mergeEdges ( other.mergeEdges ) + , curvesMatings( other.curvesMatings ) {} /// \ru Деструктор. \en Destructor. ~PatchValues() @@ -868,10 +915,27 @@ public: bool CheckSelfInt() const { return checkSelfInt; } /// \ru Установить флаг проверки самопересечений. \en Set the flag of checking self-intersection. void SetCheckSelfInt( bool c ) { checkSelfInt = c; } + /// \ru Сливать подобные ребра (true)? \en Whether to merge similar edges (true)? + bool MergeEdges() const { return mergeEdges; } + /// \ru Сливать подобные ребра. \en Whether to merge similar edges. + void SetMergingEdges( bool s ) { mergeEdges = s; } + + /// \ru Установить сопряжение кривой номер cInd. \en Set mate for curve number cInd. + void SetCurveMating( size_t cInd, MbePatchMatingType curveMate, const MbSurface * surface ); + /// \ru Выдать тип сопряжения по кривой cInd. \en Get the type of conjugation on curve cInd. + MbePatchMatingType GetCurveMatingType( size_t cInd ) const; + /// \ru Выдать поверхность сопряжения по кривой cInd. \en Get the surface of conjugation on curve cInd. + const MbSurface * GetCurveMatingSurface( size_t cInd ) const; + + /// \ru Установить сопряжение сегмента sInd контура cInd. \en Set mate for segment number sInd for contour number cInd. + void SetCurveMating( size_t cInd, size_t sInd, MbePatchMatingType curveMate, const MbSurface * surface ); + /// \ru Декомпозиция сопряжений контура номер cInd, segCount - число сегментов контура. \en Decomposition of cInd - contour mates, segCount - the number of contour segments. + void DecomposeMates( size_t cInd, size_t segCount ); + /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const PatchValues & other ) { type = other.type; checkSelfInt = other.checkSelfInt; } + void operator = ( const PatchValues & other ) { type = other.type; checkSelfInt = other.checkSelfInt; mergeEdges = other.mergeEdges; curvesMatings = other.curvesMatings; } /// \ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const PatchValues & obj, double ) const { return ((obj.type == type) && (obj.checkSelfInt == checkSelfInt)); } + bool IsSame( const PatchValues & obj, double ) const { return ((obj.type == type) && (obj.checkSelfInt == checkSelfInt) && (obj.mergeEdges == mergeEdges) && (obj.curvesMatings == curvesMatings)); } KNOWN_OBJECTS_RW_REF_OPERATORS( PatchValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; @@ -887,18 +951,18 @@ public: // --- class MATH_CLASS MbPatchCurve : public MbRefItem { private: - MbCurve3D * curve; ///< \ru Кривая. \en A curve. - double begTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start. - double endTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start. - bool isSurfaceOne; ///< \ru В ребре есть грань с первой поверхностью из кривой пересечения. \en There is face with the first surface from the intersection curve in the edge. - bool isSurfaceTwo; ///< \ru В ребре есть грань со второй поверхностью из кривой пересечения. \en There is face with the second surface from the intersection curve in the edge. - mutable bool isUsed; ///< \ru Флаг использования. \en An using flag. + c3d::SpaceCurveSPtr curve; ///< \ru Кривая. \en A curve. + double begTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start. + double endTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start. + bool isSurfaceOne; ///< \ru В ребре есть грань с первой поверхностью из кривой пересечения. \en There is face with the first surface from the intersection curve in the edge. + bool isSurfaceTwo; ///< \ru В ребре есть грань со второй поверхностью из кривой пересечения. \en There is face with the second surface from the intersection curve in the edge. + mutable bool isUsed; ///< \ru Флаг использования. \en An using flag. public: /// \ru Конструктор по кривой (копирует кривую, трансформируя по матрице). \en Constructor by a curve (copies a curve, transforms by the matrix). - MbPatchCurve( const MbCurve3D & crv, const MbMatrix3D & mtr ); + MbPatchCurve( const MbCurve3D &, const MbMatrix3D & ); /// \ru Конструктор по ребру (копирует кривую, трансформируя по матрице). \en Constructor by an edge (copies a curve, transforms by the matrix). - MbPatchCurve( const MbCurveEdge & edge, const MbMatrix3D & mtr ); + MbPatchCurve( const MbCurveEdge &, const MbMatrix3D & ); /// \ru Деструктор. \en Destructor. virtual ~MbPatchCurve(); @@ -1594,18 +1658,19 @@ private: MbeMatingType type1; ///< \ru Сопряжение на границе 1. \en Mate on the boundary 1. MbeMatingType type2; ///< \ru Сопряжение на границе 2. \en Mate on the boundary 2. MbeMatingType type3; ///< \ru Сопряжение на границе 3. \en Mate on the boundary 3. - - MbSurface * surface0; ///< \ru Сопрягаемая поверхность через границу 0 (curvesU[0]). \en Mating surface through the boundary 0 (curvesU[0]). - MbSurface * surface1; ///< \ru Сопрягаемая поверхность через границу 1 (curvesV[0]). \en Mating surface through the boundary 1 (curvesV[0]). - MbSurface * surface2; ///< \ru Сопрягаемая поверхность через границу 2 (curvesU[maxU]). \en Mating surface through the boundary 2 (curvesU[maxU]). - MbSurface * surface3; ///< \ru Сопрягаемая поверхность через границу 3 (curvesV[maxV]). \en Mating surface through the boundary 3 (curvesV[maxV]). - MbPoint3D * point; ///< \ru Точка на поверхности. Используется для уточнения. \en Point on the surface. Used for specializing. + + c3d::SurfacesVector surface0; /// \ru Сопрягаемые поверхности через curvesU[0] \en Mating surfaces through curvesU[0] + c3d::SurfacesVector surface1; /// \ru Сопрягаемые поверхности через curvesV[0] \en Mating surfaces through curvesV[0] + c3d::SurfacesVector surface2; /// \ru Сопрягаемые поверхности через curvesU[maxU] \en Mating surfaces through curvesU[maxU] + c3d::SurfacesVector surface3; /// \ru Сопрягаемые поверхности через curvesV[maxV] \en Mating surfaces through curvesV[maxV] + MbPoint3D * point; ///< \ru Точка на поверхности. Используется для уточнения. \en Point on the surface. Used for specializing. bool defaultDir0; ///< \ru Направление сопряжения на границе 0 по умолчанию. \en Default mate direction through the boundary 0. bool defaultDir1; ///< \ru Направление сопряжения на границе 1 по умолчанию. \en Default mate direction through the boundary 1. bool defaultDir2; ///< \ru Направление сопряжения на границе 2 по умолчанию. \en Default mate direction through the boundary 2. bool defaultDir3; ///< \ru Направление сопряжения на границе 3 по умолчанию. \en Default mate direction through the boundary 3. mutable uint8 directOrderV;///< \ru По второму семейству кривых порядок кривых совпадает. \en Order of the curves coincides by the second set of curves. + bool tesselate; ///< \ru Достраивать ли дополнительные сечения. \en Whether to build additional sections. private: /// \ru Конструктор копирования. \en Copy-constructor. MeshSurfaceValues( const MeshSurfaceValues &, MbRegDuplicate * ireg ); @@ -1628,24 +1693,33 @@ public: \en Closedness attribute along the u and v directions. \~ \param[in] checkSelfInt - \ru Флаг проверки на самопересечение. \en Flag of check for self-intersection. \~ + \param[in] tesselate - \ru Достраивать ли дополнительные сечения. + \en Whether to build additional sections. \~ \param[in] type0, type1, type2, type3 - \ru Типы сопряжений на границах. \en Mates types on the boundaries. \~ - \param[in] surfaces0, surfaces1, surfaces2, surfaces3 - \ru Соответствующие сопрягаемые поверхности. - \en Corresponding mating surfaces. \~ + \param[in] surf0, surf1, surf2, surf3 - \ru Соответствующие сопрягаемые поверхности. + \en Corresponding mating surfaces. \~ + \param[in] point - \ru Точка на поверхности. Используется для уточнения. + \en Point on the surface. Used for specializing.\~ \param[in] modify - \ru Флаг модификации кривых по сопряжениям. \en Flag of curves modification by mates. \~ + \param[in] direct0, direct1, direct2, direct3 - \ru Направление поверхности на границе сопряжения. + \en The direction of the surface at the border of mating. \~ + \return \ru Статус выполнения. + \en Execution status. */ bool Init( const RPArray & curvesU, bool uClosed, const RPArray & curvesV, bool vClosed, bool checkSelfInt, + bool tess = false, const RPArray * chainsU = NULL, const RPArray * chainsV = NULL, MbeMatingType type0 = trt_Position, MbeMatingType type1 = trt_Position, MbeMatingType type2 = trt_Position, MbeMatingType type3 = trt_Position, - const MbSurface * surf_0 = NULL, // \ru Сопрягаемые поверхности через curvesU[0] \en Mating surfaces through curvesU[0] - const MbSurface * surf_1 = NULL, // \ru Сопрягаемые поверхности через curvesV[0] \en Mating surfaces through curvesV[0] - const MbSurface * surf_2 = NULL, // \ru Сопрягаемые поверхности через curvesU[maxU] \en Mating surfaces through curvesU[maxU] - const MbSurface * surf_3 = NULL, // \ru Сопрягаемые поверхности через curvesV[maxV] \en Mating surfaces through curvesV[maxV] + 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, bool modify = true, bool direct0 = true, bool direct1 = true, bool direct2 = true, bool direct3 = true ); @@ -1669,32 +1743,45 @@ public: \en Checking curve. \~ \param[in] surf - \ru Проверяемая поверхность. \en Checking surface. \~ + \return \ru Признак, что кривая лежит на поверхности. + \en A sign that the curve is on the surface. */ bool IsCurveOnSurface( const MbCurve3D & curve, const MbSurface & surf ) const; - /** \brief \ru Сопрягаются ли кривые с поверхностью точках пересечения с otherCurve. - \en Whether the curves are mated with surface in the points of intersection with otherCurve. \~ - \details \ru Сопрягаются ли кривые (касательно, по нормали, гладко) с поверхностью в точках пересечения с otherCurve. - \en Whether the curves are mated (tangentially, along the normal, smoothly) with surface in the points of intersection with otherCurve. \~ + /** \brief \ru Сопрягаются ли кривые с поверхностью в точках пересечения с borderCurve. + \en Whether the curves are mated with surface in the points of intersection with borderCurve. \~ + \details \ru Сопрягаются ли кривые (касательно, по нормали, гладко) с поверхностью в точках пересечения с borderCurve. + \en Whether the curves are mated (tangentially, along the normal, smoothly) with surface in the points of intersection with borderCurve. \~ \param[in] curves - \ru Набор проверяемых кривых. \en Set of checking curves. \~ - \param[in] surf - \ru Поверхность. - \en The surface. \~ - \param[in] otherCurve - \ru Кривая на этой поверхности. - \en Curve on this surface. \~ + \param[in] borderCurve- \ru Кривая на поверхности. + \en Curve on the surface. \~ + \param[in] matSurfaces- \ru Набор поверхностей сопряжения. + \en Set of mating surfaces. \~ \param[out] isTangent - \ru Признак касательного сопряжения. \en Attribute of the tangent mate. \~ \param[out] isNormal - \ru Признак сопряжения по нормали. \en Attribute of normal mate. \~ \param[out] isSmooth - \ru Признак гладкого сопряжения. \en Attribute of the smooth mate. \~ + \param[in] uc, vc - \ru Замкнутость поверхности по u и v. + \en Surface closeness by u and v. \~ + \return \ru Признак, что кривая лежит на поверхности. + \en A sign that the curve is on the surface. */ - void AreCurvesMatingToSurface( const RPArray & curves, - const MbSurface & surf, - const MbCurve3D * otherCurve, - bool & isTangent, - bool & isNormal, - bool & isSmooth ) const; + static bool AreCurvesMatingToSurface( const RPArray & curves, + const MbCurve3D * borderCurve, + const c3d::SurfacesVector & matSurfaces, + bool & isTangent, + bool & isNormal, + bool & isSmooth, + bool uc, + bool vc ); + + /// \ru Сопрягаются ли кривые с поверхностью в точках пересечения с поверхностной кривой (borderCurve). + /// \en Whether the curves are mated with surface in the points of intersection with the surface curve (borderCurve). + static bool AreCurvesMatingToSurface( const RPArray & curves, const MbCurve3D * borderCurve, + bool & isTangent, bool & isNormal, bool & isSmooth, bool uc, bool vc ); /// \ru Получить точки скрещивания-пересечения кривой с семейством кривых. \en Get crossing-intersection points of curves with the set of curves. bool GetPointsOfCrossing( const MbCurve3D & curve, const RPArray & otherCurves, @@ -1709,9 +1796,9 @@ public: /// \ru Получить тип сопряжения на границе с номером i. \en Get i-th mate type on the boundary. MbeMatingType GetTransitType( ptrdiff_t i ) const; /// \ru Получить поверхность сопряжения на границе с номером i. \en Get i-th mate surface on the boundary. - const MbSurface * GetSurface( size_t i ) const; + void GetSurface( size_t i, c3d::ConstSurfacesVector & surfaces ) const; /// \ru Получить поверхность сопряжения на границе с номером i. \en Get i-th mate surface on the boundary. - MbSurface * SetSurface( size_t i ); + void SetSurface( size_t i, c3d::SurfacesVector & surfaces ); /// \ru Получить направление сопряжения на границе с номером i. \en Get i-th mate direction on the boundary. bool IsDefaultDirection( size_t i ) const; @@ -1811,17 +1898,34 @@ public: /// \ru Повернуть кривые вокруг оси на заданный угол. \en Rotate curves at a given angle around an axis. void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg ); /// \ru Привести кривые к поверхностной форме (кривые на поверхности) \en Convert curves to the surface form (curves on the surface) - bool TransformCurves(); + bool TransformCurves( ); + /// \ru Привести кривые к поверхностной форме (кривые на поверхности) \en Convert curves to the surface form (curves on the surface) + bool TransformForCompositeSurfaceMating(); + /// \ru Обеспечить непрерывность длины первой производной для кривых семейства dirU. + /// \en Ensure continuity of the length of the first derivative for the curves of the dirU family. + bool SetContinuousDerivativeLength( bool dirU, bool & smooth, VERSION version ); /** \} */ /// \ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MeshSurfaceValues &, double accuracy ) const; - /// \ru Набор граничных поверхность пуст? \en Whether the set of boundary surfaces is empty? - bool AreSurfacesEmpty() const { return (surface0 == NULL && surface1 == NULL && surface2 == NULL && surface3 == NULL); } /// \ru Нужно ли проверять самопересечения? \en Whether it is necessary to check self-intersections? bool CheckSelfInt() const { return checkSelfInt; } - + ///< \ru Достраивать ли дополнительные сечения. \en Whether to build additional sections. + bool IsTesselate() const { return tesselate; } + /// \ru Получить поверхность сопряжения к граничной кривой по параметру на кривой. + /// \en Get the mating surface to the border curve by the curve parameter. + static const MbSurface * + GetMatingSurface( const MbCurve3D * borderCurve, double param ); + /// \ru Получить поверхность сопряжения к граничной кривой в точке пересечения с трансверсальной кривой. + /// \en Get the mating surface to the border curve at the intersection with the transversal curve. + static const MbSurface * + GetMatingSurface( const MbCurve3D * borderCurve, const MbCurve3D * transCurve ); + /// \ru Получить поверхностную кривую в указанной точке на границе сопряжения. + /// \en Get a surface curve at a specified point on the mating border. + static bool GetSurfaceCurve( const MbCurve3D * borderCurve, double param, const MbSurfaceCurve *& sCurve, double & t ); + /// \ru Является ли кривая поверхностной по типу. \en Is the curve surface in type. + static bool IsSurfaceCurveType( const MbCurve3D * borderCurve ); private: void AddRefCurves(); // \ru Увеличить счетчик ссылок у кривых. \en Increase the reference count of curves. void AddRefPoint(); // \ru Увеличить счетчик ссылок у точки. \en Increase the reference count of point. @@ -1832,10 +1936,16 @@ private: // \ru Определить порядок следования кривых по второму направлению. \en Determine the order of curves along the second direction. void CalculateOrderV() const; // \ru Привести кривую к типу поверхностной кривой или к контура из SurfaceCurve. \en Convert the curve to type of surface curve or contour from SurfaceCurve. - bool TransformToSurfaceCurve( const MbCurve3D & initCurve, + static bool TransformToSurfaceCurve( const MbCurve3D & initCurve, + bool isWhole, const MbSurface & surface, const RPArray & constrCurves, - MbSurfaceCurve *& resCurve ) const; + MbSurfaceCurve *& resCurve ); + // \ru Привести кривую к типу поверхностной кривой или к контура из SurfaceCurve. \en Convert the curve to type of surface curve or contour from SurfaceCurve. + static bool TransformToSurfaceCurve( const MbCurve3D & initCurve, + const c3d::SurfacesVector & surfaces, + const RPArray & constrCurves, + MbCurve3D *& resCurve ); public: KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MeshSurfaceValues, MATH_FUNC_EX ) OBVIOUS_PRIVATE_COPY( MeshSurfaceValues ) @@ -2018,7 +2128,7 @@ public: enum ExtensionWay { ew_distance = -2, ///< \ru Продолжить на расстояние. \en Prolong on the distance. ew_vertex = -1, ///< \ru Продолжить до вершины. \en Prolong to the vertex. - ew_surface = 0, ///< \ru Продолжить до поверхности. \en Prolong to the surface. + ew_shell = 0, ///< \ru Продолжить до оболочки. \en Prolong to the shell. }; /** \brief \ru Способы построения боковых рёбер. \en Methods of construction of the lateral edges. \~ @@ -2040,7 +2150,7 @@ public: bool prolong; ///< \ru Продолжить по гладко стыкующимся рёбрам. \en Prolong along smoothly mating edges. bool combine; ///< \ru Объединять грани при возможности. \en Combine faces if it is possible. private: - MbFaceShell * shell; ///< \ru Оболочка. \en A shell. + MbFaceShell * shell; ///< \ru Оболочка, до которой продляются грани. \en A shell to which the faces are extended. MbItemIndex faceIndex; ///< \ru Номер грани в оболочке. \en The index of face in the shell. public: @@ -2095,7 +2205,7 @@ public: \param[in] s - \ru Тело для замены оболочки. \en Solid for replacement of shell. \~ */ - void InitBySurface ( ExtensionType t, LateralKind k, const MbFace * f, const MbSolid * s ); + 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 ); @@ -2392,47 +2502,70 @@ public: */ // --- struct MATH_CLASS MedianShellValues { + public: + /** \brief \ru Тип расчета радиуса скругления между гранями срединной оболочки. + \en Type of fillet radius calculation between faces of median shell. \~ + \details \ru Флаг можно установить через вызов MedianShellValues::SetFilletType(). + \en The flag can be set by calling MedianShellValues::SetFilletType(). \~ + */ + enum FilletType { + tf_none, ///< \ru Не определено. \en Undefined. + tf_internal, ///< \ru По внутренней грани скругления. \en Along the tangent. + tf_external, ///< \ru По внешней грани скругления. \en Along the normal. + tf_average ///< \ru По среднему значению. \en Plane patch. + }; + public: - 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. + 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. + public: /// \ru Конструктор по умолчанию. \en Default constructor. MedianShellValues() - : position ( 0.5 ) - , dmin ( 0.0 ) - , dmax ( 0.0 ) + : filletType ( tf_average ) + , position ( 0.5 ) + , dmin ( 0.0 ) + , dmax ( 0.0 ) {} /// \ru Конструктор копирования. \en Copy-constructor. MedianShellValues( const MedianShellValues & other ) - : position ( other.position ) - , dmin ( other.dmin ) - , dmax ( other.dmax ) + : filletType ( other.filletType ) + , position ( other.position ) + , dmin ( other.dmin ) + , dmax ( other.dmax ) {} /// \ru Конструктор по параметрам. \en Constructor by parameters. MedianShellValues( double pos, double d1, double d2 ) - : position ( pos ) - , dmin ( d1 ) - , dmax ( d2 ) + : filletType( tf_average ) + , position ( pos ) + , dmin ( d1 ) + , dmax ( d2 ) {} public: /// \ru Являются ли объекты равными? \en Determine whether an object is equal? bool IsSame( const MedianShellValues & obj, double accuracy ) const { - if ( (::fabs(dmin - obj.dmin) < accuracy) && + if ( filletType == obj.filletType && + (::fabs(dmin - obj.dmin) < accuracy) && (::fabs(dmax - obj.dmax) < accuracy) && - (::fabs( position - obj.position) < accuracy ) ) - { + (::fabs(position - obj.position) < accuracy) ) return true; - } return false; } + /// \ru Выдать тип заплатки. \en Get type of patch. + FilletType GetType() const { return filletType; } + /// \ru Выдать тип заплатки для изменения. \en Get type of patch for changing. + FilletType & SetType() { return filletType; } + public: /// \ru Оператор присваивания. \en Assignment operator. MedianShellValues & operator = ( const MedianShellValues & other ) { + filletType = other.filletType; position = other.position; dmin = other.dmin; dmax = other.dmax; @@ -2468,6 +2601,12 @@ public: facePairs = pairs; distances.resize( pairs.size() ); } + /// \ru Конструктор по параметрам. \en Constructor by parameters. + MedianShellFaces( const MedianShellFaces & other ) + { + facePairs = other.facePairs; + distances = other.distances; + } /// \ru Деструктор. \en Destructor. ~MedianShellFaces() {} @@ -2489,7 +2628,7 @@ public: distances.push_back( dist ); } /// \ru Получить пару граней по индексу. \en Get pair of faces by index. - const c3d::ItemIndexPair & _GetFacePair( size_t index ) const { return facePairs[index];} + const c3d::ItemIndexPair & _GetFacePair( size_t index ) const { return facePairs[index]; } /// \ru Удалить пару граней из набора. \en Remove pair of faces from set. void RemovePairByIndex( size_t index ) { @@ -2500,6 +2639,8 @@ public: const double & _GetDistance( size_t index ) const { return distances[index]; } /// \ru Установить расстояние между гранями. \en Set distance between faces. void _SetDistance( size_t index, double value ) { distances[index] = value; } + /// \ru Инвертировать пару граней в наборе. \en Inverse face pair. + void Inverse( size_t index ) { std::swap(facePairs[index].first, facePairs[index].second); } /// \ru Вернуть количество пар граней в наборе. \en Get count of pairs in given set. size_t Count() const { return facePairs.size(); } /// \ru Оператор присваивания. \en Assignment operator. @@ -2510,27 +2651,105 @@ public: } /// \ru Очистка текущего набора. \en Clear current faces set. void Clear() { facePairs.clear(); distances.clear(); } - + /// \ru Проверить наличие пары в наборе. \en Check if pair already in set. + size_t IsExist( const MbItemIndex & ind, size_t start_pos, size_t end_pos, bool & first ) const; KNOWN_OBJECTS_RW_REF_OPERATORS( MedianShellFaces ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class. }; +//------------------------------------------------------------------------------ +/** \brief \ru Параметры сшивки. + \en Stitch parameters. \~ + \details \ru Параметры сшивки оболочек. \n + \en Shells stitch parameters. \n \~ + \ingroup Build_Parameters +*/ +// --- +struct MATH_CLASS MbShellStitchParams { +private: + MbSNameMaker nameMaker; ///< \ru Именователь операции. \en An object defining names generation in the operation. + double stitchAccuracy; ///< \ru Точность сшивки (точность поиска парных ребер). \en Stitching accuracy (search accuracy of edges pairs). + bool formSolidBody; ///< \ru Флаг формирования твердого тела из результирующей оболочки. \en Whether to form a solid solid from the resultant shell. + bool mergeEdges; ///< \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). +private: + MbShellStitchParams(); +public: + /** \brief \ru Конструктор параметров сшивки оболочек. + \en Stitch faces of several solids into single solid. \~ + \details \ru Сшить стыкующиеся друг с другом грани нескольких тел в одно тело. Ориентация граней может быть изменена. \n + \en Stitch faces of several solids with coincident edges into single solid. The faces orientation can be changed. \n \~ + \param[in] operNames - \ru Именователь операции. + \en An object defining names generation in the operation. \~ + \param[in] formBody - \ru Флаг формирования твердого тела из результирующей оболочки. + \en Whether to form a solid solid from the resultant shell. \~ + \param[in] sewingAccuracy - \ru Точность сшивки (точность поиска парных ребер). + \en Stitching accuracy (search accuracy of edges pairs). \~ + \param[in] edgesMerging - \ru Сливать подобные ребра (true). + \en Whether to merge similar edges (true). \~ + */ + MbShellStitchParams( const MbSNameMaker & operNames, bool formBody, double sewingAccuracy, bool edgesMerging = true ) + : nameMaker ( operNames ) + , stitchAccuracy( sewingAccuracy ) + , formSolidBody ( formBody ) + , mergeEdges ( edgesMerging ) + {} + ~MbShellStitchParams() + {} +public: + /// \ru Получить именователь операции. \en Get the object defining names generation in the operation. + const MbSNameMaker & GetNameMaker() const { return nameMaker; } + /// \ru Получить точность поиска парных ребер. \en Get search accuracy of edges pairs. + double GetStitchAccuracy() const { return stitchAccuracy; } + /// \ru Пытаться формировать твердое тело из результирующей оболочки.. \en Whether to try forming a solid solid from the resultant shell. + bool TryBodyForming() const { return formSolidBody; } + /// \ru Сливать подобные ребра (true). \en Whether to merge similar edges (true). + bool PerformEdgesMerging() const { return mergeEdges; } + +OBVIOUS_PRIVATE_COPY ( MbShellStitchParams ) +}; + + //------------------------------------------------------------------------------ /// \ru Типы продления секущих поверхностей. \en Prolongation types of cutter surfaces. // --- enum MbeSurfaceProlongType { - cspt_None = 0x00, // 0000 ///< \ru Не продлевать. \en Don't prolong. - cspt_Planar = 0x01, // 0001 ///< \ru Плоские поверхности. \en Planar surfaces. - cspt_RevolutionAxis = 0x02, // 0010 ///< \ru Поверхности вращения (вдоль оси). \en Revolution surfaces (along axis). - cspt_RevolutionAngle = 0x04, // 0100 ///< \ru Поверхности вращения (по углу). \en Revolution surfaces (by angle). - cspt_Revolution = 0x06, // 0110 ///< \ru Поверхности вращения. \en Revolution surfaces. + cspt_None = 0x00, // 00000 ///< \ru Не продлевать. \en Don't prolong. + cspt_Planar = 0x01, // 00001 ///< \ru Плоские поверхности. \en Planar surfaces. + cspt_RevolutionAxis = 0x02, // 00010 ///< \ru Поверхности вращения (вдоль оси). \en Revolution surfaces (along axis). + cspt_RevolutionAngle = 0x04, // 00100 ///< \ru Поверхности вращения (по углу). \en Revolution surfaces (by angle). + cspt_Revolution = 0x06, // 00110 ///< \ru Поверхности вращения. \en Revolution surfaces. + cspt_ExtrusionGeneratrix = 0x08, // 01000 ///< \ru Поверхности выдавливания (по образующей). \en Extrusion surfaces (by generatrix). + cspt_ExtrusionDistance = 0x10, // 10000 ///< \ru Поверхности выдавливания (по расстоянию). \en Extrusion surfaces (by distance). + cspt_Extrusion = 0x18, // 11000 ///< \ru Поверхности выдавливания. \en Extrusion surfaces. }; + //------------------------------------------------------------------------------ /** \brief \ru Параметры операции резки оболочки. \en Shell cutting operation parameters. \~ \details \ru Параметры операции резки оболочки. \n - \en Shell cutting operation parameters. \n \~ + Предполагается взаимоисключающее состояние флагов при их активном состоянии в #MbShellCuttingParams : \n + 1. #cspt_Planar - продлять или нет грани на основе плоскости; \n + 2. #cspt_Revolution - продлять или нет поверхности, имеющие ось вращения (у которых функция поверхности GetCylinderAxis возвращает true ), + причем возможно раздельное управление : \n + #cspt_RevolutionAngle - замкнуть поверхность по углу, \n + #cspt_RevolutionAxis - продлить поверхность вдоль оси так, чтобы включить габарит тела, если это возможно); \n + 3. #cspt_Extrusion - продлять или нет поверхности, являющиеся поверхностями выдавливания (поверхность выдавливания, цилиндрическая поверхность), + причем возможно раздельное управление : \n + #cspt_ExtrusionGeneratrix - продлить вдоль образующей для включения габарита тела или замкнуть, если образующая периодична (дуга), \n + #cspt_ExtrusionDistance - продлить поверхность вдоль направления выдавливания так, чтобы включить габарит тела, если это возможно). \n + \en Shell cutting operation parameters. \n + + The mutually exclusive state of flags is assumed when they are active in #MbShellCuttingParams: \n + 1. #cspt_Planar - extend or not the face based on the plane; \n + 2. #cspt_Revolution - extend or not surfaces having a rotation axis (for which the GetCylinderAxis surface function returns true), + moreover, separate control is possible: \n + #cspt_RevolutionAngle - close the surface by angle, \n + #cspt_RevolutionAxis - extend the surface along the axis so as to embrace the body, if it's possible; \n + 3. #cspt_Extrusion - to extend or not surfaces that are extrusion surfaces (extrusion surface, cylindrical surface), + moreover, separate control is possible: \n + #cspt_ExtrusionGeneratrix - extend along the generatrix to cover the body or close if the generatrix is ​​periodic (like an arc), \n + #cspt_ExtrusionDistance - extend the surface along the extrusion direction so as to embrace the body, if it's possible. \n \~ \ingroup Build_Parameters */ // --- @@ -2788,7 +3007,7 @@ public: const MbSNameMaker & snMaker ) { if ( cutterData.InitPlaneContour( place, dir, contour, sameContour ) ) { - nameMaker.SetName( snMaker, true ); + nameMaker.SetNameMaker( snMaker, true ); booleanFlags.InitCutting( cutAsClosed ); booleanFlags.SetMerging( mergingFlags ); SetRetainedPart( part ); @@ -2840,7 +3059,7 @@ public: const MbSNameMaker & snMaker ) { if ( cutterData.InitSurfaces( surface, sameSurface ) ) { - nameMaker.SetName( snMaker, true ); + nameMaker.SetNameMaker( snMaker, true ); booleanFlags.InitCutting( cutAsClosed ); booleanFlags.SetMerging( mergingFlags ); SetRetainedPart( part ); @@ -2890,7 +3109,7 @@ public: const MbSNameMaker & snMaker ) { if ( cutterData.InitSolid( solid, sameSolid, true ) ) { - nameMaker.SetName( snMaker, true ); + nameMaker.SetNameMaker( snMaker, true ); booleanFlags.InitCutting( cutAsClosed ); booleanFlags.SetMerging( mergingFlags ); SetRetainedPart( part ); @@ -2960,7 +3179,7 @@ public: /// \ru Получить тип продления режущей поверхности. \en Get cutter surface prolong type. const ProlongState & GetProlongState() const { return prolongState; } - /// \ru Получить тип продления режущей поверхности. \en Get cutter surface prolong type. + /// \ru Сбросить тип продления режущей поверхности. \en Reset cutter surface prolong type. void ResetProlongState() { prolongState.Reset(); } /// \ru Добавить тип продления режущей поверхности. \en Add cutter surface prolong type. void SetSurfaceProlongType( MbeSurfaceProlongType pt ) { prolongState.SetActiveType( true, pt ); } diff --git a/C3d/Include/op_swept_parameter.h b/C3d/Include/op_swept_parameter.h index e8dae02..2e272eb 100644 --- a/C3d/Include/op_swept_parameter.h +++ b/C3d/Include/op_swept_parameter.h @@ -1,1416 +1,2004 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \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 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 - 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 \~ - \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. \~ - */ - MbSweptData( MbSolid & _solid ); - - /** \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; - /// \ru Есть данные о пространственных кривых? \en Is there data of spatial curves? - bool IsSpaceCurvesData() const; - /// \ru Есть данные о теле? \en Is there data about the solid? - bool IsSolidData() const; - - /// \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. - void SetSurface( MbSurface * surf ) { surface = 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 { -public: - /** \brief \ru Способ переноса образующего контура вдоль направляющей. - \en Moving method of generating contour along the spine curve. \~ - \details \ru Способ переноса образующего контура вдоль направляющей: \n - parallel <= 0 - образующая переносится параллельно самой себе; \n - parallel == 1 - образующая при переносе сохраняет исходный угол с направляющей; \n - parallel >= 2 - плоскость образующей выставляется и сохраняется ортогональной направляющей. \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 \~ - */ - int parallel; - // \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 fanction of curve scale. - SPtr winding; ///< \ru Функция вращения образующей кривой. \en The fanction of curve rotation. - -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( ) - , parallel ( 1 ) - , range ( 0.0 ) - , scaling ( NULL ) - , winding ( 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 Get the fanction 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 generatig 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 fanction of curve scale. - const MbFunction* GetScaling() const { return scaling; } - MbFunction * SetScaling() { return scaling; } - - /// \ru Выдать функцию вращения образующей кривой. \en Get the fanction of curve rotation. - const MbFunction* GetWinding() const { return winding; } - MbFunction * SetWinding() { return winding; } - -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. - bool setNormal2; ///< \ru Установлена нормаль в конце. \en The normal is set at the end. - -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 ) - {} - /// \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 ) - {} - /// \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; - 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 ( 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 & ); -}; - - -#endif // __OP_SHELL_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 + + +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 Какую сторону кривой гладко стыковать с поверхностью (синхронно с guideEdges). \en Which side should the surface join smoothly to (synchronously with guideEdges). + std::vector faces; ///< \ru Опорные грани (могут отсутствовать). \en The reference faces (may be empty). + std::vector faceSide; ///< \ru С каких сторон касаться поверхностей при form==cs_Linea (синхронно с surfaces). \en On which sides to touch surfaces when form==cs_Linea (synchronously with surfaces). + 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 accuracy ) 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 { + +public: + 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: + + const SArray & GetEdgeIndex1() const { return edgeIndex1; } + const SArray & GetFaceIndex1() const { return faceIndex1; } + const SArray & GetEdgeIndex2() const { return edgeIndex2; } + const SArray & GetFaceIndex2() const { return faceIndex2; } + + SArray & GetEdgeIndex1() { return edgeIndex1; } + SArray & GetFaceIndex1() { return faceIndex1; } + SArray & GetEdgeIndex2() { return edgeIndex2; } + SArray & GetFaceIndex2() { 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 bf685e8..a3aab3a 100644 --- a/C3d/Include/pars_equation_tree.h +++ b/C3d/Include/pars_equation_tree.h @@ -1,1549 +1,1573 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Узел бинарного дерева. - \en Node of a binary tree. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __PARS_EQUATION_TREE_H -#define __PARS_EQUATION_TREE_H - - -#include // \ru СМВ для компиляции ICC \en СМВ for compilation by ICC -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Количество параметров. - \en Parameters count. \~ - \details \ru Выдать количество параметров для типа операции.\n - \en Get the count of parameters for type of operation.\n \~ - \param[in] operationType - \ru Тип операцции. - \en An operation type. \~ - \return \ru Количество параметров операции. - \en Operation parameters count. \~ - \ingroup Parser -*/ -// --- -uint inline GetCountOfParams( PceOperationType operationType ) -{ - uint res = 1; - if ( operationType < oprt_BinaryOperation ) - res = 3; - else if ( operationType < oprt_UnaryOperation ) - res = 2; - - return res; -} - - -//----------------------------------------------------------------------------- -/** \brief \ru Информация о характерных точках дерева. - \en Information about characteristic points of a tree. \~ - \details \ru Информация о характерных точках дерева. \n - \en Information about characteristic points of a tree. \n \~ - \ingroup Parser -*/ -// --- -class BTreeNode; -struct CharacterPointInfo -{ - /** \brief \ru Тип характерной точки. - \en Type of a characteristic point. \~ - \details \ru Тип характерной точки.\n - \en Type of a characteristic point.\n \~ - */ - enum EquCharacterPointType - { - equPoint_DefRangeRight, ///< \ru Граница области определения. \en Boundary of the definition domain. - equPoint_DefRangeLeft, ///< \ru Граница области определения. \en Boundary of the definition domain. - equPoint_Extr, ///< \ru Экстремум. \en Extremum. - equPoint_Break1, ///< \ru Разрыв первого рода. \en Discontinuity of the first kind. - equPoint_Break2, ///< \ru Разрыв второго рода. \en Discontinuity of the second kind. - equPoint_DerBreak1 ///< \ru Разрыв производной. \en Derivative discontinuity. - }; - - const BTreeNode * m_tree; ///< \ru Узел дерева. Не равен NULL. \en Node of a tree. Not equal to 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. - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор.\n - \en Constructor.\n \~ - \param[in] tree - \ru Узел дерева. - \en Node of a tree. \~ - \param[in] type - \ru Тип характорной точки. - \en Type of a characteristic point. \~ - \param[in] ph - \ru Значение параметра функции. - \en Value of a function parameter. \~ - \param[in] period - \ru Период функции. - \en Period of a function. \~ - */ - CharacterPointInfo( const BTreeNode & tree, EquCharacterPointType type, double ph, double period ) - : m_tree ( &tree ) - , m_type ( type ) - , m_ph ( ph ) - , m_period( period ) - {} - -}; - - -//----------------------------------------------------------------------------- -/** \brief \ru Элемент области определения функции. - \en Element of the function definition domain. \~ - \details \ru Элемент области определения функции. \n - \en Element of the function definition domain. \n \~ - \ingroup Parser -*/ -// --- -struct DefRangeItem -{ - /** \brief \ru Тип элемента. - \en A type of the element. \~ - \details \ru Тип элемента области определения функции. \n - \en Type of an element of the function definition domain. \n \~ - */ - enum RangeItemType - { - range_def, ///< \ru Область определения. \en Definition domain. - range_break, ///< \ru Разрыв. \en Discontinuity. - range_extr, ///< \ru Экстремум. \en Extremum. - }; - - double lbound; ///< \ru Левая граница элемента области определения. \en Left bound of an element of the definition domain. - double rbound; ///< \ru Правая граница элемента области определения. \en Right bound of an element of the definition domain. - RangeItemType type; ///< \ru Тип элемента. \en A type of an element. - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор. \n - \en Constructor. \n \~ - \param[in] l - \ru Левая граница элемента области определения. - \en The left bound of an element of the definition domain. \~ - \param[in] r - \ru Правая граница элемента области определения. - \en The right bound of an element of the definition domain. \~ - \param[in] t - \ru Тип элемента. - \en A type of the element. \~ - */ - DefRangeItem( double l, double r, RangeItemType t = range_def ) - : lbound( l ) - , rbound( r ) - , type( t ) - { - if ( lbound > rbound ) - std::swap( lbound, rbound ); - } -}; - - -namespace std { -//----------------------------------------------------------------------------- -/** \brief \ru Сравнение элементов области определения. - \en Comparison of elements of the definition domain. \~ - \details \ru Сравнение элементов области определения функции. \n - \en Comparison of elements of the function definition domain. \n \~ - \ingroup Parser -*/ -// --- -template<> -struct less -{ - /** \brief \ru Сравнение элементов области определения. - \en Comparison of elements of the definition domain. \~ - \details \ru Сравнение элементов области определения функции. \n - \en Comparison of elements of the function definition domain. \n \~ - \param[in] _Left - \ru Первый элемент. - \en The first element. \~ - \param[in] _Right - \ru Второй элемент - \en The second element \~ - \return \ru true, если первый элемент меньше второго. - \en true if the first element is less than second one. \~ - */ - bool operator()(const DefRangeItem & _Left, const DefRangeItem & _Right) const - { return ( _Right.lbound - _Left.rbound > -METRIC_EPSILON ); } -}; - -} // namespace std - - -//----------------------------------------------------------------------------- -/** \brief \ru Область определения функции. - \en The function domain. \~ - \details \ru Область определения функции. \n - \en The function domain. \n \~ - \ingroup Parser -*/ -// --- -class DefRange -{ - std::set arr; - bool m_hasbreak; -public: - static const double eps; ///< \ru Погрешность. \en Tolerance. - -public: - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор области определения без разрывов. \n - \en Constructor of the definition domain without discontinuities. \n \~ - \param[in] l - \ru Левая граница области определения. - \en Left bound of the definition domain. \~ - \param[in] r - \ru Правая граница области определения. - \en Right bound of the definition domain. \~ - */ - DefRange( double l, double r ) - : m_hasbreak( false ) - { - if ( l > r ) - std::swap( l, r ); - arr.insert( DefRangeItem(l - METRIC_EPSILON, r + METRIC_EPSILON) ); - } - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор области определения без разрывов. \n - \en Constructor of the definition domain without discontinuities. \n \~ - */ - DefRange() : m_hasbreak( false ) {}; - - /// \ru Дать набор элементов области определения. \en Get a set of elements of the definition domain. - const std::set & GetSet() const { return arr; } - - /// \ru Есть ли разрывы в области определения. \en Whether the discontinuities is in the definition domain. - bool HasBreaks() const { return m_hasbreak; } - - /// \ru Разрезать область определения. \en Cut the domain. - bool Cut( DefRangeItem & i ); - /// \ru Добавить элемент области определения. \en Add element of the definition domain. - void Add( DefRangeItem & i ); - /// \ru Оператор сравнения. \en Comparison operator. - bool operator == ( const DefRange & other ); -}; - - -class BTreeConst; -class BTreeIdent; -class BTreeFunction; -class BTreeOperation; -class BTreeOperation1Arg; -class BTreeOperation3Args; -class BTreeUserFunc; - - -//----------------------------------------------------------------------------- -/** \brief \ru Значение функции и производных. - \en Value of the function and derivatives. \~ - \details \ru Значение функции и её первой, второй и третьей производных. \n - \en Values of function, its first, second and third derivatives. \n \~ - \ingroup Parser -*/ -// --- -struct DerivesValues -{ - double value; ///< \ru Значение функции. \en The value of function. - double firstDer; ///< \ru Первая производная. \en The first derivative. - double secondDer; ///< \ru Вторая производная. \en The second derivative. - double thirdDer; ///< \ru Третья производная. \en The third derivative. -}; - -//----------------------------------------------------------------------------- -/** \brief \ru Базовый класс для узлов дерева выражения. - \en Base class for nodes of the expression tree. \~ - \details \ru Базовый класс для узлов дерева выражения. \n - \en Base class for nodes of the expression tree. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS BTreeNode : public TapeBase -{ -public: - typedef std::map EqualVarsMap; ///< \ru Набор пар переменных. \en A set of pairs of variables. - typedef std::map VarsDerives; ///< \ru Набор пар: координата - значение и производные. \en A set of pairs: coordinate - value and derivatives. - -public: - BteNodeType type; ///< \ru Тип узла. \en A type of node. \~ \internal \ru Для отладки. \en For debugging. \~ \endinternal -protected: - mutable VarsDerives varDers; ///< \ru Рабочие переменные. \en Working variables. \~ - -protected: - /// \ru Конструктор по умолчанию. \en Default constructor. - BTreeNode() {} - -public: - virtual ~BTreeNode() {} - /// \ru Выдать тип узла дерева. \en Get type of a tree node. - virtual BteNodeType IsA () const = 0; - /// \ru Создать копию объекта. \en Create a copy of the object. - virtual BTreeNode * Duplicate() const = 0; - - /// \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const = 0; - - /**\ru \name Функции для вычисления значения и производной. - \en \name Functions for calculation of the value and the derivative. - \{ */ - - /** \brief \ru Вычислить значение. - \en Calculate value. \~ - \details \ru Вычислить значение узла.\n - \en Calculate value of node.\n \~ - \param[out] fValue - \ru Значение. - \en Value. \~ - \return \ru Код результата разбора строки. - \en String parsing result code. \~ - */ - virtual EquTreeResCode GetValue( double & fValue ) const = 0; - - /** \brief \ru Установить значение. - \en Set value. \~ - \details \ru Устанавливает значение v узлу дерева. - \en Set 'v' value to a tree node. \~ - \param[in] v - \ru Желаемое значение. - \en Desirable value. \~ - \param[in] unfixedDVars - \ru Переменные, значение которых можно менять. - \en Variables which values can be changed. \~ - */ - virtual bool SetValue( double v, const std::set & unfixedDVars ) = 0; - - /** \brief \ru Вычислить значение и производные. - \en Calculate a value and derivatives. \~ - \details \ru Вычислить значение и производные. \n - \en Calculate a value and derivatives. \n \~ - \param[out] fValue - \ru Значение. - \en Value. \~ - \param[out] derive1 - \ru Первая производная. - \en The first derivative. \~ - \param[out] derive2 - \ru Вторая производная. - \en The second derivative. \~ - \param[out] derive3 - \ru Третья производная. - \en The third derivative. \~ - \param[in] ders - \ru Набор значений и производных. - \en Set of values and derivatives. \~ - \return \ru Код результата разбора строки. - \en String parsing result code. \~ - */ - virtual EquTreeResCode CalculateDerives( double & fValue, double & derive1, - double & derive2, double & derive3, const VarsDerives & ders ) const = 0; - - /** \brief \ru Вычислить значение и производные. - \en Calculate a value and derivatives. \~ - \details \ru Вычислить значение и производные. \n - \en Calculate a value and derivatives. \n \~ - \param[in] coord - \ru Координата. - \en Coordinate. \~ - \param[out] v - \ru Значение. - \en Value. \~ - \param[out] fd - \ru Первая производная. - \en The first derivative. \~ - \param[out] sd - \ru Вторая производная. - \en The second derivative. \~ - \param[out] td - \ru Третья производная. - \en The third derivative. \~ - \return \ru Код результата разбора строки. - \en String parsing result code. \~ - */ - EquTreeResCode CalculateDerives( const ItCoord * coord, double & v, double & fd, double & sd, double & td ) const; - - /** \brief \ru Выдать использованные переменные. - \en Get the used variables. \~ - \details \ru Выдать использованные переменные. \n - \en Get the used variables. \n \~ - \param[out] arr - \ru Переменные. - \en Variables. \~ - \param[out] funcs - \ru Пользовательские функции. - \en User functions. \~ - */ - virtual void GetUsedVariables( SSArray & arr, SSArray & funcs ) const = 0; - - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - /** \brief \ru Заменить переменные. - \en Replace variables. \~ - \details \ru Заменить все переменные с указанными именем на новую переменную.\n - \en Replace all variables with the specified name by a new variable.\n \~ - \param[out] varName - \ru Имя. - \en Name. \~ - \param[out] newVar - \ru Новая переменная. - \en New variable. \~ - */ - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ) = 0; - - /** \brief \ru Заменить узел. - \en Replace a node. \~ - \details \ru Заменить узел на копию нового, если заданная переменная использована.\n - \en Replace a node with a copy of a new one if the given variable is used.\n \~ - \param[out] var - \ru Переменная. - \en Variable. \~ - \param[out] subTree - \ru Новый узел. - \en New node. \~ - */ - virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ) = 0; - - /** \brief \ru Заменить переменные. - \en Replace variables. \~ - \details \ru Заменить все переменные с указанными именем на новую переменную.\n - \en Replace all variables with the specified name by a new variable.\n \~ - */ - virtual void ReplaceIntVariable( const c3d::string_t &, ItIntervalTreeVariable & ) {} - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /** \brief \ru Выдать значение параметра экстремума. - \en Get value of parameter of extremum. \~ - \details \ru Выдать значение параметра экстремума, если это возможно.\n - \en Get value of parameter of extremum if it is possible.\n \~ - \param[in] interval - \ru Интервал для поиска. - \en Interval to search. \~ - \param[in] var - \ru Переменная. - \en Variable. \~ - \param[out] points - \ru Точки экстремума. - \en Points of extremum. \~ - */ - bool GetExtremumPoints( std::pair interval, ItTreeVariable & var, - std::vector & points ); - - /** \brief \ru Область определения. - \en Domain. \~ - \details \ru Область определения.\n - \en Domain.\n \~ - \param[in,out] defRange - \ru Область определения. - \en Domain. \~ - \param[out] var - \ru Переменная. - \en Variable. \~ - \param[in] stopOnBreak - \ru Не искать разрывы области определения. - \en Not to search the discontinuities in the definition domain. \~ - */ - virtual bool GetDefRange( DefRange & defRange, ItTreeVariable & var, bool stopOnBreak ) const = 0; - - /** \brief \ru Только для внутреннего использования! Порядок переменной. - \en For internal use only! Order of variable. \~ - \details \ru Порядок переменной.\n - \en Order of variable.\n \~ - \param[in] var - \ru Переменная. - \en Variable. \~ - \return \ru Порядок. - \en Order. \~ - */ - virtual size_t GetPseudoOrderByVar ( ItTreeVariable & var ) const = 0; - - /** \brief \ru Фиксированные переменные. - \en Fixed variables. \~ - \details \ru Фиксированные переменные.\n - \en Fixed variables.\n \~ - \param[in] unfixedVars - \ru Набор нефиксированных переменных. Если переменная нашлась в наборе, фиксировать копию. - \en A set of unfixed variables. If variable was found in set, then fix the copy. \~ - \param[in] newFuncs - \ru Пользовательские функции. - \en User functions. \~ - \param[out] code - \ru Коды результата разбора строки. - \en Result codes of string parsing. \~ - \return \ru Переменную для фиксирования. - \en Variable for fixation. \~ - */ - virtual std_unique_ptr FixVars ( const RPArray & unfixedVars, - PArray & newFuncs, EquTreeResCode & code ) const = 0; - - /// \ru Дать эквивалентный узел. \en Get equivalent node. - virtual std_unique_ptr GetCalcEquivalent() const = 0; - - /** \brief \ru Дать строку. - \en Get string. \~ - \details \ru Дать строку выражения.\n - \en Get expression string.\n \~ - \param[out] - \ru Строка. - \en String. \~ - */ - virtual void GetString( c3d::string_t & ) const = 0; - - /// \ru Вычислить размер в байтах. \en Get size in bytes. - virtual size_t SizeOf() const = 0; - - /** \} */ - /**\ru \name Функции сравнения. - \en \name Comparison function. - \{ */ - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] varsMap - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & varsMap ) const = 0; - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeConst & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeIdent & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeFunction & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeOperation & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeOperation1Arg & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeOperation3Args & , const EqualVarsMap & ) const { return false; } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether the node is equal to the given node.\n \~ - \return false. - */ - virtual bool IsEqual( const BTreeUserFunc & , const EqualVarsMap & ) const { return false; } - /** \} */ - -private: - // \ru не реализовано \en not implemented - BTreeNode( const BTreeNode & ); - void operator =( const BTreeNode & ); - - DECLARE_PERSISTENT_CLASS( BTreeNode ) -}; - -IMPL_PERSISTENT_OPS( BTreeNode ) - -//----------------------------------------------------------------------------- -/** \brief \ru Типы узлов бинарного дерева. - \en Types of nodes of the binary tree. \~ - \details \ru Типы узлов бинарного дерева. \n - \en Types of nodes of the binary tree. \n \~ - \ingroup Parser -*/ -// --- -enum TeIntervalNodeType -{ - tei_Const, ///< \ru Константа. \en Constant. - tei_Ident ///< \ru Идентификатор. \en Identifier. -}; - - -//----------------------------------------------------------------------------- -/** \brief \ru Узел дерева интервального выражения. - \en Node of interval expression tree. \~ - \details \ru Узел дерева интервального выражения. \n - \en Node of interval expression tree. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS TreeIntervalNode : public TapeBase/*, public BTreeBaseNode*/ -{ -protected: - TreeIntervalNode() {} - -public: - /// \ru Выдать тип узла дерева. \en Get type of a tree node. - virtual TeIntervalNodeType IsA () const = 0; - /// \ru Выдать копию объекта. \en Get a copy of the object. - virtual TreeIntervalNode * Duplicate() const = 0; - - /// \ru Дать первую переменную. \en Get the first variable. - virtual EquTreeResCode GetFirstValue ( double & ) const = 0; - /// \ru Дать вторую переменную. \en Get the second variable. - virtual EquTreeResCode GetSecondValue ( double & ) const = 0; - /// \ru Дать строку. \en Get a string. - virtual void GetString ( c3d::string_t & ) const = 0; - - /** \brief \ru Установить значение. - \en Set value. \~ - \details \ru Попытаться установить значение [f;s] узлу дерева. - \en Try to set value [f;s] to a tree node. \~ - \param[in] f - \ru Нижняя граница интервала. - \en Lower bound of the interval. \~ - \param[in] s - \ru Верхняя граница интервала. - \en Upper bound of the interval. \~ - \param[in] unfixedIVars - \ru Mножество интервальных переменных, которые можно менять. - \en Set of interval variables, which can be changed. \~ - \param[in] unfixedDVars - \ru Mножество вещественных переменных, которые можно менять. - \en Set of real variables, which can be changed. \~ - \access public - \return \ru Истину, если удалось установить значение. - \en True if it was succeeded to set value. \~ - */ - virtual std::pair SetValue ( double f, double s - , const std::set & unfixedIVars - , const std::set & unfixedDVars ) = 0; - - /** \brief \ru Заменить переменные. - \en Replace variables. \~ - \details \ru Заменить все переменные с указанными именем на новую переменную.\n - \en Replace all variables with the specified name by a new variable.\n \~ - \param[out] varName - \ru Имя. - \en Name. \~ - \param[out] newVar - \ru Новая переменная. - \en New variable. \~ - */ - virtual void ReplaceParVariable ( const c3d::string_t & varName, ItTreeVariable & newVar ) = 0; - -private: - // \ru не реализовано \en not implemented - TreeIntervalNode( const TreeIntervalNode & ); - void operator = ( const TreeIntervalNode & ); - - DECLARE_PERSISTENT_CLASS( TreeIntervalNode ) -}; - -IMPL_PERSISTENT_OPS( TreeIntervalNode ) - -//----------------------------------------------------------------------------- -/** \brief \ru Интервал простых выражений. - \en Interval of simple expressions. \~ - \details \ru Операция [] - получение интервала из простых выражений.\n - \en operation [] - obtaining of interval of simple expressions.\n \~ - \ingroup Parser -*/ -// --- -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). - -public: - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор.\n - \en Constructor.\n \~ - \param[in] firstValue - \ru Первый узел. - \en The first node. \~ - \param[in] secondValue - \ru Второй узел. - \en The second node. \~ - */ - IntervalConstNode( BTreeNode & firstValue, BTreeNode & secondValue ) - : m_firstValue ( &firstValue ) - , m_secondValue( &secondValue ) - {} - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор копирования.\n - \en Copy-constructor.\n \~ - \param[in] other - \ru Копируемый объект. - \en Object to copy. \~ - */ - IntervalConstNode( const IntervalConstNode & other ) - : m_firstValue( other.m_firstValue ) - , m_secondValue( other.m_secondValue ) - {} - -public: - /**\ru \name Функции узла дерева интервального выражения. - \en \name Functions of interval expression tree node. - \{ */ - - virtual TeIntervalNodeType IsA () const { return tei_Const; } // \ru выдать тип узла дерева \en get type of a tree node - virtual IntervalConstNode * Duplicate() const { return new IntervalConstNode( *this ); } - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetFirstValue ( double & v ) const { return m_firstValue->GetValue( v ); } - virtual EquTreeResCode GetSecondValue ( double & v ) const { return m_secondValue->GetValue( v ); } - - // \ru Установить значение. \en Set value. - virtual std::pair SetValue ( double f, double s - , const std::set & unfixedIVars - , const std::set & unfixedDVars ); - - virtual void GetString( c3d::string_t & ) const {} - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - - /** \} */ - /**\ru \name Функции операции []. - \en \name Functions of operation []. - \{ */ - - /// \ru Дать первый узел. \en Get the first node. - BTreeNode & GetFirstTree () { return *m_firstValue; } - /// \ru Дать второй узел. \en Get the second node. - BTreeNode & GetSecondTree () { return *m_secondValue; } - - /** \brief \ru Заменить переменные. - \en Replace variables. \~ - \details \ru Заменить все переменные с указанными именем на новую интервальную переменную.\n - \en Replace all variables with the specified names by a new interval variable.\n \~ - */ - virtual void ReplaceIntVariable( const c3d::string_t & /*varName*/, ItIntervalTreeVariable & /*newVar*/ ) {} - /** \} */ -// ССА K13 virtual size_t SizeOf() const = 0; - -private: - // \ru не реализовано \en not implemented - void operator =( const TreeIntervalNode & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( IntervalConstNode ) -}; - -IMPL_PERSISTENT_OPS( IntervalConstNode ) - -//----------------------------------------------------------------------------- -/** \brief \ru Интервальная переменная как узел бинарного дерева. - \en Interval variable as a node of a binary tree. \~ - \details \ru Узел дерева - интервальная переменная.\n - \en Tree node is an interval variable.\n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS IntervalIdentNode : public TreeIntervalNode -{ - ItIntervalTreeVariable * m_ident; ///< \ru Всегда не NULL. \en Always not NULL. - -public: - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по интервальной переменной.\n - \en Constructor by an interval variable.\n \~ - \param[in] ident - \ru Интервальная переменная. - \en Interval variable. \~ - */ - IntervalIdentNode( ItIntervalTreeVariable & ident ) - : m_ident( &ident ) - {} - - /// \ru Конструктор копирования. \en Copy-constructor. - IntervalIdentNode( const IntervalIdentNode & other ); - -public: - /**\ru \name Функции узла дерева интервального выражения. - \en \name Functions of the interval expression tree node. - \{ */ - virtual TeIntervalNodeType IsA () const { return tei_Ident; } // \ru выдать тип узла дерева \en get type of a tree node - virtual IntervalIdentNode * Duplicate() const { return new IntervalIdentNode( *this ); } - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetFirstValue ( double & v ) const; - virtual EquTreeResCode GetSecondValue ( double & v ) const; - virtual void GetString( c3d::string_t & ) const {}; - virtual void ReplaceParVariable( const c3d::string_t & /*varName*/, ItTreeVariable & /*newVar*/ ){} - - // \ru Установить значение. \en Set value. - virtual std::pair SetValue ( double f, double s - , const std::set & unfixedIVars - , const std::set & unfixedDVars ); - /** \} */ - -// ССА K13 virtual void ReplaceIntVariable( const string & varName, ItIntervalTreeVariable & newVar ){} -// ССА K13 virtual size_t SizeOf() const; - -private: - void operator =( const IntervalIdentNode & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( IntervalIdentNode ) -}; - -IMPL_PERSISTENT_OPS( IntervalIdentNode ) - -//------------------------------------------------------------------------------ -/** \brief \ru Константа как узел бинарного дерева. - \en Constant as a node of a binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий константу. \n - \en Node of a binary tree denoting a constant. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS BTreeConst : public BTreeNode -{ -private: - double value; ///< \ru Значение константы. \en Value of a constant. - c3d::string_t m_name; ///< \ru Имя константы, если есть, в файл не пишется. \en A name of a constant if it exists, not written to file. - -public: - - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по значению.\n - \en Constructor by value.\n \~ - \param[in] val - \ru Значение константы. - \en Value of a constant. \~ - \param[in] name - \ru Имя константы. - \en Name of a constant. \~ - */ - BTreeConst( double val, const c3d::string_t & name = _T("") ); - - /// \ru Конструктор копирования. \en Copy-constructor. - BTreeConst( const BTreeConst & ); - -public: - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA() const; - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const { return false; } - - /**\ru \name Функции для вычисления значения и производной. - \en \name Functions for calculation of the value and the derivative. - \{ */ - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetValue ( double & fvalue ) const; - virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; - - virtual bool SetValue( double, const std::set & ) { return false; } - - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & /*varName*/, ItTreeVariable & /*newVar*/ ) {} - virtual void ReplaceParVariable( const ItTreeVariable & /*var*/, const BTreeNode & /*subTree*/ ) {} - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /** \brief \ru Получить вложенный узел. - \en Get a child node. \~ - \details \ru Получить вложенный узел по индексу.\n - \en Get a child node by an index.\n \~ - */ - virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } - - virtual bool GetDefRange(DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const { return true; } - - virtual void GetUsedVariables( SSArray &, SSArray & )const{} - - virtual std_unique_ptr FixVars( const RPArray & /*unfixedVars*/, - PArray & /*newFuncs*/, EquTreeResCode & ) const - { return std_unique_ptr(Duplicate()); } - - virtual std_unique_ptr GetCalcEquivalent() const - { return std_unique_ptr(Duplicate()); } - - virtual void GetString( c3d::string_t & str ) const; - virtual size_t SizeOf() const; - - // \ru доступ к данным \en access to data - double GetValue() const { return value; } ///< \ru Дать переменную. \en Get variable. - void SetValue( double val ) { value = val; } ///< \ru Установить значение переменную. \en Set value of a variable. - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether the node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual ( const BTreeConst & other, const EqualVarsMap & ) const { return other.value == value; } - /** \} */ -private: - void operator =( const BTreeConst & ); // \ru не реализовано \en not implemented - virtual size_t GetPseudoOrderByVar( ItTreeVariable & ) const { return 0; } // \ru Только для внутреннего использования! \en For internal use only! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeConst ) -}; - -IMPL_PERSISTENT_OPS( BTreeConst ) - -//------------------------------------------------------------------------------ -/** \brief \ru Переменная как узел бинарного дерева. - \en Variable as a node of a binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий переменную. \n - \en Node of a binary tree denoting variable. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS BTreeIdent : public BTreeNode -{ -private: - ItTreeVariable * id; - -public : - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор по переменной. \n - \en Constructor by a variable \n \~ - */ - BTreeIdent( ItTreeVariable & ); - - /// \ru Копирующий конструктор. \en Copy-constructor. - BTreeIdent( const BTreeIdent & ); - - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA () const; - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const; - - /**\ru \name Функции для вычисления значения и производной. - \en \name Functions for calculation of the value and the derivative. - \{ */ - - virtual EquTreeResCode GetValue ( double & fvalue ) const; - virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables ( SSArray &, SSArray & ) const; - - virtual bool SetValue( double, const std::set & ); - - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & /*subTree*/ ) {} - - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. - virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } - - virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const{ return true; } - - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const { return std_unique_ptr(Duplicate()); } - - virtual void GetString( c3d::string_t & str ) const { str += id->GetName(); } - virtual size_t SizeOf() const; - - // \ru доступ к данным \en access to data - ItTreeVariable & GetVariable() const { C3D_ASSERT( id ); return *id; } ///< \ru Дать параметрический идентификатор (переменную). \en Get parametric identifier (variable). - void SetVariable( ItTreeVariable & var ) { id = &var; } ///< \ru Установить параметрический идентификатор (переменную) \en Set a parametric identifier (variable). - - /** \} */ - /**\ru \name Функции сравнения. - \en \name Comparison function. - \{ */ - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual( const BTreeIdent & other, const EqualVarsMap & equVars ) const; - -private: - void operator = ( const BTreeIdent & ); // \ru не реализовано \en not implemented - virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const { return ( &var == id ) ? 1 : 0; } // \ru Только для внутреннего использования! \en For internal use only! - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeIdent ) -}; - -IMPL_PERSISTENT_OPS( BTreeIdent ) - -//------------------------------------------------------------------------------ -/** \brief \ru Функция как узел бинарного дерева. - \en Function as node of a binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий функцию. \n - \en Node of a binary tree denoting a function. \n \~ - \ingroup Parser -*/ -// --- -class BTreeFunction : public BTreeNode -{ -public: - - /** \brief \ru Типы функций. - \en Types of functions. \~ - \details \ru Типы функций. \n - \en Types of functions. \n \~ - */ - // \ru ССА K13 не менять! Пишутся в файл! \en ССА K13 not to change! Are written to file! - enum EquFnCode - { - eFnCode_unknown = -1, ///< \ru Неизвестный тип. \en An unknown type. - eFnCode_first = 0, ///< \ru Начало диапазона известных функций. \en Start of the range of known functions. - eFnCode_sin = eFnCode_first, ///< \ru Синус. \en Sine. - eFnCode_cos, ///< \ru Косинус. \en Cosine. - eFnCode_tan, ///< \ru Тангенс. \en Tangent. - eFnCode_sqrt, ///< \ru Квадратный корень. \en Square root. - eFnCode_atan, ///< \ru Арктангенс. \en Arctangent. - eFnCode_exp, ///< \ru Экспонента. \en Exponent. - eFnCode_ln, ///< \ru Натуральный логарифм. \en Natural logarithm. - eFnCode_abs, ///< \ru Модуль. \en Absolute value. - eFnCode_DegBegin, ///< \ru Начала диапазона функций с аргументом в градусах. \en Start of the range of functions with argument in degrees. - eFnCode_sind = eFnCode_DegBegin, ///< \ru Синус угла в градусах. \en Sine of the angle in degrees. - eFnCode_cosd, ///< \ru Косинус угла в градусах. \en Cosine of the angle in degrees. - eFnCode_tand, ///< \ru Тангенс угла в градусах. \en Tangent of the angle in degrees. - eFnCode_DegEnd = eFnCode_tand, ///< \ru Конец диапазона функций с аргументом в градусах. \en End of the range of functions with argument in degrees. - eFnCode_atand, ///< \ru Арктангенс с результатом в градусах. \en Arctangent with the result in degrees. - eFnCode_lg, ///< \ru Десятичный логарифм. \en Decimal logarithm. - eFnCode_ceil, ///< \ru Ближайшее большее целое число. \en Nearest largest integer number. - eFnCode_floor, ///< \ru Ближайшее меньшее целое число. \en Nearest smallest integer number. - eFnCode_round, ///< \ru Ближайшее целое число. \en Nearest integer number. - eFnCode_acos, ///< \ru Арккосинус. \en Arccosine. - eFnCode_acosd, ///< \ru Арккосинус с результатом в градусах. \en Arccosine with the result in degrees. - eFnCode_asin, ///< \ru Арксинус. \en Arcsine. - eFnCode_asind, ///< \ru Арксинус с результатом в градусах. \en Arcsine with the result in degrees. - eFnCode_rad, ///< \ru Перевод из градусов в радианы. \en Conversion from degrees to radians. - eFnCode_deg, ///< \ru Перевод из радиан в градусы. \en Conversion from radians to degrees. - eFnCode_last = eFnCode_deg ///< \ru Конец диапазона известных функций. \en End of the range of known functions. - }; - -private : - EquFnCode fnCode; // \ru код функции \en code of function - BTreeNode * par; // \ru параметр функции \en parameter of the function - -public : - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор. \n - \en Constructor. \n \~ - \param[in] code - \ru Тип функции. - \en Type of a function. \~ - \param[in] p - \ru Параметр функции. - \en Parameter of a function. \~ - */ - BTreeFunction( EquFnCode code, BTreeNode & p ); - - /// \ru Копирующий конструктор. \en Copy-constructor. - BTreeFunction( const BTreeFunction & ); - - /// \ru Деструктор. \en Destructor. - virtual ~BTreeFunction(); - -public : - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA () const; - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const; - - /**\ru \name Функции для вычисления значения и производной. - \en \name Functions for calculation of the value and the derivative. - \{ */ - - virtual EquTreeResCode GetValue ( double & value ) const; - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode CalculateDerives ( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables ( SSArray &, SSArray & ) const; - - virtual bool SetValue ( double, const std::set & ) { return false; } // \ru не реализовано \en not implemented - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ); - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. - virtual BTreeNode * GetSubNode( size_t i ); - virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const; - - virtual void GetString( c3d::string_t & str ) const; - virtual size_t SizeOf() const; - - /** \} */ - /**\ru \name Функции сравнения. - \en \name Comparison function. - \{ */ - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual ( const BTreeFunction & other, const EqualVarsMap & equVars )const; - /** \} */ - - bool IsCos() const; ///< \ru имеет ли вид a * cos() + b \en looks like a * cos() + b - - - -private: - // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). - virtual bool GetCharacterPoints( std::vector & ) const; - EquTreeResCode GetValue( double arg, double & value ) const; - // \ru Только для внутреннего использования! \en For internal use only! - virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; - void operator = ( const BTreeFunction & ); // \ru не реализовано \en not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeFunction ) -}; - -IMPL_PERSISTENT_OPS( BTreeFunction ) - -//------------------------------------------------------------------------------ -/** \brief \ru Дать тип функции. - \en Get type of function. \~ - \details \ru Дать тип функции по имени.\n - \en Get type of function by name.\n \~ - \param[in] name - \ru Имя функции. - \en Name of function. \~ - \return \ru Тип функции. - \en Type of a function. \~ - \ingroup Parser -*/ -// --- -BTreeFunction::EquFnCode GetFunCodeByName( const c3d::string_t & name ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Дать имя функции. - \en Get name of function. \~ - \details \ru Дать имя функции по типу.\n - \en Get name of function by type.\n \~ - \param[in] code - \ru Тип функции. - \en Type of a function. \~ - \param[out] name - \ru Имя функции. - \en Name of function. \~ - \ingroup Parser -*/ -// --- -void GetFunNameByCode( BTreeFunction::EquFnCode code, c3d::string_t & name ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Операция с двумя аргументами как узел бинарного дерева. - \en Operation with two arguments as node of binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий операцию с двумя аргументами. \n - \en Node of binary tree denoting operation with two arguments. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS BTreeOperation : public BTreeNode -{ -private: - PceOperationType opCode; ///< \ru Код операции. \en Code of operation. - BTreeNode * op1; ///< \ru Первый операнд. \en The first operand. - BTreeNode * op2; ///< \ru Второй операнд. \en The second operand. - - static SArray varsDerives; ///< \ru Производные аргументов для вычисления производных показательно-степенной функции \en Derivatives of arguments for calculation of derivatives of exponential-power function - static std_unique_ptr deriveFunc; ///< \ru Функция для вычисления производной показательно-степенной функции \en Function for calculation of derivative of the exponential-power function - -public: - /** \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор.\n - \en Constructor.\n \~ - \param[in] code - \ru Код операции. - \en Code of operation. \~ - \param[in] op1 - \ru Первый операнд. - \en The first operand. \~ - \param[in] op2 - \ru Второй операнд. - \en The second operand. \~ - \ingroup Parser - */ - BTreeOperation( PceOperationType code, BTreeNode & op1, BTreeNode & op2 ); - - /// \ru Конструктор копирования. \en Copy-constructor. - BTreeOperation( const BTreeOperation & ); - - /// \ru Деструктор. \en Destructor. - virtual ~BTreeOperation(); - -public: - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA () const; - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const; - - /**\ru \name Функции для вычисления значения и производной. - \en \name Functions for calculation of the value and the derivative. - \{ */ - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetValue ( double &fvalue ) const; - virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables( SSArray &, SSArray & ) const; - - virtual bool SetValue ( double, const std::set & ) { return false; }// \ru не реализовано \en not implemented - - /** \} */ - /**\ru \name Функции замены переменных по именам. - \en \name Functions for replacing variables by names. - \{ */ - - // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ); - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. - virtual BTreeNode * GetSubNode( size_t i ); - virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const; - virtual void GetString( c3d::string_t & str ) const; - virtual size_t SizeOf() const; - - /** \} */ - /**\ru \name Функции сравнения. - \en \name Comparison function. - \{ */ - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - - /** \brief \ru Равен ли узел заданному узлу. - \en Whether a node is equal to the given node. \~ - \details \ru Равен ли узел заданному узлу.\n - \en Whether a node is equal to the given node.\n \~ - \param[in] other - \ru Узел для сравнения. - \en Node for comparison. \~ - \param[in] equVars - \ru Набор пар равных переменных. - \en A set of pairs of equal variables. \~ - \return \ru true, если узлы равны. - \en true if nodes are equal. \~ - */ - virtual bool IsEqual( const BTreeOperation & other, const EqualVarsMap & equVars ) const; - - /** \} */ - /**\ru \name Функции доступа к данным. - \en \name Functions for access to data. - \{ */ - - /// \ru Код операции. \en Code of operation. - int16 GetOperationCode() const { return (int16)opCode; } - /// \ru Первый операнд. \en The first operand. - BTreeNode & GetFirstOperand () const { C3D_ASSERT( op1 ); return *op1; } - /// \ru Второй операнд. \en The second operand. - BTreeNode & GetSecondOperand() const { C3D_ASSERT( op2 ); return *op2; } - /** \} */ - - ///< \ru имеет ли вид a * cos() + b. \en look like a * cos() + b. - virtual bool IsCos ( double &a, double& b ) const; - -private: - void operator = ( const BTreeOperation & ); // \ru не реализовано \en not implemented - EquTreeResCode GetValue( double par1, double par2, double & value ) const; - // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). - virtual bool GetCharacterPoints( std::vector &, const ItTreeVariable & ) const; - // \ru Только для внутреннего использования! \en For internal use only! - virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; - - static MbUserFunc & GetFuncForDerInvolving(); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation ) -}; - -IMPL_PERSISTENT_OPS( BTreeOperation ) - -//------------------------------------------------------------------------------ -/** \brief \ru Операция с одним аргументом как узел бинарного дерева. - \en Operation with one argument as a node of a binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий операцию с одним аргументом. \n - \en Node of a binary tree denoting an operation with one argument. \n \~ - \ingroup Parser -*/ -// --- -class BTreeOperation1Arg : public BTreeNode -{ -private : - PceOperationType opCode; ///< \ru Код операции. \en Code of operation. - BTreeNode * op; ///< \ru Операнд. \en Operand. - -public : - BTreeOperation1Arg( PceOperationType code, BTreeNode & ); - BTreeOperation1Arg( const BTreeOperation1Arg & ); - virtual ~BTreeOperation1Arg(); - - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA () const; - PceOperationType GetOperationType() const { return opCode; } - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const; - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetValue ( double &fvalue ) const; - virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables( SSArray &, SSArray & ) const; - - virtual bool SetValue ( double, const std::set & ); - - /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); - virtual BTreeNode * GetSubNode( size_t i ); - // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). - virtual bool GetCharacterPoints( std::vector & ) const; - virtual bool GetDefRange( DefRange & range, ItTreeVariable & var, bool stopOnBreak ) const { C3D_ASSERT( op ); - return op->GetDefRange( range, var, stopOnBreak ); } - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const; - virtual void GetString( c3d::string_t & str ) const; - - virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - virtual bool IsEqual ( const BTreeOperation1Arg & other, const EqualVarsMap & equVars ) const; - virtual size_t SizeOf() const; - -private: - void operator =( const BTreeOperation1Arg & ); // \ru не реализовано \en not implemented - EquTreeResCode GetValue( double arg, double & value ) const; - // \ru Только для внутреннего использования! \en For internal use only! - virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const { return opCode == oprt_NOT ? SYS_MAX_T : op->GetPseudoOrderByVar(var); } - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation1Arg ) -}; - -IMPL_PERSISTENT_OPS( BTreeOperation1Arg ) - -//------------------------------------------------------------------------------ -/** \brief \ru Операция с тремя аргументами как узел синтаксического дерева. - \en Operation with three arguments as node of syntax tree. \~ - \details \ru Узел бинарного дерева, обозначающий операцию с тремя аргументами. \n - \en Node of binary tree denoting operation with three arguments. \n \~ - \ingroup Parser -*/ -// --- -class BTreeOperation3Args : public BTreeNode -{ -private : - BTreeNode * op1; ///< \ru Первый операнд. \en The first operand. - BTreeNode * op2; ///< \ru Второй операнд. \en The second operand. - BTreeNode * op3; ///< \ru Третий операнд. \en The third operand. - -public : - BTreeOperation3Args( BTreeNode &, BTreeNode &, BTreeNode & ); - BTreeOperation3Args( const BTreeOperation3Args & ); - virtual ~BTreeOperation3Args(); - - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA() const; - virtual BTreeNode * Duplicate() const; - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const; - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetValue ( double & fVal ) const; - virtual EquTreeResCode CalculateDerives ( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables ( SSArray &, SSArray & ) const; - - virtual bool SetValue ( double, const std::set & ){ return false;} // \ru не реализовано \en not implemented - - /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); - virtual BTreeNode * GetSubNode( size_t i ); - virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const; - virtual void GetString( c3d::string_t & str ) const; - - virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - virtual bool IsEqual ( const BTreeOperation3Args & other, const EqualVarsMap & equVars ) const; - virtual size_t SizeOf() const; - -private: - // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). - virtual bool GetCharacterPoints( std::vector &, ItTreeVariable & ) const; - // \ru Только для внутреннего использования! \en For internal use only! - virtual size_t GetPseudoOrderByVar( ItTreeVariable & ) const { return SYS_MAX_T; } - void operator =( const BTreeOperation3Args & ); // \ru не реализовано \en not implemented - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation3Args ) -}; - -IMPL_PERSISTENT_OPS( BTreeOperation3Args ) - -//------------------------------------------------------------------------------ -/** \brief \ru Пользовательская функция как узел бинарного дерева. - \en User-defined function as a node of a binary tree. \~ - \details \ru Узел бинарного дерева, обозначающий пользовательскую функцию. \n - \en Node of a binary tree denoting a user-defined function. \n \~ - \ingroup Parser -*/ -// --- -class BTreeUserFunc : public BTreeNode -{ - ItUserFunc * func; ///< \ru Пользовательская функция. \en A user-defined function. - PArray pars; - -public: - BTreeUserFunc( const BTreeUserFunc & other ); - BTreeUserFunc( ItUserFunc & _func, const RPArray & _pars ); - - // \ru выдать тип узла дерева \en get type of a tree node - virtual BteNodeType IsA () const { return bt_Function; } - virtual BTreeNode * Duplicate() const { return new BTreeUserFunc( *this ); } - - // \ru Функция линейная. \en Function is linear. - virtual bool IsLine() const {return false; } - - virtual bool SetValue( double, const std::set & ) { return false; } // \ru не реализовано \en not implemented - - // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V - virtual EquTreeResCode GetValue ( double & ) const; - virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; - virtual void GetUsedVariables( SSArray &, SSArray & ) const; - /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' - virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); - virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); - virtual BTreeNode * GetSubNode ( size_t i ); - // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). -// ССА K13 virtual bool GetCharacterPoints( std::vector & ) const { return false; } - virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; - virtual std_unique_ptr FixVars( const RPArray & unfixed, - PArray & newFuncs, EquTreeResCode & ) const; - - virtual std_unique_ptr GetCalcEquivalent() const; - - virtual void GetString( c3d::string_t & str ) const; - - virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } - virtual bool IsEqual ( const BTreeUserFunc & other, const EqualVarsMap & equVars ) const; - - virtual size_t SizeOf() const { return 0; }; - -private: - void operator =( const BTreeOperation3Args & ); // \ru не реализовано \en not implemented - EquTreeResCode GetValue( SArray &, double & value ) const; - // \ru Только для внутреннего использования! \en For internal use only! - virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeUserFunc ); -}; - -IMPL_PERSISTENT_OPS( BTreeUserFunc ) - -#endif // __PARS_EQUATION_TREE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Узел бинарного дерева. + \en Node of a binary tree. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __PARS_EQUATION_TREE_H +#define __PARS_EQUATION_TREE_H + + +#include // \ru СМВ для компиляции ICC \en СМВ for compilation by ICC +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Количество параметров. + \en Parameters count. \~ + \details \ru Выдать количество параметров для типа операции.\n + \en Get the count of parameters for type of operation.\n \~ + \param[in] operationType - \ru Тип операции. + \en An operation type. \~ + \return \ru Количество параметров операции. + \en Operation parameters count. \~ + \ingroup Parser +*/ +// --- +inline +uint GetCountOfParams( PceOperationType operationType ) +{ + uint res = 1; + if ( operationType < oprt_BinaryOperation ) + res = 3; + else if ( operationType < oprt_UnaryOperation ) + res = 2; + + return res; +} + + +//----------------------------------------------------------------------------- +/** \brief \ru Информация о характерных точках дерева. + \en Information about characteristic points of a tree. \~ + \details \ru Информация о характерных точках дерева. \n + \en Information about characteristic points of a tree. \n \~ + \ingroup Parser +*/ +// --- +class BTreeNode; +struct CharacterPointInfo +{ + /** \brief \ru Тип характерной точки. + \en Type of a characteristic point. \~ + \details \ru Тип характерной точки.\n + \en Type of a characteristic point.\n \~ + */ + enum EquCharacterPointType + { + equPoint_DefRangeRight, ///< \ru Граница области определения. \en Boundary of the definition domain. + equPoint_DefRangeLeft, ///< \ru Граница области определения. \en Boundary of the definition domain. + equPoint_Extr, ///< \ru Экстремум. \en Extremum. + equPoint_Break1, ///< \ru Разрыв первого рода. \en Discontinuity of the first kind. + equPoint_Break2, ///< \ru Разрыв второго рода. \en Discontinuity of the second kind. + equPoint_DerBreak1 ///< \ru Разрыв производной. \en Derivative discontinuity. + }; + + const BTreeNode * m_tree; ///< \ru Узел дерева. Не равен NULL. \en Node of a tree. Not equal to 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. + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор.\n + \en Constructor.\n \~ + \param[in] tree - \ru Узел дерева. + \en Node of a tree. \~ + \param[in] type - \ru Тип характерной точки. + \en Type of a characteristic point. \~ + \param[in] ph - \ru Значение параметра функции. + \en Value of a function parameter. \~ + \param[in] period - \ru Период функции. + \en Period of a function. \~ + */ + CharacterPointInfo( const BTreeNode & tree, EquCharacterPointType type, double ph, double period ) + : m_tree ( &tree ) + , m_type ( type ) + , m_ph ( ph ) + , m_period( period ) + {} + +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru Элемент области определения функции. + \en Element of the function definition domain. \~ + \details \ru Элемент области определения функции. \n + \en Element of the function definition domain. \n \~ + \ingroup Parser +*/ +// --- +struct DefRangeItem +{ + /** \brief \ru Тип элемента. + \en A type of the element. \~ + \details \ru Тип элемента области определения функции. \n + \en Type of an element of the function definition domain. \n \~ + */ + enum RangeItemType + { + range_def, ///< \ru Область определения. \en Definition domain. + range_break, ///< \ru Разрыв. \en Discontinuity. + range_extr, ///< \ru Экстремум. \en Extremum. + }; + + double lbound; ///< \ru Левая граница элемента области определения. \en Left bound of an element of the definition domain. + double rbound; ///< \ru Правая граница элемента области определения. \en Right bound of an element of the definition domain. + RangeItemType type; ///< \ru Тип элемента. \en A type of an element. + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор. \n + \en Constructor. \n \~ + \param[in] l - \ru Левая граница элемента области определения. + \en The left bound of an element of the definition domain. \~ + \param[in] r - \ru Правая граница элемента области определения. + \en The right bound of an element of the definition domain. \~ + \param[in] t - \ru Тип элемента. + \en A type of the element. \~ + */ + DefRangeItem( double l, double r, RangeItemType t = range_def ) + : lbound( l ) + , rbound( r ) + , type( t ) + { + if ( lbound > rbound ) + std::swap( lbound, rbound ); + } +}; + + +namespace std { +//----------------------------------------------------------------------------- +/** \brief \ru Сравнение элементов области определения. + \en Comparison of elements of the definition domain. \~ + \details \ru Сравнение элементов области определения функции. \n + \en Comparison of elements of the function definition domain. \n \~ + \ingroup Parser +*/ +// --- +template<> +struct less +{ + /** \brief \ru Сравнение элементов области определения. + \en Comparison of elements of the definition domain. \~ + \details \ru Сравнение элементов области определения функции. \n + \en Comparison of elements of the function definition domain. \n \~ + \param[in] _Left - \ru Первый элемент. + \en The first element. \~ + \param[in] _Right - \ru Второй элемент + \en The second element \~ + \return \ru true, если первый элемент меньше второго. + \en true if the first element is less than second one. \~ + */ + bool operator()(const DefRangeItem & _Left, const DefRangeItem & _Right) const + { return ( _Right.lbound - _Left.rbound > -METRIC_EPSILON ); } +}; + +} // namespace std + + +//----------------------------------------------------------------------------- +/** \brief \ru Область определения функции. + \en The function domain. \~ + \details \ru Область определения функции. \n + \en The function domain. \n \~ + \ingroup Parser +*/ +// --- +class DefRange +{ + std::set arr; + bool m_hasbreak; +public: + static const double eps; ///< \ru Погрешность. \en Tolerance. + +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор области определения без разрывов. \n + \en Constructor of the definition domain without discontinuities. \n \~ + \param[in] l - \ru Левая граница области определения. + \en Left bound of the definition domain. \~ + \param[in] r - \ru Правая граница области определения. + \en Right bound of the definition domain. \~ + */ + DefRange( double l, double r ) + : m_hasbreak( false ) + { + if ( l > r ) + std::swap( l, r ); + arr.insert( DefRangeItem(l - METRIC_EPSILON, r + METRIC_EPSILON) ); + } + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор области определения без разрывов. \n + \en Constructor of the definition domain without discontinuities. \n \~ + */ + DefRange() : m_hasbreak( false ) {}; + + /// \ru Дать набор элементов области определения. \en Get a set of elements of the definition domain. + const std::set & GetSet() const { return arr; } + + /// \ru Есть ли разрывы в области определения. \en Whether the discontinuities is in the definition domain. + bool HasBreaks() const { return m_hasbreak; } + + /// \ru Разрезать область определения. \en Cut the domain. + bool Cut( DefRangeItem & i ); + /// \ru Добавить элемент области определения. \en Add element of the definition domain. + void Add( DefRangeItem & i ); + /// \ru Оператор сравнения. \en Comparison operator. + bool operator == ( const DefRange & other ); +}; + + +class BTreeConst; +class BTreeIdent; +class BTreeFunction; +class BTreeOperation; +class BTreeOperation1Arg; +class BTreeOperation3Args; +class BTreeUserFunc; + + +//----------------------------------------------------------------------------- +/** \brief \ru Значение функции и производных. + \en Value of the function and derivatives. \~ + \details \ru Значение функции и её первой, второй и третьей производных. \n + \en Values of function, its first, second and third derivatives. \n \~ + \ingroup Parser +*/ +// --- +struct DerivesValues +{ + double value; ///< \ru Значение функции. \en The value of function. + double firstDer; ///< \ru Первая производная. \en The first derivative. + double secondDer; ///< \ru Вторая производная. \en The second derivative. + double thirdDer; ///< \ru Третья производная. \en The third derivative. +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru Базовый класс для узлов дерева выражения. + \en Base class for nodes of the expression tree. \~ + \details \ru Базовый класс для узлов дерева выражения. \n + \en Base class for nodes of the expression tree. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeNode : public TapeBase +{ +public: + typedef std::map EqualVarsMap; ///< \ru Набор пар переменных. \en A set of pairs of variables. + typedef std::map VarsDerives; ///< \ru Набор пар: координата - значение и производные. \en A set of pairs: coordinate - value and derivatives. + +public: + BteNodeType type; ///< \ru Тип узла. \en A type of node. \~ \internal \ru Для отладки. \en For debugging. \~ \endinternal +protected: + mutable VarsDerives varDers; ///< \ru Рабочие переменные. \en Working variables. \~ + +protected: + /// \ru Конструктор по умолчанию. \en Default constructor. + BTreeNode() {} + +public: + virtual ~BTreeNode() {} + /// \ru Выдать тип узла дерева. \en Get type of a tree node. + virtual BteNodeType IsA () const = 0; + /// \ru Создать копию объекта. \en Create a copy of the object. + virtual BTreeNode * Duplicate() const = 0; + + /// \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const = 0; + + /**\ru \name Функции для вычисления значения и производной. + \en \name Functions for calculation of the value and the derivative. + \{ */ + + /** \brief \ru Вычислить значение. + \en Calculate value. \~ + \details \ru Вычислить значение узла.\n + \en Calculate value of node.\n \~ + \param[out] fValue - \ru Значение. + \en Value. \~ + \return \ru Код результата разбора строки. + \en String parsing result code. \~ + */ + virtual EquTreeResCode GetValue( double & fValue ) const = 0; + + /** \brief \ru Установить значение. + \en Set value. \~ + \details \ru Устанавливает значение v узлу дерева. + \en Set 'v' value to a tree node. \~ + \param[in] v - \ru Желаемое значение. + \en Desirable value. \~ + \param[in] unfixedDVars - \ru Переменные, значение которых можно менять. + \en Variables which values can be changed. \~ + */ + virtual bool SetValue( double v, const std::set & unfixedDVars ) = 0; + + /** \brief \ru Вычислить значение и производные. + \en Calculate a value and derivatives. \~ + \details \ru Вычислить значение и производные. \n + \en Calculate a value and derivatives. \n \~ + \param[out] fValue - \ru Значение. + \en Value. \~ + \param[out] derive1 - \ru Первая производная. + \en The first derivative. \~ + \param[out] derive2 - \ru Вторая производная. + \en The second derivative. \~ + \param[out] derive3 - \ru Третья производная. + \en The third derivative. \~ + \param[in] ders - \ru Набор значений и производных. + \en Set of values and derivatives. \~ + \return \ru Код результата разбора строки. + \en String parsing result code. \~ + */ + virtual EquTreeResCode CalculateDerives( double & fValue, double & derive1, + double & derive2, double & derive3, const VarsDerives & ders ) const = 0; + + /** \brief \ru Вычислить значение и производные. + \en Calculate a value and derivatives. \~ + \details \ru Вычислить значение и производные. \n + \en Calculate a value and derivatives. \n \~ + \param[in] coord - \ru Координата. + \en Coordinate. \~ + \param[out] v - \ru Значение. + \en Value. \~ + \param[out] fd - \ru Первая производная. + \en The first derivative. \~ + \param[out] sd - \ru Вторая производная. + \en The second derivative. \~ + \param[out] td - \ru Третья производная. + \en The third derivative. \~ + \return \ru Код результата разбора строки. + \en String parsing result code. \~ + */ + EquTreeResCode CalculateDerives( const ItCoord * coord, double & v, double & fd, double & sd, double & td ) const; + + /** \brief \ru Выдать использованные переменные. + \en Get the used variables. \~ + \details \ru Выдать использованные переменные. \n + \en Get the used variables. \n \~ + \param[out] arr - \ru Переменные. + \en Variables. \~ + \param[out] funcs - \ru Пользовательские функции. + \en User functions. \~ + */ + virtual void GetUsedVariables( SSArray & arr, SSArray & funcs ) const = 0; + + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + /** \brief \ru Заменить переменные. + \en Replace variables. \~ + \details \ru Заменить все переменные с указанными именем на новую переменную.\n + \en Replace all variables with the specified name by a new variable.\n \~ + \param[out] varName - \ru Имя. + \en Name. \~ + \param[out] newVar - \ru Новая переменная. + \en New variable. \~ + */ + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ) = 0; + + /** \brief \ru Заменить узел. + \en Replace a node. \~ + \details \ru Заменить узел на копию нового, если заданная переменная использована.\n + \en Replace a node with a copy of a new one if the given variable is used.\n \~ + \param[out] var - \ru Переменная. + \en Variable. \~ + \param[out] subTree - \ru Новый узел. + \en New node. \~ + */ + virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ) = 0; + + /** \brief \ru Заменить переменные. + \en Replace variables. \~ + \details \ru Заменить все переменные с указанными именем на новую переменную.\n + \en Replace all variables with the specified name by a new variable.\n \~ + */ + virtual void ReplaceIntVariable( const c3d::string_t &, ItIntervalTreeVariable & ) {} + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /** \brief \ru Выдать значение параметра экстремума. + \en Get value of parameter of extremum. \~ + \details \ru Выдать значение параметра экстремума, если это возможно.\n + \en Get value of parameter of extremum if it is possible.\n \~ + \param[in] interval - \ru Интервал для поиска. + \en Interval to search. \~ + \param[in] var - \ru Переменная. + \en Variable. \~ + \param[out] points - \ru Точки экстремума. + \en Points of extremum. \~ + */ + bool GetExtremumPoints( const c3d::DoublePair & interval, + ItTreeVariable & var, + c3d::DoubleVector & points ); + /** \brief \ru Область определения. + \en Domain. \~ + \details \ru Область определения.\n + \en Domain.\n \~ + \param[in,out] defRange - \ru Область определения. + \en Domain. \~ + \param[out] var - \ru Переменная. + \en Variable. \~ + \param[in] stopOnBreak - \ru Не искать разрывы области определения. + \en Not to search the discontinuities in the definition domain. \~ + */ + virtual bool GetDefRange( DefRange & defRange, ItTreeVariable & var, bool stopOnBreak ) const = 0; + + /** \brief \ru Только для внутреннего использования! Порядок переменной. + \en For internal use only! Order of variable. \~ + \details \ru Порядок переменной.\n + \en Order of variable.\n \~ + \param[in] var - \ru Переменная. + \en Variable. \~ + \return \ru Порядок. + \en Order. \~ + */ + virtual size_t GetPseudoOrderByVar ( ItTreeVariable & var ) const = 0; + + /** \brief \ru Фиксированные переменные. + \en Fixed variables. \~ + \details \ru Фиксированные переменные.\n + \en Fixed variables.\n \~ + \param[in] unfixedVars - \ru Набор нефиксированных переменных. Если переменная нашлась в наборе, фиксировать копию. + \en A set of unfixed variables. If variable was found in set, then fix the copy. \~ + \param[in] newFuncs - \ru Пользовательские функции. + \en User functions. \~ + \param[out] code - \ru Коды результата разбора строки. + \en Result codes of string parsing. \~ + \return \ru Переменную для фиксирования. + \en Variable for fixation. \~ + */ + virtual std_unique_ptr FixVars( const RPArray & unfixedVars, + PArray & newFuncs, EquTreeResCode & code ) const = 0; + /// \ru Дать эквивалентный узел. \en Get equivalent node. + virtual std_unique_ptr GetCalcEquivalent() const = 0; + + /** \brief \ru Дать строку. + \en Get string. \~ + \details \ru Дать строку выражения.\n + \en Get expression string.\n \~ + \param[out] - \ru Строка. + \en String. \~ + */ + virtual void GetString( c3d::string_t & ) const = 0; + + /// \ru Вычислить размер в байтах. \en Get size in bytes. + virtual size_t SizeOf() const = 0; + + /** \} */ + /**\ru \name Функции сравнения. + \en \name Comparison function. + \{ */ + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] varsMap - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & varsMap ) const = 0; + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeConst & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeIdent & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeFunction & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeOperation & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeOperation1Arg & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeOperation3Args & , const EqualVarsMap & ) const { return false; } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether the node is equal to the given node.\n \~ + \return false. + */ + virtual bool IsEqual( const BTreeUserFunc & , const EqualVarsMap & ) const { return false; } + /** \} */ + +private: + // \ru не реализовано \en not implemented + BTreeNode( const BTreeNode & ); + void operator =( const BTreeNode & ); + + DECLARE_PERSISTENT_CLASS( BTreeNode ) +}; + +IMPL_PERSISTENT_OPS( BTreeNode ) + + +//----------------------------------------------------------------------------- +/** \brief \ru Типы узлов бинарного дерева. + \en Types of nodes of the binary tree. \~ + \details \ru Типы узлов бинарного дерева. \n + \en Types of nodes of the binary tree. \n \~ + \ingroup Parser +*/ +// --- +enum TeIntervalNodeType +{ + tei_Const, ///< \ru Константа. \en Constant. + tei_Ident ///< \ru Идентификатор. \en Identifier. +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru Узел дерева интервального выражения. + \en Node of interval expression tree. \~ + \details \ru Узел дерева интервального выражения. \n + \en Node of interval expression tree. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS TreeIntervalNode : public TapeBase +{ +protected: + TreeIntervalNode() {} +public: + virtual ~TreeIntervalNode() {} + +public: + /// \ru Выдать тип узла дерева. \en Get type of a tree node. + virtual TeIntervalNodeType IsA () const = 0; + /// \ru Выдать копию объекта. \en Get a copy of the object. + virtual TreeIntervalNode * Duplicate() const = 0; + + /// \ru Дать первую переменную. \en Get the first variable. + virtual EquTreeResCode GetFirstValue ( double & ) const = 0; + /// \ru Дать вторую переменную. \en Get the second variable. + virtual EquTreeResCode GetSecondValue( double & ) const = 0; + /// \ru Дать строку. \en Get a string. + virtual void GetString( c3d::string_t & ) const = 0; + /** \brief \ru Установить значение. + \en Set value. \~ + \details \ru Попытаться установить значение [f;s] узлу дерева. + \en Try to set value [f;s] to a tree node. \~ + \param[in] f - \ru Нижняя граница интервала. + \en Lower bound of the interval. \~ + \param[in] s - \ru Верхняя граница интервала. + \en Upper bound of the interval. \~ + \param[in] unfixedIVars - \ru Множество интервальных переменных, которые можно менять. + \en Set of interval variables, which can be changed. \~ + \param[in] unfixedDVars - \ru Множество вещественных переменных, которые можно менять. + \en Set of real variables, which can be changed. \~ + \access public + \return \ru Истину, если удалось установить значение. + \en True if it was succeeded to set value. \~ + */ + virtual c3d::BoolPair SetValue( double f, double s + , const std::set & unfixedIVars + , const std::set & unfixedDVars ) = 0; + /** \brief \ru Заменить переменные. + \en Replace variables. \~ + \details \ru Заменить все переменные с указанными именем на новую переменную.\n + \en Replace all variables with the specified name by a new variable.\n \~ + \param[out] varName - \ru Имя. + \en Name. \~ + \param[out] newVar - \ru Новая переменная. + \en New variable. \~ + */ + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ) = 0; + +DECLARE_PERSISTENT_CLASS( TreeIntervalNode ) +OBVIOUS_PRIVATE_COPY( TreeIntervalNode ) +}; + +IMPL_PERSISTENT_OPS( TreeIntervalNode ) + + +//----------------------------------------------------------------------------- +/** \brief \ru Интервал простых выражений. + \en Interval of simple expressions. \~ + \details \ru Операция [] - получение интервала из простых выражений.\n + \en operation [] - obtaining of interval of simple expressions.\n \~ + \ingroup Parser +*/ +// --- +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). + +public: + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор.\n + \en Constructor.\n \~ + \param[in] firstValue - \ru Первый узел. + \en The first node. \~ + \param[in] secondValue - \ru Второй узел. + \en The second node. \~ + */ + IntervalConstNode( BTreeNode & firstValue, BTreeNode & secondValue ) + : m_firstValue ( &firstValue ) + , m_secondValue( &secondValue ) + {} + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор копирования.\n + \en Copy-constructor.\n \~ + \param[in] other - \ru Копируемый объект. + \en Object to copy. \~ + */ + IntervalConstNode( const IntervalConstNode & other ) + : m_firstValue ( other.m_firstValue->Duplicate() ) // ( other.m_firstValue ) + , m_secondValue( other.m_secondValue->Duplicate() ) // ( other.m_secondValue ) + {} + /** \brief \ru Деструктор. + \en Destructor. \~ + \details \ru Деструктор.\n + \en Destructor.\n \~ + */ + virtual ~IntervalConstNode(); + +public: + /**\ru \name Функции узла дерева интервального выражения. + \en \name Functions of interval expression tree node. + \{ */ + + virtual TeIntervalNodeType IsA () const { return tei_Const; } // \ru выдать тип узла дерева \en get type of a tree node + virtual IntervalConstNode * Duplicate() const { return new IntervalConstNode( *this ); } + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetFirstValue ( double & v ) const { return m_firstValue->GetValue( v ); } + virtual EquTreeResCode GetSecondValue( double & v ) const { return m_secondValue->GetValue( v ); } + virtual void GetString( c3d::string_t & ) const {} + // \ru Установить значение. \en Set value. + virtual c3d::BoolPair SetValue( double f, double s + , const std::set & unfixedIVars + , const std::set & unfixedDVars ); + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + /** \brief \ru Заменить переменные. + \en Replace variables. \~ + \details \ru Заменить все переменные с указанными именем на новую интервальную переменную.\n + \en Replace all variables with the specified names by a new interval variable.\n \~ + */ + virtual void ReplaceIntVariable( const c3d::string_t & /*varName*/, ItIntervalTreeVariable & /*newVar*/ ) {} + + /** \} */ + + /**\ru \name Функции операции []. + \en \name Functions of operation []. + \{ */ + + /// \ru Дать первый узел. \en Get the first node. + const BTreeNode & GetFirstTree () const { return *m_firstValue; } + /// \ru Дать второй узел. \en Get the second node. + const BTreeNode & GetSecondTree() const { return *m_secondValue; } + /// \ru Дать первый узел. \en Get the first node. + BTreeNode & SetFirstTree () { return *m_firstValue; } + /// \ru Дать второй узел. \en Get the second node. + BTreeNode & SetSecondTree() { return *m_secondValue; } + + + /** \} */ + //virtual size_t SizeOf() const = 0; + +private: + // \ru не реализовано \en not implemented + void operator =( const TreeIntervalNode & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( IntervalConstNode ) +}; + +IMPL_PERSISTENT_OPS( IntervalConstNode ) + +//----------------------------------------------------------------------------- +/** \brief \ru Интервальная переменная как узел бинарного дерева. + \en Interval variable as a node of a binary tree. \~ + \details \ru Узел дерева - интервальная переменная.\n + \en Tree node is an interval variable.\n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS IntervalIdentNode : public TreeIntervalNode +{ + ItIntervalTreeVariable * m_ident; ///< \ru Всегда не NULL. \en Always not NULL. + +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по интервальной переменной.\n + \en Constructor by an interval variable.\n \~ + \param[in] ident - \ru Интервальная переменная. + \en Interval variable. \~ + */ + IntervalIdentNode( ItIntervalTreeVariable & ident ) + : m_ident( &ident ) + {} + + /// \ru Конструктор копирования. \en Copy-constructor. + IntervalIdentNode( const IntervalIdentNode & other ); + +public: + /**\ru \name Функции узла дерева интервального выражения. + \en \name Functions of the interval expression tree node. + \{ */ + virtual TeIntervalNodeType IsA () const { return tei_Ident; } // \ru выдать тип узла дерева \en get type of a tree node + virtual IntervalIdentNode * Duplicate() const { return new IntervalIdentNode( *this ); } + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetFirstValue ( double & ) const; + virtual EquTreeResCode GetSecondValue( double & ) const; + virtual void GetString ( c3d::string_t & ) const {} + // \ru Установить значение. \en Set value. + virtual std::pair SetValue( double f, double s + , const std::set & unfixedIVars + , const std::set & unfixedDVars ); + + virtual void ReplaceParVariable( const c3d::string_t & /*varName*/, ItTreeVariable & /*newVar*/ ) {} + //virtual void ReplaceIntVariable( const string & varName, ItIntervalTreeVariable & newVar ){} + + /** \} */ + +private: + void operator = ( const IntervalIdentNode & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( IntervalIdentNode ) +}; + +IMPL_PERSISTENT_OPS( IntervalIdentNode ) + + +//------------------------------------------------------------------------------ +/** \brief \ru Константа как узел бинарного дерева. + \en Constant as a node of a binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий константу. \n + \en Node of a binary tree denoting a constant. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeConst : public BTreeNode +{ +private: + double value; ///< \ru Значение константы. \en Value of a constant. + c3d::string_t m_name; ///< \ru Имя константы, если есть, в файл не пишется. \en A name of a constant if it exists, not written to file. + +public: + + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по значению.\n + \en Constructor by value.\n \~ + \param[in] val - \ru Значение константы. + \en Value of a constant. \~ + \param[in] name - \ru Имя константы. + \en Name of a constant. \~ + */ + BTreeConst( double val, const c3d::string_t & name = _T("") ); + + /// \ru Конструктор копирования. \en Copy-constructor. + BTreeConst( const BTreeConst & ); + + virtual ~BTreeConst(); + +public: + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA() const; + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const { return false; } + + /**\ru \name Функции для вычисления значения и производной. + \en \name Functions for calculation of the value and the derivative. + \{ */ + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetValue ( double & fvalue ) const; + virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; + + virtual bool SetValue( double, const std::set & ) { return false; } + + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & /*varName*/, ItTreeVariable & /*newVar*/ ) {} + virtual void ReplaceParVariable( const ItTreeVariable & /*var*/, const BTreeNode & /*subTree*/ ) {} + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /** \brief \ru Получить вложенный узел. + \en Get a child node. \~ + \details \ru Получить вложенный узел по индексу.\n + \en Get a child node by an index.\n \~ + */ + virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } + + virtual bool GetDefRange(DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const { return true; } + + virtual void GetUsedVariables( SSArray &, SSArray & )const{} + + virtual std_unique_ptr FixVars( const RPArray & /*unfixedVars*/, + PArray & /*newFuncs*/, EquTreeResCode & ) const + { return std_unique_ptr(Duplicate()); } + + virtual std_unique_ptr GetCalcEquivalent() const + { return std_unique_ptr(Duplicate()); } + + virtual void GetString( c3d::string_t & str ) const; + virtual size_t SizeOf() const; + + // \ru доступ к данным \en access to data + double GetValue() const { return value; } ///< \ru Дать переменную. \en Get variable. + void SetValue( double val ) { value = val; } ///< \ru Установить значение переменную. \en Set value of a variable. + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether the node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual ( const BTreeConst & other, const EqualVarsMap & ) const { return other.value == value; } + /** \} */ +private: + void operator =( const BTreeConst & ); // \ru не реализовано \en not implemented + virtual size_t GetPseudoOrderByVar( ItTreeVariable & ) const { return 0; } // \ru Только для внутреннего использования! \en For internal use only! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeConst ) +}; + +IMPL_PERSISTENT_OPS( BTreeConst ) + +//------------------------------------------------------------------------------ +/** \brief \ru Переменная как узел бинарного дерева. + \en Variable as a node of a binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий переменную. \n + \en Node of a binary tree denoting variable. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeIdent : public BTreeNode +{ +private: + ItTreeVariable * id; + +public : + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор по переменной. \n + \en Constructor by a variable \n \~ + */ + BTreeIdent( ItTreeVariable & ); + + /// \ru Копирующий конструктор. \en Copy-constructor. + BTreeIdent( const BTreeIdent & ); + + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA () const; + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const; + + /**\ru \name Функции для вычисления значения и производной. + \en \name Functions for calculation of the value and the derivative. + \{ */ + + virtual EquTreeResCode GetValue ( double & fvalue ) const; + virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables ( SSArray &, SSArray & ) const; + + virtual bool SetValue( double, const std::set & ); + + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & /*subTree*/ ) {} + + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. + virtual BTreeNode * GetSubNode( size_t /*i*/ ) { return NULL; } + + virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool /*stopOnBreak*/ ) const{ return true; } + + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + + virtual std_unique_ptr GetCalcEquivalent() const { return std_unique_ptr(Duplicate()); } + + virtual void GetString( c3d::string_t & str ) const { str += id->GetName(); } + virtual size_t SizeOf() const; + + // \ru доступ к данным \en access to data + ItTreeVariable & GetVariable() const { C3D_ASSERT( id ); return *id; } ///< \ru Дать параметрический идентификатор (переменную). \en Get parametric identifier (variable). + void SetVariable( ItTreeVariable & var ) { id = &var; } ///< \ru Установить параметрический идентификатор (переменную) \en Set a parametric identifier (variable). + + /** \} */ + /**\ru \name Функции сравнения. + \en \name Comparison function. + \{ */ + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual( const BTreeIdent & other, const EqualVarsMap & equVars ) const; + +private: + void operator = ( const BTreeIdent & ); // \ru не реализовано \en not implemented + virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const { return ( &var == id ) ? 1 : 0; } // \ru Только для внутреннего использования! \en For internal use only! + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeIdent ) +}; + +IMPL_PERSISTENT_OPS( BTreeIdent ) + +//------------------------------------------------------------------------------ +/** \brief \ru Функция как узел бинарного дерева. + \en Function as node of a binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий функцию. \n + \en Node of a binary tree denoting a function. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeFunction : public BTreeNode +{ +public: + + /** \brief \ru Типы функций. + \en Types of functions. \~ + \details \ru Типы функций. \n + \en Types of functions. \n \~ + */ + // \ru ССА K13 не менять! Пишутся в файл! \en ССА K13 not to change! Are written to file! + enum EquFnCode + { + eFnCode_unknown = -1, ///< \ru Неизвестный тип. \en An unknown type. + eFnCode_first = 0, ///< \ru Начало диапазона известных функций. \en Start of the range of known functions. + eFnCode_sin = eFnCode_first, ///< \ru Синус. \en Sine. + eFnCode_cos, ///< \ru Косинус. \en Cosine. + eFnCode_tan, ///< \ru Тангенс. \en Tangent. + eFnCode_sqrt, ///< \ru Квадратный корень. \en Square root. + eFnCode_atan, ///< \ru Арктангенс. \en Arctangent. + eFnCode_exp, ///< \ru Экспонента. \en Exponent. + eFnCode_ln, ///< \ru Натуральный логарифм. \en Natural logarithm. + eFnCode_abs, ///< \ru Модуль. \en Absolute value. + eFnCode_DegBegin, ///< \ru Начала диапазона функций с аргументом в градусах. \en Start of the range of functions with argument in degrees. + eFnCode_sind = eFnCode_DegBegin, ///< \ru Синус угла в градусах. \en Sine of the angle in degrees. + eFnCode_cosd, ///< \ru Косинус угла в градусах. \en Cosine of the angle in degrees. + eFnCode_tand, ///< \ru Тангенс угла в градусах. \en Tangent of the angle in degrees. + eFnCode_DegEnd = eFnCode_tand, ///< \ru Конец диапазона функций с аргументом в градусах. \en End of the range of functions with argument in degrees. + eFnCode_atand, ///< \ru Арктангенс с результатом в градусах. \en Arctangent with the result in degrees. + eFnCode_lg, ///< \ru Десятичный логарифм. \en Decimal logarithm. + eFnCode_ceil, ///< \ru Ближайшее большее целое число. \en Nearest largest integer number. + eFnCode_floor, ///< \ru Ближайшее меньшее целое число. \en Nearest smallest integer number. + eFnCode_round, ///< \ru Ближайшее целое число. \en Nearest integer number. + eFnCode_acos, ///< \ru Арккосинус. \en Arccosine. + eFnCode_acosd, ///< \ru Арккосинус с результатом в градусах. \en Arccosine with the result in degrees. + eFnCode_asin, ///< \ru Арксинус. \en Arcsine. + eFnCode_asind, ///< \ru Арксинус с результатом в градусах. \en Arcsine with the result in degrees. + eFnCode_rad, ///< \ru Перевод из градусов в радианы. \en Conversion from degrees to radians. + eFnCode_deg, ///< \ru Перевод из радиан в градусы. \en Conversion from radians to degrees. + eFnCode_last = eFnCode_deg ///< \ru Конец диапазона известных функций. \en End of the range of known functions. + }; + +private : + EquFnCode fnCode; // \ru код функции \en code of function + BTreeNode * par; // \ru параметр функции \en parameter of the function + +public : + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор. \n + \en Constructor. \n \~ + \param[in] code - \ru Тип функции. + \en Type of a function. \~ + \param[in] p - \ru Параметр функции. + \en Parameter of a function. \~ + */ + BTreeFunction( EquFnCode code, BTreeNode & p ); + + /// \ru Копирующий конструктор. \en Copy-constructor. + BTreeFunction( const BTreeFunction & ); + + /// \ru Деструктор. \en Destructor. + virtual ~BTreeFunction(); + +public : + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA () const; + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const; + + /**\ru \name Функции для вычисления значения и производной. + \en \name Functions for calculation of the value and the derivative. + \{ */ + + virtual EquTreeResCode GetValue ( double & value ) const; + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode CalculateDerives ( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables ( SSArray &, SSArray & ) const; + + virtual bool SetValue ( double, const std::set & ) { return false; } // \ru не реализовано \en not implemented + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ); + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. + virtual BTreeNode * GetSubNode( size_t i ); + virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + + virtual std_unique_ptr GetCalcEquivalent() const; + + virtual void GetString( c3d::string_t & str ) const; + virtual size_t SizeOf() const; + + /** \} */ + /**\ru \name Функции сравнения. + \en \name Comparison function. + \{ */ + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual ( const BTreeFunction & other, const EqualVarsMap & equVars )const; + /** \} */ + + bool IsCos() const; ///< \ru имеет ли вид a * cos() + b \en looks like a * cos() + b + + + +private: + // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). + virtual bool GetCharacterPoints( std::vector & ) const; + EquTreeResCode GetValue( double arg, double & value ) const; + // \ru Только для внутреннего использования! \en For internal use only! + virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; + void operator = ( const BTreeFunction & ); // \ru не реализовано \en not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeFunction ) +}; + +IMPL_PERSISTENT_OPS( BTreeFunction ) + +//------------------------------------------------------------------------------ +/** \brief \ru Дать тип функции. + \en Get type of function. \~ + \details \ru Дать тип функции по имени.\n + \en Get type of function by name.\n \~ + \param[in] name - \ru Имя функции. + \en Name of function. \~ + \return \ru Тип функции. + \en Type of a function. \~ + \ingroup Parser +*/ +// --- +BTreeFunction::EquFnCode GetFunCodeByName( const c3d::string_t & name ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Дать имя функции. + \en Get name of function. \~ + \details \ru Дать имя функции по типу.\n + \en Get name of function by type.\n \~ + \param[in] code - \ru Тип функции. + \en Type of a function. \~ + \param[out] name - \ru Имя функции. + \en Name of function. \~ + \ingroup Parser +*/ +// --- +void GetFunNameByCode( BTreeFunction::EquFnCode code, c3d::string_t & name ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Операция с двумя аргументами как узел бинарного дерева. + \en Operation with two arguments as node of binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий операцию с двумя аргументами. \n + \en Node of binary tree denoting operation with two arguments. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeOperation : public BTreeNode +{ +private: + PceOperationType opCode; ///< \ru Код операции. \en Code of operation. + BTreeNode * op1; ///< \ru Первый операнд. \en The first operand. + BTreeNode * op2; ///< \ru Второй операнд. \en The second operand. + + static SArray varsDerives; ///< \ru Производные аргументов для вычисления производных показательно-степенной функции \en Derivatives of arguments for calculation of derivatives of exponential-power function + static std_unique_ptr deriveFunc; ///< \ru Функция для вычисления производной показательно-степенной функции \en Function for calculation of derivative of the exponential-power function + +public: + /** \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор.\n + \en Constructor.\n \~ + \param[in] code - \ru Код операции. + \en Code of operation. \~ + \param[in] op1 - \ru Первый операнд. + \en The first operand. \~ + \param[in] op2 - \ru Второй операнд. + \en The second operand. \~ + \ingroup Parser + */ + BTreeOperation( PceOperationType code, BTreeNode & op1, BTreeNode & op2 ); + + /// \ru Конструктор копирования. \en Copy-constructor. + BTreeOperation( const BTreeOperation & ); + + /// \ru Деструктор. \en Destructor. + virtual ~BTreeOperation(); + +public: + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA () const; + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const; + + /**\ru \name Функции для вычисления значения и производной. + \en \name Functions for calculation of the value and the derivative. + \{ */ + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetValue ( double & fvalue ) const; + virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables( SSArray &, SSArray & ) const; + virtual bool SetValue ( double, const std::set & ) { return false; }// \ru не реализовано \en not implemented + + /** \} */ + /**\ru \name Функции замены переменных по именам. + \en \name Functions for replacing variables by names. + \{ */ + + // \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable & var, const BTreeNode & subTree ); + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /// \ru Дать вложенный узел по индексу. \en Get a child node by an index. + virtual BTreeNode * GetSubNode( size_t i ); + virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; + + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + virtual std_unique_ptr GetCalcEquivalent() const; + + virtual void GetString( c3d::string_t & str ) const; + virtual size_t SizeOf() const; + + /** \} */ + /**\ru \name Функции сравнения. + \en \name Comparison function. + \{ */ + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + + /** \brief \ru Равен ли узел заданному узлу. + \en Whether a node is equal to the given node. \~ + \details \ru Равен ли узел заданному узлу.\n + \en Whether a node is equal to the given node.\n \~ + \param[in] other - \ru Узел для сравнения. + \en Node for comparison. \~ + \param[in] equVars - \ru Набор пар равных переменных. + \en A set of pairs of equal variables. \~ + \return \ru true, если узлы равны. + \en true if nodes are equal. \~ + */ + virtual bool IsEqual( const BTreeOperation & other, const EqualVarsMap & equVars ) const; + + /** \} */ + /**\ru \name Функции доступа к данным. + \en \name Functions for access to data. + \{ */ + + /// \ru Код операции. \en Code of operation. + int16 GetOperationCode() const { return (int16)opCode; } + /// \ru Первый операнд. \en The first operand. + BTreeNode & GetFirstOperand () const { C3D_ASSERT( op1 ); return *op1; } + /// \ru Второй операнд. \en The second operand. + BTreeNode & GetSecondOperand() const { C3D_ASSERT( op2 ); return *op2; } + /** \} */ + + ///< \ru имеет ли вид a * cos() + b. \en look like a * cos() + b. + virtual bool IsCos ( double &a, double& b ) const; + +private: + void operator = ( const BTreeOperation & ); // \ru не реализовано \en not implemented + EquTreeResCode GetValue( double par1, double par2, double & value ) const; + // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). + virtual bool GetCharacterPoints( std::vector &, const ItTreeVariable & ) const; + // \ru Только для внутреннего использования! \en For internal use only! + virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; + + static MbUserFunc & GetFuncForDerInvolving(); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation ) +}; + +IMPL_PERSISTENT_OPS( BTreeOperation ) + +//------------------------------------------------------------------------------ +/** \brief \ru Операция с одним аргументом как узел бинарного дерева. + \en Operation with one argument as a node of a binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий операцию с одним аргументом. \n + \en Node of a binary tree denoting an operation with one argument. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeOperation1Arg : public BTreeNode +{ +private : + PceOperationType opCode; ///< \ru Код операции. \en Code of operation. + BTreeNode * op; ///< \ru Операнд. \en Operand. + +public : + BTreeOperation1Arg( PceOperationType code, BTreeNode & ); + BTreeOperation1Arg( const BTreeOperation1Arg & ); + virtual ~BTreeOperation1Arg(); + + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA () const; + PceOperationType GetOperationType() const { return opCode; } + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const; + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetValue ( double &fvalue ) const; + virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables( SSArray &, SSArray & ) const; + + virtual bool SetValue ( double, const std::set & ); + + /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); + virtual BTreeNode * GetSubNode( size_t i ); + // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). + virtual bool GetCharacterPoints( std::vector & ) const; + virtual bool GetDefRange( DefRange & range, ItTreeVariable & var, bool stopOnBreak ) const { C3D_ASSERT( op ); + return op->GetDefRange( range, var, stopOnBreak ); } + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + virtual std_unique_ptr GetCalcEquivalent() const; + + virtual void GetString( c3d::string_t & str ) const; + virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + virtual bool IsEqual ( const BTreeOperation1Arg & other, const EqualVarsMap & equVars ) const; + virtual size_t SizeOf() const; + +private: + void operator =( const BTreeOperation1Arg & ); // \ru не реализовано \en not implemented + EquTreeResCode GetValue( double arg, double & value ) const; + // \ru Только для внутреннего использования! \en For internal use only! + virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const { return opCode == oprt_NOT ? SYS_MAX_T : op->GetPseudoOrderByVar(var); } + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation1Arg ) +}; + +IMPL_PERSISTENT_OPS( BTreeOperation1Arg ) + +//------------------------------------------------------------------------------ +/** \brief \ru Операция с тремя аргументами как узел синтаксического дерева. + \en Operation with three arguments as node of syntax tree. \~ + \details \ru Узел бинарного дерева, обозначающий операцию с тремя аргументами. \n + \en Node of binary tree denoting operation with three arguments. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeOperation3Args : public BTreeNode +{ +private : + BTreeNode * op1; ///< \ru Первый операнд. \en The first operand. + BTreeNode * op2; ///< \ru Второй операнд. \en The second operand. + BTreeNode * op3; ///< \ru Третий операнд. \en The third operand. + +public : + BTreeOperation3Args( BTreeNode &, BTreeNode &, BTreeNode & ); + BTreeOperation3Args( const BTreeOperation3Args & ); + virtual ~BTreeOperation3Args(); + + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA() const; + virtual BTreeNode * Duplicate() const; + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const; + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetValue ( double & fVal ) const; + virtual EquTreeResCode CalculateDerives ( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables ( SSArray &, SSArray & ) const; + + virtual bool SetValue ( double, const std::set & ){ return false;} // \ru не реализовано \en not implemented + + /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); + virtual BTreeNode * GetSubNode( size_t i ); + virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; + + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + virtual std_unique_ptr GetCalcEquivalent() const; + + virtual void GetString( c3d::string_t & str ) const; + virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + virtual bool IsEqual ( const BTreeOperation3Args & other, const EqualVarsMap & equVars ) const; + virtual size_t SizeOf() const; + +private: + // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). + virtual bool GetCharacterPoints( std::vector &, ItTreeVariable & ) const; + // \ru Только для внутреннего использования! \en For internal use only! + virtual size_t GetPseudoOrderByVar( ItTreeVariable & ) const { return SYS_MAX_T; } + void operator =( const BTreeOperation3Args & ); // \ru не реализовано \en not implemented + + DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeOperation3Args ) +}; + +IMPL_PERSISTENT_OPS( BTreeOperation3Args ) + +//------------------------------------------------------------------------------ +/** \brief \ru Пользовательская функция как узел бинарного дерева. + \en User-defined function as a node of a binary tree. \~ + \details \ru Узел бинарного дерева, обозначающий пользовательскую функцию. \n + \en Node of a binary tree denoting a user-defined function. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS BTreeUserFunc : public BTreeNode +{ + ItUserFunc * func; ///< \ru Пользовательская функция. \en A user-defined function. + PArray pars; + +public: + // Конструктор копирования + BTreeUserFunc( const BTreeUserFunc & other ) + : func( other.func ) + { + for ( size_t i = 0, c = other.pars.size(); i < c; ++i ) + pars.Add( other.pars[i]->Duplicate() ); + } + // Конструктор + template + BTreeUserFunc( ItUserFunc & _func, const BTreeNodesVector & _pars ) + : func( &_func ) + { + C3D_ASSERT( _pars.size() == func->GetParsCount() ); + pars.reserve( _pars.size() ); + for ( size_t i = 0, c = _pars.size(); i < c; ++i ) { + pars.push_back( _pars[i] ); + } + } + + // \ru выдать тип узла дерева \en get type of a tree node + virtual BteNodeType IsA () const { return bt_Function; } + virtual BTreeNode * Duplicate() const { return new BTreeUserFunc( *this ); } + + // \ru Функция линейная. \en Function is linear. + virtual bool IsLine() const { return false; } + + virtual bool SetValue( double, const std::set & ) { return false; } // \ru не реализовано \en not implemented + + // \ru вычисление значения функции и производной по переменной V \en calculate the value of a function and the derivative with respect to V + virtual EquTreeResCode GetValue ( double & ) const; + virtual EquTreeResCode CalculateDerives( double &, double &, double &, double &, const VarsDerives & ) const; + virtual void GetUsedVariables( SSArray &, SSArray & ) const; + /// \ru Заменить все переменные с именем varName на переменную newVar \en Replace all variables with name 'varName' by variable 'newVar' + virtual void ReplaceParVariable( const c3d::string_t & varName, ItTreeVariable & newVar ); + virtual void ReplaceParVariable( const ItTreeVariable &, const BTreeNode & ); + virtual BTreeNode * GetSubNode ( size_t i ); + // \ru выдать значение параметра для экстремума( если это возможно ). \en get value of parameter of extremum( if it is possible ). +// ССА K13 virtual bool GetCharacterPoints( std::vector & ) const { return false; } + virtual bool GetDefRange( DefRange &, ItTreeVariable &, bool stopOnBreak ) const; + + virtual std_unique_ptr FixVars( const RPArray & unfixed, + PArray & newFuncs, EquTreeResCode & ) const; + virtual std_unique_ptr GetCalcEquivalent() const; + + virtual void GetString( c3d::string_t & str ) const; + virtual bool IsEqual ( const BTreeNode & other, const EqualVarsMap & equVars ) const { return other.IsEqual( *this, equVars ); } + virtual bool IsEqual ( const BTreeUserFunc & other, const EqualVarsMap & equVars ) const; + virtual size_t SizeOf() const { return 0; }; + +private: + void operator =( const BTreeOperation3Args & ); // \ru не реализовано \en not implemented + EquTreeResCode GetValue( SArray &, double & value ) const; + // \ru Только для внутреннего использования! \en For internal use only! + virtual size_t GetPseudoOrderByVar( ItTreeVariable & var ) const; + +DECLARE_PERSISTENT_CLASS_NEW_DEL( BTreeUserFunc ) +}; + +IMPL_PERSISTENT_OPS( BTreeUserFunc ) + +#endif // __PARS_EQUATION_TREE_H diff --git a/C3d/Include/pars_list.h b/C3d/Include/pars_list.h index a108591..525deb7 100644 --- a/C3d/Include/pars_list.h +++ b/C3d/Include/pars_list.h @@ -20,7 +20,7 @@ //------------------------------------------------------------------------------ /** \brief \ru Список переменных. \en List of variables. \~ - \details \ru Список переменных симфольной записи выражения. \n + \details \ru Список переменных символьной записи выражения. \n \en A list of variables with symbol writing of expression. \n \~ \ingroup Parser */ @@ -41,12 +41,11 @@ public: /// \ru Количество переменных. \en The number of variables. size_t CountVariables() const; /// \ru Добавить переменную. \en Add a variable. - void AddVariable ( MbVar * var ); + void AddVariable ( MbVar * ); /// \ru Убрать переменную. \en Remove a variable. - void RemoveVariable( MbVar * var ); -private: - MbListVars( const MbListVars & other ); - MbListVars & operator = ( const MbListVars & other ); + void RemoveVariable( MbVar * ); + +OBVIOUS_PRIVATE_COPY( MbListVars ) }; diff --git a/C3d/Include/pars_tree_variable.h b/C3d/Include/pars_tree_variable.h index 1a9edd4..c6fd543 100644 --- a/C3d/Include/pars_tree_variable.h +++ b/C3d/Include/pars_tree_variable.h @@ -1,233 +1,233 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Интерфейс переменной. - \en Interface of variable. -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ITTREEVARS_H -#define __ITTREEVARS_H - -#include - -class DefRange; -class BTreeNode; -struct DerivesValues; - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы узлов бинарного дерева. - \en Types nodes of binary tree. \~ - \details \ru Типы узлов бинарного дерева.\n - \en Types nodes of binary tree.\n \~ - \ingroup Parser -*/ -// --- -enum BteNodeType -{ - bt_Const, ///< \ru Константа. \en Constant. - bt_Ident, ///< \ru Идентификатор. \en Identifier. - bt_Function, ///< \ru Функция. \en A function. - bt_Operation2Args, ///< \ru Операция c двумя аргументами. \en Operation with two arguments. - bt_Operation1Arg, ///< \ru Операция c одним аргументом. \en Operation with one argument. - bt_Operation3Args, ///< \ru Операция c тремя аргументами. \en Operation with three arguments. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Типы операций. - \en Operations types. \~ - \details \ru Типы операций.\n - \en Operations types.\n \~ - \attention \ru Значения пишутся в файл. \en Values are written in file. \~ - \ingroup Parser -*/ -// --- -enum PceOperationType -{ - oprt_TernaryOperation = 0, ///< \ru Тернарная операция. \en Ternary operation. - oprt_BinaryOperation = 8, ///< \ru Бинарная операция. \en Binary operation. - oprt_Addition = oprt_BinaryOperation, ///< \ru Сложение. \en Addition. - oprt_Subtraction = 9, ///< \ru Вычитание. \en Subtraction. - oprt_Division = 10, ///< \ru Деление. \en Division. - oprt_Multiplication = 11, ///< \ru Умножение. \en Multiplication - oprt_IntDivision = 12, ///< \ru Целочисленное деление. \en Integer division. - oprt_OR = 13, ///< \ru Или. \en Or. - oprt_AND = 14, ///< \ru И. \en And. - oprt_NEQU = 15, ///< \ru Не равно. \en Not equal. - oprt_EQU = 16, ///< \ru Равно. \en Equal. - oprt_GT = 17, ///< \ru Больше. \en More. - oprt_GE = 18, ///< \ru Больше или равно. \en More or equal. - oprt_LT = 19, ///< \ru Меньше. \en Less. - oprt_LE = 20, ///< \ru Меньше или равно. \en Less or equal. - oprt_Involution = 21, ///< \ru Возведение в степень. \en Involution. - oprt_UnaryOperation = 22, ///< \ru Унарная операция. \en Unary operation. - oprt_NOT = oprt_UnaryOperation, ///< \ru Не. \en Not. - oprt_UnaryMinus = 23, ///< \ru Унарный минус. \en Unary minus. - oprt_UnaryPlus = 24, ///< \ru Унарный плюс. \en Unary plus. - oprt_Parentheses = 25 ///< \ru Скобки. \en Brackets. -}; - - -//----------------------------------------------------------------------------- -/** \brief \ru Коды результата разбора строки. - \en Result codes of string parsing. \~ - \details \ru Коды результата разбора строки.\n - \en Result codes of string parsing.\n \~ - \ingroup Parser -*/ -// --- -enum EquTreeResCode { - // \ru Эта группа кодов ошибок полностью повторяет то, что было до V9. \en This group of result codes fully repeats all that was before V9. - equTreeResCode_Ok = 0, ///< \ru Все хорошо. \en Everything is OK. - equTreeResCode_First = 1, ///< \ru Начало диапазона ошибок. \en Start of errors range. - equTreeResCode_SyntaxError = equTreeResCode_First, ///< \ru Ошибка: Синтаксическая ошибка в выражении. \en Error: Syntax error in expression. - equTreeResCode_TooComplex, ///< \ru Ошибка: Слишком сложное выражение. \en Error: Expression is too complex. - equTreeResCode_InvalidAssignment, ///< \ru Ошибка: Переменная присваивается самой себе. \en Error: Variable is assigned by itself. - equTreeResCode_NoVariables, ///< \ru Ошибка: В выражении должна быть хотя бы одна переменная. \en Error: There should be at least one variable in expression. - equTreeResCode_TooLargeIdent, ///< \ru Ошибка: Превышено количество символов в имени переменной. \en Error: The number of symbols in a name of variable is exceeded. - equTreeResCode_TangentsDomain , ///< \ru Ошибка: Аргумент тангенса не в области определения. \en Error: An argument of tangent is out of domain. - equTreeResCode_SqrtDomain, ///< \ru Ошибка: Недопустимое значение аргумента для sqrt. \en Error: Invalid argument value for sqrt. - equTreeResCode_LogarithmDomain, ///< \ru Ошибка: Недопустимое значение аргумента для логарифмической функции. \en Error: Invalid argument value for logarithmic function. - equTreeResCode_ZeroDivide, ///< \ru Ошибка: Деление на ноль. \en Error: Division by zero. - equTreeResCode_TrigonometricDomain, ///< \ru Ошибка: Аргумент тригонометрической функции не в области определения. \en Error: An argument of trigonometric function is out of domain. - equTreeResCode_CyclicRelation, ///< \ru Ошибка: Найдена замкнутая зависимость. \en Error: There is found a closed dependence. - equTreeResCode_PowDomain, ///< \ru Ошибка: недопустимое значение аргумента для степенной функции. \en Error: Invalid argument value for power function. - equTreeResCode_WrongFuncFormat, ///< \ru Ошибка: Выражение содержит функцию, не соответствующую своему формату. \en Error: Expression contains a function which does not correspond to its format. - - // \ru ДОБАВЛЯТЬ НОВЫЕ СООБЩЕНИЯ ТОЛЬКО ПЕРЕД ЭТОЙ СТРОКОЙ; \en ADD NEW MESSAGES ONLY BEFORE THIS STRING; - equTreeResCode_Last ///< \ru Конец диапазона ошибок. \en End of errors range. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс координаты. - \en Interface of coordinate. \~ - \details \ru Интерфейс координаты. \n - \en Interface of coordinate. \n \~ - \ingroup Parser -*/ -// --- -struct ItCoord -{ - virtual void SetValue( double v ) = 0; ///< \ru Установить переменную. \en Set variable. - virtual double GetValue() const = 0; ///< \ru Дать переменную. \en Get variable. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс переменной. - \en Interface of variable. \~ - \details \ru Интерфейс переменной. \n - \en Interface of variable. \n \~ - \ingroup Parser -*/ -// --- -struct ItTreeVariable -{ - ItTreeVariable() {} - - /// \ru Дать имя. \en Get name. - virtual const c3d::string_t & GetName() const = 0; - /// \ru Установить имя. \en Set name. - virtual void SetName( const c3d::string_t & ) = 0; - /// \ru Дать переменную. \en Get variable. - virtual double GetValue() const = 0; - /// \ru Установить переменную. \en Set variable. - virtual void SetValue( double ) = 0; - /// \ru Дать координату. \en Get coordinate. - virtual const ItCoord & GetCoord() const = 0; - /// \ru Вычислить размер в байтах. \en Get size in bytes. - virtual size_t SizeOf() const = 0; - - /// \ru Захватить \en Catch. - virtual refcount_t AddRef () const = 0; - /// \ru Отпустить. \en Free. - virtual refcount_t Release() const = 0; - - /// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing. - virtual void SetName( const TCHAR* s ) { SetName( s ? s : _T("") ); }; - - /// \ru Операторы чтения, записи. \en Reading and writing operators. - DECLARE_PERSISTENT_OPS( ItTreeVariable ); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс интервальной переменной. - \en Interface of interval variable. \~ - \details \ru Интерфейс интервальной переменной. \n - \en Interface of interval variable. \n \~ - \ingroup Parser -*/ -// --- -struct ItIntervalTreeVariable -{ - ItIntervalTreeVariable() {} - - /// \ru Дать имя. \en Get name. - virtual const c3d::string_t & GetName() const = 0; - /// \ru Установить имя. \en Set name. - virtual void SetValue( double f, double s ) = 0; - /// \ru Первая граница. \en The first boundary. - virtual double First() const = 0; - /// \ru Вторая граница. \en The second boundary. - virtual double Second() const = 0; - - /// \ru Захватить. \en Catch. - virtual refcount_t AddRef() const = 0; - /// \ru Отпустить. \en Free. - virtual refcount_t Release() const = 0; - - /// \ru Операторы чтения, записи. \en Reading and writing operators. - DECLARE_PERSISTENT_OPS( ItIntervalTreeVariable ); -}; - - -class MbUserFunc; - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс функции. - \en Interface of function. \~ - \details \ru Интерфейс функции. \n - \en Interface of function. \n \~ - \ingroup Parser -*/ -// --- -struct ItUserFunc -{ - ItUserFunc(){}; - virtual ~ItUserFunc(){}; - - /// \ru Дать копию объекта. \en Get a copy of the object. - virtual ItUserFunc & Duplicate() const = 0; - /// \ru Дать имя. \en Get name. - virtual const c3d::string_t & GetName() const = 0; - /// \ru Дать количество параметров. \en Get count of parameters.. - virtual size_t GetParsCount() const = 0; - /// \ru Значение функции. \en Value of function. - virtual EquTreeResCode GetValue ( const SArray &, double & ) const = 0; - /// \ru Значение функции и производных. \en Value of function and derivatives. - virtual EquTreeResCode GetDerivates( const SArray &, - double & v, double & f, - double & s, double & t, - size_t dIndex = 0 ) const = 0; - /// \ru Внешние переменные. \en External variables. - virtual void GetExternalVars( SSArray & vars, - SSArray & funcs ) const = 0; - /// \ru Только для внутреннего использования! Степень функции по индексу переменной. \en For internal use only! Function degree by the index of variable. - virtual size_t GetPseudoOrderByPar ( size_t index ) const = 0; - /// \ru Область определения. \en Domain. - virtual bool GetDefRange( DefRange &, ItTreeVariable & var, - const std::vector & ) const = 0; - /// \ru Равны ли функции. \en Whether functions are equal. - virtual bool IsEqual ( const ItUserFunc & other ) const = 0; - /// \ru Равны ли функции. \en Whether functions are equal. - virtual bool IsEqual ( const MbUserFunc & other ) const = 0; - - /// \ru Операторы чтения, записи. \en Reading and writing operators. - DECLARE_PERSISTENT_OPS( ItUserFunc ); -}; - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Интерфейс переменной. + \en Interface of variable. +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __ITTREEVARS_H +#define __ITTREEVARS_H + +#include + +class DefRange; +class BTreeNode; +struct DerivesValues; + + +//------------------------------------------------------------------------------ +/** \brief \ru Типы узлов бинарного дерева. + \en Types nodes of binary tree. \~ + \details \ru Типы узлов бинарного дерева.\n + \en Types nodes of binary tree.\n \~ + \ingroup Parser +*/ +// --- +enum BteNodeType +{ + bt_Const, ///< \ru Константа. \en Constant. + bt_Ident, ///< \ru Идентификатор. \en Identifier. + bt_Function, ///< \ru Функция. \en A function. + bt_Operation2Args, ///< \ru Операция c двумя аргументами. \en Operation with two arguments. + bt_Operation1Arg, ///< \ru Операция c одним аргументом. \en Operation with one argument. + bt_Operation3Args, ///< \ru Операция c тремя аргументами. \en Operation with three arguments. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Типы операций. + \en Operations types. \~ + \details \ru Типы операций.\n + \en Operations types.\n \~ + \attention \ru Значения пишутся в файл. \en Values are written in file. \~ + \ingroup Parser +*/ +// --- +enum PceOperationType +{ + oprt_TernaryOperation = 0, ///< \ru Тернарная операция. \en Ternary operation. + oprt_BinaryOperation = 8, ///< \ru Бинарная операция. \en Binary operation. + oprt_Addition = oprt_BinaryOperation, ///< \ru Сложение. \en Addition. + oprt_Subtraction = 9, ///< \ru Вычитание. \en Subtraction. + oprt_Division = 10, ///< \ru Деление. \en Division. + oprt_Multiplication = 11, ///< \ru Умножение. \en Multiplication + oprt_IntDivision = 12, ///< \ru Целочисленное деление. \en Integer division. + oprt_OR = 13, ///< \ru Или. \en Or. + oprt_AND = 14, ///< \ru И. \en And. + oprt_NEQU = 15, ///< \ru Не равно. \en Not equal. + oprt_EQU = 16, ///< \ru Равно. \en Equal. + oprt_GT = 17, ///< \ru Больше. \en More. + oprt_GE = 18, ///< \ru Больше или равно. \en More or equal. + oprt_LT = 19, ///< \ru Меньше. \en Less. + oprt_LE = 20, ///< \ru Меньше или равно. \en Less or equal. + oprt_Involution = 21, ///< \ru Возведение в степень. \en Involution. + oprt_UnaryOperation = 22, ///< \ru Унарная операция. \en Unary operation. + oprt_NOT = oprt_UnaryOperation, ///< \ru Не. \en Not. + oprt_UnaryMinus = 23, ///< \ru Унарный минус. \en Unary minus. + oprt_UnaryPlus = 24, ///< \ru Унарный плюс. \en Unary plus. + oprt_Parentheses = 25 ///< \ru Скобки. \en Brackets. +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru Коды результата разбора строки. + \en Result codes of string parsing. \~ + \details \ru Коды результата разбора строки.\n + \en Result codes of string parsing.\n \~ + \ingroup Parser +*/ +// --- +enum EquTreeResCode { + // \ru Эта группа кодов ошибок полностью повторяет то, что было до V9. \en This group of result codes fully repeats all that was before V9. + equTreeResCode_Ok = 0, ///< \ru Все хорошо. \en Everything is OK. + equTreeResCode_First = 1, ///< \ru Начало диапазона ошибок. \en Start of errors range. + equTreeResCode_SyntaxError = equTreeResCode_First, ///< \ru Ошибка: Синтаксическая ошибка в выражении. \en Error: Syntax error in expression. + equTreeResCode_TooComplex, ///< \ru Ошибка: Слишком сложное выражение. \en Error: Expression is too complex. + equTreeResCode_InvalidAssignment, ///< \ru Ошибка: Переменная присваивается самой себе. \en Error: Variable is assigned by itself. + equTreeResCode_NoVariables, ///< \ru Ошибка: В выражении должна быть хотя бы одна переменная. \en Error: There should be at least one variable in expression. + equTreeResCode_TooLargeIdent, ///< \ru Ошибка: Превышено количество символов в имени переменной. \en Error: The number of symbols in a name of variable is exceeded. + equTreeResCode_TangentsDomain , ///< \ru Ошибка: Аргумент тангенса не в области определения. \en Error: An argument of tangent is out of domain. + equTreeResCode_SqrtDomain, ///< \ru Ошибка: Недопустимое значение аргумента для sqrt. \en Error: Invalid argument value for sqrt. + equTreeResCode_LogarithmDomain, ///< \ru Ошибка: Недопустимое значение аргумента для логарифмической функции. \en Error: Invalid argument value for logarithmic function. + equTreeResCode_ZeroDivide, ///< \ru Ошибка: Деление на ноль. \en Error: Division by zero. + equTreeResCode_TrigonometricDomain, ///< \ru Ошибка: Аргумент тригонометрической функции не в области определения. \en Error: An argument of trigonometric function is out of domain. + equTreeResCode_CyclicRelation, ///< \ru Ошибка: Найдена замкнутая зависимость. \en Error: There is found a closed dependence. + equTreeResCode_PowDomain, ///< \ru Ошибка: недопустимое значение аргумента для степенной функции. \en Error: Invalid argument value for power function. + equTreeResCode_WrongFuncFormat, ///< \ru Ошибка: Выражение содержит функцию, не соответствующую своему формату. \en Error: Expression contains a function which does not correspond to its format. + + // \ru ДОБАВЛЯТЬ НОВЫЕ СООБЩЕНИЯ ТОЛЬКО ПЕРЕД ЭТОЙ СТРОКОЙ; \en ADD NEW MESSAGES ONLY BEFORE THIS STRING; + equTreeResCode_Last ///< \ru Конец диапазона ошибок. \en End of errors range. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс координаты. + \en Interface of coordinate. \~ + \details \ru Интерфейс координаты. \n + \en Interface of coordinate. \n \~ + \ingroup Parser +*/ +// --- +struct ItCoord +{ + virtual void SetValue( double v ) = 0; ///< \ru Установить переменную. \en Set variable. + virtual double GetValue() const = 0; ///< \ru Дать переменную. \en Get variable. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс переменной. + \en Interface of variable. \~ + \details \ru Интерфейс переменной. \n + \en Interface of variable. \n \~ + \ingroup Parser +*/ +// --- +struct ItTreeVariable +{ + ItTreeVariable() {} + + /// \ru Дать имя. \en Get name. + virtual const c3d::string_t & GetName() const = 0; + /// \ru Установить имя. \en Set name. + virtual void SetName( const c3d::string_t & ) = 0; + /// \ru Дать переменную. \en Get variable. + virtual double GetValue() const = 0; + /// \ru Установить переменную. \en Set variable. + virtual void SetValue( double ) = 0; + /// \ru Дать координату. \en Get coordinate. + virtual const ItCoord & GetCoord() const = 0; + /// \ru Вычислить размер в байтах. \en Get size in bytes. + virtual size_t SizeOf() const = 0; + + /// \ru Захватить \en Catch. + virtual refcount_t AddRef () const = 0; + /// \ru Отпустить. \en Free. + virtual refcount_t Release() const = 0; + + /// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing. + virtual void SetName( const TCHAR * s ) { SetName( s ? s : _T("") ); }; + + /// \ru Операторы чтения, записи. \en Reading and writing operators. + DECLARE_PERSISTENT_OPS( ItTreeVariable ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс интервальной переменной. + \en Interface of interval variable. \~ + \details \ru Интерфейс интервальной переменной. \n + \en Interface of interval variable. \n \~ + \ingroup Parser +*/ +// --- +struct ItIntervalTreeVariable +{ + ItIntervalTreeVariable() {} + + /// \ru Дать имя. \en Get name. + virtual const c3d::string_t & GetName() const = 0; + /// \ru Установить имя. \en Set name. + virtual void SetValue( double f, double s ) = 0; + /// \ru Первая граница. \en The first boundary. + virtual double First() const = 0; + /// \ru Вторая граница. \en The second boundary. + virtual double Second() const = 0; + + /// \ru Захватить. \en Catch. + virtual refcount_t AddRef() const = 0; + /// \ru Отпустить. \en Free. + virtual refcount_t Release() const = 0; + + /// \ru Операторы чтения, записи. \en Reading and writing operators. + DECLARE_PERSISTENT_OPS( ItIntervalTreeVariable ) +}; + + +class MbUserFunc; + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс функции. + \en Interface of function. \~ + \details \ru Интерфейс функции. \n + \en Interface of function. \n \~ + \ingroup Parser +*/ +// --- +struct ItUserFunc +{ + ItUserFunc() {}; + virtual ~ItUserFunc() {}; + + /// \ru Дать копию объекта. \en Get a copy of the object. + virtual ItUserFunc & Duplicate() const = 0; + /// \ru Дать имя. \en Get name. + virtual const c3d::string_t & GetName() const = 0; + /// \ru Дать количество параметров. \en Get count of parameters.. + virtual size_t GetParsCount() const = 0; + /// \ru Значение функции. \en Value of function. + virtual EquTreeResCode GetValue ( const SArray &, double & ) const = 0; + /// \ru Значение функции и производных. \en Value of function and derivatives. + virtual EquTreeResCode GetDerivates( const SArray &, + double & v, double & f, + double & s, double & t, + size_t dIndex = 0 ) const = 0; + /// \ru Внешние переменные. \en External variables. + virtual void GetExternalVars( SSArray & vars, + SSArray & funcs ) const = 0; + /// \ru Только для внутреннего использования! Степень функции по индексу переменной. \en For internal use only! Function degree by the index of variable. + virtual size_t GetPseudoOrderByPar ( size_t index ) const = 0; + /// \ru Область определения. \en Domain. + virtual bool GetDefRange( DefRange &, ItTreeVariable & var, + const std::vector & ) const = 0; + /// \ru Равны ли функции. \en Whether functions are equal. + virtual bool IsEqual ( const ItUserFunc & other ) const = 0; + /// \ru Равны ли функции. \en Whether functions are equal. + virtual bool IsEqual ( const MbUserFunc & other ) const = 0; + + /// \ru Операторы чтения, записи. \en Reading and writing operators. + DECLARE_PERSISTENT_OPS( ItUserFunc ) +}; + #endif //__ITTREEVARS_H \ No newline at end of file diff --git a/C3d/Include/pars_user_function.h b/C3d/Include/pars_user_function.h index 4d01112..1f7e73a 100644 --- a/C3d/Include/pars_user_function.h +++ b/C3d/Include/pars_user_function.h @@ -1,114 +1,114 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Пользовательская функция. - \en User-defined function. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __PARS_USER_FUNCTION_H -#define __PARS_USER_FUNCTION_H - - -#include -#include -#include -#include -#include -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Пользовательская функция. - \en User-defined function. \~ - \details \ru Пользовательская функция. \n - \en User-defined function. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS MbUserFunc : public TapeBase, public ItUserFunc, public MbSyncItem -{ -protected: - c3d::string_t m_name; ///< \ru Имя пользовательской функции. \en A name of user-defined function. - c3d::string_t m_expression; ///< \ru Выражение. \en Expression. - BTreeNode * m_tree; ///< \ru Дерево разбора выражения (обязательно должно быть). \en A tree of expression parsing (it should be for sure). - IFC_Array m_vars; ///< \ru Формальные параметры функции. \en Formal parameters of function. - PArray m_intFuncs; ///< \ru Внутренние функции. \en Internal functions. - -public: - MbUserFunc( const c3d::string_t & name, const std::vector & pars ); ///< \ru Конструктор по имени функции и массиву аргументов. \en Constructor by function name and array of arguments. - MbUserFunc( const MbUserFunc & other ); ///< \ru Конструктор копирования. \en Copy-constructor. - MbUserFunc( const c3d::string_t & name ); ///< \ru Конструктор по имени функции. \en Constructor by function name. - virtual ~MbUserFunc(); - -public: - /// \ru Сделать копию. \en Create a copy. - virtual ItUserFunc & Duplicate() const { return *new MbUserFunc(*this); } - /// \ru Получить имя функции. \en Get function name. - virtual const c3d::string_t & GetName() const { return m_name; } - /// \ru Получить область определения функции. \en Get function domain. - virtual bool GetDefRange( DefRange &, ItTreeVariable & var, - const std::vector & ) const; - /// \ru Получить область определения функции. \en Get function domain. - bool GetDefRange( DefRange &, size_t ind, bool stopOnBreak ) const; - - /// \ru Количество аргументов (параметров). \en Parameters (arguments) count. - virtual size_t GetParsCount() const { return m_vars.Count(); } - /// \ru Внешние переменные. \en External variables. - virtual void GetExternalVars( SSArray & vars - , SSArray & funcs ) const; - - /// \ru Сравнить пользовательские функции. \en Compare symbolic (user-defined) functions. - virtual bool IsEqual( const ItUserFunc & other ) const { return other.IsEqual( *this ); } - /// \ru Сравнить пользовательские функции. \en Compare symbolic (user-defined) functions. - virtual bool IsEqual( const MbUserFunc & ) const; - /// \ru Вычислить значение функции в случае массива аргументов \en Calculate the value of a function in a case of arguments array - virtual EquTreeResCode GetValue( const SArray & params, double & v ) const; - /// \ru Вычислить значение функции и производные в случае массива аргументов \en Calculate the value of a function and derivatives in a case of arguments array - virtual EquTreeResCode GetDerivates( const SArray & params, - double & v, double & fd, - double & sd, double & td, - size_t dIndex = 0 ) const; - /// \ru Вычислить значение функции в случае одного аргумента \en Calculate the value of a function in a case of one argument - EquTreeResCode GetValue( double t, double & v ) const; - /// \ru Вычислить значение функции и производные в случае одного аргумента \en Calculate the value of a function and derivatives in a case of one argument - EquTreeResCode GetDerivates( double t, - double & v, double & fd, - double & sd, double & td ) const; - /// \ru Функция константная. \en Function is const. - bool IsConst() const; - /// \ru Функция линейная. \en Function is linear. - bool IsLine() const; - - /// \ru Установить выражение. \en Set expression. - EquTreeResCode SetExpression( const c3d::string_t & expr, const BTreeNode & tree ); - EquTreeResCode SetExpression( const TCHAR* expr, const BTreeNode & tree ); - /// \ru Получить выражение. \en Get expression. - const c3d::string_t & GetExpression() const { return m_expression; } - /// \ru Получить дерево разбора выражения \en Get expression parsing tree. - const BTreeNode & GetTree() const { return *m_tree; } - /// \ru Сравнение с пользовательской функцией. \en Comparison with user-defined function. - bool IsEqualValue( const MbUserFunc & other ) const; - /// \ru Получить массив параметров особых точек для данного аргумента, заданного индексом на заданном интервале. \en Get an array of parameters of singular points for the argument which is given by the index on the given interval. - bool GetExtremumPoints( size_t parIndex, std::pair interval, std::vector & points ); - /// \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; } - /// \ru Поготовить объект к записи. \en Prepare an object for writing. - void WritingBeginEnd( bool begin ) { RegisterVars( begin ? registrable : noRegistrable ); } - /// \ru Оператор присваивания. \en Assignment operator. - const MbUserFunc & operator = ( const MbUserFunc & ); -private: - /// \ru Только для внутреннего использования! Порядок функции по номеру параметра. \en For internal use only! Degree of function by the number of parameter. - virtual size_t GetPseudoOrderByPar( size_t index ) const; - void RegisterVars( RegistrableRec ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserFunc ) -}; - -IMPL_PERSISTENT_OPS( MbUserFunc ) - -#endif // __PARS_USER_FUNCTION_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Пользовательская функция. + \en User-defined function. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __PARS_USER_FUNCTION_H +#define __PARS_USER_FUNCTION_H + + +#include +#include +#include +#include +#include +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Пользовательская функция. + \en User-defined function. \~ + \details \ru Пользовательская функция. \n + \en User-defined function. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS MbUserFunc : public TapeBase, public ItUserFunc, public MbSyncItem +{ +protected: + c3d::string_t m_name; ///< \ru Имя пользовательской функции. \en A name of user-defined function. + c3d::string_t m_expression; ///< \ru Выражение. \en Expression. + BTreeNode * m_tree; ///< \ru Дерево разбора выражения (обязательно должно быть). \en A tree of expression parsing (it should be for sure). + IFC_Array m_vars; ///< \ru Формальные параметры функции. \en Formal parameters of function. + PArray m_intFuncs; ///< \ru Внутренние функции. \en Internal functions. + +public: + MbUserFunc( const c3d::string_t & name, const std::vector & pars ); ///< \ru Конструктор по имени функции и массиву аргументов. \en Constructor by function name and array of arguments. + MbUserFunc( const MbUserFunc & other ); ///< \ru Конструктор копирования. \en Copy-constructor. + MbUserFunc( const c3d::string_t & name ); ///< \ru Конструктор по имени функции. \en Constructor by function name. + virtual ~MbUserFunc(); + +public: + /// \ru Сделать копию. \en Create a copy. + virtual ItUserFunc & Duplicate() const { return *new MbUserFunc(*this); } + /// \ru Получить имя функции. \en Get function name. + virtual const c3d::string_t & GetName() const { return m_name; } + /// \ru Получить область определения функции. \en Get function domain. + virtual bool GetDefRange( DefRange &, ItTreeVariable & var, + const std::vector & ) const; + /// \ru Получить область определения функции. \en Get function domain. + bool GetDefRange( DefRange &, size_t ind, bool stopOnBreak ) const; + + /// \ru Количество аргументов (параметров). \en Parameters (arguments) count. + virtual size_t GetParsCount() const { return m_vars.Count(); } + /// \ru Внешние переменные. \en External variables. + virtual void GetExternalVars( SSArray & vars + , SSArray & funcs ) const; + + /// \ru Сравнить пользовательские функции. \en Compare symbolic (user-defined) functions. + virtual bool IsEqual( const ItUserFunc & other ) const { return other.IsEqual( *this ); } + /// \ru Сравнить пользовательские функции. \en Compare symbolic (user-defined) functions. + virtual bool IsEqual( const MbUserFunc & ) const; + /// \ru Вычислить значение функции в случае массива аргументов \en Calculate the value of a function in a case of arguments array + virtual EquTreeResCode GetValue( const SArray & params, double & v ) const; + /// \ru Вычислить значение функции и производные в случае массива аргументов \en Calculate the value of a function and derivatives in a case of arguments array + virtual EquTreeResCode GetDerivates( const SArray & params, + double & v, double & fd, + double & sd, double & td, + size_t dIndex = 0 ) const; + /// \ru Вычислить значение функции в случае одного аргумента \en Calculate the value of a function in a case of one argument + EquTreeResCode GetValue( double t, double & v ) const; + /// \ru Вычислить значение функции и производные в случае одного аргумента \en Calculate the value of a function and derivatives in a case of one argument + EquTreeResCode GetDerivates( double t, + double & v, double & fd, + double & sd, double & td ) const; + /// \ru Функция константная. \en Function is const. + bool IsConst() const; + /// \ru Функция линейная. \en Function is linear. + bool IsLine() const; + + /// \ru Установить выражение. \en Set expression. + EquTreeResCode SetExpression( const c3d::string_t & expr, const BTreeNode & tree ); + EquTreeResCode SetExpression( const TCHAR* expr, const BTreeNode & tree ); + /// \ru Получить выражение. \en Get expression. + const c3d::string_t & GetExpression() const { return m_expression; } + /// \ru Получить дерево разбора выражения \en Get expression parsing tree. + const BTreeNode & GetTree() const { return *m_tree; } + /// \ru Сравнение с пользовательской функцией. \en Comparison with user-defined function. + bool IsEqualValue( const MbUserFunc & other ) const; + /// \ru Получить массив параметров особых точек для данного аргумента, заданного индексом на заданном интервале. \en Get an array of parameters of singular points for the argument which is given by the index on the given interval. + bool GetExtremumPoints( size_t parIndex, const c3d::DoublePair & interval, c3d::DoubleVector & points ); + /// \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; } + /// \ru Подготовить объект к записи. \en Prepare an object for writing. + void WritingBeginEnd( bool begin ) { RegisterVars( begin ? registrable : noRegistrable ); } + /// \ru Оператор присваивания. \en Assignment operator. + const MbUserFunc & operator = ( const MbUserFunc & ); +private: + /// \ru Только для внутреннего использования! Порядок функции по номеру параметра. \en For internal use only! Degree of function by the number of parameter. + virtual size_t GetPseudoOrderByPar( size_t index ) const; + void RegisterVars( RegistrableRec ) const; + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbUserFunc ) +}; + +IMPL_PERSISTENT_OPS( MbUserFunc ) + +#endif // __PARS_USER_FUNCTION_H diff --git a/C3d/Include/pars_var.h b/C3d/Include/pars_var.h index 72f032e..fb8aaef 100644 --- a/C3d/Include/pars_var.h +++ b/C3d/Include/pars_var.h @@ -11,7 +11,6 @@ #define __VAR_H #include -//#include #include #include diff --git a/C3d/Include/pars_variable.h b/C3d/Include/pars_variable.h index 67cedeb..88a056f 100644 --- a/C3d/Include/pars_variable.h +++ b/C3d/Include/pars_variable.h @@ -1,100 +1,101 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Переменная. - \en Variable. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MBVARIABLE_H -#define __MBVARIABLE_H - -#include -#include - - -//----------------------------------------------------------------------------- -/** \brief \ru Координата. - \en Coordinate. \~ - \details \ru Координата. \n - \en Coordinate. \n \~ - \ingroup Parser -*/ -// --- -class MbCoord : public ItCoord -{ -private: - double m_coord; // \ru Значение координаты. \en A value of coordinate. -public: - /// \ru Конструктор по значению. \en Constructor by the value. - MbCoord( double v ) : m_coord(v) {} - /// \ru Установить значение. \en Set value. - virtual void SetValue( double v ){ m_coord = v; } - /// \ru Получить значение. \en Get the value. - virtual double GetValue() const { return m_coord; } - /// \ru Вычислить размер координаты в байтах. \en Get size of coordinate in bytes. - size_t SizeOf() const { return sizeof(double);} - - /// \ru Операторы чтения, записи. \en Reading and writing operators. - KNOWN_OBJECTS_RW_REF_OPERATORS( MbCoord ); -}; - - -//----------------------------------------------------------------------------- -/** \brief \ru Переменная. - \en Variable. \~ - \details \ru Переменная. \n - \en Variable. \n \~ - \ingroup Parser -*/ -// --- -class MATH_CLASS MbTreeVariable : public TapeBase, public ItTreeVariable -{ -private: - MbCoord m_coord; ///< \ru Координата. \en Coordinate. - c3d::string_t m_name; ///< \ru Имя переменной. \en A name of variable. - mutable size_t useCount; ///< \ru Количество использований. \en The number of uses. - -public: - /// \ru Конструктор по имени и значению. \en Constructor by the name and the value. - MbTreeVariable( const c3d::string_t & name, double v ); - virtual ~MbTreeVariable(); - -public: - /// \ru Получить имя. \en Get name. - virtual const c3d::string_t & GetName () const { return m_name; } - /// \ru Установить имя. \en Set name. - virtual void SetName ( const c3d::string_t & name ) { m_name = name; } - /// \ru Установить имя. Обработка нулевого указателяю \en Set name. Null pointer processing. - virtual void SetName( const TCHAR* s ) { m_name.assign( s ? s : _T("") ); }; - /// \ru Получение значение. \en Get value. - virtual double GetValue () const { return m_coord.GetValue(); } - /// \ru Установить значение. \en Set value. - virtual void SetValue ( double v ) { m_coord.SetValue( v ); } - /// \ru Получить координату. \en Get coordinate. - virtual const MbCoord & GetCoord () const { return m_coord; } - /// \ru Вычислить размер переменной в байтах. \en Get size of variable in bytes. - virtual size_t SizeOf () const { -#ifdef C3D_WINDOWS //_MSC_VER // method SizeOf() - return /*m_name.*/sizeof( m_name ) + sizeof( TCHAR ) * (m_name.length()) + m_coord.SizeOf(); -#else // C3D_WINDOWS - // \ru необходимо корректное вычилсение размера занимаемой памяти std::string \en there must be a correct calculation of size of memory allocated for std::string - return sizeof(m_name) + m_coord.SizeOf(); // \ru если данный SizeOf требуется для выделения памяти \en if the given SizeOf is required for the memory allocation - // \ru то все Ок, поскольку std::string сам разберется с выделением памяти себе. \en then everything is OK because std::string controls the memory allocation for itself. -#endif // C3D_WINDOWS - } - /// \ru Создать копию переменной. \en Create a copy of variable. - MbTreeVariable & Duplicate() const { return *new MbTreeVariable( GetName(), GetValue() ); } - /// \ru Увеличить счетчик использований. \en Increase a counter of uses. - virtual refcount_t AddRef () const { return ++useCount; } - /// \ru Уменьшить счетчик использований и удалить объект, если он никому уже не нужен. \en Decrease a counter of uses and delete an object if it is not used any more. - virtual refcount_t Release() const; - - /// \ru Операторы чтения, записи. \en Reading and writing operators. - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTreeVariable ); -}; - -IMPL_PERSISTENT_OPS( MbTreeVariable ) - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Переменная. + \en Variable. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MBVARIABLE_H +#define __MBVARIABLE_H + +#include +#include +#include + + +//----------------------------------------------------------------------------- +/** \brief \ru Координата. + \en Coordinate. \~ + \details \ru Координата. \n + \en Coordinate. \n \~ + \ingroup Parser +*/ +// --- +class MbCoord : public ItCoord +{ +private: + double m_coord; // \ru Значение координаты. \en A value of coordinate. +public: + /// \ru Конструктор по значению. \en Constructor by the value. + MbCoord( double v ) : m_coord(v) {} + /// \ru Установить значение. \en Set value. + virtual void SetValue( double v ){ m_coord = v; } + /// \ru Получить значение. \en Get the value. + virtual double GetValue() const { return m_coord; } + /// \ru Вычислить размер координаты в байтах. \en Get size of coordinate in bytes. + size_t SizeOf() const { return sizeof(double);} + + /// \ru Операторы чтения, записи. \en Reading and writing operators. + KNOWN_OBJECTS_RW_REF_OPERATORS( MbCoord ); +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru Переменная. + \en Variable. \~ + \details \ru Переменная. \n + \en Variable. \n \~ + \ingroup Parser +*/ +// --- +class MATH_CLASS MbTreeVariable : public TapeBase, public ItTreeVariable +{ +private: + MbCoord m_coord; ///< \ru Координата. \en Coordinate. + c3d::string_t m_name; ///< \ru Имя переменной. \en A name of variable. + mutable size_t useCount; ///< \ru Количество использований. \en The number of uses. + +public: + /// \ru Конструктор по имени и значению. \en Constructor by the name and the value. + MbTreeVariable( const c3d::string_t & name, double v ); + virtual ~MbTreeVariable(); + +public: + /// \ru Получить имя. \en Get name. + virtual const c3d::string_t & GetName () const { return m_name; } + /// \ru Установить имя. \en Set name. + virtual void SetName ( const c3d::string_t & name ) { m_name = name; } + /// \ru Установить имя. Обработка нулевого указателя. \en Set name. Null pointer processing. + virtual void SetName( const TCHAR* s ) { m_name.assign( s ? s : _T("") ); }; + /// \ru Получение значение. \en Get value. + virtual double GetValue () const { return m_coord.GetValue(); } + /// \ru Установить значение. \en Set value. + virtual void SetValue ( double v ) { m_coord.SetValue( v ); } + /// \ru Получить координату. \en Get coordinate. + virtual const MbCoord & GetCoord () const { return m_coord; } + /// \ru Вычислить размер переменной в байтах. \en Get size of variable in bytes. + virtual size_t SizeOf () const { +#ifdef C3D_WINDOWS //_MSC_VER // method SizeOf() + return /*m_name.*/sizeof( m_name ) + sizeof( TCHAR ) * (m_name.length()) + m_coord.SizeOf(); +#else // C3D_WINDOWS + // \ru необходимо корректное вычилсение размера занимаемой памяти std::string \en there must be a correct calculation of size of memory allocated for std::string + return sizeof(m_name) + m_coord.SizeOf(); // \ru если данный SizeOf требуется для выделения памяти \en if the given SizeOf is required for the memory allocation + // \ru то все Ок, поскольку std::string сам разберется с выделением памяти себе. \en then everything is OK because std::string controls the memory allocation for itself. +#endif // C3D_WINDOWS + } + /// \ru Создать копию переменной. \en Create a copy of variable. + MbTreeVariable & Duplicate() const { return *new MbTreeVariable( GetName(), GetValue() ); } + /// \ru Увеличить счетчик использований. \en Increase a counter of uses. + virtual refcount_t AddRef () const { return ++useCount; } + /// \ru Уменьшить счетчик использований и удалить объект, если он никому уже не нужен. \en Decrease a counter of uses and delete an object if it is not used any more. + virtual refcount_t Release() const; + +/// \ru Операторы чтения, записи. \en Reading and writing operators. +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbTreeVariable ) +}; + +IMPL_PERSISTENT_OPS( MbTreeVariable ) + #endif // __MBVARIABLE_H \ No newline at end of file diff --git a/C3d/Include/pars_yacc.h b/C3d/Include/pars_yacc.h index 67993f0..973e75f 100644 --- a/C3d/Include/pars_yacc.h +++ b/C3d/Include/pars_yacc.h @@ -1,181 +1,176 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Алгоритм синтаксического разбора алгебраического выражения. - \en Algorithm of syntax parsing of algebraic expression. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __YACC_H -#define __YACC_H - -#include -#include -#include -#include - -class BTreeNode; -struct ItTreeVariable; -struct ItUserFunc; -struct ItIntervalTreeVariable; -class TreeIntervalNode; - -template class RPArray; - - -// \ru Максимальная длина переменной (BUG_20492) используется при создании переменной и при разборе уравнения в калькуляторе. \en Maximum length of variable (BUG_20492) is used when creating a variable and parsing of equation in calculator. - -/// \ru Максимальная длина переменной. \en Maximum length of variable. -#define MAX_VARIABLE_NAME_LENGTH 512 - -/// \ru Максимальная длина выражения. \en Maximum length of expression. -#define MAX_EQU_LENGTH 2048 - - -//------------------------------------------------------------------------------- -// -// --- -struct ItEquVarCreator -{ - virtual ~ItEquVarCreator() - { - } - - virtual ItTreeVariable * GetVariable( const c3d::string_t & name ) = 0; - virtual ItIntervalTreeVariable * GetIntervalVariable( const c3d::string_t & name ) = 0; - virtual ItUserFunc * GetFunc ( const c3d::string_t & name, size_t parCount ) = 0; - virtual bool CreateFunc ( const c3d::string_t & name, const std::vector & parNames ) = 0; - virtual bool CreateInterval( const c3d::string_t & name ) = 0; - virtual bool CreateVariable( const c3d::string_t & name ) = 0; - - virtual ItTreeVariable * GetVariable( const TCHAR* name ) = 0; - virtual ItIntervalTreeVariable * GetIntervalVariable( const TCHAR* name ) = 0; - virtual ItUserFunc * GetFunc ( const TCHAR* name, size_t parCount ) = 0; - virtual bool CreateInterval( const TCHAR* name ) = 0; - virtual bool CreateVariable( const TCHAR* name ) = 0; - virtual unsigned int GetUsedCoordsCount() const = 0; - virtual ItTreeVariable & CreateAuxVar() = 0; - - // \ru Использовались ли какие-либо переменные? \en Were any variables used? - virtual bool WereVarsUsed() const = 0; - // \ru Использовались ли несуществующие (новые) переменные? \en Were any not existed (new) variables used? - virtual bool WereNewVarsUsed() const = 0; -}; - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать дерево уравнения (a = b + c) через параметрический калькулятор. - \en Create a tree of equations (a = b + c) by parametric calculator. \~ - \details \ru Создать дерево уравнения a = b + c) через параметрический калькулятор. \n - \en Create a tree of equations (a = b + c) by parametric calculator. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateBTreeForEquation( const c3d::string_t & equstr - , ItEquVarCreator & varsCreator - , std_unique_ptr & dRoot - ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. - \en Create a tree of equations (b + c + d) by parametric calculator. \~ - \details \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. \n - \en Create a tree of equations (b + c + d) by parametric calculator. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateBTreeForExpression( const c3d::string_t & equstr - , ItEquVarCreator * varsCreator - , std_unique_ptr & root - , std_unique_ptr & iRoot - ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать переменную. - \en Create variable. \~ - \details \ru Создать переменную по строке. \n - \en Create variable by string. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateVariable( const c3d::string_t & expression, ItEquVarCreator & ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Является ли выражение неравенством. - \en Whether expression is inequation. \~ - \details \ru Является ли выражение неравенством. \n - \en Whether expression is inequation. \n \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(bool) IsInequality( const c3d::string_t & equstr ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать дерево уравнения (a = b + c) через параметрический калькулятор. - \en Create a tree of equations (a = b + c) by parametric calculator. \~ - \details \ru Создать дерево уравнения a = b + c) через параметрический калькулятор. \n - \en Create a tree of equations (a = b + c) by parametric calculator. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateBTreeForEquation( const TCHAR * equstr - , ItEquVarCreator & varsCreator - , std_unique_ptr & dRoot - ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. - \en Create a tree of equations (b + c + d) by parametric calculator. \~ - \details \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. \n - \en Create a tree of equations (b + c + d) by parametric calculator. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateBTreeForExpression( const TCHAR * equstr - , ItEquVarCreator * varsCreator - , std_unique_ptr & root - , std_unique_ptr & iRoot - ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Создать переменную. - \en Create variable. \~ - \details \ru Создать переменную по строке. \n - \en Create variable by string. \n \~ - \return \ru Код результата операции. - \en Operation result code. \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(EquTreeResCode) CreateVariable( const TCHAR* expression, ItEquVarCreator & ); - - -//------------------------------------------------------------------------------- -/** \brief \ru Является ли выражение неравенством. - \en Whether expression is inequation. \~ - \details \ru Является ли выражение неравенством. \n - \en Whether expression is inequation. \n \~ - \ingroup Parser -*/ -// --- -MATH_FUNC(bool) IsInequality( const TCHAR* equstr ); - - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Алгоритм синтаксического разбора алгебраического выражения. + \en Algorithm of syntax parsing of algebraic expression. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __YACC_H +#define __YACC_H + +#include +#include +#include +#include + +class MATH_CLASS BTreeNode; +class MATH_CLASS TreeIntervalNode; +struct ItTreeVariable; +struct ItUserFunc; +struct ItIntervalTreeVariable; + + +/// \ru Максимальная длина переменной. \en Maximum length of variable. +const_expr size_t MAX_VARIABLE_NAME_LENGTH = 512; +/// \ru Максимальная длина выражения. \en Maximum length of expression. +const_expr size_t MAX_EQU_LENGTH = 2048; + + +//------------------------------------------------------------------------------- +// +// --- +struct ItEquVarCreator +{ + virtual ~ItEquVarCreator() + { + } + + virtual ItTreeVariable * GetVariable( const c3d::string_t & ) = 0; + virtual ItIntervalTreeVariable * GetIntervalVariable( const c3d::string_t & ) = 0; + virtual ItUserFunc * GetFunc ( const c3d::string_t &, size_t parCount ) = 0; + virtual bool CreateFunc ( const c3d::string_t &, const std::vector & parNames ) = 0; + virtual bool CreateInterval( const c3d::string_t & ) = 0; + virtual bool CreateVariable( const c3d::string_t &) = 0; + + virtual ItTreeVariable * GetVariable( const TCHAR * ) = 0; + virtual ItIntervalTreeVariable * GetIntervalVariable( const TCHAR * ) = 0; + virtual ItUserFunc * GetFunc ( const TCHAR *, size_t parCount ) = 0; + virtual bool CreateInterval( const TCHAR * ) = 0; + virtual bool CreateVariable( const TCHAR * ) = 0; + virtual unsigned int GetUsedCoordsCount() const = 0; + virtual ItTreeVariable & CreateAuxVar() = 0; + + // \ru Использовались ли какие-либо переменные? \en Were any variables used? + virtual bool WereVarsUsed() const = 0; + // \ru Использовались ли несуществующие (новые) переменные? \en Were any not existed (new) variables used? + virtual bool WereNewVarsUsed() const = 0; +}; + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать дерево уравнения (a = b + c) через параметрический калькулятор. + \en Create a tree of equations (a = b + c) by parametric calculator. \~ + \details \ru Создать дерево уравнения a = b + c) через параметрический калькулятор. \n + \en Create a tree of equations (a = b + c) by parametric calculator. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateBTreeForEquation( const c3d::string_t & equstr + , ItEquVarCreator & varsCreator + , std_unique_ptr & dRoot + ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. + \en Create a tree of equations (b + c + d) by parametric calculator. \~ + \details \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. \n + \en Create a tree of equations (b + c + d) by parametric calculator. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateBTreeForExpression( const c3d::string_t & equstr + , ItEquVarCreator * varsCreator + , std_unique_ptr & root + , std_unique_ptr & iRoot + ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать переменную. + \en Create variable. \~ + \details \ru Создать переменную по строке. \n + \en Create variable by string. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateVariable( const c3d::string_t & expression, ItEquVarCreator & ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Является ли выражение неравенством. + \en Whether expression is inequation. \~ + \details \ru Является ли выражение неравенством. \n + \en Whether expression is inequation. \n \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(bool) IsInequality( const c3d::string_t & ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать дерево уравнения (a = b + c) через параметрический калькулятор. + \en Create a tree of equations (a = b + c) by parametric calculator. \~ + \details \ru Создать дерево уравнения a = b + c) через параметрический калькулятор. \n + \en Create a tree of equations (a = b + c) by parametric calculator. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateBTreeForEquation( const TCHAR * equstr + , ItEquVarCreator & varsCreator + , std_unique_ptr & dRoot + ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. + \en Create a tree of equations (b + c + d) by parametric calculator. \~ + \details \ru Создать дерево выражения (b + c + d) через параметрический калькулятор. \n + \en Create a tree of equations (b + c + d) by parametric calculator. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateBTreeForExpression( const TCHAR * equstr + , ItEquVarCreator * varsCreator + , std_unique_ptr & root + , std_unique_ptr & iRoot + ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Создать переменную. + \en Create variable. \~ + \details \ru Создать переменную по строке. \n + \en Create variable by string. \n \~ + \return \ru Код результата операции. + \en Operation result code. \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(EquTreeResCode) CreateVariable( const TCHAR * expression, ItEquVarCreator & ); + + +//------------------------------------------------------------------------------- +/** \brief \ru Является ли выражение неравенством. + \en Whether expression is inequation. \~ + \details \ru Является ли выражение неравенством. \n + \en Whether expression is inequation. \n \~ + \ingroup Parser +*/ +// --- +MATH_FUNC(bool) IsInequality( const TCHAR * ); + + #endif \ No newline at end of file diff --git a/C3d/Include/plane_instance.h b/C3d/Include/plane_instance.h index d6211dc..b385b7d 100644 --- a/C3d/Include/plane_instance.h +++ b/C3d/Include/plane_instance.h @@ -1,197 +1,328 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Вставка двумерного объекта. - \en Instance of a two-dimensional object. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __PLANE_INSTANCE_H -#define __PLANE_INSTANCE_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbPlaneInstance; -namespace c3d // namespace C3D -{ -typedef SPtr PInstanceSPtr; -typedef SPtr ConstPInstanceSPtr; - -typedef std::vector PInstancesVector; -typedef std::vector ConstPInstancesVector; - -typedef std::vector PInstancesSPtrVector; -typedef std::vector ConstPInstancesSPtrVector; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Вставка двумерных объектов эскиза. - \en Instance of a two-dimensional sketch objects. \~ - \details \ru Вставка позволяет работать с двумерными геометрическими объектами как с объектом геометрической модели. - Двумерные геометрические объекты MbPlaneItem располагаются в плоскости XOY локальной системы координат MbPlacement3D.\n - \en The instance allows to deal with two-dimensional geometric objects as with object of geometric model. - Two-dimensional MbPlaneItem geometric objects located in XOY-plane of MbPlacement3D local coordinate system.\n \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbPlaneInstance : public MbItem { -protected : - MbPlacement3D place; ///< \ru Локальная система координат объекта. \en Local coordinate system of the object. - std::vector planeItems; ///< \ru Множество двумерных объектов эскиза. \en A set of two-dimensional sketch objects. - -protected : - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbPlaneInstance( const MbPlaneInstance &, MbRegDuplicate * ); -public : - /// \ru Конструктор по локальной системе координат без двумерных объектов. \en Constructor by a local coordinate system without two-dimensional objects. - MbPlaneInstance( const MbPlacement3D & ); - /// \ru Конструктор по двумерному объекту (используется оригинал) и локальной системе координат. \en Constructor by two-dimensional object (original is used) and a local coordinate system. - MbPlaneInstance( const MbPlaneItem &, const MbPlacement3D & ); - /// \ru Конструктор по двумерным объектам (используются оригиналы) и локальной системе координат. \en Constructor by two-dimensional object (originals are used) and a local coordinate system. - template - MbPlaneInstance( const MbPlacement3D &, const PlaneItems & ); - /// \ru Деструктор \en Destructor - virtual ~MbPlaneInstance(); - -public : - VISITING_CLASS( MbPlaneInstance ); - - // \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 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 the distance to a 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 bounding box in the local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - virtual MbProperty & CreateProperty( MbePrompt ) const; // \ru Создать собственное свойство. \en Create a custom property. - 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( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. - virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. - // \ru Получить локальную систему координат объекта. \en Get the local coordinate system of an object. - virtual bool GetPlacement( MbPlacement3D & ) const; - // \ru Установить локальную систему координат объекта. \en Set the local coordinate system of an object. - virtual bool SetPlacement( const MbPlacement3D & ); - - // \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 Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; - - /** \ru \name Общие функции вставки двумерного объекта. - \en \name Common functions of instance of two-dimensional object. - \{ */ - /// \ru Выдать число двумерных геометрических объектов. \en Get number of two-dimensional geometric objects. - size_t PlaneItemsCount() const; - /// \ru Выдать двумерный геометрический объект. \en Get two-dimensional geometric object. - const MbPlaneItem * GetPlaneItem( size_t ind = 0 ) const; - /// \ru Выдать двумерный геометрический объект для возможного редактирования. \en Get two-dimensional object for possible editing. - 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). - 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 ); - /// \ru Выдать локальную систему координат объекта. \en Get the local coordinate system of an object. - const MbPlacement3D & GetPlacement() const { return place; } - /// \ru Выдать локальную систему координат объекта для редактирования. \en Get the local coordinate system of an object for editing. - MbPlacement3D & SetPlacement() { return place; } - - /// \ru Преобразовать двумерный объект согласно матрице. \en Transform two-dimensional object according to the matrix. - void Transform( const MbMatrix &, MbRegTransform * iReg = NULL ); - /// \ru Сдвинуть двумерный объект вдоль вектора. \en Translate two-dimensional object along a vector. - void Move ( const MbVector &, MbRegTransform * iReg = 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 ); - /// \ru Повернуть двумерный объект вокруг точки на заданный угол. \en Rotate two-dimensional object at a given angle around an axis. - void Rotate ( const MbCartPoint & pnt, double angle, MbRegTransform * iReg = NULL ); - - /// \ru Удалить все объекты эскиза. \en Delete all the sketch items. - void DeleteItems(); - /// \ru Удалить объект эскиза. \en Delete the sketch item by index. - bool DeleteItem( size_t ind ); - /// \ru Удалить объект эскиза. \en Delete the sketch item by index. - MbPlaneItem * DetachItem( size_t ind ); - - /** \brief \ru Заменить объект. - \en Replace an item. \~ - \details \ru Заменить объект новым. - \en Replace an item by a new one. \~ - \param[in] item - \ru Заменяемый объект. - \en An item to be replaced. \~ - \param[in] newItem - \ru Новый объект. - \en A new item. \~ - \return \ru Возвращает true, если замена была выполнена. - \en Returns true if the replacement has been performed. \~ - */ - bool ReplaceItem( const MbPlaneItem & item, MbPlaneItem & newItem ); - - /// \ru Выдать все объекты. \en Get all the items. - template - void GetItems( PlaneItems & ) const; - - /** \} */ - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPlaneInstance ) -OBVIOUS_PRIVATE_COPY( MbPlaneInstance ) -}; - -IMPL_PERSISTENT_OPS( MbPlaneInstance ); - -//------------------------------------------------------------------------------ -// Конструктор -// --- -template -inline MbPlaneInstance::MbPlaneInstance( const MbPlacement3D & p, const PlaneItems & inits ) - : MbItem ( ) - , place ( p ) - , planeItems( ) -{ - size_t addCnt = inits.size(); - planeItems.reserve( addCnt ); - for ( size_t k = 0; k < addCnt; ++k ) { - const MbPlaneItem * planeItem = inits[k]; - if ( planeItem != NULL ) { - planeItem->AddRef(); - planeItems.push_back( const_cast( planeItem ) ); - } - } - C3D_ASSERT( !planeItems.empty() ); -} - - -//------------------------------------------------------------------------------ -// дать все объекты -// --- -template -void MbPlaneInstance::GetItems( PlaneItems & items ) const -{ - size_t addCnt = planeItems.size(); - items.reserve( items.size() + addCnt ); - SPtr item_i; - for ( size_t i = 0; i < addCnt; ++i ) { - if ( planeItems[i] != NULL ) { - item_i = planeItems[i]; - items.push_back( item_i ); - } - } -} - - -#endif // __PLANE_INSTANCE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вставка двумерного объекта. + \en Instance of a two-dimensional object. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __PLANE_INSTANCE_H +#define __PLANE_INSTANCE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbPlaneInstance; +namespace c3d // namespace C3D +{ +typedef SPtr PInstanceSPtr; +typedef SPtr ConstPInstanceSPtr; + +typedef std::vector PInstancesVector; +typedef std::vector ConstPInstancesVector; + +typedef std::vector PInstancesSPtrVector; +typedef std::vector ConstPInstancesSPtrVector; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Вставка двумерных объектов эскиза. + \en Instance of a two-dimensional sketch objects. \~ + \details \ru Вставка позволяет работать с двумерными геометрическими объектами как с объектом геометрической модели. + Двумерные геометрические объекты MbPlaneItem располагаются в плоскости XOY локальной системы координат MbPlacement3D.\n + \en The instance allows to deal with two-dimensional geometric objects as with object of geometric model. + Two-dimensional MbPlaneItem geometric objects located in XOY-plane of MbPlacement3D local coordinate system.\n \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbPlaneInstance : public MbItem { +protected : + MbPlacement3D place; ///< \ru Локальная система координат объекта. \en Local coordinate system of the object. + std::vector planeItems; ///< \ru Множество двумерных объектов эскиза. \en A set of two-dimensional sketch objects. + +protected : + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbPlaneInstance( const MbPlaneInstance &, MbRegDuplicate * ); +public : + /// \ru Конструктор по локальной системе координат без двумерных объектов. \en Constructor by a local coordinate system without two-dimensional objects. + MbPlaneInstance( const MbPlacement3D & ); + /// \ru Конструктор по двумерному объекту (используется оригинал) и локальной системе координат. \en Constructor by two-dimensional object (original is used) and a local coordinate system. + MbPlaneInstance( const MbPlaneItem &, const MbPlacement3D & ); + /// \ru Конструктор по двумерным объектам (используются оригиналы) и локальной системе координат. \en Constructor by two-dimensional object (originals are used) and a local coordinate system. + template + MbPlaneInstance( const MbPlacement3D &, const PlaneItems & ); + /// \ru Деструктор \en Destructor + virtual ~MbPlaneInstance(); + +public : + VISITING_CLASS( MbPlaneInstance ); + + // \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 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 the distance to a 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 bounding box in the local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + virtual MbProperty & CreateProperty( MbePrompt ) const; // \ru Создать собственное свойство. \en Create a custom property. + 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( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. + virtual void SetBasisPoints( const MbControlData & ); // \ru Изменить объект по контрольным точкам. \en Change the object by control points. + // \ru Получить локальную систему координат объекта. \en Get the local coordinate system of an object. + virtual bool GetPlacement( MbPlacement3D & ) const; + // \ru Установить локальную систему координат объекта. \en Set the local coordinate system of an object. + virtual bool SetPlacement( const MbPlacement3D & ); + + // \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 Найти объект по геометрическому объекту (MbPlaneItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbPlaneItem * s, MbPath & path, MbMatrix3D & from ) const; + + /** \ru \name Общие функции вставки двумерного объекта. + \en \name Common functions of instance of two-dimensional object. + \{ */ + /// \ru Выдать число двумерных геометрических объектов. \en Get number of two-dimensional geometric objects. + size_t PlaneItemsCount() const; + /// \ru Выдать двумерный геометрический объект. \en Get two-dimensional geometric object. + const MbPlaneItem * GetPlaneItem( size_t ind = 0 ) const; + /// \ru Выдать двумерный геометрический объект для возможного редактирования. \en Get two-dimensional object for possible editing. + 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). + 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 ); + /// \ru Выдать локальную систему координат объекта. \en Get the local coordinate system of an object. + const MbPlacement3D & GetPlacement() const { return place; } + /// \ru Выдать локальную систему координат объекта для редактирования. \en Get the local coordinate system of an object for editing. + MbPlacement3D & SetPlacement() { return place; } + + /// \ru Преобразовать двумерный объект согласно матрице. \en Transform two-dimensional object according to the matrix. + void Transform( const MbMatrix &, MbRegTransform * iReg = NULL ); + /// \ru Сдвинуть двумерный объект вдоль вектора. \en Translate two-dimensional object along a vector. + void Move ( const MbVector &, MbRegTransform * iReg = 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 ); + /// \ru Повернуть двумерный объект вокруг точки на заданный угол. \en Rotate two-dimensional object at a given angle around an axis. + void Rotate ( const MbCartPoint & pnt, double angle, MbRegTransform * iReg = NULL ); + + /// \ru Удалить все объекты эскиза. \en Delete all the sketch items. + void DeleteItems(); + /// \ru Удалить объект эскиза. \en Delete the sketch item by index. + bool DeleteItem( size_t ind ); + /// \ru Удалить объект эскиза. \en Delete the sketch item by index. + MbPlaneItem * DetachItem( size_t ind ); + + /** \brief \ru Заменить объект. + \en Replace an item. \~ + \details \ru Заменить объект новым. + \en Replace an item by a new one. \~ + \param[in] item - \ru Заменяемый объект. + \en An item to be replaced. \~ + \param[in] newItem - \ru Новый объект. + \en A new item. \~ + \return \ru Возвращает true, если замена была выполнена. + \en Returns true if the replacement has been performed. \~ + */ + bool ReplaceItem( const MbPlaneItem & item, MbPlaneItem & newItem ); + + /// \ru Выдать все объекты. \en Get all the items. + template + void GetItems( PlaneItems & ) const; + + /** \} */ + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPlaneInstance ) +OBVIOUS_PRIVATE_COPY( MbPlaneInstance ) +}; + +IMPL_PERSISTENT_OPS( MbPlaneInstance ); + + +//------------------------------------------------------------------------------ +// Конструктор +// --- +template +inline MbPlaneInstance::MbPlaneInstance( const MbPlacement3D & p, const PlaneItems & inits ) + : MbItem ( ) + , place ( p ) + , planeItems( ) +{ + size_t addCnt = inits.size(); + planeItems.reserve( addCnt ); + for ( size_t k = 0; k < addCnt; ++k ) { + const MbPlaneItem * planeItem = inits[k]; + if ( planeItem != NULL ) { + planeItem->AddRef(); + planeItems.push_back( const_cast( planeItem ) ); + } + } + C3D_ASSERT( !planeItems.empty() ); +} + + +//------------------------------------------------------------------------------ +// дать все объекты +// --- +template +void MbPlaneInstance::GetItems( PlaneItems & items ) const +{ + size_t addCnt = planeItems.size(); + items.reserve( items.size() + addCnt ); + SPtr item_i; + for ( size_t i = 0; i < addCnt; ++i ) { + if ( planeItems[i] != NULL ) { + item_i = planeItems[i]; + items.push_back( item_i ); + } + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Набор ошибок - результат диагностики эскиза. + \en A set of errors is the result of a sketch diagnosis. \~ + \details \ru Набор ошибок и соответствующих объектов эскиза - результат диагностики эскиза. \n + \en A set of errors and corresponding sketch objects is the result of sketch diagnostics. \n \~ + \ingroup Data_Structures +*/ +// --- +class MATH_CLASS MbSketchErrors { +private: + std::multimap> errors; ///< \ru Набор ошибок ошибок. \en Set of errors. + +public: + /// \ru Конструктор. \en Constructor. + MbSketchErrors() {} + +public: + /// \ru Добавить к набору тип ошибки и соответствующие объекты эскиза. \en Add error type and corresponding sketch objects to the set. + void AddError( MbResultType errorType, std::vector & items ) { + errors.insert( std::pair< MbResultType, std::vector >( errorType, items ) ); + } + + /// \ru Есть ли ошибка типа errorType. \en Is there any error like errorType. + bool IsAnyError( MbResultType errorType ) const { return errors.find( errorType ) != errors.end(); } + + /// \ru Дать набор объектов по типу ошибки. \en Give a set of objects by type of error. + void GetItemsByErrorType( MbResultType errorType, std::vector & items ) const; + + /// \ru Дать набор пар пересекающихся контуров. \en Give a set of pairs of intersecting contours. + void GetIntersectedItemsPairs( std::vector> & items ) const; +}; + + +//------------------------------------------------------------------------------- +/** \brief \ru Параметры диагностики эскиза. + \en Sketch diagnostic parameters. \~ + \details \ru Параметры диагностики эскиза с набором необходимых проверок. По умолчанию проводятся все проверки. \n + Возможные проверки: \n + - проверка контуров на взаимное пересечение (rt_Intersection), \n + - самопересечение (rt_SelfIntersection), \n + - поиск разрывов (rt_ContourGapError), \n + - поиск наложений (rt_ContourSegmentsOverlapError), \n + - соответствие флага замкнутости и фактической замкнутости (rt_MustBeOpen, rt_MustBeClosed), \n + - проверка гладкой стыковки сегментов по касательной ( G1 ) с указанной угловой погрешностью (rt_ContourSegmentsNoTangentJoint). \n + \en Sketch diagnostic parameters with a set of necessary checks. By default, all checks are performed. \n + Possible checks: \n + - checking contours for intersections (rt_Intersection), \n + - self-intersections (rt_SelfIntersection), \n + - searching for gaps (rt_ContourGapError), \n + - searching overlaps (rt_ContourSegmentsOverlapError), \n + - correspondence of the flag of closure and actual closure (rt_MustBeOpen, rt_MustBeClosed), \n + - check of tangent smooth joining of segments ( G1 ) with the specified angular tolerance (rt_ContourSegmentsNoTangentJoint). \n \~ + \ingroup Data_Structures +*/ +// --- +class MATH_CLASS MbSketchCheckParameters { +private: + std::set checkedErrors; ///< \ru Набор проверок. При пустом контейнере выполняются все проверки. \en A set of checks. If the container is empty, all checks are performed. + double metricEpsilon; ///< \ru Метрическая погрешность. \en Metric tolerance. + double angleEpsilon; ///< \ru Угловая погрешность. \en Angular tolerance. + +public: + /// \ru Конструктор. \en Constructor. + MbSketchCheckParameters() + : metricEpsilon( Math::metricEpsilon ) + , angleEpsilon ( Math::angleEpsilon ) + {} + + /// \ru Можно ли задать этот тип проверки? \en Can I set this type of check? + bool CanSetThisCheckType( MbResultType errorType ) const { + return errorType == rt_InvalidType || + errorType == rt_SelfIntersection || + errorType == rt_Intersection || + errorType == rt_ContourGapError || + errorType == rt_ContourSegmentsOverlapError || + errorType == rt_MustBeOpen || + errorType == rt_MustBeClosed || + errorType == rt_ContourSegmentsNoTangentJoint; + } + + /// \ru Добавить тип проверки эскиза. \en Add a sketch verification type. + void AddCheckType( MbResultType errorType ) { + if ( CanSetThisCheckType( errorType ) ) + checkedErrors.insert( errorType ); + } + + /// \ru Установить метрическую погрешность. \en Set metric tolerance. + void SetMetricEpsilon( double mEpsilon ) { metricEpsilon = mEpsilon; } + /// \ru Установить угловую погрешность. \en Set angular tolerance. + void SetAngleEpsilon( double aEpsilon ) { angleEpsilon = aEpsilon; } + + /// \ru Проверять ли на наличие ошибки типа errorType. \en Do I need to check for errors like errorType. + bool IsErrorTypeSetToCheck( MbResultType errorType ) const { + if ( checkedErrors.empty() ) + return CanSetThisCheckType( errorType ); + else + return std::find( checkedErrors.begin(), checkedErrors.end(), errorType ) != checkedErrors.end(); + } + + /// \ru Выдать метрическую погрешность. \en Get metric tolerance. + double GetMetricEpsilon() const { return metricEpsilon; } + /// \ru Выдать угловую погрешность. \en Get angular tolerance. + double GetAngleEpsilon() const { return angleEpsilon; } +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить эскиз. + \en Check sketch. \~ + \details \ru Диагностика эскиза. Проверка контуров на взаимное пересечение (rt_Intersection), + самопересечение (rt_SelfIntersection), + поиск разрывов (rt_ContourGapError) и наложений (rt_ContourSegmentsOverlapError), + соответствие флага замкнутости и фактической замкнутости (rt_MustBeOpen, rt_MustBeClosed). + \en Sketch diagnostics. Checking contours for intersections (rt_Intersection), + self-intersections (rt_SelfIntersection), + searching for gaps (rt_ContourGapError) and overlaps (rt_ContourSegmentsOverlapError), + correspondence of the flag of closure and actual closure (rt_MustBeOpen, rt_MustBeClosed). \~ + \param[in] planeInstance - \ru Эскиз, содержащий набор контуров. + \en A sketch containing a set of contours. \~ + \param[in] parameters - \ru Параметры проверки. + \en Parameters of check. \~ + \param[out] errors - \ru Набор ошибок. + \en Errors set. \~ +*/ +// --- +MATH_FUNC( void ) CheckSketch( const MbPlaneInstance & planeInstance, + const MbSketchCheckParameters & parameters, + MbSketchErrors & errors ); + + +#endif // __PLANE_INSTANCE_H diff --git a/C3d/Include/plane_item.h b/C3d/Include/plane_item.h index 4286009..a4e3fb7 100644 --- a/C3d/Include/plane_item.h +++ b/C3d/Include/plane_item.h @@ -390,7 +390,7 @@ public : The function sets a flag that allow to write the object once and to use the references to the recorded instance in the other records. Reading is performed once too, in other cases of reading the address of the already read object is used. \~ */ - void PrepareWrite() { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } DECLARE_PERSISTENT_CLASS( MbPlaneItem ) OBVIOUS_PRIVATE_COPY( MbPlaneItem ) diff --git a/C3d/Include/point3d.h b/C3d/Include/point3d.h index 6f37724..0f0479a 100644 --- a/C3d/Include/point3d.h +++ b/C3d/Include/point3d.h @@ -1,101 +1,101 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Пространственная точка со свойствами геометрического объекта. - \en Spatial point with properties of geometric object. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __POINT3D_H -#define __POINT3D_H - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Трёхмерная точка со свойствами геометрического объекта. - \en Three-dimensional point with properties of geometric object. \~ - \details \ru Точка cодержит трехмерную точку MbCartPoint3D и является - наследником геометрического объекта в пространстве.\n - \en The point contains three-dimensional point MbCartPoint3D and also is - the inheritor of a geometric object in space.\n \~ - \ingroup Point_3D -*/ -// --- -class MATH_CLASS MbPoint3D : public MbSpaceItem { -protected: - MbCartPoint3D point; ///< \ru Трехмерная точка. \en Three-dimensional point. - -private: - /// \ru Конструктор копирования. \en Copy-constructor. - MbPoint3D ( const MbPoint3D & ); -public: - /// \ru Конструктор. \en Constructor. - MbPoint3D (); - /// \ru Конструктор по точке. \en Constructor by point. - MbPoint3D ( const MbCartPoint3D & ); - /// \ru Конструктор по координатам. \en Constructor by coordinates. - MbPoint3D ( double x, double y, double z ); - /// \ru Деструктор. \en Destructor. - virtual ~MbPoint3D (); - -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 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 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. - virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. - virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - 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. - - /** \ru \name Функции точки. - \en \name Functions of point. - \{ */ - /// \ru Выдать декартову точку. \en Get Cartesian point. - void GetCartPoint( MbCartPoint3D & ) const; - /// \ru Выдать декартову точку. \en Get Cartesian point. - const MbCartPoint3D & GetCartPoint() const { return point; } - /// \ru Выдать декартову точку для возможного редактирования. \en Get Cartesian point for possible editing. - MbCartPoint3D & SetCartPoint() { return point; } - /// \ru Проверить равенство с другой точкой. \en Check for equality with another point. - bool operator == ( const MbPoint3D & ) const; - /// \ru Проверить на неравенство с другой точкой. \en Check for inequality with another point. - bool operator != ( const MbPoint3D & ) const; - /// \ru Инициализировать точку по другой точке. \en Initialize point by another point. - void Init( const MbPoint3D & init ) { point.Init(init.point); } - /// \ru Инициализировать точку по другой точке. \en Initialize point by another point. - void Init( const MbCartPoint3D & init ) { point.Init(init); } - /// \ru Инициализировать точку по координатам. \en Initialize point by coordinates. - void Init( double xx, double yy, double zz ) { point.Init(xx,yy,zz); } - /// \ru Обнуление координат. \en Set coordinates to zero. - void SetZero() { point.SetZero(); } - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const MbPoint3D & ); - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPoint3D ) -}; // MbPoint3D - -IMPL_PERSISTENT_OPS( MbPoint3D ) - -#endif // __POINT3D_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Пространственная точка со свойствами геометрического объекта. + \en Spatial point with properties of geometric object. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __POINT3D_H +#define __POINT3D_H + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Трёхмерная точка со свойствами геометрического объекта. + \en Three-dimensional point with properties of geometric object. \~ + \details \ru Точка cодержит трехмерную точку MbCartPoint3D и является + наследником геометрического объекта в пространстве.\n + \en The point contains three-dimensional point MbCartPoint3D and also is + the inheritor of a geometric object in space.\n \~ + \ingroup Point_3D +*/ +// --- +class MATH_CLASS MbPoint3D : public MbSpaceItem { +protected: + MbCartPoint3D point; ///< \ru Трехмерная точка. \en Three-dimensional point. + +private: + /// \ru Конструктор копирования. \en Copy-constructor. + MbPoint3D ( const MbPoint3D & ); +public: + /// \ru Конструктор. \en Constructor. + MbPoint3D (); + /// \ru Конструктор по точке. \en Constructor by point. + MbPoint3D ( const MbCartPoint3D & ); + /// \ru Конструктор по координатам. \en Constructor by coordinates. + MbPoint3D ( double x, double y, double z ); + /// \ru Деструктор. \en Destructor. + virtual ~MbPoint3D (); + +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 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 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. + virtual void AddYourGabaritTo( MbCube & r ) const; // \ru Добавь свой габарит в куб. \en Add bounding box into a cube. + virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + 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. + + /** \ru \name Функции точки. + \en \name Functions of point. + \{ */ + /// \ru Выдать декартову точку. \en Get Cartesian point. + void GetCartPoint( MbCartPoint3D & ) const; + /// \ru Выдать декартову точку. \en Get Cartesian point. + const MbCartPoint3D & GetCartPoint() const { return point; } + /// \ru Выдать декартову точку для возможного редактирования. \en Get Cartesian point for possible editing. + MbCartPoint3D & SetCartPoint() { return point; } + /// \ru Проверить равенство с другой точкой. \en Check for equality with another point. + bool operator == ( const MbPoint3D & ) const; + /// \ru Проверить на неравенство с другой точкой. \en Check for inequality with another point. + bool operator != ( const MbPoint3D & ) const; + /// \ru Инициализировать точку по другой точке. \en Initialize point by another point. + void Init( const MbPoint3D & init ) { point.Init(init.point); } + /// \ru Инициализировать точку по другой точке. \en Initialize point by another point. + void Init( const MbCartPoint3D & init ) { point.Init(init); } + /// \ru Инициализировать точку по координатам. \en Initialize point by coordinates. + void Init( double xx, double yy, double zz ) { point.Init(xx,yy,zz); } + /// \ru Обнуление координат. \en Set coordinates to zero. + void SetZero() { point.SetZero(); } + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const MbPoint3D & ); + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbPoint3D ) +}; // MbPoint3D + +IMPL_PERSISTENT_OPS( MbPoint3D ) + +#endif // __POINT3D_H diff --git a/C3d/Include/point_frame.h b/C3d/Include/point_frame.h index 4d9894e..e930442 100644 --- a/C3d/Include/point_frame.h +++ b/C3d/Include/point_frame.h @@ -21,6 +21,7 @@ #include class MATH_CLASS MbPointFrame; +class MATH_CLASS MbPoint3D; namespace c3d // namespace C3D @@ -58,6 +59,8 @@ public: explicit MbPointFrame( const MbVertex &, bool same ); /// \ru Конструктор по точке. \en Constructor by point. explicit MbPointFrame( const MbCartPoint3D & ); + /// \ru Конструктор по точке. \en Constructor by point. + explicit MbPointFrame( const MbPoint3D & ); /// \ru Конструктор по координатам. \en Constructor by coordinates. MbPointFrame( double x, double y, double z ); /// \ru Конструктор по массиву вершин и флагу использования этих объектов, а не их копий. \en Constructor by array of vertices and by flag of use of these objects instead of their copies. @@ -108,7 +111,7 @@ public: virtual MbProperty & CreateProperty( MbePrompt n ) const; // \ru Создать собственное свойство. \en Create a custom property. 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 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. @@ -126,12 +129,43 @@ public: 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 ); } - /// \ru Получить вершину по индексу для модификации. \en Get vertex by an index for modification. - MbVertex * GetVertex( size_t k ) { return ((k < vertices.size()) ? vertices[k] : NULL ); } + /// \ru Получить вершину по индексу для возможного редактирования. \en Get vertex by an index for the possible editing. + MbVertex * SetVertex( size_t k ) { return ((k < vertices.size()) ? vertices[k] : NULL ); } + + /// \ru Получить вершины. \en Get vertices. + template + void GetVertices( VerticesVector & dstVertices ) const + { + if ( !vertices.empty() ) { + size_t addCnt = vertices.size(); + dstVertices.reserve( dstVertices.size() + addCnt ); + c3d::ConstVertexSPtr vertex; + for ( size_t k = 0; k < addCnt; ++k ) { + vertex = vertices[k]; + dstVertices.push_back( vertex ); + } + } + } + /// \ru Получить вершины для возможного редактирования. \en Get vertices for the possible editing. + template + void SetVertices( VerticesVector & dstVertices ) + { + if ( !vertices.empty() ) { + size_t addCnt = vertices.size(); + dstVertices.reserve( dstVertices.size() + addCnt ); + c3d::VertexSPtr vertex; + for ( size_t k = 0; k < addCnt; ++k ) { + vertex = vertices[k]; + dstVertices.push_back( vertex ); + } + } + } /// \ru Добавить вершину по точке. \en Add vertex by point. void AddVertex( const MbCartPoint3D & ); - /// \ru Добавить вершину или ее копию, что определяется флагом использования самого объекта. \en Add vertex or its copy (defined by flag of use of object). - void AddVertex( const MbVertex &, bool same ); + /// \ru Добавить вершину или ее копию, что определяется флагом. \en Add vertex or its copy (defined by flag). + void AddVertex( const MbVertex &, bool sameVertex ); + /// \ru Добавить вершины или их копию, что определяется флагом. \en Add vertices or theirs copies (defined by flag). + bool AddVertices( const MbPointFrame &, bool sameVertices ); /// \ru Вставить вершину по номеру и точке. \en Insert vertex by index and point. void InsertVertex( size_t k, const MbCartPoint3D & ); /// \ru Вставить по номеру вершину или ее копию, что определяется флагом использования самого объекта. \en Insert vertex or its copy (defined by flag of use of object) by index. diff --git a/C3d/Include/position_data.h b/C3d/Include/position_data.h index efd0f69..9e729a0 100644 --- a/C3d/Include/position_data.h +++ b/C3d/Include/position_data.h @@ -1,188 +1,188 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Данные для размеров операции. - \en Data for operation dimensions. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __POSITION_DATA_H -#define __POSITION_DATA_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbCurveEdge; - - -//------------------------------------------------------------------------------ -/** \brief \ru Данные для размеров операции. - \en Data for operation dimensions. \~ - \details \ru Данные для позиционирования размеров операции скругления и фаски рёбер. \n - \en Data for positioning dimensions of operations of fillet and chamfer of edges. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbPositionData { -public: - MbCartPoint3D point1; ///< \ru Опорная точка размера. \en Support point of dimension. - MbCartPoint3D point2; ///< \ru Опорная точка размера. \en Support point of dimension. - MbCartPoint3D origin; ///< \ru Начальна точка или центр. \en Start point or center. - MbVector3D normal; ///< \ru Нормаль плоскости размера. \en Plane normal of dimension. - double param; ///< \ru Положение размера в процентах длины ребра. \en Position of dimension in percentage of edge length. - MbName itemName; ///< \ru Имя объекта. \en A name of an object. - -public: - /// \ru Пустой конструктор. \en Empty constructor. - MbPositionData() - : point1() - , point2() - , origin() - , normal( 0.0, 0.0, 1.0 ) - , param (0.5) - , itemName() - {} - /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. - MbPositionData( const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbCartPoint3D & _or, - const MbVector3D & nor, double t, const MbName & n ) - : point1( p1 ) - , point2( p2 ) - , origin( _or ) - , normal( nor ) - , param ( t ) - , itemName( n ) - {} - /// \ru Конструктор копирования. \en Copy-constructor. - MbPositionData( const MbPositionData & other ) - : point1( other.point1 ) - , point2( other.point2 ) - , origin( other.origin ) - , normal( other.normal ) - , param ( other.param ) - , itemName( other.itemName ) - {} - /// \ru Деструктор. \en Destructor. - ~MbPositionData() {} - /// \ru Функция копирования данных. \en Copy function of data. - void Init( const MbPositionData & other ) { - point1 = other.point1; - point2 = other.point2; - origin = other.origin; - normal = other.normal; - param = other.param; - itemName.SetName( other.itemName ); - } - - /// \ru Первая контрольная точка. \en The first control point. - const MbCartPoint3D & GetPoint1() const { return point1; } - /// \ru Вторая контрольная точка. \en The second control point. - const MbCartPoint3D & GetPoint2() const { return point2; } - /// \ru Начальная точка. \en The starting point. - const MbCartPoint3D & GetOrigin() const { return origin; } - /// \ru Нормаль плоскости размера. \en Plane normal of dimension. - const MbVector3D & Normal() const { return normal; } - /// \ru Положение размера в процентах длины ребра. \en Position of dimension in percentage of edge length. - const double & GetParam() const { return param; } - /// \ru Имя объекта. \en A name of an object. - const MbName & GetName() const { return itemName; } - /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const MbPositionData & other ) { - point1 = other.point1; - point2 = other.point2; - origin = other.origin; - normal = other.normal; - param = other.param; - itemName.SetName( other.itemName ); - } - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPositionData, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbPositionData, MATH_FUNC_EX ); - DECLARE_NEW_DELETE_CLASS( MbPositionData ) - DECLARE_NEW_DELETE_CLASS_EX( MbPositionData ) -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Последовательность рёбер. - \en Sequence of edges. \~ - \details \ru Последовательность гладко стыкующихся рёбер, скругляемых одновременно. \n - \en Sequence of smooth mating edges rounded at the same time. \n \~ - \ingroup Data_Structures -*/ -// --- -struct MATH_CLASS MbEdgeSequence { -public: - RPArray edges; ///< \ru Рёбра последовательности. \en Edges of sequence. - SArray sense; ///< \ru Направленность рёбер в последовательности. \en Direction of edges in the sequence. - bool closed; ///< \ru Замкнутость последовательности. \en Closedness of sequence. - -public: - /// \ru Пустой конструктор. \en Empty constructor. - MbEdgeSequence() - : edges( 0, 1 ) - , sense( 0, 1 ) - , closed( false ) - {} - /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. - MbEdgeSequence( const MbCurveEdge & edge, bool s, bool c ) - : edges( 1, 1 ) - , sense( 1, 1 ) - , closed( c ) - { - edges.Add( &edge ); - sense.Add( s ); - } - /// \ru Конструктор копирования. \en Copy-constructor. - MbEdgeSequence( const MbEdgeSequence & other ) - : edges( other.edges.Count(), 1 ) - , sense( other.sense ) - , closed( other.closed ) - { - edges.AddArray( other.edges ); - } - /// \ru Деструктор. \en Destructor. - ~MbEdgeSequence() {} - /// \ru Функция копирования данных. \en Copy function of data. - void Init( const MbEdgeSequence & other ) { - edges.DetachAll(); - sense.Flush(); - edges.AddArray( other.edges ); - sense = other.sense; - closed = other.closed; - } - /// \ru Зарезервировать место под столько элементов. \en Reserve space for a given count of elements. - void Reserve( size_t count ) { - edges.Reserve( count ); - sense.Reserve( count ); - } - /// \ru Добавить ребро. \en Add an edge. - void AddEdge( const MbCurveEdge & edge, bool s ) { - edges.Add( &edge ); - sense.Add( s ); - } - /// \ru Добавить в последовательность все гладко стыкующиеся с ней ребра. \en Add all smooth mating edges to a sequence. - bool CollectEdges( double epsilon ); - /// \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 bool Sense( size_t i ) const { return ( i < sense.Count() ) ? sense[i] : false; } - size_t Count() const { return edges.Count(); } - /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const MbEdgeSequence & other ) { - Init( other ); - } - - KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbEdgeSequence, MATH_FUNC_EX ); - KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbEdgeSequence, MATH_FUNC_EX ); - DECLARE_NEW_DELETE_CLASS( MbEdgeSequence ) - DECLARE_NEW_DELETE_CLASS_EX( MbEdgeSequence ) -}; - - -#endif // __POSITION_DATA_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Данные для размеров операции. + \en Data for operation dimensions. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __POSITION_DATA_H +#define __POSITION_DATA_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbCurveEdge; + + +//------------------------------------------------------------------------------ +/** \brief \ru Данные для размеров операции. + \en Data for operation dimensions. \~ + \details \ru Данные для позиционирования размеров операции скругления и фаски рёбер. \n + \en Data for positioning dimensions of operations of fillet and chamfer of edges. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MATH_CLASS MbPositionData { +public: + MbCartPoint3D point1; ///< \ru Опорная точка размера. \en Support point of dimension. + MbCartPoint3D point2; ///< \ru Опорная точка размера. \en Support point of dimension. + MbCartPoint3D origin; ///< \ru Начальна точка или центр. \en Start point or center. + MbVector3D normal; ///< \ru Нормаль плоскости размера. \en Plane normal of dimension. + double param; ///< \ru Положение размера в процентах длины ребра. \en Position of dimension in percentage of edge length. + MbName itemName; ///< \ru Имя объекта. \en A name of an object. + +public: + /// \ru Пустой конструктор. \en Empty constructor. + MbPositionData() + : point1() + , point2() + , origin() + , normal( 0.0, 0.0, 1.0 ) + , param (0.5) + , itemName() + {} + /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. + MbPositionData( const MbCartPoint3D & p1, const MbCartPoint3D & p2, const MbCartPoint3D & _or, + const MbVector3D & nor, double t, const MbName & n ) + : point1( p1 ) + , point2( p2 ) + , origin( _or ) + , normal( nor ) + , param ( t ) + , itemName( n ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbPositionData( const MbPositionData & other ) + : point1( other.point1 ) + , point2( other.point2 ) + , origin( other.origin ) + , normal( other.normal ) + , param ( other.param ) + , itemName( other.itemName ) + {} + /// \ru Деструктор. \en Destructor. + ~MbPositionData() {} + /// \ru Функция копирования данных. \en Copy function of data. + void Init( const MbPositionData & other ) { + point1 = other.point1; + point2 = other.point2; + origin = other.origin; + normal = other.normal; + param = other.param; + itemName.SetName( other.itemName ); + } + + /// \ru Первая контрольная точка. \en The first control point. + const MbCartPoint3D & GetPoint1() const { return point1; } + /// \ru Вторая контрольная точка. \en The second control point. + const MbCartPoint3D & GetPoint2() const { return point2; } + /// \ru Начальная точка. \en The starting point. + const MbCartPoint3D & GetOrigin() const { return origin; } + /// \ru Нормаль плоскости размера. \en Plane normal of dimension. + const MbVector3D & Normal() const { return normal; } + /// \ru Положение размера в процентах длины ребра. \en Position of dimension in percentage of edge length. + const double & GetParam() const { return param; } + /// \ru Имя объекта. \en A name of an object. + const MbName & GetName() const { return itemName; } + /// \ru Оператор присваивания. \en Assignment operator. + void operator = ( const MbPositionData & other ) { + point1 = other.point1; + point2 = other.point2; + origin = other.origin; + normal = other.normal; + param = other.param; + itemName.SetName( other.itemName ); + } + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbPositionData, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbPositionData, MATH_FUNC_EX ); + DECLARE_NEW_DELETE_CLASS( MbPositionData ) + DECLARE_NEW_DELETE_CLASS_EX( MbPositionData ) +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Последовательность рёбер. + \en Sequence of edges. \~ + \details \ru Последовательность гладко стыкующихся рёбер, скругляемых одновременно. \n + \en Sequence of smooth mating edges rounded at the same time. \n \~ + \ingroup Data_Structures +*/ +// --- +struct MATH_CLASS MbEdgeSequence { +public: + RPArray edges; ///< \ru Рёбра последовательности. \en Edges of sequence. + SArray sense; ///< \ru Направленность рёбер в последовательности. \en Direction of edges in the sequence. + bool closed; ///< \ru Замкнутость последовательности. \en Closedness of sequence. + +public: + /// \ru Пустой конструктор. \en Empty constructor. + MbEdgeSequence() + : edges( 0, 1 ) + , sense( 0, 1 ) + , closed( false ) + {} + /// \ru Конструктор по толщинам и замкнутости. \en Constructor by thicknesses and closedness. + MbEdgeSequence( const MbCurveEdge & edge, bool s, bool c ) + : edges( 1, 1 ) + , sense( 1, 1 ) + , closed( c ) + { + edges.Add( &edge ); + sense.Add( s ); + } + /// \ru Конструктор копирования. \en Copy-constructor. + MbEdgeSequence( const MbEdgeSequence & other ) + : edges( other.edges.Count(), 1 ) + , sense( other.sense ) + , closed( other.closed ) + { + edges.AddArray( other.edges ); + } + /// \ru Деструктор. \en Destructor. + ~MbEdgeSequence() {} + /// \ru Функция копирования данных. \en Copy function of data. + void Init( const MbEdgeSequence & other ) { + edges.DetachAll(); + sense.Flush(); + edges.AddArray( other.edges ); + sense = other.sense; + closed = other.closed; + } + /// \ru Зарезервировать место под столько элементов. \en Reserve space for a given count of elements. + void Reserve( size_t count ) { + edges.Reserve( count ); + sense.Reserve( count ); + } + /// \ru Добавить ребро. \en Add an edge. + void AddEdge( const MbCurveEdge & edge, bool s ) { + edges.Add( &edge ); + sense.Add( s ); + } + /// \ru Добавить в последовательность все гладко стыкующиеся с ней ребра. \en Add all smooth mating edges to a sequence. + bool CollectEdges( double epsilon ); + /// \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 bool Sense( size_t i ) const { return ( i < sense.Count() ) ? sense[i] : false; } + size_t Count() const { return edges.Count(); } + /// \ru Оператор присваивания. \en Assignment operator. + void operator = ( const MbEdgeSequence & other ) { + Init( other ); + } + + KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MbEdgeSequence, MATH_FUNC_EX ); + KNOWN_OBJECTS_RW_PTR_OPERATORS_EX( MbEdgeSequence, MATH_FUNC_EX ); + DECLARE_NEW_DELETE_CLASS( MbEdgeSequence ) + DECLARE_NEW_DELETE_CLASS_EX( MbEdgeSequence ) +}; + + +#endif // __POSITION_DATA_H diff --git a/C3d/Include/reference_item.h b/C3d/Include/reference_item.h index 9dbe037..f8f459c 100644 --- a/C3d/Include/reference_item.h +++ b/C3d/Include/reference_item.h @@ -1,1021 +1,1021 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Счетчик ссылок (владельцев объекта). - \en Reference counter (of an object owners). \~ - -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __REFERENCE_ITEM_H -#define __REFERENCE_ITEM_H - - -#include -#include -#include -#include -#include -#include -#include -//#include -#include - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Типы объекта со счетчиком ссылок. - \en Types of object with reference counter. \~ - \details \ru Тип несёт информацию об объекте-наследнике. \n - \en Type has an information of inheritor object. \n \~ - \ingroup Geometric_Items -*/ -// --- -enum MbeRefType -{ - rt_RefItem = 0, ///< \ru Некоторый объект. \en Some object. - rt_PlaneItem, ///< \ru Двумерный геометрически объект. \en Two-dimensional geometric object. - rt_SpaceItem, ///< \ru Трехмерный геометрический объект. \en Three-dimensional geometric object. - rt_TopItem, ///< \ru Топологический объект. \en A topological object. - rt_Creator, ///< \ru Строитель объекта. \en Object constructor - rt_Attribute, ///< \ru Атрибут объекта. \en Attribute of an object. - rt_Primitive, ///< \ru Элемент полигонального объекта. \en Element of polygonal object. - // \ru В конец можно добавлять новые нужные \en It is possible to add new necessary ones to the end -}; - - -class MATH_CLASS MbRefItem; -namespace c3d // namespace C3D -{ -typedef SPtr RefItemSPtr; -typedef SPtr ConstRefItemSPtr; - -typedef std::vector RefItemsVector; -typedef std::vector ConstRefItemsVector; - -typedef std::vector RefItemsSPtrVector; -typedef std::vector ConstRefItemsSPtrVector; -} - -//---------------------------------------------------------------------------------------- -/** \brief \ru Объект с подсчетом ссылок. - \en Reference-counted object. \~ - \details \ru Объект, считающий количество своих владельцев. \n - Используется в качестве одного из родительских классов геометрических объектов. \n - Если наследник данного класса захватывается другим объектом или алгоритмом,то другой - объект или алгоритм должен увеличить счетчик ссылок на единицу методом AddRef(). - При отказе от использования наследника данного класса другим объектом (например, при деструктурировании) - или алгоритмом другой объект или алгоритм должны уменьшить счетчик ссылок на единицу - методом Release(). Такое правило позволяет использовать одного и того же наследника - данного класса несколькими другим объектами или алгоритмами одновременно и гарантирует, - что объект будет удалён, когда он станет никому не нужен.\n - - \en Object counting number of its owners. \n - Is used as one of parent classes of geometric objects. \n - If inheritor of current class is captured by other object or algorithm, then the other - object or algorithm has to increase reference counter by one by AddRef() method. - At refusal of use of the successor of this class by other object (for example at destruction) - or by algorithm, the other object or algorithm has to decrease reference counter - by one by Release() method. Such rule allows to use the same inheritor of current - class simultaneously by several other objects or algorithms and guarantees that the - object will be removed when it becomes unnecessary.\n \~ - - \note \ru Рекомендуется применение автоматических указателей типа SPtr к экземплярам - данного класса. Это упростит работу с кодом, где нужно позаботится об автоматической - сборке мусора. - \en It is recommended to use smart pointers of type SPtr to instances of - this class. This will simplify the work with the code where you want to take care of - the automatic garbage collection. \~ - \sa #SPtr - \ingroup Geometric_Items -*/ -// --- -class MATH_CLASS MbRefItem { -private: - mutable use_count_type useCount; ///< \ru Счетчик ссылок на объект, изменяемый владельцами объекта. \en A counter of references to an object modifiable by owners of object. -public: - /// \ru Конструктор без параметров. \en Constructor without parameters. - MbRefItem(); -protected: - virtual ~MbRefItem(); - -public: - /** \ru \name Функции регистрации ссылок на геометрический объект владельцами объекта. - \en \name Functions for registration of references to geometric object by owners of object. - \{ */ - /// \ru Выдать количество ссылок (выдать количество владельцев объекта). \en Get count of references (get count of owners of an object). - refcount_t GetUseCount() const; - /// \ru Увеличить количество ссылок на единицу. \en Increase count of references by one. - refcount_t AddRef() const; - /// \ru Уменьшить количество ссылок на единицу. \en Decrease count of references by one. - refcount_t DecRef() const; - /// \ru Уменьшить количество ссылок на единицу и, если количество ссылок стало равным нулю, удалить себя. \en Decrease count of references by one and if count of references became zero, then remove itself. - refcount_t Release() const; - /** \} */ -public: - /// \ru Регистрационный тип (для копирования, дублирования). \en Registration type (for copying, duplication). - virtual MbeRefType RefType() const; - -OBVIOUS_PRIVATE_COPY( MbRefItem ) -}; - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Шаблон класса сериализации (порядковой нумерации создаваемых объектов). - \en Serialization class template (ordinal numbering of created objects). \~ - \details \ru Шаблон класса сериализации (порядковой нумерации создаваемых объектов). \n - Применение: наследовать от данного класса. - Аргумент шаблона позволяет иметь несколько сериализаций одновременно: \n - если нужна сериализация объектов класса T, можно записать class T: virtual public MbSerialItem \n - если объекты U должны иметь ту же сериализацию, можно записать class U: virtual public MbSerialItem \n - или же создать пустой класс для сериализации типа class MbBasicSerializer {} - и наследоваться от MbSerialItem. \n - - \en Serialization class template (ordinal numbering of created objects). \n - How to use: inherit from this class. \n - The template argument allows multiple serializations at the same time: \n - if you need serialization of objects of class T, you can write class T: virtual public MbSerialItem \n - if U objects must have the same serialization, you can write a class U: virtual public MbSerialItem \n - or you can create an empty class to serialize the class type MbBasicSerializer \n - and inherit it from MbSerialItem . \n \~ - - \ingroup Geometric_Items -*/ -// --- -template class MbSerialItem { -private: - static serial_type serialLast; ///< \ru Индекс последнего созданного объекта (0 в случае отсутствия объектов). \en Index of the last object created (0 if there are no objects). - static serial_type serialCount; ///< \ru Счетчик объектов. \en Counter of objects. - serial_type serialThis; ///< \ru Уникальный порядковый номер объекта, выдается при создании. В дальнейшем не меняется. \en The unique sequence number of the object, issued at creation. In the future it is not changed. -public: - MbSerialItem(); ///< \ru Конструктор. \en Constructor. -protected: - virtual ~MbSerialItem(); ///< \ru Деструктор. \en Destructor. -public: - size_t GetSerial() const { return SerialTypeValue( serialThis ); } ///< \ru Выдать порядковый номер объекта. \en Get object serial identifier. - -OBVIOUS_PRIVATE_COPY( MbSerialItem ) -}; - - -// \ru Инициализация статических переменных шаблона класса сериализации. \en Initializing static variables of the serialization class template. -template serial_type MbSerialItem::serialLast = 0; -template serial_type MbSerialItem::serialCount = 0; - - -//----------------------------------------------------------------------------- -// \ru Конструктор. \en Constructor. -// --- -template MbSerialItem::MbSerialItem() -{ // Set the serial number and promote the counters - PRECONDITION( serialLast != SYS_MAX_T ); // number overflow - serialThis = ++serialLast; - ++serialCount; -} - - -//----------------------------------------------------------------------------- -// \ru Деструктор. \en Destructor. -// --- -template MbSerialItem::~MbSerialItem() -{ - PRECONDITION( SerialTypeValue( serialCount ) != 0 ); // If it equals 0 then it means that the counter is damaged. - if ( --serialCount == 0 ) // The case when the last of the instantiated objects is deleted - serialLast = 0; // Set serialization to zero - at the subsequent creation of objects the numbering will start again (serially since 1). -} - - - -//------------------------------------------------------------------------------ -/// \ru Удалить объект без ссылок. \en Delete an object without references. -//--- -template -inline void DeleteMatItem( Type *& item ) -{ - if ( item != NULL ) { - delete item; - item = NULL; - } -} - - -//------------------------------------------------------------------------------ -/// \ru Удалить объекты без ссылок. \en Delete objects without references. -// --- -template -void DeleteMatItems( Vector & items ) -{ - for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) - ::DeleteMatItem( items[k] ); - items.clear(); -} - - -//------------------------------------------------------------------------------ -/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. -// --- -template -Type & DuplicateIfUsed( Type & item ) -{ - Type * resItem = &item; - if ( item.GetUseCount() > 0 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. - resItem = static_cast( &item.Duplicate() ); - - return *resItem; -} - - -//------------------------------------------------------------------------------ -/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. -// --- -template -Type & DuplicateIfUsed( Type & item, RegType * iReg ) -{ - Type * resItem = &item; - if ( item.GetUseCount() > 0 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. - resItem = static_cast( &item.Duplicate( iReg ) ); - - return *resItem; -} - - -//------------------------------------------------------------------------------ -/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. -// --- -template -Type * DuplicateIfUsed( SPtr & item ) -{ - if ( item == NULL ) - return NULL; - Type * resItem = item.get(); - if ( item->GetUseCount() > 1 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. - resItem = static_cast( &item->Duplicate() ); - - return resItem; -} - - -//------------------------------------------------------------------------------ -/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. -// --- -template -Type * DuplicateIfUsed( SPtr & item, RegType * iReg ) -{ - if ( item == NULL ) - return 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 ) ); - - return resItem; -} - -//------------------------------------------------------------------------------ -/// \ru Удалить объект, если он больше никому не нужен. \en Delete an object if it is unnecessary. -// --- -template -void DeleteItem( Type *& item ) -{ - if ( item != NULL ) { - if ( item->GetUseCount() < 1 ) - delete item; - item = NULL; - } -} - -//------------------------------------------------------------------------------ -/// \ru Освободить ссылку на объект. \en Release the reference to object. -// --- -template -void ReleaseItem( Type *& item ) -{ - if ( item != NULL ) { - item->Release(); - item = NULL; - } -} - -//------------------------------------------------------------------------------ -/// \ru Захватить объект. \en Catch an object. -// --- -template -void AddRefItem( const Type * item ) -{ - if ( item != NULL ) - item->AddRef(); -} - -//------------------------------------------------------------------------------ -/// \ru Отпустить объект без удаления. \en Detach an object without removing. -// --- -template -void DecRefItem( const Type * item ) -{ - if ( item != NULL ) - item->DecRef(); -} - - -//------------------------------------------------------------------------------ -/// \ru Захватить объекты. \en Catch objects. -// --- -template -void AddRefItems( const Vector & items ) -{ - for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { - if ( items[k] != NULL ) - items[k]->AddRef(); - } -} - - -//------------------------------------------------------------------------------ -/// \ru Отпустить объекты без удаления. \en Detach objects without removing. -// --- -template -void DecRefItems( const Vector & items ) -{ - for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { - if ( items[k] != NULL ) - items[k]->DecRef(); - } -} - - -//------------------------------------------------------------------------------ -/// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. -// --- -template -void DeleteItems( Vector & items ) -{ - for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) - ::DeleteItem( items[k] ); - items.clear(); -} - - -//------------------------------------------------------------------------------ -/// \ru Отпустить объекты с возможным удалением. \en Detach objects with possible removing. -// --- -template -void ReleaseItems( Vector & items ) -{ - for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) - ::ReleaseItem( items[k] ); - items.clear(); -} - - -//------------------------------------------------------------------------------ -/// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. -// --- -template -void DeleteItems( Vector & 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 Detach objects with possible removing. -// --- -template -void ReleaseItems( Vector & 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 Put elements with capturing and with possible copying. -// --- -template -void AddRefItems( const TypeVector & srcItems, bool same, RPArray & dstItems ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); - dstItem->AddRef(); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. -// --- -template -void AddRefItems( const TypeVector & srcItems, bool same, std::vector< SPtr > & dstItems ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - SPtr dstItem; - dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. -// --- -template -void AddRefItems( const TypeVector & srcItems, bool same, std::vector & dstItems ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); - dstItem->AddRef(); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. -// --- -template -void AddRefRegItems( const TypeVector & srcItems, bool same, RPArray & dstItems, RegType * iReg ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItem->AddRef(); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. -// --- -template -void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector< SPtr > & dstItems, RegType * iReg ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - SPtr dstItem; - dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. -// --- -template -void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector & dstItems, RegType * iReg ) -{ - 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 ) { - Type * srcItem = &const_cast(*srcItems[k]); - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItem->AddRef(); - dstItems.push_back( dstItem ); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. -// --- -template -bool IsItemSame( const Item * item1, const Item * item2, double accuracy ) -{ - if ( (item1 == NULL) && (item2 == NULL) ) - return true; - else if ( (item1 != NULL) && (item2 != NULL) && item1->IsSame( *item2, accuracy ) ) - return true; - return false; -} - - -//------------------------------------------------------------------------------ -/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. -// --- -template -bool AreItemsSame( const Vector & items1, const Vector & items2, double accuracy ) -{ - bool areEqual = false; - - const size_t cnt = items1.size(); - 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 ) ) { - areEqual = false; - break; - } - } - } - - return areEqual; -} - - -//------------------------------------------------------------------------------ -/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. -// --- -template -bool AreObjectsSame( const Vector & items1, const Vector & items2, double accuracy ) -{ - bool areEqual = false; - - const size_t cnt = items1.size(); - if ( cnt == items2.size() ) { - areEqual = true; - for ( size_t k = 0; k < cnt; ++k ) { - if ( !items1[k].IsSame( items2[k], accuracy ) ) { - areEqual = false; - break; - } - } - } - - return areEqual; -} - - -//------------------------------------------------------------------------------ -/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. -// --- -template -bool AreItemsSimilar( const Vector & items1, const Vector & items2 ) -{ - bool areEqual = false; - - const size_t cnt = items1.size(); - 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] ) ) { - areEqual = false; - break; - } - } - } - - return areEqual; -} - - -//------------------------------------------------------------------------------ -/// \ru Сделать равными. \en Make equal. -// --- -template -bool SetItemsEqual( const Vector & srcItems, Vector & dstItems ) -{ - bool setEqual = false; - - size_t cnt = srcItems.size(); - if ( cnt == dstItems.size() ) { - setEqual = ::AreItemsSimilar( srcItems, dstItems ); - - if ( setEqual ) { - for ( size_t k = 0; k < cnt; ++k ) { - if ( srcItems[k] == NULL || dstItems[k] == NULL || !dstItems[k]->SetEqual( *srcItems[k] ) ) { - setEqual = false; - break; - } - } - } - } - - return setEqual; -} - - -//------------------------------------------------------------------------------ -/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). -// --- -template -void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, RPArray & dstItems ) -{ - C3D_ASSERT( dstItems.size() < 1 ); - dstItems.Reserve( srcItems.size() ); - for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItems.push_back( dstItem ); - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). -// --- -template -void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std::vector< SPtr > & dstItems ) -{ - C3D_ASSERT( dstItems.size() < 1 ); - dstItems.reserve( dstItems.size() + srcItems.size() ); - for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { - SPtr dstItem; - dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItems.push_back( dstItem ); - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). -// --- -template -void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std::vector & dstItems ) -{ - C3D_ASSERT( dstItems.size() < 1 ); - dstItems.reserve( dstItems.size() + srcItems.size() ); - for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { - Type * srcItem = srcItems[k]; - if ( srcItem != NULL ) { - Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); - dstItems.push_back( dstItem ); - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Преобразовать элементы согласно матрице. \en Transform elements according to the matrix. -// --- -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 ) - items[k]->Transform( matr, iReg ); - } -} - -//------------------------------------------------------------------------------ -/// \ru Преобразовать элементы согласно матрице. \en Transform elements according to the matrix. -// --- -template -void TransformObjects( Array & objects, const Matrix & matr ) -{ - for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) - objects[k].Transform( matr ); -} - - -//------------------------------------------------------------------------------ -/// \ru Сдвинуть вдоль объекты вектора. \en Translate objects along a vector. -// --- -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 ) - items[k]->Move( to, iReg ); - } -} - -//------------------------------------------------------------------------------ -/// \ru Сдвинуть вдоль объекты вектора. \en Translate objects along a vector. -// --- -template -void MoveObjects( Array & objects, const Vector & to ) -{ - for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) - objects[k].Move( to ); -} - - -//------------------------------------------------------------------------------ -/// \ru Повернуть вокруг оси. \en Rotate about an axis. -// --- -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 ) - items[k]->Rotate( axis, angle, iReg ); - } -} - -//------------------------------------------------------------------------------ -/// \ru Повернуть вокруг оси. \en Rotate about an axis. -// --- -template -void RotateObjects( Array & objects, const Axis & axis, double angle ) -{ - for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) - objects[k].Rotate( axis, angle ); -} - - -//------------------------------------------------------------------------------ -/// \ru Запись объектов в поток. \en Write objects to the stream. -// --- -template -void WriteRefItems( const Vector & items, Writer & out ) -{ - size_t k, cnt = items.size(); - - for ( k = 0; k < cnt; ++k ) { - if ( items[k] == NULL ) - cnt--; - } - - WriteCOUNT( out, cnt ); - - if ( out.good() ) { - for ( k = 0; k < cnt; ++k ) { - if ( items[k] != NULL ) { - items[k]->PrepareWrite(); - out << &(*items[k]); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Запись объекты в поток. \en Write objects to the stream. -// --- -template -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 ) - cnt--; - } - - WriteCOUNT( out, cnt ); - - if ( out.good() ) { - for ( k = 0; k < cnt; ++k ) { - if ( items[k] != NULL ) { - items[k]->PrepareWrite(); - out << items[k].get(); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. -// --- -template -void ReadRefItems( Reader & in, RPArray & items ) -{ - size_t cnt = ReadCOUNT( in ); - - if ( in.good() && cnt > 0 ) { - items.reserve( items.size() + cnt ); - - for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; - in >> item; - if ( item != NULL ) { - items.push_back( item ); - item->AddRef(); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. -// --- -template -void ReadRefItems( Reader & in, std::vector & items ) -{ - size_t cnt = ReadCOUNT( in ); - - if ( in.good() && cnt > 0 ) { - for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; - in >> item; - if ( item != NULL ) { - items.push_back( item ); - item->AddRef(); - } - } - } -} - - -//------------------------------------------------------------------------------ -/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. -// --- -template -void ReadRefItems( Reader & in, std::vector< SPtr > & items ) -{ - size_t cnt = ReadCOUNT( in ); - - if ( in.good() && cnt > 0 ) { - for ( size_t i = 0; i < cnt; ++i ) { - Type * item = NULL; - in >> item; - if ( item != NULL ) - items.push_back( SPtr(item) ); - } - } -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Отцепить от массива и уменьшить счетчик ссылок. - \en Detach from array and decrease reference counter. \~ - \details \ru Отцепить от массива и уменьшить счетчик ссылок без проверок.\n - \en Detach from array and decrease reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] index - \ru Номер элемента. Не проверяется на корректность. - \en Index of element. Isn't checked for correctness. \~ -*/ -// --- -template -void ReleaseAndDetachItem_( Vector & items, size_t index ) -{ - items[index]->Release(); - items.erase( items.begin() + index ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить объект и увеличить счетчик ссылок. - \en Add an object and increase reference counter. \~ - \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n - \en Add an object and increase reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] newItem - \ru Новый элемент. - \en New element. \~ -*/ -// --- -template -void AddRefAndAddItem_( Vector & items, Type * newItem ) -{ - newItem->AddRef(); - items.push_back( newItem ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить объект и увеличить счетчик ссылок. - \en Add an object and increase reference counter. \~ - \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n - \en Add an object and increase reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] newItem - \ru Новый элемент. - \en New element. \~ - \param[in] index - \ru Номер элемента. Не проверяется на корректность. - \en Index of element. Isn't checked for correctness. \~ -*/ -// --- -template -void AddRefAndAddAtItem_( Vector & items, Type * newItem, size_t index ) -{ - newItem->AddRef(); - items.insert( index, newItem ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Отцепить от массива и уменьшить счетчик ссылок. - \en Detach from array and decrease reference counter. \~ - \details \ru Отцепить от массива и уменьшить счетчик ссылок без проверок.\n - \en Detach from array and decrease reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] index - \ru Номер элемента. Не проверяется на корректность. - \en Index of element. Isn't checked for correctness. \~ -*/ -// --- -template -void ReleaseAndDetachItem_( std::vector > & items, size_t index ) -{ - items[index].reset(); - items.erase( items.begin() + index ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить объект и увеличить счетчик ссылок. - \en Add an object and increase reference counter. \~ - \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n - \en Add an object and increase reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] newItem - \ru Новый элемент. - \en New element. \~ -*/ -// --- -template -void AddRefAndAddItem_( std::vector > & items, Type * newItem ) -{ - items.push_back( SPtr(newItem) ); -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить объект и увеличить счетчик ссылок. - \en Add an object and increase reference counter. \~ - \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n - \en Add an object and increase reference counter without checks.\n \~ - \param[in,out] items - \ru Множество элементов. - \en An array of elements. \~ - \param[in] newItem - \ru Новый элемент. - \en New element. \~ - \param[in] index - \ru Номер элемента. Не проверяется на корректность. - \en Index of element. Isn't checked for correctness. \~ -*/ -// --- -template -void AddRefAndAddAtItem_( std::vector > & items, Type * newItem, size_t index ) -{ - items.insert( items.begin() + index, SPtr(newItem) ); -} - - -//------------------------------------------------------------------------------ -/// \ru Отцепить объект из владеющего указателя. \en Detach object from owning pointer. -// --- -template -inline Type * DetachItem( SPtr & itemOwner ) -{ - return itemOwner.detach(); -} - - -//------------------------------------------------------------------------------ -/// \ru Заменить объект на копию. \en Replace object by copy. -// --- -template -void ReplaceByCopy( Type *& item ) -{ - if ( item != NULL ) { - Type * temp = (Type *)&item->Duplicate(); - ::DeleteItem( item ); - item = temp; - } -} - - -//------------------------------------------------------------------------------ -/// \ru Включить габариты объектов массива в общий габарит. \en Include bounding boxes of an array of objects in a common bounding box. -//--- -template -void AddYourGabaritTo( Objects & objects, Gab & gab ) -{ - for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) { - if ( objects[k] ) - objects[k]->AddYourGabaritTo( gab ); - } -} - - -#endif // __REFERENCE_ITEM_H +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Счетчик ссылок (владельцев объекта). + \en Reference counter (of an object owners). \~ + +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __REFERENCE_ITEM_H +#define __REFERENCE_ITEM_H + + +#include +#include +#include +#include +#include +#include +#include +//#include +#include + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Типы объекта со счетчиком ссылок. + \en Types of object with reference counter. \~ + \details \ru Тип несёт информацию об объекте-наследнике. \n + \en Type has an information of inheritor object. \n \~ + \ingroup Geometric_Items +*/ +// --- +enum MbeRefType +{ + rt_RefItem = 0, ///< \ru Некоторый объект. \en Some object. + rt_PlaneItem, ///< \ru Двумерный геометрически объект. \en Two-dimensional geometric object. + rt_SpaceItem, ///< \ru Трехмерный геометрический объект. \en Three-dimensional geometric object. + rt_TopItem, ///< \ru Топологический объект. \en A topological object. + rt_Creator, ///< \ru Строитель объекта. \en Object constructor + rt_Attribute, ///< \ru Атрибут объекта. \en Attribute of an object. + rt_Primitive, ///< \ru Элемент полигонального объекта. \en Element of polygonal object. + // \ru В конец можно добавлять новые нужные \en It is possible to add new necessary ones to the end +}; + + +class MATH_CLASS MbRefItem; +namespace c3d // namespace C3D +{ +typedef SPtr RefItemSPtr; +typedef SPtr ConstRefItemSPtr; + +typedef std::vector RefItemsVector; +typedef std::vector ConstRefItemsVector; + +typedef std::vector RefItemsSPtrVector; +typedef std::vector ConstRefItemsSPtrVector; +} + +//---------------------------------------------------------------------------------------- +/** \brief \ru Объект с подсчетом ссылок. + \en Reference-counted object. \~ + \details \ru Объект, считающий количество своих владельцев. \n + Используется в качестве одного из родительских классов геометрических объектов. \n + Если наследник данного класса захватывается другим объектом или алгоритмом,то другой + объект или алгоритм должен увеличить счетчик ссылок на единицу методом AddRef(). + При отказе от использования наследника данного класса другим объектом (например, при деструктурировании) + или алгоритмом другой объект или алгоритм должны уменьшить счетчик ссылок на единицу + методом Release(). Такое правило позволяет использовать одного и того же наследника + данного класса несколькими другим объектами или алгоритмами одновременно и гарантирует, + что объект будет удалён, когда он станет никому не нужен.\n + + \en Object counting number of its owners. \n + Is used as one of parent classes of geometric objects. \n + If inheritor of current class is captured by other object or algorithm, then the other + object or algorithm has to increase reference counter by one by AddRef() method. + At refusal of use of the successor of this class by other object (for example at destruction) + or by algorithm, the other object or algorithm has to decrease reference counter + by one by Release() method. Such rule allows to use the same inheritor of current + class simultaneously by several other objects or algorithms and guarantees that the + object will be removed when it becomes unnecessary.\n \~ + + \note \ru Рекомендуется применение автоматических указателей типа SPtr к экземплярам + данного класса. Это упростит работу с кодом, где нужно позаботится об автоматической + сборке мусора. + \en It is recommended to use smart pointers of type SPtr to instances of + this class. This will simplify the work with the code where you want to take care of + the automatic garbage collection. \~ + \sa #SPtr + \ingroup Geometric_Items +*/ +// --- +class MATH_CLASS MbRefItem { +private: + mutable use_count_type useCount; ///< \ru Счетчик ссылок на объект, изменяемый владельцами объекта. \en A counter of references to an object modifiable by owners of object. +public: + /// \ru Конструктор без параметров. \en Constructor without parameters. + MbRefItem(); +protected: + virtual ~MbRefItem(); + +public: + /** \ru \name Функции регистрации ссылок на геометрический объект владельцами объекта. + \en \name Functions for registration of references to geometric object by owners of object. + \{ */ + /// \ru Выдать количество ссылок (выдать количество владельцев объекта). \en Get count of references (get count of owners of an object). + refcount_t GetUseCount() const; + /// \ru Увеличить количество ссылок на единицу. \en Increase count of references by one. + refcount_t AddRef() const; + /// \ru Уменьшить количество ссылок на единицу. \en Decrease count of references by one. + refcount_t DecRef() const; + /// \ru Уменьшить количество ссылок на единицу и, если количество ссылок стало равным нулю, удалить себя. \en Decrease count of references by one and if count of references became zero, then remove itself. + refcount_t Release() const; + /** \} */ +public: + /// \ru Регистрационный тип (для копирования, дублирования). \en Registration type (for copying, duplication). + virtual MbeRefType RefType() const; + +OBVIOUS_PRIVATE_COPY( MbRefItem ) +}; + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Шаблон класса сериализации (порядковой нумерации создаваемых объектов). + \en Serialization class template (ordinal numbering of created objects). \~ + \details \ru Шаблон класса сериализации (порядковой нумерации создаваемых объектов). \n + Применение: наследовать от данного класса. + Аргумент шаблона позволяет иметь несколько сериализаций одновременно: \n + если нужна сериализация объектов класса T, можно записать class T: virtual public MbSerialItem \n + если объекты U должны иметь ту же сериализацию, можно записать class U: virtual public MbSerialItem \n + или же создать пустой класс для сериализации типа class MbBasicSerializer {} + и наследоваться от MbSerialItem. \n + + \en Serialization class template (ordinal numbering of created objects). \n + How to use: inherit from this class. \n + The template argument allows multiple serializations at the same time: \n + if you need serialization of objects of class T, you can write class T: virtual public MbSerialItem \n + if U objects must have the same serialization, you can write a class U: virtual public MbSerialItem \n + or you can create an empty class to serialize the class type MbBasicSerializer \n + and inherit it from MbSerialItem . \n \~ + + \ingroup Geometric_Items +*/ +// --- +template class MbSerialItem { +private: + static serial_type serialLast; ///< \ru Индекс последнего созданного объекта (0 в случае отсутствия объектов). \en Index of the last object created (0 if there are no objects). + static serial_type serialCount; ///< \ru Счетчик объектов. \en Counter of objects. + serial_type serialThis; ///< \ru Уникальный порядковый номер объекта, выдается при создании. В дальнейшем не меняется. \en The unique sequence number of the object, issued at creation. In the future it is not changed. +public: + MbSerialItem(); ///< \ru Конструктор. \en Constructor. +protected: + virtual ~MbSerialItem(); ///< \ru Деструктор. \en Destructor. +public: + size_t GetSerial() const { return SerialTypeValue( serialThis ); } ///< \ru Выдать порядковый номер объекта. \en Get object serial identifier. + +OBVIOUS_PRIVATE_COPY( MbSerialItem ) +}; + + +// \ru Инициализация статических переменных шаблона класса сериализации. \en Initializing static variables of the serialization class template. +template serial_type MbSerialItem::serialLast( 0 ); +template serial_type MbSerialItem::serialCount( 0 ); + + +//----------------------------------------------------------------------------- +// \ru Конструктор. \en Constructor. +// --- +template MbSerialItem::MbSerialItem() +{ // Set the serial number and promote the counters + PRECONDITION( serialLast != SYS_MAX_T ); // number overflow + serialThis = ++serialLast; + ++serialCount; +} + + +//----------------------------------------------------------------------------- +// \ru Деструктор. \en Destructor. +// --- +template MbSerialItem::~MbSerialItem() +{ + PRECONDITION( SerialTypeValue( serialCount ) != 0 ); // If it equals 0 then it means that the counter is damaged. + if ( --serialCount == 0 ) // The case when the last of the instantiated objects is deleted + serialLast = 0; // Set serialization to zero - at the subsequent creation of objects the numbering will start again (serially since 1). +} + + + +//------------------------------------------------------------------------------ +/// \ru Удалить объект без ссылок. \en Delete an object without references. +//--- +template +inline void DeleteMatItem( Type *& item ) +{ + if ( item != NULL ) { + delete item; + item = NULL; + } +} + + +//------------------------------------------------------------------------------ +/// \ru Удалить объекты без ссылок. \en Delete objects without references. +// --- +template +void DeleteMatItems( Vector & items ) +{ + for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) + ::DeleteMatItem( items[k] ); + items.clear(); +} + + +//------------------------------------------------------------------------------ +/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. +// --- +template +Type & DuplicateIfUsed( Type & item ) +{ + Type * resItem = &item; + if ( item.GetUseCount() > 0 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. + resItem = static_cast( &item.Duplicate() ); + + return *resItem; +} + + +//------------------------------------------------------------------------------ +/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. +// --- +template +Type & DuplicateIfUsed( Type & item, RegType * iReg ) +{ + Type * resItem = &item; + if ( item.GetUseCount() > 0 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. + resItem = static_cast( &item.Duplicate( iReg ) ); + + return *resItem; +} + + +//------------------------------------------------------------------------------ +/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. +// --- +template +Type * DuplicateIfUsed( SPtr & item ) +{ + if ( item == NULL ) + return NULL; + Type * resItem = item.get(); + if ( item->GetUseCount() > 1 ) // \ru Если оригинал, то делаем копию. \en If there is original, then make a copy. + resItem = static_cast( &item->Duplicate() ); + + return resItem; +} + + +//------------------------------------------------------------------------------ +/// \ru Сделать копию, если объект используется, иначе вернуть оригинал. \en Create a copy if object is used, otherwise return original. +// --- +template +Type * DuplicateIfUsed( SPtr & item, RegType * iReg ) +{ + if ( item == NULL ) + return 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 ) ); + + return resItem; +} + +//------------------------------------------------------------------------------ +/// \ru Удалить объект, если он больше никому не нужен. \en Delete an object if it is unnecessary. +// --- +template +void DeleteItem( Type *& item ) +{ + if ( item != NULL ) { + if ( item->GetUseCount() < 1 ) + delete item; + item = NULL; + } +} + +//------------------------------------------------------------------------------ +/// \ru Освободить ссылку на объект. \en Release the reference to object. +// --- +template +void ReleaseItem( Type *& item ) +{ + if ( item != NULL ) { + item->Release(); + item = NULL; + } +} + +//------------------------------------------------------------------------------ +/// \ru Захватить объект. \en Catch an object. +// --- +template +void AddRefItem( const Type * item ) +{ + if ( item != NULL ) + item->AddRef(); +} + +//------------------------------------------------------------------------------ +/// \ru Отпустить объект без удаления. \en Detach an object without removing. +// --- +template +void DecRefItem( const Type * item ) +{ + if ( item != NULL ) + item->DecRef(); +} + + +//------------------------------------------------------------------------------ +/// \ru Захватить объекты. \en Catch objects. +// --- +template +void AddRefItems( const Vector & items ) +{ + for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { + if ( items[k] != NULL ) + items[k]->AddRef(); + } +} + + +//------------------------------------------------------------------------------ +/// \ru Отпустить объекты без удаления. \en Detach objects without removing. +// --- +template +void DecRefItems( const Vector & items ) +{ + for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) { + if ( items[k] != NULL ) + items[k]->DecRef(); + } +} + + +//------------------------------------------------------------------------------ +/// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. +// --- +template +void DeleteItems( Vector & items ) +{ + for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) + ::DeleteItem( items[k] ); + items.clear(); +} + + +//------------------------------------------------------------------------------ +/// \ru Отпустить объекты с возможным удалением. \en Detach objects with possible removing. +// --- +template +void ReleaseItems( Vector & items ) +{ + for ( size_t k = 0, itemsCnt = items.size(); k < itemsCnt; ++k ) + ::ReleaseItem( items[k] ); + items.clear(); +} + + +//------------------------------------------------------------------------------ +/// \ru Удалить никому не нужные объекты. \en Remove unnecessary objects. +// --- +template +void DeleteItems( Vector & 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 Detach objects with possible removing. +// --- +template +void ReleaseItems( Vector & 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 Put elements with capturing and with possible copying. +// --- +template +void AddRefItems( const TypeVector & srcItems, bool same, RPArray & dstItems ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); + dstItem->AddRef(); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. +// --- +template +void AddRefItems( const TypeVector & srcItems, bool same, std::vector< SPtr > & dstItems ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + SPtr dstItem; + dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. +// --- +template +void AddRefItems( const TypeVector & srcItems, bool same, std::vector & dstItems ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate() ); + dstItem->AddRef(); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. +// --- +template +void AddRefRegItems( const TypeVector & srcItems, bool same, RPArray & dstItems, RegType * iReg ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItem->AddRef(); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. +// --- +template +void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector< SPtr > & dstItems, RegType * iReg ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + SPtr dstItem; + dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Переложить элементы с захватом и возможным копированием. \en Put elements with capturing and with possible copying. +// --- +template +void AddRefRegItems( const TypeVector & srcItems, bool same, std::vector & dstItems, RegType * iReg ) +{ + 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 ) { + Type * srcItem = &const_cast(*srcItems[k]); + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItem->AddRef(); + dstItems.push_back( dstItem ); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. +// --- +template +bool IsItemSame( const Item * item1, const Item * item2, double accuracy ) +{ + if ( (item1 == NULL) && (item2 == NULL) ) + return true; + else if ( (item1 != NULL) && (item2 != NULL) && item1->IsSame( *item2, accuracy ) ) + return true; + return false; +} + + +//------------------------------------------------------------------------------ +/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. +// --- +template +bool AreItemsSame( const Vector & items1, const Vector & items2, double accuracy ) +{ + bool areEqual = false; + + const size_t cnt = items1.size(); + 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 ) ) { + areEqual = false; + break; + } + } + } + + return areEqual; +} + + +//------------------------------------------------------------------------------ +/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. +// --- +template +bool AreObjectsSame( const Vector & items1, const Vector & items2, double accuracy ) +{ + bool areEqual = false; + + const size_t cnt = items1.size(); + if ( cnt == items2.size() ) { + areEqual = true; + for ( size_t k = 0; k < cnt; ++k ) { + if ( !items1[k].IsSame( items2[k], accuracy ) ) { + areEqual = false; + break; + } + } + } + + return areEqual; +} + + +//------------------------------------------------------------------------------ +/// \ru Являются ли объекты подобными. \en Determine whether the objects are similar. +// --- +template +bool AreItemsSimilar( const Vector & items1, const Vector & items2 ) +{ + bool areEqual = false; + + const size_t cnt = items1.size(); + 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] ) ) { + areEqual = false; + break; + } + } + } + + return areEqual; +} + + +//------------------------------------------------------------------------------ +/// \ru Сделать равными. \en Make equal. +// --- +template +bool SetItemsEqual( const Vector & srcItems, Vector & dstItems ) +{ + bool setEqual = false; + + size_t cnt = srcItems.size(); + if ( cnt == dstItems.size() ) { + setEqual = ::AreItemsSimilar( srcItems, dstItems ); + + if ( setEqual ) { + for ( size_t k = 0; k < cnt; ++k ) { + if ( srcItems[k] == NULL || dstItems[k] == NULL || !dstItems[k]->SetEqual( *srcItems[k] ) ) { + setEqual = false; + break; + } + } + } + } + + return setEqual; +} + + +//------------------------------------------------------------------------------ +/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). +// --- +template +void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, RPArray & dstItems ) +{ + C3D_ASSERT( dstItems.size() < 1 ); + dstItems.Reserve( srcItems.size() ); + for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { + Type * srcItem = srcItems[k]; + if ( srcItem != NULL ) { + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItems.push_back( dstItem ); + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). +// --- +template +void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std::vector< SPtr > & dstItems ) +{ + C3D_ASSERT( dstItems.size() < 1 ); + dstItems.reserve( dstItems.size() + srcItems.size() ); + for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { + Type * srcItem = srcItems[k]; + if ( srcItem != NULL ) { + SPtr dstItem; + dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItems.push_back( dstItem ); + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Дублировать c регистратором (опционально переложить оригиналы). \en Duplicate with registrator (optionally put originals). +// --- +template +void DuplicateItems( const TypeVector & srcItems, RegType * iReg, bool same, std::vector & dstItems ) +{ + C3D_ASSERT( dstItems.size() < 1 ); + dstItems.reserve( dstItems.size() + srcItems.size() ); + for ( size_t k = 0, cnt = srcItems.size(); k < cnt; ++k ) { + Type * srcItem = srcItems[k]; + if ( srcItem != NULL ) { + Type * dstItem = same ? srcItem : static_cast( &srcItem->Duplicate( iReg ) ); + dstItems.push_back( dstItem ); + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Преобразовать элементы согласно матрице. \en Transform elements according to the matrix. +// --- +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 ) + items[k]->Transform( matr, iReg ); + } +} + +//------------------------------------------------------------------------------ +/// \ru Преобразовать элементы согласно матрице. \en Transform elements according to the matrix. +// --- +template +void TransformObjects( Array & objects, const Matrix & matr ) +{ + for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) + objects[k].Transform( matr ); +} + + +//------------------------------------------------------------------------------ +/// \ru Сдвинуть вдоль объекты вектора. \en Translate objects along a vector. +// --- +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 ) + items[k]->Move( to, iReg ); + } +} + +//------------------------------------------------------------------------------ +/// \ru Сдвинуть вдоль объекты вектора. \en Translate objects along a vector. +// --- +template +void MoveObjects( Array & objects, const Vector & to ) +{ + for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) + objects[k].Move( to ); +} + + +//------------------------------------------------------------------------------ +/// \ru Повернуть вокруг оси. \en Rotate about an axis. +// --- +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 ) + items[k]->Rotate( axis, angle, iReg ); + } +} + +//------------------------------------------------------------------------------ +/// \ru Повернуть вокруг оси. \en Rotate about an axis. +// --- +template +void RotateObjects( Array & objects, const Axis & axis, double angle ) +{ + for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) + objects[k].Rotate( axis, angle ); +} + + +//------------------------------------------------------------------------------ +/// \ru Запись объектов в поток. \en Write objects to the stream. +// --- +template +void WriteRefItems( const Vector & items, Writer & out ) +{ + size_t k, cnt = items.size(); + + for ( k = 0; k < cnt; ++k ) { + if ( items[k] == NULL ) + cnt--; + } + + WriteCOUNT( out, cnt ); + + if ( out.good() ) { + for ( k = 0; k < cnt; ++k ) { + if ( items[k] != NULL ) { + items[k]->PrepareWrite(); + out << &(*items[k]); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Запись объекты в поток. \en Write objects to the stream. +// --- +template +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 ) + cnt--; + } + + WriteCOUNT( out, cnt ); + + if ( out.good() ) { + for ( k = 0; k < cnt; ++k ) { + if ( items[k] != NULL ) { + items[k]->PrepareWrite(); + out << items[k].get(); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. +// --- +template +void ReadRefItems( Reader & in, RPArray & items ) +{ + size_t cnt = ReadCOUNT( in ); + + if ( in.good() && cnt > 0 ) { + items.reserve( items.size() + cnt ); + + for ( size_t i = 0; i < cnt; ++i ) { + Type * item = NULL; + in >> item; + if ( item != NULL ) { + items.push_back( item ); + item->AddRef(); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. +// --- +template +void ReadRefItems( Reader & in, std::vector & items ) +{ + size_t cnt = ReadCOUNT( in ); + + if ( in.good() && cnt > 0 ) { + for ( size_t i = 0; i < cnt; ++i ) { + Type * item = NULL; + in >> item; + if ( item != NULL ) { + items.push_back( item ); + item->AddRef(); + } + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Чтение массива объектов из потока с захватом. \en Read an array of objects with capturing from the stream. +// --- +template +void ReadRefItems( Reader & in, std::vector< SPtr > & items ) +{ + size_t cnt = ReadCOUNT( in ); + + if ( in.good() && cnt > 0 ) { + for ( size_t i = 0; i < cnt; ++i ) { + Type * item = NULL; + in >> item; + if ( item != NULL ) + items.push_back( SPtr(item) ); + } + } +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Отцепить от массива и уменьшить счетчик ссылок. + \en Detach from array and decrease reference counter. \~ + \details \ru Отцепить от массива и уменьшить счетчик ссылок без проверок.\n + \en Detach from array and decrease reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] index - \ru Номер элемента. Не проверяется на корректность. + \en Index of element. Isn't checked for correctness. \~ +*/ +// --- +template +void ReleaseAndDetachItem_( Vector & items, size_t index ) +{ + items[index]->Release(); + items.erase( items.begin() + index ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить объект и увеличить счетчик ссылок. + \en Add an object and increase reference counter. \~ + \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n + \en Add an object and increase reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] newItem - \ru Новый элемент. + \en New element. \~ +*/ +// --- +template +void AddRefAndAddItem_( Vector & items, Type * newItem ) +{ + newItem->AddRef(); + items.push_back( newItem ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить объект и увеличить счетчик ссылок. + \en Add an object and increase reference counter. \~ + \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n + \en Add an object and increase reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] newItem - \ru Новый элемент. + \en New element. \~ + \param[in] index - \ru Номер элемента. Не проверяется на корректность. + \en Index of element. Isn't checked for correctness. \~ +*/ +// --- +template +void AddRefAndAddAtItem_( Vector & items, Type * newItem, size_t index ) +{ + newItem->AddRef(); + items.insert( index, newItem ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Отцепить от массива и уменьшить счетчик ссылок. + \en Detach from array and decrease reference counter. \~ + \details \ru Отцепить от массива и уменьшить счетчик ссылок без проверок.\n + \en Detach from array and decrease reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] index - \ru Номер элемента. Не проверяется на корректность. + \en Index of element. Isn't checked for correctness. \~ +*/ +// --- +template +void ReleaseAndDetachItem_( std::vector > & items, size_t index ) +{ + items[index].reset(); + items.erase( items.begin() + index ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить объект и увеличить счетчик ссылок. + \en Add an object and increase reference counter. \~ + \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n + \en Add an object and increase reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] newItem - \ru Новый элемент. + \en New element. \~ +*/ +// --- +template +void AddRefAndAddItem_( std::vector > & items, Type * newItem ) +{ + items.push_back( SPtr(newItem) ); +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить объект и увеличить счетчик ссылок. + \en Add an object and increase reference counter. \~ + \details \ru Добавить объект и увеличить счетчик ссылок без проверок.\n + \en Add an object and increase reference counter without checks.\n \~ + \param[in,out] items - \ru Множество элементов. + \en An array of elements. \~ + \param[in] newItem - \ru Новый элемент. + \en New element. \~ + \param[in] index - \ru Номер элемента. Не проверяется на корректность. + \en Index of element. Isn't checked for correctness. \~ +*/ +// --- +template +void AddRefAndAddAtItem_( std::vector > & items, Type * newItem, size_t index ) +{ + items.insert( items.begin() + index, SPtr(newItem) ); +} + + +//------------------------------------------------------------------------------ +/// \ru Отцепить объект из владеющего указателя. \en Detach object from owning pointer. +// --- +template +inline Type * DetachItem( SPtr & itemOwner ) +{ + return itemOwner.detach(); +} + + +//------------------------------------------------------------------------------ +/// \ru Заменить объект на копию. \en Replace object by copy. +// --- +template +void ReplaceByCopy( Type *& item ) +{ + if ( item != NULL ) { + Type * temp = (Type *)&item->Duplicate(); + ::DeleteItem( item ); + item = temp; + } +} + + +//------------------------------------------------------------------------------ +/// \ru Включить габариты объектов массива в общий габарит. \en Include bounding boxes of an array of objects in a common bounding box. +//--- +template +void AddYourGabaritTo( Objects & objects, Gab & gab ) +{ + for ( size_t k = 0, cnt = objects.size(); k < cnt; ++k ) { + if ( objects[k] ) + objects[k]->AddYourGabaritTo( gab ); + } +} + + +#endif // __REFERENCE_ITEM_H diff --git a/C3d/Include/region.h b/C3d/Include/region.h index 8cde1e6..cc0c05c 100644 --- a/C3d/Include/region.h +++ b/C3d/Include/region.h @@ -64,19 +64,19 @@ public: 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 & matr, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ); // \ru Преобразовать согласно матрице. \en Transform according to the matrix. - virtual void Move ( const MbVector & to, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ); // \ru Сдвинуть вдоль вектора. \en Move along a vector. - virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * iReg = NULL, const MbSurface * newSurface = NULL ); - virtual bool IsSame ( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. - virtual bool SetEqual ( const MbPlaneItem & item ); // \ru Сделать объекты равным. \en Make objects equal. - virtual void AddYourGabaritTo( MbRect & r ) const; // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. - virtual bool IsVisibleInRect( const MbRect & r, bool exact = false ) const; // \ru Виден ли объект в заданном прямоугольнике. \en Whether the object is visible in the given rectangle - virtual double DistanceToPoint( const MbCartPoint & to ) const; // \ru Вычислить расстояние до точки to. \en Calculate the distance to a point 'to'. - virtual bool DistanceToPointIfLess( const MbCartPoint & to, - double & distance ) const; // \ru Вычислить расстояние до точки to, если оно меньше d. \en Calculate the distance to the point 'to' if it is less than d. - virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. + 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 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. + virtual bool IsVisibleInRect( const MbRect &, bool exact = false ) const; // \ru Виден ли объект в заданном прямоугольнике. \en Whether the object is visible in the given rectangle + virtual double DistanceToPoint( const MbCartPoint & ) const; // \ru Вычислить расстояние до точки to. \en Calculate the distance to a point 'to'. + virtual bool DistanceToPointIfLess( const MbCartPoint &, + double & distance ) const; // \ru Вычислить расстояние до точки to, если оно меньше d. \en Calculate the distance to the point 'to' if it is less than d. + virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. - virtual MbProperty & CreateProperty( MbePrompt name ) const; // \ru Создать собственное свойство. \en Create a custom property. + virtual MbProperty & CreateProperty( MbePrompt ) const; // \ru Создать собственное свойство. \en Create a custom property. 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( MbControlData & ) const; // \ru Выдать контрольные точки объекта. \en Get control points of object. @@ -107,7 +107,21 @@ public: /// \ru Отсоединить используемые контуры и удалить остальные. \en Detach used contours and delete other. void DeleteContours(); /// \ru Отцепить все контуры региона без удаления. \en Detach all region contours without deletion. - void DetachContours( RPArray & ); + template + void DetachContours( ContoursVector & dstContours ) + { + size_t addCnt = contours.size(); + dstContours.reserve( dstContours.size() + addCnt ); + c3d::PlaneContourSPtr contour; + for ( size_t k = 0; k < addCnt; ++k ) { + ::DecRefItem( contours[k] ); + contour = contours[k]; + dstContours.push_back( contour ); + ::DetachItem( contour ); + } + contours.clear(); + setCorrect = ts_neutral; + } /// \ru Сделать регион корректным (если это нужно и возможно). \en Make region correct (if this is possible). bool SetCorrect(); diff --git a/C3d/Include/sheet_metal_param.h b/C3d/Include/sheet_metal_param.h index da57f9b..3ee36ae 100644 --- a/C3d/Include/sheet_metal_param.h +++ b/C3d/Include/sheet_metal_param.h @@ -111,6 +111,11 @@ public: return isSame; } + ///\ru Трансформировать по матрице. \en To transform by the matrix. + void Transform( const MbMatrix3D & matr ) { + matr.TransformLength( radius ); + } + KNOWN_OBJECTS_RW_REF_OPERATORS( MbBendValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -268,6 +273,12 @@ public: return isSame; } + void Transform( const MbMatrix3D & matr ) { + matr.TransformLength( width ); + matr.TransformLength( depth ); + matr.TransformLength( radius ); + } + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSlotValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -553,6 +564,13 @@ struct MATH_CLASS MbClosedCornerValues { return isSame; } + ///\ru Трансформировать по матрице. \en To transform by the matrix. + void Transform( const MbMatrix3D & matr ) { + matr.TransformLength( gap ); + matr.TransformLength( diameter ); + matr.TransformLength( shift ); + } + KNOWN_OBJECTS_RW_REF_OPERATORS( MbClosedCornerValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -663,6 +681,14 @@ public: return isSame; } + + ///\ru Трансформировать по матрице. \en To transform by the matrix. + void Transform( const MbMatrix3D & matr ) { + matr.TransformLength( distance ); + matr.TransformLength( widening ); + matr.TransformLength( length ); + } + }; // \ru Параметры одного края сгиба \en Parameters of one boundary of bend public: @@ -806,6 +832,18 @@ public: return isSame; } + ///\ru Трансформировать по матрице. \en To transform by the matrix. + void Transform( const MbMatrix3D & matr ) { + MbBendValues::Transform( matr ); + matr.TransformLength( deepness ); + sideLeft.Transform( matr ); + sideRight.Transform( matr ); + miterBegin.Transform( matr ); + miterEnd.Transform( matr ); + miterMiddle.Transform( matr ); + slot.Transform( matr ); + } + KNOWN_OBJECTS_RW_REF_OPERATORS( MbBendByEdgeValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; @@ -1645,9 +1683,9 @@ public: /// \ru Конструктор по умолчанию. \en Default constructor. MbSMBendNames() : MbBendValues(), - segName1 ( SimpleName(SIMPLENAME_MAX) ), - segName2 ( SimpleName(SIMPLENAME_MAX) ), - extraName( SimpleName(SIMPLENAME_MAX) ), + segName1 ( SimpleName(c3d::SIMPLENAME_MAX) ), + segName2 ( SimpleName(c3d::SIMPLENAME_MAX) ), + extraName( SimpleName(c3d::SIMPLENAME_MAX) ), groupNumber( SYS_MAX_UINT ), innerFaceName(), outerFaceName() {} @@ -1857,51 +1895,127 @@ private: //------------------------------------------------------------------------------ /** \brief \ru Параметры штамповки телом-инструментом. \en The parameters of stamping by a tool solid. \~ - \details \ru Параметры шатмповки телом-инструментом определяют толщину формованной части и радиус скругления основания.\n - \en The parameters of stamping by a tool solid is specified a thickness of a stamped part and fillet radius of stamping base.\n \~ + \details \ru Параметры шатмповки телом-инструментом определяют толщину формованной части и радиусы скругления основания.\n + \en The parameters of stamping by a tool solid is specified a thickness of a stamped part and fillet radiuses of stamping base.\n \~ \ingroup Build_Parameters */ // --- -struct MATH_CLASS MbUserStampingValues { - double baseFilletRadius; ///< \ru Радиус скругления основания (отрицательное значение запрещает скругление). \en Fillet radius of base (negative value prohibits fillet). - double stampThickness; ///< \ru Толщина формованной части. \en Thickness of a stamped part. +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 stampThickness; ///< \ru Толщина формованной части. \en Thickness of a stamped part. + bool constantThickness; ///< \ru Флаг постоянной толщины на штамповке. \en Constant thickness flag. /// \ru Конструктор по умолчанию. \en Default constructor. - MbUserStampingValues() : - baseFilletRadius ( 0.0 ), - stampThickness ( 0.0 ) + MbToolStampingValues() : + punchFilletRadius( 0.0 ), + dieFilletRadius ( 0.0 ), + stampThickness ( 0.0 ), + constantThickness( true ) {} /// \ru Конструктор копирования. \en Copy-constructor. - MbUserStampingValues( const MbUserStampingValues & other ) : - baseFilletRadius ( other.baseFilletRadius ), - stampThickness ( other.stampThickness ) + MbToolStampingValues( const MbToolStampingValues & other ) : + punchFilletRadius( other.punchFilletRadius ), + dieFilletRadius ( other.dieFilletRadius ), + stampThickness ( other.stampThickness ), + constantThickness( other.constantThickness ) {} /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. - MbUserStampingValues( double baseRad, double thick ) : - baseFilletRadius ( baseRad ), - stampThickness ( thick ) + MbToolStampingValues( double punchRad, double dieRad, double thick, bool constThick ) : + punchFilletRadius( punchRad ), + dieFilletRadius ( dieRad ), + stampThickness ( thick ), + constantThickness( constThick ) {} /// \ru Оператор присваивания. \en Assignment operator. - MbUserStampingValues & operator = ( const MbUserStampingValues &other ) { Init( other ); return *this; } + MbToolStampingValues & operator = ( const MbToolStampingValues &other ) { Init( other ); return *this; } /// \ru Инициализация по другому объекту. \en Initialization by another object. - void Init( const MbUserStampingValues & other ) { - baseFilletRadius = other.baseFilletRadius; + void Init( const MbToolStampingValues & other ) { + punchFilletRadius = other.punchFilletRadius; + dieFilletRadius = other.dieFilletRadius; stampThickness = other.stampThickness; + constantThickness = other.constantThickness; } ///\ru Являются ли объекты равными? \en Determine whether an object is equal? - bool IsSame( const MbUserStampingValues & other, double accuracy ) const { + bool IsSame( const MbToolStampingValues & other, double accuracy ) const { bool isSame = false; - if ( ::fabs(baseFilletRadius - other.baseFilletRadius) < accuracy && - ::fabs(stampThickness - other.stampThickness) < accuracy ) + if ( ::fabs(punchFilletRadius - other.punchFilletRadius) < accuracy && + ::fabs(dieFilletRadius - other.dieFilletRadius) < accuracy && + ::fabs(stampThickness - other.stampThickness) < accuracy && + constantThickness == other.constantThickness ) isSame = true; return isSame; } - KNOWN_OBJECTS_RW_REF_OPERATORS( MbUserStampingValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class + KNOWN_OBJECTS_RW_REF_OPERATORS( MbToolStampingValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class }; -#endif // __SHEET_METAL_PARAM_H \ No newline at end of file + +//------------------------------------------------------------------------------ +/** \brief \ru Параметры построения листового тела по произвольному телу. + \en The parameters of sheet metal solid building based on an arbitrary solid. \~ + \details \ru Параметры построения оболочки из листового материала на основе граней и ребер произвольного тела.\n + \en The parameters of the sheet metal shell based on faces and edges of an arbitrary solid.\n \~ + \ingroup Build_Parameters + \warning \ru В разработке. + \en Under development. \~ +*/ +// --- +struct MATH_CLASS MbSolidToSheetMetalValues { +public: + double k; ///< \ru Коэффициент, определяющий положение нейтрального слоя. \en Coefficient determining the position of the neutral layer. + double sheetThickness; ///< \ru Толщина листового тела. \en Thickness of a sheet solid. + double bendRadius; ///< \ru Внутренний радиус сгиба. \en The internal radius of the bend. + SArray bendEdgesIndices; ///< \ru Индексы ребер сгиба. \en Indicies of bend edges. + SArray cutEdgesIndices; ///< \ru Индексы ребер разреза. \en Indicies of cut edges. + + /// \ru Конструктор по умолчанию. \en Default constructor. + MbSolidToSheetMetalValues() : + sheetThickness ( 1.0 ), + bendRadius ( 0.0 ), + bendEdgesIndices( ), + cutEdgesIndices ( ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbSolidToSheetMetalValues( const MbSolidToSheetMetalValues & other ) : + sheetThickness ( other.sheetThickness ), + bendRadius ( other.bendRadius ), + bendEdgesIndices( other.bendEdgesIndices ), + cutEdgesIndices ( other.cutEdgesIndices ) + {} + /// \ru Конструктор по конкретным параметрам. \en Constructor by specific parameters. + MbSolidToSheetMetalValues( double thick, double rad, SArray & bIndicies, SArray & cIndicies ) : + sheetThickness ( thick ), + bendRadius ( rad ), + bendEdgesIndices( bIndicies ), + cutEdgesIndices ( cIndicies ) + {} + + /// \ru Оператор присваивания. \en Assignment operator. + MbSolidToSheetMetalValues & operator = ( const MbSolidToSheetMetalValues &other ) { Init( other ); return *this; } + /// \ru Инициализация по другому объекту. \en Initialization by another object. + void Init( const MbSolidToSheetMetalValues & other ) { + sheetThickness = other.sheetThickness; + bendRadius = other.bendRadius; + bendEdgesIndices = other.bendEdgesIndices; + cutEdgesIndices = other.cutEdgesIndices; + } + + ///\ru Являются ли объекты равными? \en Determine whether an object is equal? + bool IsSame( const MbSolidToSheetMetalValues & other, double accuracy ) const { + bool isSame = false; + if ( ::fabs(sheetThickness - other.sheetThickness) < accuracy && + ::fabs(bendRadius - other.bendRadius) < accuracy ) + isSame = true; + + return isSame; + } + + KNOWN_OBJECTS_RW_REF_OPERATORS( MbSolidToSheetMetalValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class +}; + +#endif // __SHEET_METAL_PARAM_H diff --git a/C3d/Include/shell_history.h b/C3d/Include/shell_history.h index 5fddebc..1f117b6 100644 --- a/C3d/Include/shell_history.h +++ b/C3d/Include/shell_history.h @@ -52,12 +52,8 @@ public: RPArray & SetCopyFaces() { return copyFaces; } /// \ru Заменить в shell неизменённые copy-объекты на origin-объекты. \en Replace in 'shell' the unchanged 'copy'-objects by the 'origin'-objects. void SetOrigins ( MbFaceShell & shell ); - -private: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbShellHistory( const MbShellHistory & ); // \ru Не реализовано \en Not implemented - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbShellHistory & ); // \ru Не реализовано \en Not implemented + +OBVIOUS_PRIVATE_COPY( MbShellHistory ) }; diff --git a/C3d/Include/solid.h b/C3d/Include/solid.h index 2ceecc6..2aaafcb 100644 --- a/C3d/Include/solid.h +++ b/C3d/Include/solid.h @@ -143,7 +143,7 @@ public : 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 bool IsSame ( const MbSpaceItem &, double accuracy = LENGTH_EPSILON ) const; // \ru Являются ли объекты равными? \en Determine whether objects are equal. + 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. virtual double DistanceToPoint( const MbCartPoint3D & ) const; // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. @@ -396,7 +396,7 @@ public : MbFace * FindFaceByName ( const MbName & ); /// \ru Создать именователь тела. \en Create name-maker of solid. - MbSNameMaker GetYourName() const; + MbSNameMaker GetYourNameMaker() const; /// \ru Установить заданный флаг измененности для всех граней, рёбер и вершин. \en Set flag of changes for all the faces, edges and vertices. void SetOwnChangedThrough( MbeChangedType ); diff --git a/C3d/Include/space_instance.h b/C3d/Include/space_instance.h index cf887f5..63ba5d0 100644 --- a/C3d/Include/space_instance.h +++ b/C3d/Include/space_instance.h @@ -1,121 +1,121 @@ -////////////////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Вставка трёхмерного объекта. - \en Instance of three-dimensional object. \~ - -*/ -////////////////////////////////////////////////////////////////////////////////////////// - -#ifndef __SPACE_INSTANCE_H -#define __SPACE_INSTANCE_H - - -#include -#include -#include -#include - - -class MATH_CLASS MbLegend; -class MATH_CLASS MbPoint3D; -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbSurface; - - -class MATH_CLASS MbSpaceInstance; -namespace c3d // namespace C3D -{ -typedef SPtr SInstanceSPtr; -typedef SPtr ConstSInstanceSPtr; - -typedef std::vector SInstancesVector; -typedef std::vector ConstSInstancesVector; - -typedef std::vector SInstancesSPtrVector; -typedef std::vector ConstSInstancesSPtrVector; -} - - -//---------------------------------------------------------------------------------------- -/** \brief \ru Вставка трёхмерного объекта. - \en Instance of three-dimensional object. \~ - \details \ru Вставка позволяет работать с трёхмерным геометрическим объектом, как с - объектом геометричекой модели. Вставка позволяет использовать в геометричекой - модели любые другие объекты MbSpaceItem, например, резьбу и условные обозначения. - \en Instance allows to deal with three-dimensional object as with object of - geometric model. Instance allows to use any objects inherited from MbSpaceItem - such as thread and conventional notations in geometric model. \~ - \ingroup Model_Items -*/ -// --- -class MATH_CLASS MbSpaceInstance : public MbItem { -protected : - MbSpaceItem * spaceItem; ///< \ru Трёхмерный геометрический объект. \en Three-dimensional geometric object. - -protected : - /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. - explicit MbSpaceInstance( const MbSpaceInstance &, MbRegDuplicate * ); -public : - /// \ru Конструктор по вспомогательному объекту. \en Constructor by auxiliary item. - MbSpaceInstance( MbLegend & ); - /// \ru Конструктор по точке. \en Constructor by point. - MbSpaceInstance( MbPoint3D & ); - /// \ru Конструктор по кривой. \en Constructor by curve. - MbSpaceInstance( MbCurve3D & ); - /// \ru Конструктор по поверхности. \en Constructor by surface. - MbSpaceInstance( MbSurface & ); - /// \ru Деструктор. \en Destructor. - virtual ~MbSpaceInstance(); - -public : - VISITING_CLASS( MbSpaceInstance ); - - // \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 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. - 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 CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - - 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. - - // \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 Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). - virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; - // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ - virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, - RPArray & items, SArray & matrs ); - // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ - virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; - - /** \ru \name Общие функции вставки трёхмерного объекта. - \en \name Common functions of instance of three-dimensional object. - \{ */ - /// \ru Выдать трёхмерный геометрический объект. \en Get three-dimensional geometric object. - const MbSpaceItem * GetSpaceItem() const; - /// \ru Выдать трёхмерный геометрический объект для модификации. \en Get three-dimensional geometric object for modification. - MbSpaceItem * SetSpaceItem(); - /// \ru Заменить геометрический объект. \en Replace geometric object. - void SetSpaceItem( MbSpaceItem * init ); - /** \} */ - -DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpaceInstance ) -OBVIOUS_PRIVATE_COPY( MbSpaceInstance ) -}; - -IMPL_PERSISTENT_OPS( MbSpaceInstance ) - -#endif // __SPACE_INSTANCE_H +////////////////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Вставка трёхмерного объекта. + \en Instance of three-dimensional object. \~ + +*/ +////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef __SPACE_INSTANCE_H +#define __SPACE_INSTANCE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbLegend; +class MATH_CLASS MbPoint3D; +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbSurface; + + +class MATH_CLASS MbSpaceInstance; +namespace c3d // namespace C3D +{ +typedef SPtr SInstanceSPtr; +typedef SPtr ConstSInstanceSPtr; + +typedef std::vector SInstancesVector; +typedef std::vector ConstSInstancesVector; + +typedef std::vector SInstancesSPtrVector; +typedef std::vector ConstSInstancesSPtrVector; +} + + +//---------------------------------------------------------------------------------------- +/** \brief \ru Вставка трёхмерного объекта. + \en Instance of three-dimensional object. \~ + \details \ru Вставка позволяет работать с трёхмерным геометрическим объектом, как с + объектом геометричекой модели. Вставка позволяет использовать в геометричекой + модели любые другие объекты MbSpaceItem, например, резьбу и условные обозначения. + \en Instance allows to deal with three-dimensional object as with object of + geometric model. Instance allows to use any objects inherited from MbSpaceItem + such as thread and conventional notations in geometric model. \~ + \ingroup Model_Items +*/ +// --- +class MATH_CLASS MbSpaceInstance : public MbItem { +protected : + MbSpaceItem * spaceItem; ///< \ru Трёхмерный геометрический объект. \en Three-dimensional geometric object. + +protected : + /// \ru Конструктор копирования с регистратором. \en Copy-constructor with the registrator. + explicit MbSpaceInstance( const MbSpaceInstance &, MbRegDuplicate * ); +public : + /// \ru Конструктор по вспомогательному объекту. \en Constructor by auxiliary item. + MbSpaceInstance( MbLegend & ); + /// \ru Конструктор по точке. \en Constructor by point. + MbSpaceInstance( MbPoint3D & ); + /// \ru Конструктор по кривой. \en Constructor by curve. + MbSpaceInstance( MbCurve3D & ); + /// \ru Конструктор по поверхности. \en Constructor by surface. + MbSpaceInstance( MbSurface & ); + /// \ru Деструктор. \en Destructor. + virtual ~MbSpaceInstance(); + +public : + VISITING_CLASS( MbSpaceInstance ); + + // \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 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. + 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 CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; // \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + + 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. + + // \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 Найти объект по геометрическому объекту (MbSpaceItem). \en Find the object by a geometric object (MbSpaceItem). + virtual const MbItem * FindItem( const MbSpaceItem * s, MbPath & path, MbMatrix3D & from ) const; + // \ru Дать все объекты указанного типа. \en Get all objects by type. \~ + virtual bool GetItems( MbeSpaceType type, const MbMatrix3D & from, + RPArray & items, SArray & matrs ); + // \ru Дать все уникальные объекты указанного типа. \en Get all unique objects by type . \~ + virtual bool GetUniqItems( MbeSpaceType type, CSSArray & items ) const; + + /** \ru \name Общие функции вставки трёхмерного объекта. + \en \name Common functions of instance of three-dimensional object. + \{ */ + /// \ru Выдать трёхмерный геометрический объект. \en Get three-dimensional geometric object. + const MbSpaceItem * GetSpaceItem() const; + /// \ru Выдать трёхмерный геометрический объект для модификации. \en Get three-dimensional geometric object for modification. + MbSpaceItem * SetSpaceItem(); + /// \ru Заменить геометрический объект. \en Replace geometric object. + void SetSpaceItem( MbSpaceItem * init ); + /** \} */ + +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpaceInstance ) +OBVIOUS_PRIVATE_COPY( MbSpaceInstance ) +}; + +IMPL_PERSISTENT_OPS( MbSpaceInstance ) + +#endif // __SPACE_INSTANCE_H diff --git a/C3d/Include/space_item.h b/C3d/Include/space_item.h index a89a3ab..3b014ad 100644 --- a/C3d/Include/space_item.h +++ b/C3d/Include/space_item.h @@ -148,6 +148,7 @@ enum MbeSpaceType { st_ConicUnbendedSurface = 345, ///< \ru Поверхность, полученная коническим разгибом. \en Surface constructed by conical unbending. st_GregoryRibbonPatchSurface= 346, ///< \ru Поверхность Грегори с граничными условиями. \en Gregory patch surface with ribbons. st_ExplorationSurface = 347, ///< \ru Поверхность заметания с масштабированием и поворотом образующей кривой. \en Swept surface with scaling and winding of generating curve. + st_SectionSurface = 348, ///< \ru Поверхность заметания переменного сечения. \en The swept mutable section surface. st_FreeSurface = 400, ///< \ru Тип для поверхностей, созданных пользователем. \en Type for the user-defined surfaces. \n // \ru Типы вспомогательных объектов. \en Helper object types. @@ -451,7 +452,7 @@ public : and make a reference to the written instance of the other records. Reading is performed once, and there is substitution of already read object for all the remaining reading cases. */ - void PrepareWrite() { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } DECLARE_PERSISTENT_CLASS( MbSpaceItem ) OBVIOUS_PRIVATE_COPY( MbSpaceItem ) diff --git a/C3d/Include/surf_chamfer_surface.h b/C3d/Include/surf_chamfer_surface.h index c7c09a0..07fe82a 100644 --- a/C3d/Include/surf_chamfer_surface.h +++ b/C3d/Include/surf_chamfer_surface.h @@ -184,6 +184,9 @@ public: \{ */ virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна вдоль v. \en Curvature along v. + virtual void CalculateGabarit( MbCube & ) const; // \ru Выдать габарит. \en Get the bounding box. + virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к.. \en Calculate bounding box relative to the local coordinate system. + virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Creation of an offset surface. virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru Построить NURBS копию поверхности. \en Construct a NURBS copy of the surface. diff --git a/C3d/Include/surf_channel_surface.h b/C3d/Include/surf_channel_surface.h index 27c8a1c..1cc3bad 100644 --- a/C3d/Include/surf_channel_surface.h +++ b/C3d/Include/surf_channel_surface.h @@ -1,275 +1,273 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность скругления с переменным радиусом обычная или с сохранением кромки. - \en Fillet surface with variable radius is normal or with preservation of edges. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_CHANNEL_SURFACE_H -#define __SURF_CHANNEL_SURFACE_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность скругления с переменным радиусом обычная или с сохранением кромки. - \en Fillet surface with variable radius is normal or with preservation of edges. \~ - \details \ru Поверхность скругления с переменным радиусом является NURBS-поверхностью, - построенной по трём кривым: curve1, curve0, curve2. - Первый параметр поверхности совпадает с параметром кривых curve1, curve0, curve2. - Второй параметр изменяется от нуля (точки совпадают с curve1) до единицы (точки совпадают с curve2). - Функция function определяет изменение радиуса и равна отношению текущего радиуса к заданному для поверхности радиусу. - Параметр функции радиуса совпадает с параметром кривых curve1, curve0, curve2. - Если коэффициент формы conic = _ARC_ ( 0 ), то вес каждой точки кривой curve0 задаётся функцией weights0 и - вычислен так, что сечение поверхности вдоль её второго параметра будет дугой окружности, - то есть при любом параметре u три точки curve1(u), curve0(u), curve2(u) определяют NURBS-кривую в форме дуги окружности. - Если коэффициент формы conic != _ARC_, то вес каждой точки кривой curve0 равен conic / ( 1.0 - conic ). - При conic = 0.5 сечение поверхности вдоль её второго параметра будет параболой. \n - \en Fillet surface with variable radius is NURBS-surface - constructed on three curves: curve1, curve0, curve2. - The first surface parameter coincides with the parameter of curve1, curve0, curve2 curves. - The second parameter is changed from zero (points coincide with curve1) to unit (points coincide with curve2). - Function "function" determines the change of the radius and equals the ratio of the current radius to given for surface. - The parameter of radius function coincides with the parameter of curves curve1, curve0, curve2. - If coefficient of shape conic = _ARC_ ( 0 ), then the weight of each point of the curve0 curve determined by the function weights0 and - calculated so that the section of surface along its second parameter is a circular arc - i.e. for any parameter u three points of curve1(u), curve0(u), curve2(u) determine the NURBS-curve with the shape of a circular arc. - If coefficient of shape conic != _ARC_, then the weight of each point of the curve0 curve is equal to conic / ( 1.0 - conic ). - If conic = 0.5, then the surface section along its second parameter is parabola. \n \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbChannelSurface : public MbFilletSurface { -private: - MbFunction * function; ///< \ru Функция изменения радиуса (переменный коэффициент). \en Function of change of the radius (variable coefficient). - -public: - - /** \brief \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and type of mate. \~ - \details \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and type of mate. \~ - \param[in] curv1 - \ru Опорная кривая на первой поверхности - \en Support curve on the first surface \~ - \param[in] curv2 - \ru Опорная кривая на второй поверхности - \en Support curve on the second surface \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой \n - st_Fillet - скругление с заданными радиусами - \en Mate type: \n - st_Span - fillet with a given chord \n - st_Fillet - fillet with given radii. \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) - \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ - \param[in] func - \ru Функция изменения радиуса - \en Function of change of the radius \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Uniform parametrization by arc or not \~ - */ - MbChannelSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, - double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool ev ); - - /** \brief \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and type of mate. \~ - \details \ru Конструктор поверхности с сохранением кромки по двум кривым и типу сопряжения. - \en Constructor of surface with preservation of edges by two curves and mate type. \~ - \param[in] curv1 - \ru Опорная кривая на первой поверхности - \en Support curve on the first surface \~ - \param[in] curv2 - \ru Опорная кривая на второй поверхности - \en Support curve on the second surface \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой \n - st_Fillet - скругление с заданными радиусами - \en Mate type: \n - st_Span - fillet with a given chord \n - st_Fillet - fillet with given radii. \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) - \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ - \param[in] func - \ru Функция изменения радиуса - \en Function of change of the radius \~ - \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой - \en True - curve2 curve is edge, false - curve1 curve is edge \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Uniform parametrization by arc or not \~ - */ - MbChannelSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, - double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool byFirst, bool ev ); - - /** \brief \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and type of mate. \~ - \details \ru Конструктор поверхности с сохранением кромки по двум кривым и типу сопряжения. - \en Constructor of surface with preservation of edges by two curves and mate type. \~ - \param[in] surf1 - \ru Первая поверхность - \en First surface \~ - \param[in] curv1 - \ru Опорная кривая в параметрах первой поверхности - \en Support curve at parameters of the first surface \~ - \param[in] surf2 - \ru Вторая поверхность - \en Second surface \~ - \param[in] curv2 - \ru Опорная кривая в параметрах второй поверхности - \en Support curve at parameters of the second surface \~ - \param[in] curv0 - \ru Кривая пересеченния касательных к поверхностям - \en Intersection curve of tangents to surfaces \~ - \param[in] weig0 - \ru Функция изменения веса. - \en Function of change of the weights. \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой \n - st_Fillet - скругление с заданными радиусами - \en Mate type: \n - st_Span - fillet with a given chord \n - st_Fillet - fillet with given radii. \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) - \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ - \param[in] func - \ru Функция изменения радиуса. - \en Function of change of the radius. \~ - \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой - \en True - curve2 curve is edge, false - curve1 curve is edge \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Uniform parametrization by arc or not \~ - */ - MbChannelSurface( MbSurface & surf1, MbCurve & curv1, - MbSurface & surf2, MbCurve & curv2, - MbCurve3D & curv0, MbFunction & weig0, - double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool ev ); - -protected: - MbChannelSurface( const MbChannelSurface &, MbRegDuplicate * ); - MbChannelSurface( const MbChannelSurface * ); // \ru Конструктор копирования с теми же опорными поверхностями для CurvesDuplicate() \en Copy constructor with the same support surfaces for CurvesDuplicate() - -private: - MbChannelSurface( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. - -public: - virtual ~MbChannelSurface (); - -public: - VISITING_CLASS( MbChannelSurface ); - - /** \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 Сделать копию элемента. \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 GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. - /** \} */ - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Creation of an offset surface. - virtual double GetFilletRadius( const MbCartPoint3D & p ) const; - /** \} */ - /** \ru \name Функции поверхности сопряжения - \en \name Functions of smooth surface - \{ */ - virtual MbSmoothSurface & CurvesDuplicate() const; // \ru Копия с теми же опорными поверхностями. \en Copy with the same support surfaces. - virtual double GetSmoothRadius() const; // \ru Дать радиус. \en Get radius. - virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; - /** \} */ - /** \ru \name Функции поверхности скругления с переменным радиусом обычная или с сохранением кромки - \en \name Functions of fillet surface with variable radius is normal or with preservation of edges - \{ */ - - /** \brief \ru Добавить точку в опорные кривые границы. - \en Add a point to the support curves of the boundary. \~ - \details \ru Добавить точку в опорные кривые границы.\n - Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. - \en Add a point to the support curves of the boundary.\n - A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ - \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) - \en Parameter of a point on the first curve (if add1 equals true) \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую - \en Whether to add a point to the first curve \~ - \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) - \en Parameter of a point on the second curve (if add2 equals true) \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую - \en Whether to add a point to the second curve \~ - */ - virtual bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, - double & t2, const MbCartPoint & p2, bool add2 ); - - /** \brief \ru Проверить наличие полюса. - \en Check pole availability. \~ - \details \ru Проверить наличие полюса. - \en Check pole availability. \~ - \param[in] u - \ru Начальное приближение параметра по U для поиска полюса - \en Initial approximation of parameter U to search pole \~ - \param[in] bModify - \ru Флаг модификации поверхности \n - если true, то поверхность корректирует свои параметры по U - и соответственно им опорные кривые curve1 и curve2 - \en Flag of surface modification \n - if true, then the surface corrects its parameters along U - and according to them the support curves curve1 and curve2 \~ - \return \ru true - если нашли полюс - \en True - if pole has been found \~ - */ - bool CheckPole( double & u, bool bModify = true ); - /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. - const MbFunction & GetFunction() const { return *function; } - /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. - MbFunction & SetFunction() { return *function; } - /// \ru Заменить функцию изменения радиуса. \en Set a function of radius changing. - void SetFunction( MbFunction & funcNew ); // \ru (новая функция должна быть корректна) \en (new function must be correct) - - /** \} */ -protected: - void CalculateCurves( bool insertPoints ); - -private: - // \ru Дать коэффициент для радиуса \en Get coefficient for radius - virtual double FunctionValue( double u ) const; - void CheckPole(); // \ru Проверить полюса \en Check poles - // \ru Добавить точку в опорные кривые границы поверхности с постоянной хордой. \en Add a point to the support curves of the boundary of surface with constant chord. \~ - bool InsertForSpan( double & t1, const MbCartPoint & p1, bool add1, - double & t2, const MbCartPoint & p2, bool add2 ); - void operator = ( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChannelSurface ) -}; - -IMPL_PERSISTENT_OPS( MbChannelSurface ) - -//------------------------------------------------------------------------------ -// \ru Создать поверхность переменного радиуса \en Create surface with variable radius -// --- -MbSmoothSurface * CreateChannelSurface( const MbSurface & surface1, SArray & points1, - const MbSurface & surface2, SArray & points2, - MbeSmoothForm form, double distance1, double distance2, double conic, - SArray & dFactor, SArray & dTendency, - bool even ); - - -//------------------------------------------------------------------------------ -// \ru Создать поверхность переменного радиуса с сохранением кромки \en Create surface with variable radius with preservation of edges -// --- -MbSmoothSurface * CreateKerbChannelSurface( const MbSurface & surface1, SArray & points1, - const MbSurface & surface2, SArray & points2, - MbeSmoothForm form, double distance1, double distance2, double conic, - const MbSurfaceIntersectionCurve & guideCurve, SArray & params, - SArray & dFactor, - bool byFirstSurface, bool even ); - - -#endif // __SURF_CHANNEL_SURFACE_H - +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность скругления с переменным радиусом обычная или с сохранением кромки. + \en Fillet surface with variable radius is normal or with preservation of edges. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_CHANNEL_SURFACE_H +#define __SURF_CHANNEL_SURFACE_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность скругления с переменным радиусом обычная или с сохранением кромки. + \en Fillet surface with variable radius is normal or with preservation of edges. \~ + \details \ru Поверхность скругления с переменным радиусом является NURBS-поверхностью, + построенной по трём кривым: curve1, curve0, curve2. + Первый параметр поверхности совпадает с параметром кривых curve1, curve0, curve2. + Второй параметр изменяется от нуля (точки совпадают с curve1) до единицы (точки совпадают с curve2). + Функция function определяет изменение радиуса и равна отношению текущего радиуса к заданному для поверхности радиусу. + Параметр функции радиуса совпадает с параметром кривых curve1, curve0, curve2. + Если коэффициент формы conic = _ARC_ ( 0 ), то вес каждой точки кривой curve0 задаётся функцией weights0 и + вычислен так, что сечение поверхности вдоль её второго параметра будет дугой окружности, + то есть при любом параметре u три точки curve1(u), curve0(u), curve2(u) определяют NURBS-кривую в форме дуги окружности. + Если коэффициент формы conic != _ARC_, то вес каждой точки кривой curve0 равен conic / ( 1.0 - conic ). + При conic = 0.5 сечение поверхности вдоль её второго параметра будет параболой. \n + \en Fillet surface with variable radius is NURBS-surface + constructed on three curves: curve1, curve0, curve2. + The first surface parameter coincides with the parameter of curve1, curve0, curve2 curves. + The second parameter is changed from zero (points coincide with curve1) to unit (points coincide with curve2). + Function "function" determines the change of the radius and equals the ratio of the current radius to given for surface. + The parameter of radius function coincides with the parameter of curves curve1, curve0, curve2. + If coefficient of shape conic = _ARC_ ( 0 ), then the weight of each point of the curve0 curve determined by the function weights0 and + calculated so that the section of surface along its second parameter is a circular arc + i.e. for any parameter u three points of curve1(u), curve0(u), curve2(u) determine the NURBS-curve with the shape of a circular arc. + If coefficient of shape conic != _ARC_, then the weight of each point of the curve0 curve is equal to conic / ( 1.0 - conic ). + If conic = 0.5, then the surface section along its second parameter is parabola. \n \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbChannelSurface : public MbFilletSurface { +private: + MbFunction * function; ///< \ru Функция изменения радиуса (переменный коэффициент). \en Function of change of the radius (variable coefficient). + +public: + + /** \brief \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and type of mate. \~ + \details \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and type of mate. \~ + \param[in] curv1 - \ru Опорная кривая на первой поверхности + \en Support curve on the first surface \~ + \param[in] curv2 - \ru Опорная кривая на второй поверхности + \en Support curve on the second surface \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой \n + st_Fillet - скругление с заданными радиусами + \en Mate type: \n + st_Span - fillet with a given chord \n + st_Fillet - fillet with given radii. \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) + \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ + \param[in] func - \ru Функция изменения радиуса + \en Function of change of the radius \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Uniform parametrization by arc or not \~ + */ + MbChannelSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, + double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool ev ); + + /** \brief \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and type of mate. \~ + \details \ru Конструктор поверхности с сохранением кромки по двум кривым и типу сопряжения. + \en Constructor of surface with preservation of edges by two curves and mate type. \~ + \param[in] curv1 - \ru Опорная кривая на первой поверхности + \en Support curve on the first surface \~ + \param[in] curv2 - \ru Опорная кривая на второй поверхности + \en Support curve on the second surface \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой \n + st_Fillet - скругление с заданными радиусами + \en Mate type: \n + st_Span - fillet with a given chord \n + st_Fillet - fillet with given radii. \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) + \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ + \param[in] func - \ru Функция изменения радиуса + \en Function of change of the radius \~ + \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой + \en True - curve2 curve is edge, false - curve1 curve is edge \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Uniform parametrization by arc or not \~ + */ + MbChannelSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, + double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool byFirst, bool ev ); + + /** \brief \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and type of mate. \~ + \details \ru Конструктор поверхности с сохранением кромки по двум кривым и типу сопряжения. + \en Constructor of surface with preservation of edges by two curves and mate type. \~ + \param[in] surf1 - \ru Первая поверхность + \en First surface \~ + \param[in] curv1 - \ru Опорная кривая в параметрах первой поверхности + \en Support curve at parameters of the first surface \~ + \param[in] surf2 - \ru Вторая поверхность + \en Second surface \~ + \param[in] curv2 - \ru Опорная кривая в параметрах второй поверхности + \en Support curve at parameters of the second surface \~ + \param[in] curv0 - \ru Кривая пересеченния касательных к поверхностям + \en Intersection curve of tangents to surfaces \~ + \param[in] weig0 - \ru Функция изменения веса. + \en Function of change of the weights. \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой \n + st_Fillet - скругление с заданными радиусами + \en Mate type: \n + st_Span - fillet with a given chord \n + st_Fillet - fillet with given radii. \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) + \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ + \param[in] func - \ru Функция изменения радиуса. + \en Function of change of the radius. \~ + \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой + \en True - curve2 curve is edge, false - curve1 curve is edge \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Uniform parametrization by arc or not \~ + */ + MbChannelSurface( MbSurface & surf1, MbCurve & curv1, + MbSurface & surf2, MbCurve & curv2, + MbCurve3D & curv0, MbFunction & weig0, + double d1, double d2, MbeSmoothForm fm, double cn, MbFunction & func, bool ev ); + +protected: + MbChannelSurface( const MbChannelSurface &, MbRegDuplicate * ); + MbChannelSurface( const MbChannelSurface * ); // \ru Конструктор копирования с теми же опорными поверхностями для CurvesDuplicate() \en Copy constructor with the same support surfaces for CurvesDuplicate() + +private: + MbChannelSurface( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. + +public: + virtual ~MbChannelSurface (); + +public: + VISITING_CLASS( MbChannelSurface ); + + /** \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 Сделать копию элемента. \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 GetProperties( MbProperties & properties ); // \ru Выдать свойства объекта. \en Get properties of the object. + /** \} */ + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Creation of an offset surface. + virtual double GetFilletRadius( const MbCartPoint3D & p ) const; + virtual double GetFilletRadius( double u ) const; + /** \} */ + /** \ru \name Функции поверхности сопряжения + \en \name Functions of smooth surface + \{ */ + virtual MbSmoothSurface & CurvesDuplicate() const; // \ru Копия с теми же опорными поверхностями. \en Copy with the same support surfaces. + virtual double GetSmoothRadius() const; // \ru Дать радиус. \en Get radius. + virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; + /** \} */ + /** \ru \name Функции поверхности скругления с переменным радиусом обычная или с сохранением кромки + \en \name Functions of fillet surface with variable radius is normal or with preservation of edges + \{ */ + + /** \brief \ru Добавить точку в опорные кривые границы. + \en Add a point to the support curves of the boundary. \~ + \details \ru Добавить точку в опорные кривые границы.\n + Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. + \en Add a point to the support curves of the boundary.\n + A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ + \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) + \en Parameter of a point on the first curve (if add1 equals true) \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую + \en Whether to add a point to the first curve \~ + \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) + \en Parameter of a point on the second curve (if add2 equals true) \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую + \en Whether to add a point to the second curve \~ + */ + virtual bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, + double & t2, const MbCartPoint & p2, bool add2 ); + + /** \brief \ru Проверить наличие полюса. + \en Check pole availability. \~ + \details \ru Проверить наличие полюса. + \en Check pole availability. \~ + \param[in] u - \ru Начальное приближение параметра по U для поиска полюса + \en Initial approximation of parameter U to search pole \~ + \param[in] bModify - \ru Флаг модификации поверхности \n + если true, то поверхность корректирует свои параметры по U + и соответственно им опорные кривые curve1 и curve2 + \en Flag of surface modification \n + if true, then the surface corrects its parameters along U + and according to them the support curves curve1 and curve2 \~ + \return \ru true - если нашли полюс + \en True - if pole has been found \~ + */ + bool CheckPole( double & u, bool bModify = true ); + /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. + const MbFunction & GetFunction() const { return *function; } + /// \ru Получить функцию изменения радиуса. \en Get a function of radius changing. + MbFunction & SetFunction() { return *function; } + /// \ru Заменить функцию изменения радиуса. \en Set a function of radius changing. + void SetFunction( MbFunction & funcNew ); // \ru (новая функция должна быть корректна) \en (new function must be correct) + + /** \} */ +private: + // \ru Дать коэффициент для радиуса \en Get coefficient for radius + virtual double FunctionValue( double u ) const; + void CheckPole(); // \ru Проверить полюса \en Check poles + // \ru Добавить точку в опорные кривые границы поверхности с постоянной хордой. \en Add a point to the support curves of the boundary of surface with constant chord. \~ + bool InsertForSpan( double & t1, const MbCartPoint & p1, bool add1, + double & t2, const MbCartPoint & p2, bool add2 ); + void operator = ( const MbChannelSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbChannelSurface ) +}; + +IMPL_PERSISTENT_OPS( MbChannelSurface ) + +//------------------------------------------------------------------------------ +// \ru Создать поверхность переменного радиуса \en Create surface with variable radius +// --- +MbSmoothSurface * CreateChannelSurface( const MbSurface & surface1, SArray & points1, + const MbSurface & surface2, SArray & points2, + MbeSmoothForm form, double distance1, double distance2, double conic, + SArray & dFactor, SArray & dTendency, + bool even ); + + +//------------------------------------------------------------------------------ +// \ru Создать поверхность переменного радиуса с сохранением кромки \en Create surface with variable radius with preservation of edges +// --- +MbSmoothSurface * CreateKerbChannelSurface( const MbSurface & surface1, SArray & points1, + const MbSurface & surface2, SArray & points2, + MbeSmoothForm form, double distance1, double distance2, double conic, + const MbSurfaceIntersectionCurve & guideCurve, SArray & params, + SArray & dFactor, + bool byFirstSurface, bool even ); + + +#endif // __SURF_CHANNEL_SURFACE_H + diff --git a/C3d/Include/surf_coons_surface.h b/C3d/Include/surf_coons_surface.h index 97e72f4..c5d2fd0 100644 --- a/C3d/Include/surf_coons_surface.h +++ b/C3d/Include/surf_coons_surface.h @@ -1,523 +1,529 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Бикубическая поверхность Кунса на четырех кривых и их поперечных производных. - \en Bicubic Coons surface on four curves and its transverse derivatives. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_COONS_SURFACE_H -#define __SURF_COONS_SURFACE_H - - -#include -#include -#include - - -class MATH_CLASS MbCurve; - - -#define COONS_COUNT 4 ///< \ru Число кривых, используемых для построения поверхности Кунса \en Count of curves used to construct Coons surface. - - -//------------------------------------------------------------------------------ -/** \brief \ru Способ расчёта поверхности Кунса. -\en Type of calculation of Coons surface. \~ -\details \ru Способ расчёта поверхности Кунса. \n -\en Type of calculation of Coons surface. \n \~ -\ingroup Surfaces -*/ -// --- -enum MbeCoonsSurfaceCalcType { - cst_DefaultType = 0, ///< \ru Способ по умолчанию. \en Default type. - cst_SurfaceType, ///< \ru Точный способ по кривым на поверхностях. \en Exact type by Curves on surfaces. -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность Кунса на четырех кривых. - \en Coons surface on four curves. \~ - \details \ru Бикубическая поверхность Кунса определяется четырьмя кривыми и - производными поверхности на этих кривых в поперечном к кривым направлениях. - Поверхность проходит через определяющие её кривые и - имеет заданные производные на этих кривых в поперечном к кривым направлениях. \n - \en Bicubic Coons surface is determined by four curves and - surface derivatives on these curves in transverse directions to curves. - Surface passes through its determining curves and - has specified derivatives on this curves in transverse directions to curves. \n \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbCoonsPatchSurface : public MbSurface { - -// curve2V -// t2min curve2 t2max -// P3 ______________________ P2 -// t3max | | t1max -// | | -// | | -// curve3 | | curve1 -// curve3U | | curve1U -// 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 -// curve0V -// \ru Не переименовывать в MbCoonsSurface - хэш совпал с существующим объектом (BUG_60351). \en No renaming to MbCoonsSurface - hash was coincided with existing object (BUG_60351). - -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. - MbCurve3D * curve0V; ///< \ru Производная по v вдоль кривой 0. \en Derivative by v along curve 0. - MbCurve3D * curve1U; ///< \ru Производная по u вдоль кривой 1. \en Derivative by u along curve 1. - MbCurve3D * curve2V; ///< \ru Производная по v вдоль кривой 2. \en Derivative by v along curve 2. - MbCurve3D * curve3U; ///< \ru Производная по u вдоль кривой 3. \en Derivative by u along curve 3. - MbCartPoint3D vertex[COONS_COUNT]; ///< \ru Вершины. \en Vertices. - MbCartPoint3D vertexU[COONS_COUNT]; ///< \ru Производная по u в вершинах. \en Derivative by u at vertices. - MbCartPoint3D vertexV[COONS_COUNT]; ///< \ru Производная по v в вершинах. \en Derivative by v at vertices. - MbCartPoint3D vertexUV[COONS_COUNT]; ///< \ru Производная по uv в вершинах. \en Derivative by uv at 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 Closeness by u. - bool vclosed; ///< \ru Замкнутость по v. \en Closeness 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. - MbeCoonsSurfaceCalcType calcType; ///< \ru Версия реализации определяет способ расчёта поверхности. \en Version of implementation determines a type of calculation of surface. - -protected: - /** \brief \ru Конструктор поверхности Кунса. - \en Constructor of Coons surface. \~ - \details \ru Конструктор поверхности Кунса по набору кривых и производных вдоль кривых. - \en Constructor of Coons surface by set of curves and derivatives along 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. \~ - \param[in] derVCurve0 - \ru Производная по v вдоль кривой 0. - \en Derivative by v along curve 0. \~ - \param[in] derUCurve1 - \ru Производная по u вдоль кривой 1. - \en Derivative by u along curve 1. \~ - \param[in] derVCurve2 - \ru Производная по v вдоль кривой 2. - \en Derivative by v along curve 2. \~ - \param[in] derUCurve3 - \ru Производная по u вдоль кривой 3. - \en Derivative by u along curve 3. \~ - */ - MbCoonsPatchSurface ( MbCurve3D & initCurve0, MbCurve3D & initCurve1, MbCurve3D & initCurve2, MbCurve3D & initCurve3, - MbCurve3D & derVCurve0, MbCurve3D & derUCurve1, MbCurve3D & derVCurve2, MbCurve3D & derUCurve3, - double w0min, double w0max, double w1min, double w1max, double w2min, double w2max, double w3min, double w3max, - MbeCoonsSurfaceCalcType calcType = cst_DefaultType ); -private: - MbCoonsPatchSurface( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. - MbCoonsPatchSurface( const MbCoonsPatchSurface &, MbRegDuplicate * ); ///< \ru Конструктор копирования. \en Copy-constructor. -public: - virtual ~MbCoonsPatchSurface( void ); - -public: - VISITING_CLASS( MbCoonsPatchSurface ); - - /// \ru Создание поверхности Кунса заданным кривым на поверхностях. \en Creation of Coons surface by curves on surfaces. - static MbCoonsPatchSurface * Create( const MbCurve3D & curve0, - const MbCurve3D & curve1, - const MbCurve3D & curve2, - const MbCurve3D & curve3, - MbResultType & resType ); - - /// \ru Инициализация поверхности Кунса заданной поверхностью Кунса. \en Initialization of Coons surface by specified Coons surface. - void Init( const MbCoonsPatchSurface & ); - - /** \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 & ); // \ru Выдать свойства объекта \en Get properties of the object - virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object - virtual void GetBasisItems ( RPArray &s ); // \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. - 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 & ) const; // \ru Точка на поверхности \en Point on the surface - virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void Normal ( double & u, double & v, MbVector3D & ) 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 & ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void _Normal ( double u, double v, MbVector3D & ) 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 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 - - virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier - // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region - - 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 Получить кривую производной в трансверсальном направлении к кривой 0. \en Get derivative curve transversal to curve 0. - const MbCurve3D & GetDerCurve0() const { return *curve0V; } - /// \ru Получить кривую производной в трансверсальном направлении к кривой 1. \en Get derivative curve transversal to curve 1. - const MbCurve3D & GetDerCurve1() const { return *curve1U; } - /// \ru Получить кривую производной в трансверсальном направлении к кривой 2. \en Get derivative curve transversal to curve 2. - const MbCurve3D & GetDerCurve2() const { return *curve2V; } - /// \ru Получить кривую производной в трансверсальном направлении к кривой 3. \en Get derivative curve transversal to curve 3. - 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. - /** \} */ - 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. - - /** \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(); - -private: - void operator = ( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. - void Setup(); - void CheckParams( double & u, double & v ) const; // \ru Проверить и изменить при необходимости параметры. \en Check and correct parameters. - // \ru Определение местных координат. \en Determination of local coordinates. - void CalculateCoordinate( double & u, double & v, - double & t0, double & t1, double & t2, double & t3 ) const; - void CalculatePoint ( double & u, double & v, - MbCartPoint3D * point, MbCartPoint3D * pointUV ) const; - void CalculateFirst ( double & u, double & v, - MbCartPoint3D * point, MbVector3D * first, - MbCartPoint3D * pointUV, MbVector3D * firstUV ) const; - void CalculateThird ( double & u, double & v, - MbCartPoint3D * point, MbVector3D * third, - MbCartPoint3D * pointUV, MbVector3D * thirdUV ) const; - void CalculateExplore( double & u, double & v, - MbCartPoint3D * point, MbVector3D * first, MbVector3D * second, - MbCartPoint3D * pointUV, MbVector3D * firstUV, MbVector3D * secondUV ) const; - // \ru Производные. \en Derivatives with respect to u and to v. - void Derivatives( double & u, double & v, MbVector3D & uDer, MbVector3D & vDer ) const; - // \ru Нормаль. \en Calculate surface normal with refinement on borders. - void Normal( double u, double v, MbVector3D & derU, MbVector3D & derV, MbVector3D & norm ) const; - inline void ParamPoint ( double w, double * t ) const; - inline void ParamFirst ( double w, double * t ) const; - inline void ParamSecond( double w, double * t ) const; - inline void ParamThird ( double w, double * t ) const; - // \ru Добавить матрицу поверхности. \en Add the matrix of the surface. - inline void AddMatrix ( double * uu, double * vv, MbVector3D & p ) const; - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoonsPatchSurface ) -}; // MbCoonsSurface - - -IMPL_PERSISTENT_OPS( MbCoonsPatchSurface ) - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметра точки \en Determination of array of degrees of point parameter -// --- -inline void MbCoonsPatchSurface::ParamPoint ( double w, double * t ) const { - t[0] = 1.0 - 3.0 * w * w + 2.0 * w * w * w; //*/ 1.0 - 10.0 * w * w * w + 15.0 * w * w * w * w - 6.0 * w * w * w * w * w; - t[1] = 3.0 * w * w - 2.0 * w * w * w; //*/ 10.0 * w * w * w - 15.0 * w * w * w * w + 6.0 * w * w * w * w * w; - t[2] = w - 2.0 * w * w + w * w * w; //*/ 0.0; - t[3] = - w * w + w * w * w; //*/ 0.0; -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметра производной \en Determination of array of degrees of derivative parameter -// --- -inline void MbCoonsPatchSurface::ParamFirst ( double w, double * t ) const { - t[0] = - 6.0 * w + 6.0 * w * w; //*/ -30.0 * w * w + 60.0 * w * w * w - 30.0 * w * w * w * w; - t[1] = 6.0 * w - 6.0 * w * w; //*/ 30.0 * w * w - 60.0 * w * w * w + 30.0 * w * w * w * w; - t[2] = 1.0 - 4.0 * w + 3.0 * w * w; //*/ 0.0; - t[3] = - 2.0 * w + 3.0 * w * w; //*/ 0.0; -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметра второй производной \en Determination of array of degrees of second derivative parameter -// --- -inline void MbCoonsPatchSurface::ParamSecond( double w, double * t ) const { - t[0] = - 6.0 + 12.0 * w; //*/ -60.0 * w + 180.0 * w * w - 120.0 * w * w * w; - t[1] = 6.0 - 12.0 * w; //*/ 60.0 * w - 180.0 * w * w + 120.0 * w * w * w; - t[2] = - 4.0 + 6.0 * w; //*/ 0.0; - t[3] = - 2.0 + 6.0 * w; //*/ 0.0; -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметра третьей производной \en Determination of array of degrees of third derivative parameter -// --- -inline void MbCoonsPatchSurface::ParamThird ( double /*w*/, double * t ) const { - t[0] = 12.0; //*/ -60.0 + 360.0 * w - 360.0 * w * w; - t[1] = -12.0; //*/ 60.0 - 360.0 * w + 360.0 * w * w; - t[2] = 6.0; //*/ 0.0; - t[3] = 6.0; //*/ 0.0; -} - - -//------------------------------------------------------------------------------ -// \ru Добавить матрицу поверхности. \en Add the matrix of the surface. -// --- -inline void MbCoonsPatchSurface::AddMatrix( double * uu, double * vv, MbVector3D & p ) const { - 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( vertexUV[0], -uu[2]*vv[2], vertexUV[1], -uu[3]*vv[2], vertexUV[2], -uu[3]*vv[3], vertexUV[3], -uu[2]*vv[3] ); -} - - -//------------------------------------------------------------------------------ -// \ru Получить кривую по индексу \en Get curve by an index -// --- -inline const MbCurve3D * MbCoonsPatchSurface::GetCurve( size_t ind ) const -{ - if ( ind >= COONS_COUNT ) - ind = ind % COONS_COUNT; - switch ( ind ) { - case 0 : { return curve0; } - case 1 : { return curve1; } - case 2 : { return curve2; } - case 3 : { return curve3; } - } - return NULL; -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// Вспомогательные объекты бикубической поверхности Кунса. -// Auxiliary objects for bicubic Coons surface. -// -//////////////////////////////////////////////////////////////////////////////// - - -//------------------------------------------------------------------------------ -// \ru Кривая производных, обслуживающаяя точную бикубическую поверхность Кунса, построенная кривой на поверхности. -// \en The curve of derivetives 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 calculatiob of the transverse derivative in first point of curve. - MbVector rail2; ///< \ru Вектор для вычисления поперечной производной во второй точке кривой. \en The vector for calculatiob of the transverse derivative in second point of curve. - double turner; ///< \ru Угол поворота векторов на единицу изменения параметра. \en The angle of rotation of vectors per unit of parameter change. - -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. - - 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 +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Бикубическая поверхность Кунса на четырех кривых и их поперечных производных. + \en Bicubic Coons surface on four curves and its transverse derivatives. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_COONS_SURFACE_H +#define __SURF_COONS_SURFACE_H + + +#include +#include +#include + + +class MATH_CLASS MbCurve; + + +#define COONS_COUNT 4 ///< \ru Число кривых, используемых для построения поверхности Кунса \en Count of curves used to construct Coons surface. + + +//------------------------------------------------------------------------------ +/** \brief \ru Способ расчёта поверхности Кунса. +\en Type of calculation of Coons surface. \~ +\details \ru Способ расчёта поверхности Кунса. \n +\en Type of calculation of Coons surface. \n \~ +\ingroup Surfaces +*/ +// --- +enum MbeCoonsSurfaceCalcType { + cst_DefaultType = 0, ///< \ru Способ по умолчанию. \en Default type. + cst_SurfaceType, ///< \ru Точный способ по кривым на поверхностях. \en Exact type by Curves on surfaces. +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность Кунса на четырех кривых. + \en Coons surface on four curves. \~ + \details \ru Бикубическая поверхность Кунса определяется четырьмя кривыми и + производными поверхности на этих кривых в поперечном к кривым направлениях. + Поверхность проходит через определяющие её кривые и + имеет заданные производные на этих кривых в поперечном к кривым направлениях. \n + \en Bicubic Coons surface is determined by four curves and + surface derivatives on these curves in transverse directions to curves. + Surface passes through its determining curves and + has specified derivatives on this curves in transverse directions to curves. \n \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbCoonsPatchSurface : public MbSurface { + +// curve2V +// t2min curve2 t2max +// P3 ______________________ P2 +// t3max | | t1max +// | | +// | | +// curve3 | | curve1 +// curve3U | | curve1U +// 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 +// curve0V +// \ru Не переименовывать в MbCoonsSurface - хэш совпал с существующим объектом (BUG_60351). \en No renaming to MbCoonsSurface - hash was coincided with existing object (BUG_60351). + +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. + MbCurve3D * curve0V; ///< \ru Производная по v вдоль кривой 0. \en Derivative by v along curve 0. + MbCurve3D * curve1U; ///< \ru Производная по u вдоль кривой 1. \en Derivative by u along curve 1. + MbCurve3D * curve2V; ///< \ru Производная по v вдоль кривой 2. \en Derivative by v along curve 2. + MbCurve3D * curve3U; ///< \ru Производная по u вдоль кривой 3. \en Derivative by u along curve 3. + MbCartPoint3D vertex[COONS_COUNT]; ///< \ru Вершины. \en Vertices. + MbCartPoint3D vertexU[COONS_COUNT]; ///< \ru Производная по u в вершинах. \en Derivative by u at vertices. + MbCartPoint3D vertexV[COONS_COUNT]; ///< \ru Производная по v в вершинах. \en Derivative by v at vertices. + MbCartPoint3D vertexUV[COONS_COUNT]; ///< \ru Производная по uv в вершинах. \en Derivative by uv at 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 Closeness by u. + bool vclosed; ///< \ru Замкнутость по v. \en Closeness 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. + MbeCoonsSurfaceCalcType calcType; ///< \ru Версия реализации определяет способ расчёта поверхности. \en Version of implementation determines a type of calculation of surface. + +protected: + /** \brief \ru Конструктор поверхности Кунса. + \en Constructor of Coons surface. \~ + \details \ru Конструктор поверхности Кунса по набору кривых и производных вдоль кривых. + \en Constructor of Coons surface by set of curves and derivatives along 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. \~ + \param[in] derVCurve0 - \ru Производная по v вдоль кривой 0. + \en Derivative by v along curve 0. \~ + \param[in] derUCurve1 - \ru Производная по u вдоль кривой 1. + \en Derivative by u along curve 1. \~ + \param[in] derVCurve2 - \ru Производная по v вдоль кривой 2. + \en Derivative by v along curve 2. \~ + \param[in] derUCurve3 - \ru Производная по u вдоль кривой 3. + \en Derivative by u along curve 3. \~ + */ + MbCoonsPatchSurface ( MbCurve3D & initCurve0, MbCurve3D & initCurve1, MbCurve3D & initCurve2, MbCurve3D & initCurve3, + MbCurve3D & derVCurve0, MbCurve3D & derUCurve1, MbCurve3D & derVCurve2, MbCurve3D & derUCurve3, + double w0min, double w0max, double w1min, double w1max, double w2min, double w2max, double w3min, double w3max, + MbeCoonsSurfaceCalcType calcType = cst_DefaultType ); +private: + MbCoonsPatchSurface( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. + MbCoonsPatchSurface( const MbCoonsPatchSurface &, MbRegDuplicate * ); ///< \ru Конструктор копирования. \en Copy-constructor. +public: + virtual ~MbCoonsPatchSurface( void ); + +public: + VISITING_CLASS( MbCoonsPatchSurface ); + + /// \ru Создание поверхности Кунса по заданным кривым на поверхностях. \en Creation of Coons surface by curves on surfaces. + static MbCoonsPatchSurface * Create( const MbCurve3D & curve0, + const MbCurve3D & curve1, + const MbCurve3D & curve2, + const MbCurve3D & curve3, + MbResultType & resType ); + /// \ru Создание поверхности Кунса по заданным кривым на поверхностях. \en Creation of Coons surface by curves on surfaces. + static MbCoonsPatchSurface * Create( const MbCurve3D & curve0, bool tangent0, + const MbCurve3D & curve1, bool tangent1, + const MbCurve3D & curve2, bool tangent2, + const MbCurve3D & curve3, bool tangent3, + MbResultType & resType ); + + /// \ru Инициализация поверхности Кунса заданной поверхностью Кунса. \en Initialization of Coons surface by specified Coons surface. + void Init( const MbCoonsPatchSurface & ); + + /** \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 & ); // \ru Выдать свойства объекта \en Get properties of the object + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта \en Set properties of the object + virtual void GetBasisItems ( RPArray &s ); // \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. + 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 & ) const; // \ru Точка на поверхности \en Point on the surface + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void Normal ( double & u, double & v, MbVector3D & ) 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 & ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void _Normal ( double u, double v, MbVector3D & ) 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 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 + + virtual void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя \en Changing of carrier + // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + + 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 Получить кривую производной в трансверсальном направлении к кривой 0. \en Get derivative curve transversal to curve 0. + const MbCurve3D & GetDerCurve0() const { return *curve0V; } + /// \ru Получить кривую производной в трансверсальном направлении к кривой 1. \en Get derivative curve transversal to curve 1. + const MbCurve3D & GetDerCurve1() const { return *curve1U; } + /// \ru Получить кривую производной в трансверсальном направлении к кривой 2. \en Get derivative curve transversal to curve 2. + const MbCurve3D & GetDerCurve2() const { return *curve2V; } + /// \ru Получить кривую производной в трансверсальном направлении к кривой 3. \en Get derivative curve transversal to curve 3. + 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. + /** \} */ + 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. + + /** \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(); + +private: + void operator = ( const MbCoonsPatchSurface & ); // \ru Не реализовано. \en Not implemented. + void Setup(); + void CheckParams( double & u, double & v, bool ext = false ) const; // \ru Проверить и изменить при необходимости параметры. \en Check and correct parameters. + // \ru Определение местных координат. \en Determination of local coordinates. + void CalculateCoordinate( double & u, double & v, + double & t0, double & t1, double & t2, double & t3 ) const; + void CalculatePoint ( double & u, double & v, + MbCartPoint3D * point, MbCartPoint3D * pointUV ) const; + void CalculateFirst ( double & u, double & v, + MbCartPoint3D * point, MbVector3D * first, + MbCartPoint3D * pointUV, MbVector3D * firstUV ) const; + void CalculateThird ( double & u, double & v, + MbCartPoint3D * point, MbVector3D * third, + MbCartPoint3D * pointUV, MbVector3D * thirdUV ) const; + void CalculateExplore( double & u, double & v, + MbCartPoint3D * point, MbVector3D * first, MbVector3D * second, + MbCartPoint3D * pointUV, MbVector3D * firstUV, MbVector3D * secondUV ) const; + // \ru Производные. \en Derivatives with respect to u and to v. + void Derivatives( double & u, double & v, MbVector3D & uDer, MbVector3D & vDer ) const; + // \ru Нормаль. \en Calculate surface normal with refinement on borders. + void Normal( double u, double v, MbVector3D & derU, MbVector3D & derV, MbVector3D & norm ) const; + inline void ParamPoint ( double w, double * t ) const; + inline void ParamFirst ( double w, double * t ) const; + inline void ParamSecond( double w, double * t ) const; + inline void ParamThird ( double w, double * t ) const; + // \ru Добавить матрицу поверхности. \en Add the matrix of the surface. + inline void AddMatrix ( double * uu, double * vv, MbVector3D & p ) const; + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCoonsPatchSurface ) +}; // MbCoonsSurface + + +IMPL_PERSISTENT_OPS( MbCoonsPatchSurface ) + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметра точки \en Determination of array of degrees of point parameter +// --- +inline void MbCoonsPatchSurface::ParamPoint ( double w, double * t ) const { + t[0] = 1.0 - 3.0 * w * w + 2.0 * w * w * w; //*/ 1.0 - 10.0 * w * w * w + 15.0 * w * w * w * w - 6.0 * w * w * w * w * w; + t[1] = 3.0 * w * w - 2.0 * w * w * w; //*/ 10.0 * w * w * w - 15.0 * w * w * w * w + 6.0 * w * w * w * w * w; + t[2] = w - 2.0 * w * w + w * w * w; //*/ 0.0; + t[3] = - w * w + w * w * w; //*/ 0.0; +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметра производной \en Determination of array of degrees of derivative parameter +// --- +inline void MbCoonsPatchSurface::ParamFirst ( double w, double * t ) const { + t[0] = - 6.0 * w + 6.0 * w * w; //*/ -30.0 * w * w + 60.0 * w * w * w - 30.0 * w * w * w * w; + t[1] = 6.0 * w - 6.0 * w * w; //*/ 30.0 * w * w - 60.0 * w * w * w + 30.0 * w * w * w * w; + t[2] = 1.0 - 4.0 * w + 3.0 * w * w; //*/ 0.0; + t[3] = - 2.0 * w + 3.0 * w * w; //*/ 0.0; +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметра второй производной \en Determination of array of degrees of second derivative parameter +// --- +inline void MbCoonsPatchSurface::ParamSecond( double w, double * t ) const { + t[0] = - 6.0 + 12.0 * w; //*/ -60.0 * w + 180.0 * w * w - 120.0 * w * w * w; + t[1] = 6.0 - 12.0 * w; //*/ 60.0 * w - 180.0 * w * w + 120.0 * w * w * w; + t[2] = - 4.0 + 6.0 * w; //*/ 0.0; + t[3] = - 2.0 + 6.0 * w; //*/ 0.0; +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметра третьей производной \en Determination of array of degrees of third derivative parameter +// --- +inline void MbCoonsPatchSurface::ParamThird ( double /*w*/, double * t ) const { + t[0] = 12.0; //*/ -60.0 + 360.0 * w - 360.0 * w * w; + t[1] = -12.0; //*/ 60.0 - 360.0 * w + 360.0 * w * w; + t[2] = 6.0; //*/ 0.0; + t[3] = 6.0; //*/ 0.0; +} + + +//------------------------------------------------------------------------------ +// \ru Добавить матрицу поверхности. \en Add the matrix of the surface. +// --- +inline void MbCoonsPatchSurface::AddMatrix( double * uu, double * vv, MbVector3D & p ) const { + 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( vertexUV[0], -uu[2]*vv[2], vertexUV[1], -uu[3]*vv[2], vertexUV[2], -uu[3]*vv[3], vertexUV[3], -uu[2]*vv[3] ); +} + + +//------------------------------------------------------------------------------ +// \ru Получить кривую по индексу \en Get curve by an index +// --- +inline const MbCurve3D * MbCoonsPatchSurface::GetCurve( size_t ind ) const +{ + if ( ind >= COONS_COUNT ) + ind = ind % COONS_COUNT; + switch ( ind ) { + case 0 : { return curve0; } + case 1 : { return curve1; } + case 2 : { return curve2; } + case 3 : { return curve3; } + } + return 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. + +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. + + 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_corner_surface.h b/C3d/Include/surf_corner_surface.h index c456ccf..33b2518 100644 --- a/C3d/Include/surf_corner_surface.h +++ b/C3d/Include/surf_corner_surface.h @@ -1,346 +1,346 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Треугольная поверхность на сетке из трех кривых. - \en Triangular surface on grid of three curves. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_CORNER_SURFACE_H -#define __SURF_CORNER_SURFACE_H - - -#include - - -#define CORNER_COUNT 3 ///< \ru Число кривых, нужных для построения треугольной поверхности. \en Count of curves used to construct triangular surface. -#define VECT_CNT CORNER_COUNT - - -class MATH_CLASS MbContour3D; - - -//------------------------------------------------------------------------------ -/** \brief \ru Треугольная поверхность на кривых. - \en Triangular surface on curves. \~ - \details \ru Треугольная поверхность на сетке из трех кривых. - Кривые должны попарно пересекаться или иметь точки скрещения. - Если кривые попарно пересекаются, то поверхность проходит через определяющиее её кривые. \n - \en Triangular surface on grid of three curves. - 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 MbCornerSurface : public MbSurface { -// P2 -// t1max ^* t0min -// R(s0,s1,s2) = / * -// (curve2(1-s1)+curve1(s2)-P0)*s0+ / * -// (curve0(1-s2)+curve2(s0)-P1)*s1+ / * -// (curve1(1-s0)+curve0(s1)-P2)*s2 curve1 / * curve0 -// / R * -// s0(u,v) + s1(u,v) + s2(u,v) = 1 / * -// R(0,s1,s2) = curve0(s1) / * -// R(s0,0,s2) = curve1(s2) t1min <----------------v t0max -// R(s0,s1,0) = curve2(s0) P0 P1 -// t2max curve2 t2min -// -// \ru s0,s1,s2 - Барицентрические (треугольные) координаты, \en S0,s1,s2 - Baricentric (triangular) coordinates. -// \ru P0 - полюс \en P0 - pole -private: - MbCurve3D * curve0; ///< \ru Кривая 0. \en Curve 0. - MbCurve3D * curve1; ///< \ru Кривая 1. \en Curve 1. - MbCurve3D * curve2; ///< \ru Кривая 2. \en Curve 2. - MbCartPoint3D vertex[CORNER_COUNT]; ///< \ru Вершины P0, P1, P2. \en Vertices P0, P1, P2. - 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. - -public: - /** \brief \ru Конструктор треугольной поверхности. - \en Constructor of triangular surface. \~ - \details \ru Конструктор треугольной поверхности по набору кривых. - \en Constructor of triangular 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. \~ - */ - MbCornerSurface ( const MbCurve3D & initCurve0, const MbCurve3D & initCurve1, const MbCurve3D & initCurve2 ); -private: - MbCornerSurface( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. - MbCornerSurface( const MbCornerSurface & init, MbRegDuplicate * ); -public: - virtual ~MbCornerSurface( void ); - -public: - VISITING_CLASS( MbCornerSurface ); - - /// \ru Инициализация треугольной поверхности заданной треугольной поверхностью. \en Initialization of triangular surface by given triangular surface. - void Init( const MbCornerSurface &init ); - - /** \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 CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, - size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const; - - 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 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. - 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 TangentV ( double & u, double & v, MbVector3D & p ) const; - 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 _TangentV ( double u, double v, MbVector3D & p ) const; - virtual void _Normal ( double u, double v, MbVector3D & p ) const; // \ru Нормаль \en Normal - virtual void _NormalV ( double u, double v, MbVector3D & p ) const; // \ru Производная нормали \en Derivative of 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 the approximation step with consideration of the curvature radius by U - virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по V \en Calculation of the approximation step with consideration of the curvature radius by V - 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 there is pole on boundary of parametric region - - 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 Получить кривую по индексу. \en Get curve by an index. - const MbCurve3D * GetCurve( size_t ind ) const; - /// \ru Получить количество кривых. \en Get count of curves. - size_t GetCurvesCount() const { return 3; } //-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 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. - /** \} */ - -private: - void Init(); - inline void CalculateCoordinate( double & u, double & v, bool ext, - double & s0, double & s1, double & s2, - double & c0, double & c1, double & c2, - double & t0, double & t1, double & t2 ) const; - void CalculatePoint ( double & u, double & v, bool ext, - MbCartPoint3D & point ) const; - void CalculateFirst ( double & u, double & v, bool ext, - MbVector3D * first ) const; - void CalculateSecond( double & u, double & v, bool ext, - MbVector3D * second ) const; - void CalculateThird ( double & u, double & v, bool ext, - MbVector3D * second, MbVector3D * third ) const; - void CalculateExplore( double & u, double & v, bool ext, - MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; - bool GetNormalFactor( MbVector3D & norm ) const; // \ru Нормаль в точке с параметрами u=0. \en Normal at u=0. - void Derivatives( double u, double v, bool ext, MbVector3D & uDer, MbVector3D & vDer ) const; // \ru Ппроизводные. \en Derivatives with respect to u and to v. - void operator = ( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCornerSurface ) -}; // MbCornerSurface - -IMPL_PERSISTENT_OPS( MbCornerSurface ) - -//------------------------------------------------------------------------------ -// \ru Определение местных координат \en Determination of local coordinates -// --- -inline void MbCornerSurface::CalculateCoordinate( double & u, double & v, bool ext, - double & s0, double & s1, double & s2, - double & c0, double & c1, double & c2, - double & t0, double & t1, double & t2 ) const -{ - if ( !ext ) { - if ( v <-1.0 ) v =-1.0; - if ( u > 1.0 ) u = 1.0; - if ( v > 1.0 ) v = 1.0; - } - if (u < 0.0) - u = 0.0; // \ru Нельзя заходить за полюс. \en Is impossible to go behind a pole - - s0 = 1.0 - u; - s1 = 0.5 * (u - u*v); - s2 = 0.5 * (u + u*v); -// \ru Пересчет параметров u,v в параметры a,b,c \en Recalculation of u,v parameters to a,b,c parameters -// -// v c=1 -// +1 | /| -// | / | -// curve1 / | curve0 -// |/ | -// a=1+----+--> u -// |\ |1 -// curve2 \ | -// | \ | -// -1 | \| -// | b=1 -// - c0 = t0min*(1.0-s1) + t0max*s1; - c1 = t1min*(1.0-s2) + t1max*s2; - c2 = t2min*(1.0-s0) + t2max*s0; - t0 = t0min*s2 + t0max*(1.0-s2); - t1 = t1min*s0 + t1max*(1.0-s0); - t2 = t2min*s1 + t2max*(1.0-s1); - - //if ( u < PARAM_EPSILON ) { - // if ( vc> PARAM_EPSILON && v> PARAM_EPSILON ) - // v = 1.0; - // else - // if ( vc<-PARAM_EPSILON && v<-PARAM_EPSILON ) - // v =-1.0; - //} -} - - -//------------------------------------------------------------------------------ -// \ru Получить кривую по индексу \en Get curve by an index -// --- -inline const MbCurve3D * MbCornerSurface::GetCurve( size_t ind ) const -{ - if ( ind >= CORNER_COUNT ) - ind = ind % CORNER_COUNT; - switch ( ind ) { - case 0 : { return curve0; } - case 1 : { return curve1; } - case 2 : { return curve2; } - } - return NULL; -} - - -//------------------------------------------------------------------------------ -// \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. -// --- -inline double MbCornerSurface::GetTMin( size_t ind ) const -{ - if ( ind >= CORNER_COUNT ) - ind = ind % CORNER_COUNT; - switch ( ind ) { - case 0 : { return t0min; } - case 1 : { return t1min; } - case 2 : { return t2min; } - } - return UNDEFINED_DBL; -} - - -//------------------------------------------------------------------------------ -// \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. -// --- -inline double MbCornerSurface::GetTMax( size_t ind ) const -{ - if ( ind >= CORNER_COUNT ) - ind = ind % CORNER_COUNT; - switch ( ind ) { - case 0 : { return t0max; } - case 1 : { return t1max; } - case 2 : { return t2max; } - } - return UNDEFINED_DBL; -} - - -#endif // __SURF_CORNER_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Треугольная поверхность на сетке из трех кривых. + \en Triangular surface on grid of three curves. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_CORNER_SURFACE_H +#define __SURF_CORNER_SURFACE_H + + +#include + + +#define CORNER_COUNT 3 ///< \ru Число кривых, нужных для построения треугольной поверхности. \en Count of curves used to construct triangular surface. +#define VECT_CNT CORNER_COUNT + + +class MATH_CLASS MbContour3D; + + +//------------------------------------------------------------------------------ +/** \brief \ru Треугольная поверхность на кривых. + \en Triangular surface on curves. \~ + \details \ru Треугольная поверхность на сетке из трех кривых. + Кривые должны попарно пересекаться или иметь точки скрещения. + Если кривые попарно пересекаются, то поверхность проходит через определяющиее её кривые. \n + \en Triangular surface on grid of three curves. + 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 MbCornerSurface : public MbSurface { +// P2 +// t1max ^* t0min +// R(s0,s1,s2) = / * +// (curve2(1-s1)+curve1(s2)-P0)*s0+ / * +// (curve0(1-s2)+curve2(s0)-P1)*s1+ / * +// (curve1(1-s0)+curve0(s1)-P2)*s2 curve1 / * curve0 +// / R * +// s0(u,v) + s1(u,v) + s2(u,v) = 1 / * +// R(0,s1,s2) = curve0(s1) / * +// R(s0,0,s2) = curve1(s2) t1min <----------------v t0max +// R(s0,s1,0) = curve2(s0) P0 P1 +// t2max curve2 t2min +// +// \ru s0,s1,s2 - Барицентрические (треугольные) координаты, \en S0,s1,s2 - Baricentric (triangular) coordinates. +// \ru P0 - полюс \en P0 - pole +private: + MbCurve3D * curve0; ///< \ru Кривая 0. \en Curve 0. + MbCurve3D * curve1; ///< \ru Кривая 1. \en Curve 1. + MbCurve3D * curve2; ///< \ru Кривая 2. \en Curve 2. + MbCartPoint3D vertex[CORNER_COUNT]; ///< \ru Вершины P0, P1, P2. \en Vertices P0, P1, P2. + 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. + +public: + /** \brief \ru Конструктор треугольной поверхности. + \en Constructor of triangular surface. \~ + \details \ru Конструктор треугольной поверхности по набору кривых. + \en Constructor of triangular 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. \~ + */ + MbCornerSurface ( const MbCurve3D & initCurve0, const MbCurve3D & initCurve1, const MbCurve3D & initCurve2 ); +private: + MbCornerSurface( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. + MbCornerSurface( const MbCornerSurface & init, MbRegDuplicate * ); +public: + virtual ~MbCornerSurface( void ); + +public: + VISITING_CLASS( MbCornerSurface ); + + /// \ru Инициализация треугольной поверхности заданной треугольной поверхностью. \en Initialization of triangular surface by given triangular surface. + void Init( const MbCornerSurface &init ); + + /** \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 CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, + size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const; + + 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 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. + 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 TangentV ( double & u, double & v, MbVector3D & p ) const; + 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 _TangentV ( double u, double v, MbVector3D & p ) const; + virtual void _Normal ( double u, double v, MbVector3D & p ) const; // \ru Нормаль \en Normal + virtual void _NormalV ( double u, double v, MbVector3D & p ) const; // \ru Производная нормали \en Derivative of 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 the approximation step with consideration of the curvature radius by U + virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по V \en Calculation of the approximation step with consideration of the curvature radius by V + 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 there is pole on boundary of parametric region + + 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 Получить кривую по индексу. \en Get curve by an index. + const MbCurve3D * GetCurve( size_t ind ) const; + /// \ru Получить количество кривых. \en Get count of curves. + size_t GetCurvesCount() const { return 3; } //-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 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. + /** \} */ + +private: + void Init(); + inline void CalculateCoordinate( double & u, double & v, bool ext, + double & s0, double & s1, double & s2, + double & c0, double & c1, double & c2, + double & t0, double & t1, double & t2 ) const; + void CalculatePoint ( double & u, double & v, bool ext, + MbCartPoint3D & point ) const; + void CalculateFirst ( double & u, double & v, bool ext, + MbVector3D * first ) const; + void CalculateSecond( double & u, double & v, bool ext, + MbVector3D * second ) const; + void CalculateThird ( double & u, double & v, bool ext, + MbVector3D * second, MbVector3D * third ) const; + void CalculateExplore( double & u, double & v, bool ext, + MbCartPoint3D * point, MbVector3D * first, MbVector3D * second ) const; + bool GetNormalFactor( MbVector3D & norm ) const; // \ru Нормаль в точке с параметрами u=0. \en Normal at u=0. + void Derivatives( double u, double v, bool ext, MbVector3D & uDer, MbVector3D & vDer ) const; // \ru Ппроизводные. \en Derivatives with respect to u and to v. + void operator = ( const MbCornerSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCornerSurface ) +}; // MbCornerSurface + +IMPL_PERSISTENT_OPS( MbCornerSurface ) + +//------------------------------------------------------------------------------ +// \ru Определение местных координат \en Determination of local coordinates +// --- +inline void MbCornerSurface::CalculateCoordinate( double & u, double & v, bool ext, + double & s0, double & s1, double & s2, + double & c0, double & c1, double & c2, + double & t0, double & t1, double & t2 ) const +{ + if ( !ext ) { + if ( v <-1.0 ) v =-1.0; + if ( u > 1.0 ) u = 1.0; + if ( v > 1.0 ) v = 1.0; + } + if (u < 0.0) + u = 0.0; // \ru Нельзя заходить за полюс. \en Is impossible to go behind a pole + + s0 = 1.0 - u; + s1 = 0.5 * (u - u*v); + s2 = 0.5 * (u + u*v); +// \ru Пересчет параметров u,v в параметры a,b,c \en Recalculation of u,v parameters to a,b,c parameters +// +// v c=1 +// +1 | /| +// | / | +// curve1 / | curve0 +// |/ | +// a=1+----+--> u +// |\ |1 +// curve2 \ | +// | \ | +// -1 | \| +// | b=1 +// + c0 = t0min*(1.0-s1) + t0max*s1; + c1 = t1min*(1.0-s2) + t1max*s2; + c2 = t2min*(1.0-s0) + t2max*s0; + t0 = t0min*s2 + t0max*(1.0-s2); + t1 = t1min*s0 + t1max*(1.0-s0); + t2 = t2min*s1 + t2max*(1.0-s1); + + //if ( u < PARAM_EPSILON ) { + // if ( vc> PARAM_EPSILON && v> PARAM_EPSILON ) + // v = 1.0; + // else + // if ( vc<-PARAM_EPSILON && v<-PARAM_EPSILON ) + // v =-1.0; + //} +} + + +//------------------------------------------------------------------------------ +// \ru Получить кривую по индексу \en Get curve by an index +// --- +inline const MbCurve3D * MbCornerSurface::GetCurve( size_t ind ) const +{ + if ( ind >= CORNER_COUNT ) + ind = ind % CORNER_COUNT; + switch ( ind ) { + case 0 : { return curve0; } + case 1 : { return curve1; } + case 2 : { return curve2; } + } + return NULL; +} + + +//------------------------------------------------------------------------------ +// \ru Минимальное значение параметра на кривой с индексом ind. \en Get The minimal value of parameter on curve by index. +// --- +inline double MbCornerSurface::GetTMin( size_t ind ) const +{ + if ( ind >= CORNER_COUNT ) + ind = ind % CORNER_COUNT; + switch ( ind ) { + case 0 : { return t0min; } + case 1 : { return t1min; } + case 2 : { return t2min; } + } + return UNDEFINED_DBL; +} + + +//------------------------------------------------------------------------------ +// \ru Максимальное значение параметра на кривой с индексом ind. \en Get The maximal value of parameter on curve by index. +// --- +inline double MbCornerSurface::GetTMax( size_t ind ) const +{ + if ( ind >= CORNER_COUNT ) + ind = ind % CORNER_COUNT; + switch ( ind ) { + case 0 : { return t0max; } + case 1 : { return t1max; } + case 2 : { return t2max; } + } + return UNDEFINED_DBL; +} + + +#endif // __SURF_CORNER_SURFACE_H diff --git a/C3d/Include/surf_cover_surface.h b/C3d/Include/surf_cover_surface.h index 9d19032..94b3e23 100644 --- a/C3d/Include/surf_cover_surface.h +++ b/C3d/Include/surf_cover_surface.h @@ -196,6 +196,12 @@ public: 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 diff --git a/C3d/Include/surf_curve_bounded_surface.h b/C3d/Include/surf_curve_bounded_surface.h index 3d72a12..2b7bb35 100644 --- a/C3d/Include/surf_curve_bounded_surface.h +++ b/C3d/Include/surf_curve_bounded_surface.h @@ -88,7 +88,7 @@ class MbContoursSearchTree; \ingroup Surfaces */ // --- -class MATH_CLASS MbCurveBoundedSurface : public MbSurface, public MbNestSyncItem { +class MATH_CLASS MbCurveBoundedSurface : public MbSurface { private: MbSurface * basisSurface; ///< \ru Базовая поверхность. \en Base surface. RPArray curves; ///< \ru Множество контуров на поверхности, определяющих её края. \en Set of contours on surface determining surface boundary. @@ -114,9 +114,11 @@ public : /// \ru Конструктор с массивом контуров на плоскости (двумерных контуров). \en Constructor with array of contours on plane (two-dimensional contours). MbCurveBoundedSurface( MbSurface & initSurface, RPArray & initCurves, bool sameContours ); /// \ru Конструктор с массивом контуров на плоскости (двумерных контуров). \en Constructor with array of contours on plane (two-dimensional contours). - MbCurveBoundedSurface( MbSurface & initSurface, std::vector< SPtr > & initCurves, bool sameContours ); + MbCurveBoundedSurface( MbSurface & initSurface, c3d::PlaneContoursSPtrVector & initCurves, bool sameContours ); /// \ru Конструктор для поверхности c габаритом при чтении грани. \en Constructor for surface with bounding box at face reading. MbCurveBoundedSurface( MbSurface & initSurface, RPArray & initCurves, MbCube & gab ); + /// \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 ); /// \ru Конструктор-копия на новую базовую поверхность. \en Copy-constructor for new base surface. @@ -430,7 +432,7 @@ public : */ bool ChangeContour( size_t index, MbContourOnSurface * cntr ); /// \ru Заменить базовую поверхность. \en Replace base surface. - bool ChangeSurface( MbSurface & newsurf ); + bool ChangeSurface( const MbSurface & newsurf ); /// \ru Заменить базовую поверхность на ее копию. \en Replace base surface with its copy. void NewBasisSurface(); /// \ru Вычислить параметрические границы поверхности без сброса габарита. \en Calculate parametric bounds of surface without resetting the bounding box. @@ -458,7 +460,7 @@ public : /** \brief \ru Ориентировать ограничивающие контуры. \en Orient bounding contours. \~ - \details \ru Ориентирует внешний контур против часовой стрелки, внутренние контуры - по часовой стрелки. + \details \ru Ориентирует внешний контур против часовой стрелки, внутренние контуры - по часовой стрелке. \en External contour is oriented counterclockwise, internal contours - clockwise. \~ \return \ru Возвращает площадь параметрической области поверхности. \en Returns area of parametric region of surface. \~ diff --git a/C3d/Include/surf_cylinder_surface.h b/C3d/Include/surf_cylinder_surface.h index a1b6c92..a77edfb 100644 --- a/C3d/Include/surf_cylinder_surface.h +++ b/C3d/Include/surf_cylinder_surface.h @@ -54,7 +54,7 @@ class MATH_CLASS MbPlane; \ingroup Surfaces */ // --- -class MATH_CLASS MbCylinderSurface : public MbElementarySurface { +class MATH_CLASS MbCylinderSurface : public MbElementarySurface { private: double radius; ///< \ru Радиус цилиндра. \en Radius of cylinder. double height; ///< \ru Высота цилиндра. \en Height of cylinder. diff --git a/C3d/Include/surf_elementary_surface.h b/C3d/Include/surf_elementary_surface.h index 9cf446f..cc51887 100644 --- a/C3d/Include/surf_elementary_surface.h +++ b/C3d/Include/surf_elementary_surface.h @@ -15,9 +15,9 @@ #include -#define CIRC_COUNT 32 -#define HIDE_COUNT 16 -#define LINE_COUNT 10 +const_expr size_t CIRC_COUNT = 32; +const_expr size_t HIDE_COUNT = 16; +const_expr size_t LINE_COUNT = 10; //------------------------------------------------------------------------------ diff --git a/C3d/Include/surf_expansion_surface.h b/C3d/Include/surf_expansion_surface.h index 11b8643..199e813 100644 --- a/C3d/Include/surf_expansion_surface.h +++ b/C3d/Include/surf_expansion_surface.h @@ -20,14 +20,14 @@ \en Motion surface (plane-parallel swept surface). \~ \details \ru Поверхность плоскопараллельного движения получается путем движения образующей кривой curve по направляющей кривой spine->curve параллельно самой себе: - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = curve(u) + spine(v) - origin. \n Направляющая плоскопараллельной поверхности должна быть незамкнутой монотонной кривой. Первый параметр поверхности совпадает с параметром образующей кривой. Второй параметр поверхности совпадает с параметром направляющей кривой. \en Expansion surface is obtained by moving 'curve' generating curve along 'spine->curve" guide curve parallel to itself: - Radius-vector of surface is described by the vector function \n + Radius-vector of surface is described by the vector function \n r(u,v) = curve(u) + spine(v) - origin. \n Guide curve of plane-parallel surface should be open monotonous curve. First parameter of surface coincides with parameter of generating curve. diff --git a/C3d/Include/surf_exploration_surface.h b/C3d/Include/surf_exploration_surface.h index 07f018d..a102f9e 100644 --- a/C3d/Include/surf_exploration_surface.h +++ b/C3d/Include/surf_exploration_surface.h @@ -1,194 +1,194 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность заметания с масштабированием и поворотом образующей кривой. - \en The swept surface with scaling and winding of generation curve. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_EXTENSION_SURFACE_H -#define __SURF_EXTENSION_SURFACE_H - - -#include -#include - - -class MATH_CLASS MbFunction; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность заметания с масштабированием и поворотом образующей кривой. - \en The swept surface with scaling and winding of generation curve. \~ - \details \ru Кинематическая поверхность образуется путем движения образующей кривой curve по направляющей кривой spine->curve. - В процессе движения вдоль направляющей кривой образующая кривая сохраняет своё положение в движущейся локальной системе координат, - начало которой совпадает с текущей точкой базовой кривой. - Одна из осей движущейся локальной системы координат всегда совпадает с касательной направляющей кривой, - а две другие оси ортогональны ей. - Первый параметр поверхности совпадает с параметром образующей кривой. - Второй параметр поверхности совпадает с параметром направляющей кривой. - \en Sweep with guide curve surface is formed by moving the 'curve' generating curve along spine->curve guide curve. - While moving along a guide curve the generating curve keeps its position in the moving local coordinate system, - which origin coincides with the current point of the base curve. - One of the axes of the moving local coordinate system is always coincident to the tangent of the guide curve, - and the other two axes are orthogonal to it. - First parameter of surface coincides with parameter of generating curve. - Second parameter of surface coincides with parameter of guide curve. \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbExplorationSurface : public MbEvolutionSurface { -protected: - MbFunction * scaling; ///< \ru Функция второго параметра (v) масштабирования образующей кривой. \en The function of curve scale by second parameter (v). - MbFunction * winding; ///< \ru Функция второго параметра (v) вращения образующей кривой. \en The function of curve rotation by second parameter (v). - MbAxis3D axis; ///< \ru Не пишется. \en The axis are not writing. - -protected: - /** \brief \ru Конструктор по образующей и направляющей. - \en Constructor by generating curve and guide curve. \~ - \details \ru Конструктор по образующей и направляющей. - \en Constructor by generating curve and guide curve. \~ - \param[in] c - \ru Образующая - \en Generating curve \~ - \param[in] s - \ru Направляющая - \en Guide curve \~ - \param[in] sameCurve - \ru Признак использования оригинала образующей, а не копии - \en Attribute of usage of original of generating curve, not a copy \~ - \param[in] sameSpine - \ru Признак использования оригинала направляющей, а не копии - \en Attribute of usage of original of guide curve, not a copy \~ - */ - MbExplorationSurface( const MbCurve3D & c, const MbSpine & s, bool sameCurve, bool sameSpine, - MbFunction & _scaling, MbFunction & _winding ); - -protected: - MbExplorationSurface( const MbExplorationSurface &, MbRegDuplicate * ); -private: - MbExplorationSurface( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. -public: - virtual ~MbExplorationSurface(); - -public: - VISITING_CLASS( MbExplorationSurface ); - - /** \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 Сделать копию элемента. \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 GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. - virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. - - /** \} */ - /** \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 & ) const; // \ru Точка на поверхности. \en The point on the surface. - virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; - virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; - virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; - virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; - /** \} */ - /** \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 & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; - /** \} */ - /** \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 the parameter step in u direction by the sag. - virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. - virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. - virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. - /** \} */ - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - 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. - - 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. - - // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const; - - virtual size_t GetUCount() const; // \ru Количество разбиений по параметру u для проверки событий. \en The number of splittings by u-parameter for a check of events. - virtual size_t GetVCount() const; // \ru Количество разбиений по параметру v для проверки событий. \en The number of splittings by v-parameter for a check of events. - - 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. - - //------------------------------------------------------------------------------ - /** \brief \ru Создать кинематическую поверхность. - \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. \~ - \return \ru Возвращает созданную поверхность. - \en Return the created surface. \~ - \ingroup Surface_Modeling - */ - // --- - static MbSurface * Create( const MbCurve3D & curve, const MbSpine & spine, bool samec, bool sames, - MbFunction & _scaling, MbFunction & _winding ); - -protected : - void Init(); - -private: - void operator = ( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExplorationSurface ) -}; - - -#endif // __SURF_EXTENSION_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность заметания с масштабированием и поворотом образующей кривой. + \en The swept surface with scaling and winding of generation curve. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_EXTENSION_SURFACE_H +#define __SURF_EXTENSION_SURFACE_H + + +#include +#include + + +class MATH_CLASS MbFunction; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность заметания с масштабированием и поворотом образующей кривой. + \en The swept surface with scaling and winding of generation curve. \~ + \details \ru Кинематическая поверхность образуется путем движения образующей кривой curve по направляющей кривой spine->curve. + В процессе движения вдоль направляющей кривой образующая кривая сохраняет своё положение в движущейся локальной системе координат, + начало которой совпадает с текущей точкой базовой кривой. + Одна из осей движущейся локальной системы координат всегда совпадает с касательной направляющей кривой, + а две другие оси ортогональны ей. + Первый параметр поверхности совпадает с параметром образующей кривой. + Второй параметр поверхности совпадает с параметром направляющей кривой. + \en Sweep with guide curve surface is formed by moving the 'curve' generating curve along spine->curve guide curve. + While moving along a guide curve the generating curve keeps its position in the moving local coordinate system, + which origin coincides with the current point of the base curve. + One of the axes of the moving local coordinate system is always coincident to the tangent of the guide curve, + and the other two axes are orthogonal to it. + First parameter of surface coincides with parameter of generating curve. + Second parameter of surface coincides with parameter of guide curve. \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbExplorationSurface : public MbEvolutionSurface { +protected: + MbFunction * scaling; ///< \ru Функция второго параметра (v) масштабирования образующей кривой. \en The function of curve scale by second parameter (v). + MbFunction * winding; ///< \ru Функция второго параметра (v) вращения образующей кривой. \en The function of curve rotation by second parameter (v). + MbAxis3D axis; ///< \ru Не пишется. \en The axis are not writing. + +protected: + /** \brief \ru Конструктор по образующей и направляющей. + \en Constructor by generating curve and guide curve. \~ + \details \ru Конструктор по образующей и направляющей. + \en Constructor by generating curve and guide curve. \~ + \param[in] c - \ru Образующая + \en Generating curve \~ + \param[in] s - \ru Направляющая + \en Guide curve \~ + \param[in] sameCurve - \ru Признак использования оригинала образующей, а не копии + \en Attribute of usage of original of generating curve, not a copy \~ + \param[in] sameSpine - \ru Признак использования оригинала направляющей, а не копии + \en Attribute of usage of original of guide curve, not a copy \~ + */ + MbExplorationSurface( const MbCurve3D & c, const MbSpine & s, bool sameCurve, bool sameSpine, + MbFunction & _scaling, MbFunction & _winding ); + +protected: + MbExplorationSurface( const MbExplorationSurface &, MbRegDuplicate * ); +private: + MbExplorationSurface( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. +public: + virtual ~MbExplorationSurface(); + +public: + VISITING_CLASS( MbExplorationSurface ); + + /** \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 Сделать копию элемента. \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 GetProperties( MbProperties & ); // \ru Выдать свойства объекта. \en Get properties of the object. + virtual void SetProperties( const MbProperties & ); // \ru Записать свойства объекта. \en Set properties of the object. + + /** \} */ + /** \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 & ) const; // \ru Точка на поверхности. \en The point on the surface. + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; + /** \} */ + /** \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 & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; + /** \} */ + /** \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 the parameter step in u direction by the sag. + virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. + virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. + virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. + /** \} */ + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + 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. + + 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. + + // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; + + virtual size_t GetUCount() const; // \ru Количество разбиений по параметру u для проверки событий. \en The number of splittings by u-parameter for a check of events. + virtual size_t GetVCount() const; // \ru Количество разбиений по параметру v для проверки событий. \en The number of splittings by v-parameter for a check of events. + + 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. + + //------------------------------------------------------------------------------ + /** \brief \ru Создать кинематическую поверхность. + \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. \~ + \return \ru Возвращает созданную поверхность. + \en Return the created surface. \~ + \ingroup Surface_Modeling + */ + // --- + static MbSurface * Create( const MbCurve3D & curve, const MbSpine & spine, bool samec, bool sames, + MbFunction & _scaling, MbFunction & _winding ); + +protected : + void Init(); + +private: + void operator = ( const MbExplorationSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbExplorationSurface ) +}; + + +#endif // __SURF_EXTENSION_SURFACE_H diff --git a/C3d/Include/surf_extrusion_surface.h b/C3d/Include/surf_extrusion_surface.h index 2cc76c0..89f83fa 100644 --- a/C3d/Include/surf_extrusion_surface.h +++ b/C3d/Include/surf_extrusion_surface.h @@ -22,11 +22,11 @@ class MATH_CLASS MbOffsetSurface; /** \brief \ru Поверхность выдавливания. \en Extrusion surface. \~ \details \ru Поверхность выдавливания является кинематической поверхностью с прямолинейной образующей. - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = curve(u) + (direction distance v). \n Первый параметр поверхности совпадает с параметром образующей кривой. \en Extrusion surface is swept surface with rectilinear generating curve. - Radius-vector of surface is described by the vector function \n + Radius-vector of surface is described by the vector function \n r(u,v) = curve(u) + (direction distance v). \n First parameter of surface coincides with parameter of generating curve. \~ \ingroup Surfaces diff --git a/C3d/Include/surf_fillet_surface.h b/C3d/Include/surf_fillet_surface.h index 3faa846..9b0e375 100644 --- a/C3d/Include/surf_fillet_surface.h +++ b/C3d/Include/surf_fillet_surface.h @@ -1,712 +1,713 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность скругления с постоянными радиусами обычная или с сохранением кромки. - \en Fillet surface of constant radii, ordinary or with preservation of fillet. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_FILLET_SURFACE_H -#define __SURF_FILLET_SURFACE_H - - -#include - - -class MATH_CLASS MbFunction; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность скругления с постоянными радиусами обычная или с сохранением кромки. - \en Fillet surface of constant radii, ordinary or with preservation of fillet. \~ - \details \ru Поверхность скругления является NURBS-поверхностью, - построенной по трём кривым: curve1, curve0, curve2. - Первый параметр поверхности совпадает с параметром кривых curve1, curve0, curve2. - Второй параметр изменяется от нуля (точки совпадают с curve1) до единицы (точки совпадают с curve2). - В отличие от других поверхностей Функции PointOn и Derive... поверхность скругления не корректирует - первый параметр при выходе его за пределы области определения. - Если коэффициент формы conic = _ARC_ ( 0 ), то вес каждой точки кривой curve0 задаётся функцией weights0 и - вычислен так, что сечение поверхности вдоль её второго параметра будет дугой окружности, - то есть при любом параметре u три точки curve1(u), curve0(u), curve2(u) определяют NURBS-кривую в форме дуги окружности. - Если коэффициент формы conic != _ARC_, то вес каждой точки кривой curve0 равен conic / ( 1.0 - conic ). - При conic = 0.5 сечение поверхности вдоль её второго параметра будет параболой. \n - \en Fillet surface is NURBS-surface - constructed by three curves: curve1, curve0, curve2. - First parameter of surface coincides with parameter of curve1, curve0, curve2 curves. - Second parameter is changed between 0 (points are coincident to curve1) and 1 (points are coincident to curve2). - For fillet surface in contrast to other surfaces PointOn and Derive... functions don't correct - first parameter when it is out of domain bounds. - If coefficient of shape conic = _ARC_ ( 0 ), then weight of each point of curve0 curve is given by weights0 function and - is calculated as that the section of surface along its second parameter will be a circular arc, - that is three points curve1(u), curve0(u), curve2(u) determine NURBS-curve with shape of circular arc at any u parameter. - If coefficient of shape conic != _ARC_, then weight of each point of curve0 curve is equal to conic / ( 1.0 - conic ). - If conic = 0.5, then section of surface along its second parameter will be a parabola. \n \~ - \ingroup Surfaces -*/// --- -class MATH_CLASS MbFilletSurface : public MbSmoothSurface { -protected: - MbCurve3D * curve0; ///< \ru Кривая пересечения касательных к поверхностям - всегда не NULL. \en Intersection curve of tangents to surfaces - always not 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. - bool equable; ///< \ru true - обычная поверхность, false - curve1 или curve2 является кромкой. \en True - ordinary surface, false - curve1 or curve2 is fillet. - bool byCurve1; ///< \ru true - curve2 является кромкой, false - curve1 является кромкой. \en True - curve2 is fillet, false - curve1 is fillet. - MbCurve3D * spine; ///< \ru Кривая центров дуг окружности для случая равномерной параметризации. \en Curve of centers of circular arcs in case of uniform parameterization. - MbVector3D * spineDerUMin; // \ru Производные spine в точках uMin и uMax ( для случая равномерной параметризации ). \en Derivatives of spine at uMin and uMax points (in case of uniform parameterization). - MbVector3D * spineDerUMax; // \ru Производные spine в точках uMin и uMax ( для случая равномерной параметризации ). \en Derivatives of spine at uMin and uMax points (in case of uniform parameterization). - -public: - - /** \brief \ru Конструктор поверхности скругления. - \en Constructor of fillet surface. \~ - \details \ru Конструктор поверхности скругления. - \en Constructor of fillet surface. \~ - \param[in] curv1 - \ru Опорная кривая на первой поверхности - \en Support curve on the first surface \~ - \param[in] curv2 - \ru Опорная кривая на второй поверхности - \en Support curve on the second surface \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой curve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой curve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой - st_Fillet - скругление с заданными радиусами - \en Conjugation type: \n - st_Span - fillet with a given chord - st_Fillet - fillet with given radii \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) - \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Whether arc length parameterization is uniform or not \~ - */ - MbFilletSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, - double d1, double d2, MbeSmoothForm fm, double cn, bool ev ); - - /** \brief \ru Конструктор поверхности с сохранением кромки. - \en Constructor of surface with preservation of fillet. \~ - \details \ru Конструктор поверхности с сохранением кромки. - \en Constructor of surface with preservation of fillet. \~ - \param[in] curv1 - \ru Опорная кривая на первой поверхности - \en Support curve on the first surface \~ - \param[in] curv2 - \ru Опорная кривая на второй поверхности - \en Support curve on the second surface \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой \n - st_Fillet - скругление с заданными радиусами - \en Conjugation type: \n - st_Span - fillet with a given chord\n - st_Fillet - fillet with given radii \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) - \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ - \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой - \en True - curve2 curve is fillet, false - curve1 curve is fillet. \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Whether arc length parameterization is uniform or not \~ - */ - MbFilletSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, - double d1, double d2, MbeSmoothForm fm, double cn, bool byFirst, bool ev ); - - /** \brief \ru Конструктор поверхности скругления. - \en Constructor of fillet surface. \~ - \details \ru Конструктор поверхности скругления c кривой пересечения касательных к поверхностям. - \en Constructor of fillet surface with intersection curve of tangents to surfaces. \~ - \param[in] surf1 - \ru Первая поверхность - \en First surface \~ - \param[in] curv1 - \ru Опорная кривая в параметрах первой поверхности - \en Support curve at parameters of the first surface \~ - \param[in] surf2 - \ru Вторая поверхность - \en Second surface \~ - \param[in] curv2 - \ru Опорная кривая в параметрах второй поверхности - \en Support curve at parameters of the second surface \~ - \param[in] curv0 - \ru Кривая пересечения касательных к поверхностям - \en Intersection curve of tangents to surfaces \~ - \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой curv1 - \en Fillet radius with sign for surface of curv1 curve \~ - \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой curv2 - \en Fillet radius with sign for surface of curv2 curve \~ - \param[in] fm - \ru Тип сопряжения: \n - st_Span - скругление с заданной хордой \n - st_Fillet - скругление с заданными радиусами - \en Conjugation type: \n - st_Span - fillet with a given chord\n - st_Fillet - fillet with given radii \~ - \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) - \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ - \param[in] ev - \ru Равномерная параметризация по дуге или нет - \en Whether arc length parameterization is uniform or not \~ - */ - MbFilletSurface( MbSurface & surf1, MbCurve & curv1, - MbSurface & surf2, MbCurve & curv2, - MbCurve3D & curv0, double d1, double d2, MbeSmoothForm fm, double cn, bool ev ); - -protected: - /// \ru Конструктор для наследников обычной поверхности скругления. \en Constructor for inheritors of ordinary fillet surface. - MbFilletSurface( MbSurfaceCurve & curv1, double d1, - MbSurfaceCurve & curv2, double d2, MbeSmoothForm fm, double cn, bool ev ); - /// \ru Конструктор для наследников поверхности с сохранением кромки. \en Constructor for inheritors of surface with preservation of fillet. - MbFilletSurface( MbSurfaceCurve & curv1, double d1, - MbSurfaceCurve & curv2, double d2, MbeSmoothForm fm, double cn, bool byFirst, bool ev ); - /// \ru Конструктор поверхности скругления c кривой пересечения касательных к поверхностям. \en Constructor of fillet surface with intersection curve of tangents to surfaces. \~ - MbFilletSurface( MbSurface & surf1, MbCurve & curv1, double d1, - MbSurface & surf2, MbCurve & curv2, double d2, - MbCurve3D & curv0, MbFunction & weig0, - MbeSmoothForm fm, double cn, bool ev ); - - /// \ru Конструктор копирования. \en Copy-constructor. - MbFilletSurface( const MbFilletSurface &, MbRegDuplicate * ); - /// \ru Конструктор копирования с теми же опорными поверхностями. \en Copy-constructor with the same support surfaces. - MbFilletSurface( const MbFilletSurface * ); - // \ru Для CurvesDuplicate() \en For CurvesDuplicate() -private: - MbFilletSurface( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. -public: - virtual ~MbFilletSurface (); - -public: - VISITING_CLASS( MbFilletSurface ); - - /** \ru \name Функции инициализации - \en \name Initialization functions - \{ */ - // \ru Коррекция средней линии поверхности скругления. \en Correction of mid-line of fillet surface. - virtual void Init0( double wmin, double wmax, bool insertPoints = true ); - /** \} */ - /** \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 Сделать копию элемента. \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 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 base surfaces. - - /** \} */ - /** \ru \name Функции описания области определения поверхности - \en \name Functions for surface domain description - \{ */ - virtual double GetVPeriod() const; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. - - /** \} */ - /** \ru \name Функции для работы в области определения поверхности - Функции PointOn и Derive... поверхностей сопряжения не корректируют - первый параметр при его выходе за пределы определения параметров. - \en \name Functions for working at surface domain - Functions PointOn, Derive... of smooth surfaces don't correct - first parameter when it is out of domain bounds. - \{ */ - virtual void PointOn ( double &u, double &v, MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. - virtual void DeriveU ( double &u, double &v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - virtual void DeriveV ( double &u, double &v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - virtual void DeriveUU ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - virtual void DeriveVV ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - virtual void DeriveUV ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - virtual void DeriveUUU( double &u, double &v, MbVector3D & ) const; - virtual void DeriveUUV( double &u, double &v, MbVector3D & ) const; - virtual void DeriveUVV( double &u, double &v, MbVector3D & ) const; - virtual void DeriveVVV( double &u, double &v, MbVector3D & ) const; - virtual void Normal ( double &u, double &v, MbVector3D & ) const; // \ru Нормаль. \en Normal. - virtual void NormalU ( double &u, double &v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - virtual void NormalV ( double &u, double &v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of 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 & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; - virtual void _Normal ( double u, double v, MbVector3D & ) const; // \ru Нормаль. \en Normal. - virtual void _NormalU ( double u, double v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - virtual void _NormalV ( double u, double v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of 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 Вычислить значения всех производных в точке. \en Calculate all derivatives at point. \~ - virtual void _PointNormal( double u, double v, - MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, - MbVector3D & norm, MbVector3D & uNorm, MbVector3D & vNorm, - MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer ) 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 the parameter step in u direction by the sag. - virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. - virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. - virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. - virtual double MetricStepV ( double u, double v, double length ) const; // \ru Вычисление шага по v по заданной длине. \en Calculation of the parameter step in v direction by the given length. - /** \} */ - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна вдоль v. \en Curvature along v. - - virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru Построить NURBS копию поверхности. \en Construct a NURBS copy of a surface. - virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; // \ru Построить NURBS-копию поверхности. \en Construct a NURBS-copy of a surface. - virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Create an offset surface. - - virtual MbCurve3D * CurveV( double u, MbRect1D *pRgn, bool bApprox = 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. - virtual bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); // \ru Изменение носимых элементов. \en Change a carrier elements. - // \ru Нахождениe точки касания поверхностей \en Searching of surfaces tangency point - virtual MbeNewtonResult SurfaceTangentNewton( const MbSurface &, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, - double &u0, double &v0, double &u1, double &v1, - bool ext0, bool ext1 ) const; - - // \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 double GetFilletRadius( const MbCartPoint3D & p ) const; // \ru Является ли поверхность скруглением. \en Whether the surface is fillet. - // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. - virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; - virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; - virtual bool GetCylinderAxis( MbAxis3D &axis ) const; // \ru Дать ось вращения для поверхности. \en Get a rotation axis of a surface. - // \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 ThreeStates Salient() const; // \ru Выпуклая ли поверхность. \en Whether the surface is convex. - virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. - 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 \name Функции поверхности сопряжения - \en \name Functions of smooth surface - \{ */ - virtual MbSmoothSurface & CurvesDuplicate() const; // \ru Копия с теми же опорными поверхностями. \en Copy with the same support surfaces. - 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. - // \ru Объединить поверхности путём включения поверхности init в данную поверхность. \en Unite surfaces by inclusion of 'init' surface into current surface. - virtual bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, - const MbSurface & init, bool add, MbMatrix & matr, - const MbSurfaceIntersectionCurve * seam ); - /// \ru Дать коэффициент для радиуса. \en Get coefficient for radius. - virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; - // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const; - - /** \} */ - /** \ru \name Функции поверхности скругления - \en \name Functions of fillet surface - \{ */ - - /** \brief \ru Веса точек средней кривой. - \en Weights of points of mid-curve. \~ - \details \ru Веса точек средней кривой. - \en Weights of points of mid-curve. \~ - \param[in] u - \ru Параметр на средней кривой (по направлению U) - \en Parameter on mid-curve (by U direction) \~ - */ - double GetWeight( double u ) const; - - /** \brief \ru Угол раствора дуги. - \en Arc opening angle. \~ - \details \ru Угол раствора дуги. - \en Arc opening angle. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \return \ru Угол раствора - \en Angle of opening \~ - */ - double GetAngle( double u ) const; // \ru Дать угол раствора дуги v \en Get v arc opening angle - - /** \brief \ru Ось поверхности в данной точке. - \en Axis of surface at given point. \~ - \details \ru Ось поверхности в данной точке. - \en Axis of surface at given point. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] axis - \ru Результат - ось вращения - \en Result - rotation axis \~ - */ - double GetLocalAxis ( double u, MbAxis3D & axis ) const; // \ru Дать ось поверхности в данной точке \en Get axis of surface at given point - - /** \brief \ru Дать точку на оси. - \en Get point on axis. \~ - \details \ru Дать точку на оси. - \en Get point on axis. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] p1 - \ru Точка на первой опорной кривой по параметру U - \en Point on first support curve by U parameter \~ - \param[out] p2 - \ru Точка на второй опорной кривой по параметру U - \en Point on second support curve by U parameter \~ - \param[out] p0 - \ru Точка на кривой пересечения касательных к поверхностям по параметру u (точка на оси) - \en Point on intersection curve of tangents to surfaces by u parameter (point on axis) \~ - */ - void GetCentrePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0 ) const; - - /** \brief \ru Дать среднюю точку. - \en Get the mid-point. \~ - \details \ru Дать среднюю точку. - \en Get the mid-point. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \param[out] p1 - \ru Точка на первой опорной кривой по параметру U - \en Point on first support curve by U parameter \~ - \param[out] p2 - \ru Точка на второй опорной кривой по параметру U - \en Point on second support curve by U parameter \~ - \param[out] p0 - \ru Средняя точка - \en Mid-point \~ - \param[out] w - \ru Вес полученной средней точки - \en Weight of obtained mid-point \~ - */ - bool GetMiddlePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0, double &w ) const; - - // \ru Если параметризация равномерная, то на продолжении по V замыкается и период зависит от U \en If parameterization is uniform, then it is closed on extension by V and period depends on U - /** \brief \ru Период по направлению V. - \en Period by direction V. \~ - \details \ru Период по направлению V.\n - Если параметризация поверхности равномерная, то период по направлению V зависит от параметра U. - \en Period by direction V.\n - If parameterization of surface is uniform, then period by direction V depends on U parameter. \~ - \param[in] u - \ru Параметр по направлению U - \en Parameter by U direction \~ - \return \ru Период для заданного параметра - \en Period for given parameter \~ - */ - double GetVPeriod( double u ) const; - - /// \ru Кривая пересечения касательных к поверхностям. \en Intersection curve of tangents to surfaces. - const MbCurve3D & GetCurve0() const { return *curve0; } - - /** \brief \ru Скругление не круговое. - \en Fillet isn't circular. \~ - \details \ru Скругление не круговое. - \en Fillet isn't circular. \~ - \return \ru true, если радиусы скруглений для поверхностей не равны - \en True if surfaces fillet radii aren't equal \~ - */ - bool IsEllipse() const { return (fabs(fabs(distance1) - fabs(distance2))>=LENGTH_EPSILON); } // \ru Не равные радиусы \en Not equal radii - - /// \ru Параметризация по дуге равномерная. \en Uniform arc length parameterization. - bool IsEven() const { return even; } - - /** \brief \ru Однородная ли поверхность скругления. - \en Whether the fillet surface is homogeneous. \~ - \details \ru Однородная ли поверхность скругления. Поверхность скругления без сохранения кромки. - \en Whether the fillet surface is homogeneous. Fillet surface without preservation of fillet. \~ - \return \ru false, если одна из кривых curve1 или curve2 является кромкой - \en False if one of curve1 or curve2 curves is fillet \~ - */ - bool IsFilletSurface() const { return equable; } - - /** \brief \ru Коническое сечение общего вида. - \en General conic section. \~ - \details \ru Коническое сечение общего вида. - \en General conic section. \~ - \return \ru false, если сечение поверхности скругления является дугой окружности - \en False if section of fillet surface is circular arc \~ - */ - bool IsConic() const { return ( ::fabs(conic - c3d::_ARC_) >= EPSILON ); } // \ru Коническое сечение общего вида \en General conic section - - /** \brief \ru Коэффициент формы. - \en Coefficient of shape. \~ - \details \ru Коэффициент формы сечения поверхности скругления.\n - Изменяется от 0.05 до 0.95, при 0 сечение является дугой окружности. - \en Coefficient of shape of section of fillet surface.\n - Is changed between 0.05 and 0.95, if 0, then section is circular arc. \~ - \return \ru Коэффициент - \en Coefficient \~ - */ - double Conic() const { return conic; } - - /** \brief \ru Поверхность скругления с сохранением кромки. - \en Fillet surface with preservation of fillet. \~ - \details \ru Поверхность скругления с сохранением кромки. - \en Fillet surface with preservation of fillet. \~ - \return \ru true, если одна из кривых curve1 или curve2 является кромкой - \en True if one of curve1 or curve2 curves is fillet \~ - */ - bool IsKerbSurface() const { return !equable; } - - /** \brief \ru Является ли первая кривая кромкой. - \en Whether the first curve is fillet. \~ - \details \ru Является ли первая кривая кромкой. - \en Whether the first curve is fillet. \~ - \return \ru true, если первая кривая является кромкой - \en True if the first curve is fillet. \~ - */ - bool ByFirstCurve() const { return byCurve1; } - - /** \brief \ru Установить поверхность скругления типа с сохранением кромки. - \en Set fillet surface with preservation of fillet. - Need to call this->Init0() after this method \~ - \details \ru Установить поверхность скругления с сохранением кромки и указать определяющую кривую на поверхности. - Далее нужно вызвать метод this->Init0(). - \en Set fillet surface with preservation of fillet. \~ - \param[in] bc1 - \ru Определяющая кривая на поверхности: curve1 (bc1 = true), curve2 (bc1 = false). - \en General curve on surface: curve1 (bc1 = true), curve2 (bc1 = false). \~ - */ - void SetKerbSurface( bool bc1 ) { if ( equable ) { equable = false; byCurve1 = bc1; } } - - // \ru Выдать функцию весов точек средней кривой curve0. \en Get weight function for points of mid-curve (curve0). - const MbFunction * GetWeights() const; - // \ru Установить функцию весов точек средней кривой curve0. \en Set weight function for points of mid-curve (curve0). - bool SetWeights( MbFunction & func ); - - MbCurve3D * GetSpine() const; - void SetSpine( MbCurve3D * ); - - /** \} */ -protected: - void WeightKoefficient( double & w ) const; // \ru Вычисление веса при заданном коэффициенте \en Calculation of weight at given coefficient - void InitFilletSurface ( const MbFilletSurface & init ); - void CalculateCurve( double wmin, double wmax, bool insertPoints ); - double CalculateVParam( const MbCartPoint3D & p, double u ) const; // \ru Нахождение параметра v проекции точки на вырожденную поверхность \en Searching of v parameter of point projection onto degenerate surface - -protected: - // \ru Вычисление точки \en Calculation of a point -// void CalculateSurface( double u ) const; - // \ru Дать коэффициент для радиуса \en Get coefficient for radius - virtual double FunctionValue( double u ) const; - void CalculateData ( double & u, double & v, - MbCartPoint3D & uPoint0, MbCartPoint3D & uPoint1, MbCartPoint3D & uPoint2, // \ru Точки на кривых curve0, curve1, curve2. \en Points on curve0, curve1, curve2. - MbVector3D * uFirst0, MbVector3D * uFirst1, MbVector3D * uFirst2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. - MbVector3D * uSecond0, MbVector3D * uSecond1, MbVector3D * uSecond2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. - double & uWeight, double * wFirst, double * wSecond, // \ru Вес и его производные средней точки uPoint0. \en The weight and it derivatives of the mid-point uPoint0. - double & uP0, double & uP1, double & uP2, double & uPw, // \ru Коэффициенты точек uPoint0, uPoint1, uPoint2. \en Coefficients of points uPoint0, uPoint1, uPoint2. - double & uF0, double & uF1, double & uF2, double & uFw ) const; // \ru Коэффициенты производных uFirst0, uFirst1, uFirst2. \en Coefficients of derivatives uFirst0, uFirst1, uFirst2. - void InitSpineDerives(); - void CalculatePointOn ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. - void CalculateDeriveU ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - void CalculateDeriveV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - void CalculateDeriveUU ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - void CalculateDeriveVV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - void CalculateDeriveUV ( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. - void CalculateDeriveUUU( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - MbVector3D & ) const; - void CalculateDeriveUUV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateDeriveUVV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateDeriveVVV( double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const double & uWeight, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; - void CalculateNormal ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Нормаль. \en Normal. - void CalculateNormalU ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, - const double & uWeight, const double & wFirst, const double & wSecond, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - void CalculateNormalV ( double & u, double & v, - const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, - const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, - const double & uWeight, const double & wFirst, - const double & uP0, const double & uP1, const double & uP2, const double & uPw, - const double & uF0, const double & uF1, const double & uF2, const double & uFw, - MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. - - // \ru Проверка параметров. \en Check parameters. - void CheckUParam( double & u ) const; - void CheckVParam( double & v ) const; - - void operator = ( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFilletSurface ) -}; // MbFilletSurface - - -IMPL_PERSISTENT_OPS( MbFilletSurface ) - - -//------------------------------------------------------------------------------ -// \ru Проверка параметра u по отношению к полюсам и замкнутости \en Check u parameter against poles and closedness -// --- -inline void MbFilletSurface::CheckUParam( double & u ) const { - if ( uclosed ) { - if ( (u < umin) || (u > umax ) ) { - double tmp = umax - umin; - u -= ::floor((u - umin) / tmp) * tmp; - } - } - else { - if ( poleMin && uumax ) - u = umax; - } -} - - -//------------------------------------------------------------------------------ -// \ru Проверка параметра v \en Check v parameter -// --- -inline void MbFilletSurface::CheckVParam( double & v ) const { - if ( v < vmin ) - v = vmin; - else - if ( v > vmax ) - v = vmax; -} - - -//------------------------------------------------------------------------------ -// \ru Вычислить вес для эллиптической точки \en Calculate weight for elliptic point -// --- -inline bool FilletWeight( double cos_a, double d1, double d2, double & uW ) -{ - bool result = false; - // \ru cos_a - косинус угла между нормалями \en Cos_a - cosine of angle between normals - if ( ::fabs( cos_a ) > PARAM_PRECISION ) { // \ru Не прямой угол \en Angle not right - if ( (d1 * d2) < 0 ) - cos_a = -cos_a; - double cos2_a = cos_a * cos_a; - double sin2_a = ::fabs( 1.0 - cos2_a ); - double sin_a = ::sqrt( sin2_a ); // \ru Синус угла между нормалями \en Sine of angle between normals - bool first = ( ::fabs(d1) > ::fabs(d2) ); - double a = first ? ::fabs( d1 ) : ::fabs( d2 ); // \ru Большая полуось эллипса \en Major semi axis of ellipse - double b = first ? ::fabs( d2 ) : ::fabs( d1 ); // \ru Малая полуось эллипса \en Minor semi axis of ellipse - // \ru Эллипс наиболее удалённой от центра точкой касался одной из поверхностей \en Ellipse concerns one of the surfaces by the point most remote from the center - if ( sin_a > PARAM_PRECISION ) { // \ru Не малый угол \en Angle not small - double aa = a * a; - double bb = b * b; - double p = ::sqrt( (aa*cos2_a) + (bb*sin2_a) ); // \ru Знаменатель (расстояние от центра эллипса до касательной) \en Denominator (distance from center of ellipse to tangent) - if ( p > NULL_EPSILON ) { // \ru Всегда должно выполняться, если a!=0 и b!=0 \en Always hold, if a! =0 and b! =0 - double d = 1.0 / p; - double cos_t = a * cos_a * d; // \ru Косинус параметрического угла эллипса \en Cosine of metric angle of ellipse - uW = ::sqrt( (1.0 + cos_t) * 0.5 ); // \ru Половина косинуса параметрического угла эллипса \en Half of cosine of metric angle of ellipse - result = true; - } - } - } - return result; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Создать поверхность сопряжения. - \en Create the fillet surface. \~ - \details \ru Создать поверхность сопряжения с сохранением кромки грани. - \en Create the fillet surface with the edge. \~ - \param[in] surface1 - \ru Сопрягаемая поверхность. - \en The conjugate surface. \~ - \param[in] points1 - \ru Точки для опорной кривой на сопрягаемой поверхности. - \en Points for curve on the conjugated surface. \~ - \param[in] surface2 - \ru Сопрягаемая поверхность. - \en The conjugate surface. \~ - \param[in] points2 - \ru Точки для опорной кривой на сопрягаемой поверхности. - \en Points for curve on the conjugated surface. \~ - \param[in] form - \ru Тип повержности сопряжения. - \en The surface type \~ - \param[in] distance1 - \ru Радиус скругления со знаком для поверхности кривой crve1 - \en Fillet radius with sign for surface of crve1 curve \~ - \param[in] distance2 - \ru Радиус скругления со знаком для поверхности кривой crve2 - \en Fillet radius with sign for surface of crve2 curve \~ - \param[in] conic - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) - \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ - \param[in] curve - \ru Кривая опорной кромки. - \en The edge curve \~ - \param[in] params - \ru Параметры поверхности вдоль первого напрвыления (u). - \en The parameters of new the surface by first direction (u) \~ - \param[in] byFirstSurface - \ru Пурвая или вторая поверхность сопрягается гладко с новой поверхностью. - \en Is the first or second conjugate surface smooth with the new surface. \~ - \param[in] even - \ru Равномерная параметризация по дуге (v) или нет - \en Uniform parametrization by arc (v) or not \~ - \return \ru Возвращает созданную поверхность. - \en Return the created surface. \~ - \ingroup Surface_Modeling -*/ -MbSmoothSurface * CreateKerbSurface( const MbSurface &surface1, SArray & points1, - const MbSurface &surface2, SArray & points2, - MbeSmoothForm form, double distance1, double distance2, double conic, - const MbSurfaceIntersectionCurve & curve, SArray & params, - bool byFirstSurface, bool even, VERSION version ); - - -#endif // __SURF_FILLET_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность скругления с постоянными радиусами обычная или с сохранением кромки. + \en Fillet surface of constant radii, ordinary or with preservation of fillet. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_FILLET_SURFACE_H +#define __SURF_FILLET_SURFACE_H + + +#include + + +class MATH_CLASS MbFunction; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность скругления с постоянными радиусами обычная или с сохранением кромки. + \en Fillet surface of constant radii, ordinary or with preservation of fillet. \~ + \details \ru Поверхность скругления является NURBS-поверхностью, + построенной по трём кривым: curve1, curve0, curve2. + Первый параметр поверхности совпадает с параметром кривых curve1, curve0, curve2. + Второй параметр изменяется от нуля (точки совпадают с curve1) до единицы (точки совпадают с curve2). + В отличие от других поверхностей Функции PointOn и Derive... поверхность скругления не корректирует + первый параметр при выходе его за пределы области определения. + Если коэффициент формы conic = _ARC_ ( 0 ), то вес каждой точки кривой curve0 задаётся функцией weights0 и + вычислен так, что сечение поверхности вдоль её второго параметра будет дугой окружности, + то есть при любом параметре u три точки curve1(u), curve0(u), curve2(u) определяют NURBS-кривую в форме дуги окружности. + Если коэффициент формы conic != _ARC_, то вес каждой точки кривой curve0 равен conic / ( 1.0 - conic ). + При conic = 0.5 сечение поверхности вдоль её второго параметра будет параболой. \n + \en Fillet surface is NURBS-surface + constructed by three curves: curve1, curve0, curve2. + First parameter of surface coincides with parameter of curve1, curve0, curve2 curves. + Second parameter is changed between 0 (points are coincident to curve1) and 1 (points are coincident to curve2). + For fillet surface in contrast to other surfaces PointOn and Derive... functions don't correct + first parameter when it is out of domain bounds. + If coefficient of shape conic = _ARC_ ( 0 ), then weight of each point of curve0 curve is given by weights0 function and + is calculated as that the section of surface along its second parameter will be a circular arc, + that is three points curve1(u), curve0(u), curve2(u) determine NURBS-curve with shape of circular arc at any u parameter. + If coefficient of shape conic != _ARC_, then weight of each point of curve0 curve is equal to conic / ( 1.0 - conic ). + If conic = 0.5, then section of surface along its second parameter will be a parabola. \n \~ + \ingroup Surfaces +*/// --- +class MATH_CLASS MbFilletSurface : public MbSmoothSurface { +protected: + MbCurve3D * curve0; ///< \ru Кривая пересечения касательных к поверхностям - всегда не NULL. \en Intersection curve of tangents to surfaces - always not 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. + bool equable; ///< \ru true - обычная поверхность, false - curve1 или curve2 является кромкой. \en True - ordinary surface, false - curve1 or curve2 is fillet. + bool byCurve1; ///< \ru true - curve2 является кромкой, false - curve1 является кромкой. \en True - curve2 is fillet, false - curve1 is fillet. + MbCurve3D * spine; ///< \ru Кривая центров дуг окружности для случая равномерной параметризации. \en Curve of centers of circular arcs in case of uniform parameterization. + MbVector3D * spineDerUMin; // \ru Производные spine в точках uMin и uMax ( для случая равномерной параметризации ). \en Derivatives of spine at uMin and uMax points (in case of uniform parameterization). + MbVector3D * spineDerUMax; // \ru Производные spine в точках uMin и uMax ( для случая равномерной параметризации ). \en Derivatives of spine at uMin and uMax points (in case of uniform parameterization). + +public: + + /** \brief \ru Конструктор поверхности скругления. + \en Constructor of fillet surface. \~ + \details \ru Конструктор поверхности скругления. + \en Constructor of fillet surface. \~ + \param[in] curv1 - \ru Опорная кривая на первой поверхности + \en Support curve on the first surface \~ + \param[in] curv2 - \ru Опорная кривая на второй поверхности + \en Support curve on the second surface \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой curve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой curve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой + st_Fillet - скругление с заданными радиусами + \en Conjugation type: \n + st_Span - fillet with a given chord + st_Fillet - fillet with given radii \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) + \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Whether arc length parameterization is uniform or not \~ + */ + MbFilletSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, + double d1, double d2, MbeSmoothForm fm, double cn, bool ev ); + + /** \brief \ru Конструктор поверхности с сохранением кромки. + \en Constructor of surface with preservation of fillet. \~ + \details \ru Конструктор поверхности с сохранением кромки. + \en Constructor of surface with preservation of fillet. \~ + \param[in] curv1 - \ru Опорная кривая на первой поверхности + \en Support curve on the first surface \~ + \param[in] curv2 - \ru Опорная кривая на второй поверхности + \en Support curve on the second surface \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой crve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой crve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой \n + st_Fillet - скругление с заданными радиусами + \en Conjugation type: \n + st_Span - fillet with a given chord\n + st_Fillet - fillet with given radii \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) + \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ + \param[in] byFirst - \ru true - кривая curve2 является кромкой, false - кривая curve1 является кромкой + \en True - curve2 curve is fillet, false - curve1 curve is fillet. \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Whether arc length parameterization is uniform or not \~ + */ + MbFilletSurface( MbSurfaceCurve & curv1, MbSurfaceCurve & curv2, + double d1, double d2, MbeSmoothForm fm, double cn, bool byFirst, bool ev ); + + /** \brief \ru Конструктор поверхности скругления. + \en Constructor of fillet surface. \~ + \details \ru Конструктор поверхности скругления c кривой пересечения касательных к поверхностям. + \en Constructor of fillet surface with intersection curve of tangents to surfaces. \~ + \param[in] surf1 - \ru Первая поверхность + \en First surface \~ + \param[in] curv1 - \ru Опорная кривая в параметрах первой поверхности + \en Support curve at parameters of the first surface \~ + \param[in] surf2 - \ru Вторая поверхность + \en Second surface \~ + \param[in] curv2 - \ru Опорная кривая в параметрах второй поверхности + \en Support curve at parameters of the second surface \~ + \param[in] curv0 - \ru Кривая пересечения касательных к поверхностям + \en Intersection curve of tangents to surfaces \~ + \param[in] d1 - \ru Радиус скругления со знаком для поверхности кривой curv1 + \en Fillet radius with sign for surface of curv1 curve \~ + \param[in] d2 - \ru Радиус скругления со знаком для поверхности кривой curv2 + \en Fillet radius with sign for surface of curv2 curve \~ + \param[in] fm - \ru Тип сопряжения: \n + st_Span - скругление с заданной хордой \n + st_Fillet - скругление с заданными радиусами + \en Conjugation type: \n + st_Span - fillet with a given chord\n + st_Fillet - fillet with given radii \~ + \param[in] cn - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности) + \en Coefficient of shape is changed between 0.05 and 0.95 (if 0 - circular arc) \~ + \param[in] ev - \ru Равномерная параметризация по дуге или нет + \en Whether arc length parameterization is uniform or not \~ + */ + MbFilletSurface( MbSurface & surf1, MbCurve & curv1, + MbSurface & surf2, MbCurve & curv2, + MbCurve3D & curv0, double d1, double d2, MbeSmoothForm fm, double cn, bool ev ); + +protected: + /// \ru Конструктор для наследников обычной поверхности скругления. \en Constructor for inheritors of ordinary fillet surface. + MbFilletSurface( MbSurfaceCurve & curv1, double d1, + MbSurfaceCurve & curv2, double d2, MbeSmoothForm fm, double cn, bool ev ); + /// \ru Конструктор для наследников поверхности с сохранением кромки. \en Constructor for inheritors of surface with preservation of fillet. + MbFilletSurface( MbSurfaceCurve & curv1, double d1, + MbSurfaceCurve & curv2, double d2, MbeSmoothForm fm, double cn, bool byFirst, bool ev ); + /// \ru Конструктор поверхности скругления c кривой пересечения касательных к поверхностям. \en Constructor of fillet surface with intersection curve of tangents to surfaces. \~ + MbFilletSurface( MbSurface & surf1, MbCurve & curv1, double d1, + MbSurface & surf2, MbCurve & curv2, double d2, + MbCurve3D & curv0, MbFunction & weig0, + MbeSmoothForm fm, double cn, bool ev ); + + /// \ru Конструктор копирования. \en Copy-constructor. + MbFilletSurface( const MbFilletSurface &, MbRegDuplicate * ); + /// \ru Конструктор копирования с теми же опорными поверхностями. \en Copy-constructor with the same support surfaces. + MbFilletSurface( const MbFilletSurface * ); + // \ru Для CurvesDuplicate() \en For CurvesDuplicate() +private: + MbFilletSurface( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. +public: + virtual ~MbFilletSurface (); + +public: + VISITING_CLASS( MbFilletSurface ); + + /** \ru \name Функции инициализации + \en \name Initialization functions + \{ */ + // \ru Коррекция средней линии поверхности скругления. \en Correction of mid-line of fillet surface. + virtual void Init0( double wmin, double wmax, bool insertPoints = true ); + /** \} */ + /** \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 Сделать копию элемента. \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 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 base surfaces. + + /** \} */ + /** \ru \name Функции описания области определения поверхности + \en \name Functions for surface domain description + \{ */ + virtual double GetVPeriod() const; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. + + /** \} */ + /** \ru \name Функции для работы в области определения поверхности + Функции PointOn и Derive... поверхностей сопряжения не корректируют + первый параметр при его выходе за пределы определения параметров. + \en \name Functions for working at surface domain + Functions PointOn, Derive... of smooth surfaces don't correct + first parameter when it is out of domain bounds. + \{ */ + virtual void PointOn ( double &u, double &v, MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. + virtual void DeriveU ( double &u, double &v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void DeriveV ( double &u, double &v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void DeriveUU ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void DeriveVV ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void DeriveUV ( double &u, double &v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void DeriveUUU( double &u, double &v, MbVector3D & ) const; + virtual void DeriveUUV( double &u, double &v, MbVector3D & ) const; + virtual void DeriveUVV( double &u, double &v, MbVector3D & ) const; + virtual void DeriveVVV( double &u, double &v, MbVector3D & ) const; + virtual void Normal ( double &u, double &v, MbVector3D & ) const; // \ru Нормаль. \en Normal. + virtual void NormalU ( double &u, double &v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + virtual void NormalV ( double &u, double &v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of 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 & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; + virtual void _Normal ( double u, double v, MbVector3D & ) const; // \ru Нормаль. \en Normal. + virtual void _NormalU ( double u, double v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + virtual void _NormalV ( double u, double v, MbVector3D & ) const; // \ru Производная нормали. \en The derivative of 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 Вычислить значения всех производных в точке. \en Calculate all derivatives at point. \~ + virtual void _PointNormal( double u, double v, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer, + MbVector3D & norm, MbVector3D & uNorm, MbVector3D & vNorm, + MbVector3D & uuDer, MbVector3D & vvDer, MbVector3D & uvDer ) 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 the parameter step in u direction by the sag. + virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. + virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. + virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. + virtual double MetricStepV ( double u, double v, double length ) const; // \ru Вычисление шага по v по заданной длине. \en Calculation of the parameter step in v direction by the given length. + /** \} */ + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + virtual double CurvatureV ( double u, double v ) const; // \ru Kривизна вдоль v. \en Curvature along v. + + virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru Построить NURBS копию поверхности. \en Construct a NURBS copy of a surface. + virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; // \ru Построить NURBS-копию поверхности. \en Construct a NURBS-copy of a surface. + virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Create an offset surface. + + virtual MbCurve3D * CurveV( double u, MbRect1D *pRgn, bool bApprox = 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. + virtual bool ChangeCarrierBorne( const MbSurface & item, MbSurface & init, const MbMatrix & matr ); // \ru Изменение носимых элементов. \en Change a carrier elements. + // \ru Нахождениe точки касания поверхностей \en Searching of surfaces tangency point + virtual MbeNewtonResult SurfaceTangentNewton( const MbSurface &, MbeParamDir switchPar, double funcEpsilon, size_t iterLimit, + double &u0, double &v0, double &u1, double &v1, + bool ext0, bool ext1 ) const; + + // \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 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. + // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. + virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; + virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; + virtual bool GetCylinderAxis( MbAxis3D &axis ) const; // \ru Дать ось вращения для поверхности. \en Get a rotation axis of a surface. + // \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 ThreeStates Salient() const; // \ru Выпуклая ли поверхность. \en Whether the surface is convex. + virtual double GetRadius() const; // \ru Дать физический радиус объекта или ноль, если это невозможно. \en Get the physical radius of the object or null if it impossible. + 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 \name Функции поверхности сопряжения + \en \name Functions of smooth surface + \{ */ + virtual MbSmoothSurface & CurvesDuplicate() const; // \ru Копия с теми же опорными поверхностями. \en Copy with the same support surfaces. + 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. + // \ru Объединить поверхности путём включения поверхности init в данную поверхность. \en Unite surfaces by inclusion of 'init' surface into current surface. + virtual bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, + const MbSurface & init, bool add, MbMatrix & matr, + const MbSurfaceIntersectionCurve * seam ); + /// \ru Дать коэффициент для радиуса. \en Get coefficient for radius. + virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; + // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; + + /** \} */ + /** \ru \name Функции поверхности скругления + \en \name Functions of fillet surface + \{ */ + + /** \brief \ru Веса точек средней кривой. + \en Weights of points of mid-curve. \~ + \details \ru Веса точек средней кривой. + \en Weights of points of mid-curve. \~ + \param[in] u - \ru Параметр на средней кривой (по направлению U) + \en Parameter on mid-curve (by U direction) \~ + */ + double GetWeight( double u ) const; + + /** \brief \ru Угол раствора дуги. + \en Arc opening angle. \~ + \details \ru Угол раствора дуги. + \en Arc opening angle. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \return \ru Угол раствора + \en Angle of opening \~ + */ + double GetAngle( double u ) const; // \ru Дать угол раствора дуги v \en Get v arc opening angle + + /** \brief \ru Ось поверхности в данной точке. + \en Axis of surface at given point. \~ + \details \ru Ось поверхности в данной точке. + \en Axis of surface at given point. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] axis - \ru Результат - ось вращения + \en Result - rotation axis \~ + */ + double GetLocalAxis ( double u, MbAxis3D & axis ) const; // \ru Дать ось поверхности в данной точке \en Get axis of surface at given point + + /** \brief \ru Дать точку на оси. + \en Get point on axis. \~ + \details \ru Дать точку на оси. + \en Get point on axis. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] p1 - \ru Точка на первой опорной кривой по параметру U + \en Point on first support curve by U parameter \~ + \param[out] p2 - \ru Точка на второй опорной кривой по параметру U + \en Point on second support curve by U parameter \~ + \param[out] p0 - \ru Точка на кривой пересечения касательных к поверхностям по параметру u (точка на оси) + \en Point on intersection curve of tangents to surfaces by u parameter (point on axis) \~ + */ + void GetCentrePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0 ) const; + + /** \brief \ru Дать среднюю точку. + \en Get the mid-point. \~ + \details \ru Дать среднюю точку. + \en Get the mid-point. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \param[out] p1 - \ru Точка на первой опорной кривой по параметру U + \en Point on first support curve by U parameter \~ + \param[out] p2 - \ru Точка на второй опорной кривой по параметру U + \en Point on second support curve by U parameter \~ + \param[out] p0 - \ru Средняя точка + \en Mid-point \~ + \param[out] w - \ru Вес полученной средней точки + \en Weight of obtained mid-point \~ + */ + bool GetMiddlePoint( double u, MbCartPoint3D &p1, MbCartPoint3D &p2, MbCartPoint3D &p0, double &w ) const; + + // \ru Если параметризация равномерная, то на продолжении по V замыкается и период зависит от U \en If parameterization is uniform, then it is closed on extension by V and period depends on U + /** \brief \ru Период по направлению V. + \en Period by direction V. \~ + \details \ru Период по направлению V.\n + Если параметризация поверхности равномерная, то период по направлению V зависит от параметра U. + \en Period by direction V.\n + If parameterization of surface is uniform, then period by direction V depends on U parameter. \~ + \param[in] u - \ru Параметр по направлению U + \en Parameter by U direction \~ + \return \ru Период для заданного параметра + \en Period for given parameter \~ + */ + double GetVPeriod( double u ) const; + + /// \ru Кривая пересечения касательных к поверхностям. \en Intersection curve of tangents to surfaces. + const MbCurve3D & GetCurve0() const { return *curve0; } + + /** \brief \ru Скругление не круговое. + \en Fillet isn't circular. \~ + \details \ru Скругление не круговое. + \en Fillet isn't circular. \~ + \return \ru true, если радиусы скруглений для поверхностей не равны + \en True if surfaces fillet radii aren't equal \~ + */ + bool IsEllipse() const { return (fabs(fabs(distance1) - fabs(distance2))>=LENGTH_EPSILON); } // \ru Не равные радиусы \en Not equal radii + + /// \ru Параметризация по дуге равномерная. \en Uniform arc length parameterization. + bool IsEven() const { return even; } + + /** \brief \ru Однородная ли поверхность скругления. + \en Whether the fillet surface is homogeneous. \~ + \details \ru Однородная ли поверхность скругления. Поверхность скругления без сохранения кромки. + \en Whether the fillet surface is homogeneous. Fillet surface without preservation of fillet. \~ + \return \ru false, если одна из кривых curve1 или curve2 является кромкой + \en False if one of curve1 or curve2 curves is fillet \~ + */ + bool IsFilletSurface() const { return equable; } + + /** \brief \ru Коническое сечение общего вида. + \en General conic section. \~ + \details \ru Коническое сечение общего вида. + \en General conic section. \~ + \return \ru false, если сечение поверхности скругления является дугой окружности + \en False if section of fillet surface is circular arc \~ + */ + bool IsConic() const { return ( ::fabs(conic - c3d::_ARC_) >= EPSILON ); } // \ru Коническое сечение общего вида \en General conic section + + /** \brief \ru Коэффициент формы. + \en Coefficient of shape. \~ + \details \ru Коэффициент формы сечения поверхности скругления.\n + Изменяется от 0.05 до 0.95, при 0 сечение является дугой окружности. + \en Coefficient of shape of section of fillet surface.\n + Is changed between 0.05 and 0.95, if 0, then section is circular arc. \~ + \return \ru Коэффициент + \en Coefficient \~ + */ + double Conic() const { return conic; } + + /** \brief \ru Поверхность скругления с сохранением кромки. + \en Fillet surface with preservation of fillet. \~ + \details \ru Поверхность скругления с сохранением кромки. + \en Fillet surface with preservation of fillet. \~ + \return \ru true, если одна из кривых curve1 или curve2 является кромкой + \en True if one of curve1 or curve2 curves is fillet \~ + */ + bool IsKerbSurface() const { return !equable; } + + /** \brief \ru Является ли первая кривая кромкой. + \en Whether the first curve is fillet. \~ + \details \ru Является ли первая кривая кромкой. + \en Whether the first curve is fillet. \~ + \return \ru true, если первая кривая является кромкой + \en True if the first curve is fillet. \~ + */ + bool ByFirstCurve() const { return byCurve1; } + + /** \brief \ru Установить поверхность скругления типа с сохранением кромки. + \en Set fillet surface with preservation of fillet. + Need to call this->Init0() after this method \~ + \details \ru Установить поверхность скругления с сохранением кромки и указать определяющую кривую на поверхности. + Далее нужно вызвать метод this->Init0(). + \en Set fillet surface with preservation of fillet. \~ + \param[in] bc1 - \ru Определяющая кривая на поверхности: curve1 (bc1 = true), curve2 (bc1 = false). + \en General curve on surface: curve1 (bc1 = true), curve2 (bc1 = false). \~ + */ + void SetKerbSurface( bool bc1 ) { if ( equable ) { equable = false; byCurve1 = bc1; } } + + // \ru Выдать функцию весов точек средней кривой curve0. \en Get weight function for points of mid-curve (curve0). + const MbFunction * GetWeights() const; + // \ru Установить функцию весов точек средней кривой curve0. \en Set weight function for points of mid-curve (curve0). + bool SetWeights( MbFunction & func ); + + MbCurve3D * GetSpine() const; + void SetSpine( MbCurve3D * ); + + /** \} */ +protected: + void WeightKoefficient( double & w ) const; // \ru Вычисление веса при заданном коэффициенте \en Calculation of weight at given coefficient + void InitFilletSurface ( const MbFilletSurface & init ); + void CalculateCurve( double wmin, double wmax, bool insertPoints ); + double CalculateVParam( const MbCartPoint3D & p, double u ) const; // \ru Нахождение параметра v проекции точки на вырожденную поверхность \en Searching of v parameter of point projection onto degenerate surface + +protected: + // \ru Вычисление точки \en Calculation of a point +// void CalculateSurface( double u ) const; + // \ru Дать коэффициент для радиуса \en Get coefficient for radius + virtual double FunctionValue( double u ) const; + void CalculateData ( double & u, double & v, + MbCartPoint3D & uPoint0, MbCartPoint3D & uPoint1, MbCartPoint3D & uPoint2, // \ru Точки на кривых curve0, curve1, curve2. \en Points on curve0, curve1, curve2. + MbVector3D * uFirst0, MbVector3D * uFirst1, MbVector3D * uFirst2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. + MbVector3D * uSecond0, MbVector3D * uSecond1, MbVector3D * uSecond2, // \ru Производные кривых curve0, curve1, curve2. \en Derivatives of curve0, curve1, curve2. + double & uWeight, double * wFirst, double * wSecond, // \ru Вес и его производные средней точки uPoint0. \en The weight and it derivatives of the mid-point uPoint0. + double & uP0, double & uP1, double & uP2, double & uPw, // \ru Коэффициенты точек uPoint0, uPoint1, uPoint2. \en Coefficients of points uPoint0, uPoint1, uPoint2. + double & uF0, double & uF1, double & uF2, double & uFw ) const; // \ru Коэффициенты производных uFirst0, uFirst1, uFirst2. \en Coefficients of derivatives uFirst0, uFirst1, uFirst2. + void InitSpineDerives(); + void CalculatePointOn ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbCartPoint3D & ) const; // \ru Точка на поверхности. \en The point on the surface. + void CalculateDeriveU ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + void CalculateDeriveV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + void CalculateDeriveUU ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + void CalculateDeriveVV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + void CalculateDeriveUV ( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + void CalculateDeriveUUU( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + MbVector3D & ) const; + void CalculateDeriveUUV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateDeriveUVV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateDeriveVVV( double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const double & uWeight, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; + void CalculateNormal ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Нормаль. \en Normal. + void CalculateNormalU ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const MbVector3D & uSecond0, const MbVector3D & uSecond1, MbVector3D &uSecond2, + const double & uWeight, const double & wFirst, const double & wSecond, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + void CalculateNormalV ( double & u, double & v, + const MbCartPoint3D & uPoint0, const MbCartPoint3D & uPoint1, const MbCartPoint3D & uPoint2, + const MbVector3D & uFirst0, const MbVector3D & uFirst1, const MbVector3D & uFirst2, + const double & uWeight, const double & wFirst, + const double & uP0, const double & uP1, const double & uP2, const double & uPw, + const double & uF0, const double & uF1, const double & uF2, const double & uFw, + MbVector3D & ) const; // \ru Производная нормали. \en The derivative of normal. + + // \ru Проверка параметров. \en Check parameters. + void CheckUParam( double & u ) const; + void CheckVParam( double & v ) const; + + void operator = ( const MbFilletSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFilletSurface ) +}; // MbFilletSurface + + +IMPL_PERSISTENT_OPS( MbFilletSurface ) + + +//------------------------------------------------------------------------------ +// \ru Проверка параметра u по отношению к полюсам и замкнутости \en Check u parameter against poles and closedness +// --- +inline void MbFilletSurface::CheckUParam( double & u ) const { + if ( uclosed ) { + if ( (u < umin) || (u > umax ) ) { + double tmp = umax - umin; + u -= ::floor((u - umin) / tmp) * tmp; + } + } + else { + if ( poleMin && uumax ) + u = umax; + } +} + + +//------------------------------------------------------------------------------ +// \ru Проверка параметра v \en Check v parameter +// --- +inline void MbFilletSurface::CheckVParam( double & v ) const { + if ( v < vmin ) + v = vmin; + else + if ( v > vmax ) + v = vmax; +} + + +//------------------------------------------------------------------------------ +// \ru Вычислить вес для эллиптической точки \en Calculate weight for elliptic point +// --- +inline bool FilletWeight( double cos_a, double d1, double d2, double & uW ) +{ + bool result = false; + // \ru cos_a - косинус угла между нормалями \en Cos_a - cosine of angle between normals + if ( ::fabs( cos_a ) > PARAM_PRECISION ) { // \ru Не прямой угол \en Angle not right + if ( (d1 * d2) < 0 ) + cos_a = -cos_a; + double cos2_a = cos_a * cos_a; + double sin2_a = ::fabs( 1.0 - cos2_a ); + double sin_a = ::sqrt( sin2_a ); // \ru Синус угла между нормалями \en Sine of angle between normals + bool first = ( ::fabs(d1) > ::fabs(d2) ); + double a = first ? ::fabs( d1 ) : ::fabs( d2 ); // \ru Большая полуось эллипса \en Major semi axis of ellipse + double b = first ? ::fabs( d2 ) : ::fabs( d1 ); // \ru Малая полуось эллипса \en Minor semi axis of ellipse + // \ru Эллипс наиболее удалённой от центра точкой касался одной из поверхностей \en Ellipse concerns one of the surfaces by the point most remote from the center + if ( sin_a > PARAM_PRECISION ) { // \ru Не малый угол \en Angle not small + double aa = a * a; + double bb = b * b; + double p = ::sqrt( (aa*cos2_a) + (bb*sin2_a) ); // \ru Знаменатель (расстояние от центра эллипса до касательной) \en Denominator (distance from center of ellipse to tangent) + if ( p > NULL_EPSILON ) { // \ru Всегда должно выполняться, если a!=0 и b!=0 \en Always hold, if a! =0 and b! =0 + double d = 1.0 / p; + double cos_t = a * cos_a * d; // \ru Косинус параметрического угла эллипса \en Cosine of metric angle of ellipse + uW = ::sqrt( (1.0 + cos_t) * 0.5 ); // \ru Половина косинуса параметрического угла эллипса \en Half of cosine of metric angle of ellipse + result = true; + } + } + } + return result; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Создать поверхность сопряжения. + \en Create the fillet surface. \~ + \details \ru Создать поверхность сопряжения с сохранением кромки грани. + \en Create the fillet surface with the edge. \~ + \param[in] surface1 - \ru Сопрягаемая поверхность. + \en The conjugate surface. \~ + \param[in] points1 - \ru Точки для опорной кривой на сопрягаемой поверхности. + \en Points for curve on the conjugated surface. \~ + \param[in] surface2 - \ru Сопрягаемая поверхность. + \en The conjugate surface. \~ + \param[in] points2 - \ru Точки для опорной кривой на сопрягаемой поверхности. + \en Points for curve on the conjugated surface. \~ + \param[in] form - \ru Тип повержности сопряжения. + \en The surface type \~ + \param[in] distance1 - \ru Радиус скругления со знаком для поверхности кривой crve1 + \en Fillet radius with sign for surface of crve1 curve \~ + \param[in] distance2 - \ru Радиус скругления со знаком для поверхности кривой crve2 + \en Fillet radius with sign for surface of crve2 curve \~ + \param[in] conic - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0.5 - дуга окружности) + \en Coefficient of shape is changed from 0.05 to 0.95 (if 0.5 - circular arc) \~ + \param[in] curve - \ru Кривая опорной кромки. + \en The edge curve \~ + \param[in] params - \ru Параметры поверхности вдоль первого напрвыления (u). + \en The parameters of new the surface by first direction (u) \~ + \param[in] byFirstSurface - \ru Пурвая или вторая поверхность сопрягается гладко с новой поверхностью. + \en Is the first or second conjugate surface smooth with the new surface. \~ + \param[in] even - \ru Равномерная параметризация по дуге (v) или нет + \en Uniform parametrization by arc (v) or not \~ + \return \ru Возвращает созданную поверхность. + \en Return the created surface. \~ + \ingroup Surface_Modeling +*/ +MbSmoothSurface * CreateKerbSurface( const MbSurface &surface1, SArray & points1, + const MbSurface &surface2, SArray & points2, + MbeSmoothForm form, double distance1, double distance2, double conic, + const MbSurfaceIntersectionCurve & curve, SArray & params, + bool byFirstSurface, bool even, VERSION version ); + + +#endif // __SURF_FILLET_SURFACE_H diff --git a/C3d/Include/surf_grid_surface.h b/C3d/Include/surf_grid_surface.h index a64075e..c656a89 100644 --- a/C3d/Include/surf_grid_surface.h +++ b/C3d/Include/surf_grid_surface.h @@ -1,413 +1,412 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность на базе триангуляции. - \en Surface based on triangulation. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_GRID_SURFACE_H -#define __SURF_GRID_SURFACE_H - - -#include -#include -#include -#include -#include -#include - - -class MATH_CLASS MbCurve3D; -class MATH_CLASS MbMesh; -class MATH_CLASS MbGrid; - - -#define _C3D_3_ 3 -#define _C3D_4_ 4 - - -//------------------------------------------------------------------------------ -/// \ru Tреугольная пластина поверхности на сетке точек. \en Triangular plate. -// --- -class MbTrigon { -protected : - size_t index[_C3D_3_]; ///< \ru Номера вершин треугольника в массиве точек. \en The numbers of vertices in points array. - size_t neighbour[_C3D_3_]; ///< \ru Номера соседних треугольников. \en The numbers of neighbour triangles. SYS_MAX_T if it is absent. - -// points[index[2]] -// + -// / \ -// neighbour[2] / \ neighbour[1] -// / \ -// points[index[0]] +---------------+ points[index[1]] -// neighbour[0] - -public : - MbTrigon() { index[0] = SYS_MAX_T; index[1] = SYS_MAX_T; index[2] = SYS_MAX_T; - neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } - MbTrigon( size_t i0, size_t i1, size_t i2 ) { index[0] = i0; index[1] = i1; index[2] = i2; - neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } - MbTrigon( const MbTrigon & init ) { index[0] = init.index[0]; index[1] = init.index[1]; index[2] = init.index[2]; - neighbour[0] = init.neighbour[0]; neighbour[1] = init.neighbour[1]; neighbour[2] = init.neighbour[2]; } - MbTrigon( const MbTriangle & init ) { - uint i0, i1, i2; - init.GetTriangle( i0, i1, i2 ); - index[0] = i0; index[1] = i1; index[2] = i2; - neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } -public : - void Init( size_t i0, size_t i1, size_t i2, bool orientation ) { - if ( orientation ) { index[0] = i0; index[1] = i1; index[2] = i2; } - else { index[0] = i0; index[1] = i2; index[2] = i1; } - neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; - } - void Init( size_t i0, size_t i1, size_t i2, size_t n0, size_t n1, size_t n2 ) { - index[0] = i0; index[1] = i1; index[2] = i2; - neighbour[0] = n0; neighbour[1] = n1; neighbour[2] = n2; - } - void GetTriangle( size_t & i0, size_t & i1, size_t & i2 ) const { i0 = index[0]; i1 = index[1]; i2 = index[2]; } - void GetTriangle( size_t & i0, size_t & i1, size_t & i2, size_t & n0, size_t & n1, size_t & n2 ) const { - i0 = index[0]; i1 = index[1]; i2 = index[2]; - n0 = neighbour[0]; n1 = neighbour[1]; n2 = neighbour[2]; - } - size_t GetNunber( size_t & i ) const { return index[i % _C3D_3_]; } - size_t GetNeihbour( size_t & i ) const { return neighbour[i % _C3D_3_]; } - // \ru Инициализация соседа. \en The neighbour initiation. - void SetNeihbour( size_t i, size_t n ) { neighbour[i % _C3D_3_] = n; } - MbTrigon & operator = ( const MbTrigon & init ) { init.GetTriangle( index[0], index[1], index[2] ); - neighbour[0] = init.neighbour[0]; neighbour[1] = init.neighbour[1]; neighbour[2] = init.neighbour[2]; - return *this; } - MbTrigon & operator = ( const MbTriangle & init ) { - uint i0, i1, i2; - init.GetTriangle( i0, i1, i2 ); - index[0] = i0; index[1] = i1; index[2] = i2; - neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; - return *this; } -}; // MbTrigon - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность на базе триангуляции. - \en Surface based on triangulation. \~ - \details \ru Поверхность на базе триангуляции образована криволинейными треугольниками, - гладко стыкующимися между собой по общим сторонам. - В общих вершинах стыкующиеся треугольники имеют общую нормаль. - Сторону треугольников изменяются по кубическому закону. \n - \en Surface based on triangulation is formed by curvilinear triangles - which are smoothly connected together through common edges. - Connected triangles have common normal at common vertices. - Edges of triangles are changed by cubic law. \n \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbGridSurface : public MbSurface { - -private: - // \ru Согласованные между собой множества данных в вершинах. \en Sets of data at vertices matched each other. - std::vector params; ///< \ru Множество точек на параметрической области поверхности. \en Set of points in parametric space of surface. - std::vector points; ///< \ru Множество точек поверхности. \en Set of points of surface. - std::vector normals; ///< \ru Множество нормалей поверхности. \en Set of normals of surface. - std::vector triangles; ///< \ru Множество треугольников. \en Set of triangles. - // \ru Описание области параметров поверхности. \en Description of surface parameters region. - size_t uCount; ///< \ru Количество разбиений области по u. \en Count of splittings of region by u. - size_t vCount; ///< \ru Количество разбиений области по v. \en Count of splittings of region by v. - PArray< std::vector > cell; ///< \ru Сетка области параметров поверхности. \en Grid of surface parameters region. - std::vector boundary; ///< \ru Граничные кривые области параметров поверхности. \en Boundary curves of surface parameters region. - double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. - double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. - double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. - double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. - bool uclosed; ///< \ru Признак замкнутости по параметру u. \en Attribute of closedness by parameter u. - bool vclosed; ///< \ru Признак замкнутости по параметру v. \en Attribute of closedness by parameter v. - -private: - /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. - MbGridSurface( const MbGridSurface & init ); - MbGridSurface( const MbGridSurface & init, MbRegDuplicate * iReg ); -protected: - /// \ru Конструктор поверхности. \en Constructor of surface. - template - MbGridSurface ( const Params & _params - , const Points & _points - , const Normals & _normals - , const Triangles & _triangles - , const Bounds & _bounds) - : MbSurface () - , params () - , points () - , normals () - , triangles () - , uCount( 1 ) - , vCount( 1 ) - , cell( 0, 1, true) - , boundary () - , umin ( 0.0 ) - , vmin ( 0.0 ) - , umax ( 0.0 ) - , vmax ( 0.0 ) - , uclosed ( false ) - , vclosed ( false ) - { - size_t k, cnt; - - cnt = _params.size(); - params.reserve( cnt ); - for ( k = 0; k < cnt; k++ ) - params.push_back( _params[k] ); - cnt = _points.size(); - points.reserve( cnt ); - for ( k = 0; k < cnt; k++ ) - points.push_back( _points[k] ); - - if ( _normals.size() > 0 ) { - size_t normalsLast = _normals.size() - 1; - normals.reserve( cnt ); - for ( k = 0; k < cnt; k++ ) { - size_t ind = std_min( k, normalsLast ); - normals.push_back( _normals[ind] ); - } - } - cnt = _triangles.size(); - triangles.reserve( cnt ); - for ( k = 0; k < cnt; k++ ) - triangles.push_back( _triangles[k] ); - - cnt = _bounds.size(); - boundary.reserve(cnt); - for (k = 0; k < cnt; k++) { - _bounds[k]->AddRef(); - boundary.push_back(_bounds[k]); - } - - Init( boundary.size() == 0 ); - } - -public: - virtual ~MbGridSurface(); - -public: - VISITING_CLASS( MbGridSurface ); - - /** \name Общие функции геометрического объекта - \{ */ - // \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 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 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 - 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 Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. - /** \} */ - - /** \name Функции описания области определения поверхности - \{ */ - // \ru Функции описания области определения поверхности. \en 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. - /** \} */ - - /** \name Функции для работы в области определения поверхности - Функции PointOn, Derive... поверхностей корректируют параметры - при выходе их за пределы прямоугольной области определения параметров.\n - \{ */ - // \ru Функции для работы в области определения поверхности. \en Functions for working at surface domain. - virtual void PointOn ( double & u, double & v, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface - virtual void DeriveU ( double & u, double & v, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void DeriveV ( double & u, double & v, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void DeriveUU ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void DeriveVV ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void DeriveUV ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void DeriveUUU( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUUV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUVV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - virtual void DeriveVVV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - /** \} */ - - /** \name Функции для работы внутри и вне области определения поверхности - функции _PointOn, _Derive... поверхностей не корректируют - параметры при выходе их за пределы прямоугольной области определения параметров. - За пределами параметрической области поверхность продолжается по касательной. - \{ */ - // \ru Функции для работы внутри и вне области определения поверхности. \en Functions for working inside and outside the surface's domain. - virtual void _PointOn ( double u, double v, MbCartPoint3D & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная. \en The second derivative. - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. - /** \} */ - - /** \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 Функции движения по поверхности \en Functions of moving along the surface - virtual double StepU( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по U \en Calculation of the approximation step with consideration of the curvature radius by U - virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по V \en Calculation of the approximation step with consideration of the curvature radius by V - 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 Выдать граничную точку \en Get the boundary point - virtual void GetLimitPoint( ptrdiff_t num, MbCartPoint3D & ) const; // \ru Выдать граничную трехмерную точку. \en Get the three-dimensional boundary point. - virtual void GetLimitPoint( ptrdiff_t num, MbCartPoint & ) const; // \ru Выдать граничную двумерную точку (граничные параметры). \en Get the two-dimensional boundary point (boundary parameters). - - virtual MbeItemLocation PointClassification( const MbCartPoint &, bool ignoreClosed = false ) const; // \ru Находится ли точка в области, принадлежащей поверхности. \en Whether the point is in region belonging to the surface. - virtual double DistanceToBorder ( const MbCartPoint &, double & eps ) const; // \ru Параметрическое расстояние до ближайшей границы. \en Parametric distance to the nearest boundary. - // \ru Определение точек пересечения кривой с контурами поверхности. \en Determine intersection points of a curve with the contours on the surface. - 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. - // \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; - // \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; - // \ru Расчёт площади области определения параметров. \en Calculate area of parameter domain. - virtual double ParamArea() const; - virtual size_t GetUPairs( double v, SArray & u ) const; // \ru Вычислить U-пары от V. \en Calculate U-pairs by V. - virtual size_t GetVPairs( double u, SArray & v ) const; // \ru Вычислить V-пары от U. \en Calculate V-pairs by U. - virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. - virtual void CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, - size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const; // \ru Рассчитать сетку. \en Calculate mesh. - // \ru Аппроксимация поверхности треугольными пластинами. \en Approximation of a surface by triangular plates. - virtual void CalculateSurfaceGrid( const MbStepData & stepData, bool sense, MbGrid & grid ) const; - // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const; - // \ru Пересчитать нормали в вершинах. \en Normals Calculation on vertex. - virtual void Normalize(); - - size_t GetBoundariesCount() const { return boundary.size(); } // \ru Выдать количество граничных двумерных кривых. \en Get the two-dimensional boundary curves count. - virtual MbContour & MakeContour( bool sense ) const; // \ru Выдать граничных двумерный контур. \en Get the two-dimensional boundary contour. - virtual MbCurve & MakeSegment( size_t i, bool sense ) const; // \ru Дать граничную двумерную кривую. \en Get the two-dimensional boundary curve. - - /// \ru Инициализация объекта по другому такому же. \en Initialization of a object by same other object. - void Init( const MbGridSurface & init ); - - /// \ru Выдать количество точек. \en Get the number of points. - size_t PointsCount() const { return points.size(); } - /// \ru Выдать количество нормалей. \en Get the number of normals. - size_t NormalsCount() const { return normals.size(); } - /// \ru Выдать количество параметров. \en Get the number of parameters. - size_t ParamsCount() const { return params.size(); } - // \ru Выдать количество треугольников. \en Get the number of triangles. - size_t TrianglesCount() const { return triangles.size(); } - // \ru Выдать количество граничных кривых. \en Get the number of boundary curves. - size_t BoundariesCount() const { return boundary.size(); } - - // \ru Добавить в контейнер параметры в опорных точках поверхности. \en Get the parameters to container. - void GetParams( std::vector & paramsVector ) const; - // \ru Добавить в контейнер опорные точки. \en Get the points to container. - void GetPoints( std::vector & pointsVector ) const; - // \ru Добавить в контейнер нормали в опорных точках. \en Add the normals to container. - void GetNormals( std::vector & normalsVector ) const; - // \ru Добавить в контейнер треугольники. \en Add the triangles to container. - void GetTriangles( std::vector & tVector ) const; - // \ru Добавить в контейнер треугольники. \en Add the triangles to container. - void GetTriangles( std::vector & tVector ) const; - // \ru Добавить в контейнер граничные кривые. \en Add the boundary curves of surface parameters region. - void GetBoundaries( std::vector & bVector ) const; - - /// \ru Создание поверхности. \en Creatying of surface. - template - - static MbGridSurface * Create( const Params & _params - , const Points & _points - , const Normals & _normals - , const Triangles & _triangles - , const Bounds & _bounds ) - { - MbGridSurface * surface = NULL; - - const size_t itemsCnt = _params.size(); - - if ( (itemsCnt > 2) && (itemsCnt == _points.size()) && (_triangles.size() > 0) ) { - if ( (itemsCnt == _normals.size()) || (_normals.size() == 1) ) - surface = new MbGridSurface( _params, _points, _normals, _triangles, _bounds ); - } - return surface; - } - -private: - /// \ru Инициализация. \en Initialization. - void Init( bool bound = true ); - // \ru Инициализация граничных кривых. \en Initialization of boundary curves. - void MakeBoundary(); - // \ru Выдать треугольник. \en Get triangle. - MbTrigon & GetTriangle( size_t i ) { return triangles[i]; } - void PointOn ( double & u, double & v, bool ext, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface - void DeriveU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u - void DeriveV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v - void DeriveUU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u - void DeriveVV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v - void DeriveUV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - void DeriveUUU( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveUUV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveUVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - void DeriveVVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative - // \ru Выставить взаимные связи триангуляции. \en Set mutual connections of triangulation. - bool SetTrigonNeihbours(); - // \ru Поиск ближайшего треугольника для инициализации данных ячейки. \en Search nearest triangle for initialization of data of cell. - void FindNearest( size_t i, size_t j, std::vector & indecies, - double uDelta, double vDelta, double u, double v ); - // \ru Добавить ближайший треугольник в ячейку. \en Add nearest triangle to cell. - bool AddNearest( size_t i, size_t j, size_t ind ); - // \ru Вычислить индккс ближайшего треугольника и барицентрические координаты точки для него. \en Calculate barycentric coordinates of the nearest trianle. - size_t FindIndex( const double & u, const double & v, double & a, double & b, double & c, double & d ) const; - // \ru Расстояние до треугольника. \en The distance to a triangle. - double RangeToTriangle( size_t ind, const double & u, const double & v, double eps, - double & a, double & b, double & c, double & d ) const; - // \ru Расстояние до треугольника. \en The distance to a triangle. - double DistanceToTriangle( size_t ind, const double & u, const double & v, double eps, - MbCartPoint & p ) const; - // \ru Проверка параметров. \en Check parameters. - void CheckParam( double & u, double & v ) const; - // \ru Выдать данные триангуляции. \en Get triangulation data. - void GetTriangleData( size_t tIndex, - size_t & index1, size_t & index2, size_t & index3, - size_t & neigh1, size_t & neigh2, size_t & neigh3, - MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, - MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, - MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; - // \ru Выдать данные триангуляции соседнего треугольника. \en Get neighbour triangulation data. - bool GetNeighbourData( double u, double v, - size_t neigh1, size_t neigh2, size_t neigh3, - double & aCalc, double & bCalc, double & cCalc, double & deter, double & portion, - MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, - MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, - MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - void operator = ( const MbGridSurface & ); - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbGridSurface ) -}; // MbGridSurface - -IMPL_PERSISTENT_OPS( MbGridSurface ) - - -#endif // __SURF_GRID_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность на базе триангуляции. + \en Surface based on triangulation. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_GRID_SURFACE_H +#define __SURF_GRID_SURFACE_H + + +#include +#include +#include +#include +#include +#include + + +class MATH_CLASS MbCurve3D; +class MATH_CLASS MbMesh; +class MATH_CLASS MbGrid; + + +#define _C3D_3_ 3 +#define _C3D_4_ 4 + + +//------------------------------------------------------------------------------ +/// \ru Tреугольная пластина поверхности на сетке точек. \en Triangular plate. +// --- +class MbTrigon { +protected : + size_t index[_C3D_3_]; ///< \ru Номера вершин треугольника в массиве точек. \en The numbers of vertices in points array. + size_t neighbour[_C3D_3_]; ///< \ru Номера соседних треугольников. \en The numbers of neighbour triangles. SYS_MAX_T if it is absent. + +// points[index[2]] +// + +// / \ +// neighbour[2] / \ neighbour[1] +// / \ +// points[index[0]] +---------------+ points[index[1]] +// neighbour[0] + +public : + MbTrigon() { index[0] = SYS_MAX_T; index[1] = SYS_MAX_T; index[2] = SYS_MAX_T; + neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } + MbTrigon( size_t i0, size_t i1, size_t i2 ) { index[0] = i0; index[1] = i1; index[2] = i2; + neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } + MbTrigon( const MbTrigon & init ) { index[0] = init.index[0]; index[1] = init.index[1]; index[2] = init.index[2]; + neighbour[0] = init.neighbour[0]; neighbour[1] = init.neighbour[1]; neighbour[2] = init.neighbour[2]; } + MbTrigon( const MbTriangle & init ) { + uint i0, i1, i2; + init.GetTriangle( i0, i1, i2 ); + index[0] = i0; index[1] = i1; index[2] = i2; + neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; } +public : + void Init( size_t i0, size_t i1, size_t i2, bool orientation ) { + if ( orientation ) { index[0] = i0; index[1] = i1; index[2] = i2; } + else { index[0] = i0; index[1] = i2; index[2] = i1; } + neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; + } + void Init( size_t i0, size_t i1, size_t i2, size_t n0, size_t n1, size_t n2 ) { + index[0] = i0; index[1] = i1; index[2] = i2; + neighbour[0] = n0; neighbour[1] = n1; neighbour[2] = n2; + } + void GetTriangle( size_t & i0, size_t & i1, size_t & i2 ) const { i0 = index[0]; i1 = index[1]; i2 = index[2]; } + void GetTriangle( size_t & i0, size_t & i1, size_t & i2, size_t & n0, size_t & n1, size_t & n2 ) const { + i0 = index[0]; i1 = index[1]; i2 = index[2]; + n0 = neighbour[0]; n1 = neighbour[1]; n2 = neighbour[2]; + } + size_t GetNunber( size_t & i ) const { return index[i % _C3D_3_]; } + size_t GetNeihbour( size_t & i ) const { return neighbour[i % _C3D_3_]; } + // \ru Инициализация соседа. \en The neighbour initiation. + void SetNeihbour( size_t i, size_t n ) { neighbour[i % _C3D_3_] = n; } + MbTrigon & operator = ( const MbTrigon & init ) { init.GetTriangle( index[0], index[1], index[2] ); + neighbour[0] = init.neighbour[0]; neighbour[1] = init.neighbour[1]; neighbour[2] = init.neighbour[2]; + return *this; } + MbTrigon & operator = ( const MbTriangle & init ) { + uint i0, i1, i2; + init.GetTriangle( i0, i1, i2 ); + index[0] = i0; index[1] = i1; index[2] = i2; + neighbour[0] = SYS_MAX_T; neighbour[1] = SYS_MAX_T; neighbour[2] = SYS_MAX_T; + return *this; } +}; // MbTrigon + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность на базе триангуляции. + \en Surface based on triangulation. \~ + \details \ru Поверхность на базе триангуляции образована криволинейными треугольниками, + гладко стыкующимися между собой по общим сторонам. + В общих вершинах стыкующиеся треугольники имеют общую нормаль. + Сторону треугольников изменяются по кубическому закону. \n + \en Surface based on triangulation is formed by curvilinear triangles + which are smoothly connected together through common edges. + Connected triangles have common normal at common vertices. + Edges of triangles are changed by cubic law. \n \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbGridSurface : public MbSurface { + +private: + // \ru Согласованные между собой множества данных в вершинах. \en Sets of data at vertices matched each other. + std::vector params; ///< \ru Множество точек на параметрической области поверхности. \en Set of points in parametric space of surface. + std::vector points; ///< \ru Множество точек поверхности. \en Set of points of surface. + std::vector normals; ///< \ru Множество нормалей поверхности. \en Set of normals of surface. + std::vector triangles; ///< \ru Множество треугольников. \en Set of triangles. + // \ru Описание области параметров поверхности. \en Description of surface parameters region. + size_t uCount; ///< \ru Количество разбиений области по u. \en Count of splittings of region by u. + size_t vCount; ///< \ru Количество разбиений области по v. \en Count of splittings of region by v. + PArray< std::vector > cell; ///< \ru Сетка области параметров поверхности. \en Grid of surface parameters region. + std::vector boundary; ///< \ru Граничные кривые области параметров поверхности. \en Boundary curves of surface parameters region. + double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. + double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. + double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. + double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. + bool uclosed; ///< \ru Признак замкнутости по параметру u. \en Attribute of closedness by parameter u. + bool vclosed; ///< \ru Признак замкнутости по параметру v. \en Attribute of closedness by parameter v. + +private: + /// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default. + MbGridSurface( const MbGridSurface & init ); + MbGridSurface( const MbGridSurface & init, MbRegDuplicate * iReg ); +protected: + /// \ru Конструктор поверхности. \en Constructor of surface. + template + MbGridSurface ( const Params & _params + , const Points & _points + , const Normals & _normals + , const Triangles & _triangles + , const Bounds & _bounds) + : MbSurface () + , params () + , points () + , normals () + , triangles () + , uCount( 1 ) + , vCount( 1 ) + , cell( 0, 1, true) + , boundary () + , umin ( 0.0 ) + , vmin ( 0.0 ) + , umax ( 0.0 ) + , vmax ( 0.0 ) + , uclosed ( false ) + , vclosed ( false ) + { + size_t k, cnt; + + cnt = _params.size(); + params.reserve( cnt ); + for ( k = 0; k < cnt; k++ ) + params.push_back( _params[k] ); + cnt = _points.size(); + points.reserve( cnt ); + for ( k = 0; k < cnt; k++ ) + points.push_back( _points[k] ); + + if ( _normals.size() > 0 ) { + size_t normalsLast = _normals.size() - 1; + normals.reserve( cnt ); + for ( k = 0; k < cnt; k++ ) { + size_t ind = std_min( k, normalsLast ); + normals.push_back( _normals[ind] ); + } + } + cnt = _triangles.size(); + triangles.reserve( cnt ); + for ( k = 0; k < cnt; k++ ) + triangles.push_back( _triangles[k] ); + + cnt = _bounds.size(); + boundary.reserve(cnt); + for (k = 0; k < cnt; k++) { + _bounds[k]->AddRef(); + boundary.push_back(_bounds[k]); + } + + Init( boundary.size() == 0 ); + } + +public: + virtual ~MbGridSurface(); + +public: + VISITING_CLASS( MbGridSurface ); + + /** \name Общие функции геометрического объекта + \{ */ + // \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 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 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 + 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 Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. + /** \} */ + + /** \name Функции описания области определения поверхности + \{ */ + // \ru Функции описания области определения поверхности. \en 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. + /** \} */ + + /** \name Функции для работы в области определения поверхности + Функции PointOn, Derive... поверхностей корректируют параметры + при выходе их за пределы прямоугольной области определения параметров.\n + \{ */ + // \ru Функции для работы в области определения поверхности. \en Functions for working at surface domain. + virtual void PointOn ( double & u, double & v, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface + virtual void DeriveU ( double & u, double & v, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void DeriveV ( double & u, double & v, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void DeriveUU ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void DeriveVV ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void DeriveUV ( double & u, double & v, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void DeriveUUU( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUUV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUVV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + virtual void DeriveVVV( double & u, double & v, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + /** \} */ + + /** \name Функции для работы внутри и вне области определения поверхности + функции _PointOn, _Derive... поверхностей не корректируют + параметры при выходе их за пределы прямоугольной области определения параметров. + За пределами параметрической области поверхность продолжается по касательной. + \{ */ + // \ru Функции для работы внутри и вне области определения поверхности. \en Functions for working inside and outside the surface's domain. + virtual void _PointOn ( double u, double v, MbCartPoint3D & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная. \en The second derivative. + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная. \en The third derivative. + /** \} */ + + /** \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 Функции движения по поверхности \en Functions of moving along the surface + virtual double StepU( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по U \en Calculation of the approximation step with consideration of the curvature radius by U + virtual double StepV( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны по V \en Calculation of the approximation step with consideration of the curvature radius by V + 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 Выдать граничную точку \en Get the boundary point + virtual void GetLimitPoint( ptrdiff_t num, MbCartPoint3D & ) const; // \ru Выдать граничную трехмерную точку. \en Get the three-dimensional boundary point. + virtual void GetLimitPoint( ptrdiff_t num, MbCartPoint & ) const; // \ru Выдать граничную двумерную точку (граничные параметры). \en Get the two-dimensional boundary point (boundary parameters). + + virtual MbeItemLocation PointClassification( const MbCartPoint &, bool ignoreClosed = false ) const; // \ru Находится ли точка в области, принадлежащей поверхности. \en Whether the point is in region belonging to the surface. + virtual double DistanceToBorder ( const MbCartPoint &, double & eps ) const; // \ru Параметрическое расстояние до ближайшей границы. \en Parametric distance to the nearest boundary. + // \ru Определение точек пересечения кривой с контурами поверхности. \en Determine intersection points of a curve with the contours on the surface. + 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. + // \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; + // \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; + // \ru Расчёт площади области определения параметров. \en Calculate area of parameter domain. + virtual double ParamArea() const; + virtual size_t GetUPairs( double v, SArray & u ) const; // \ru Вычислить U-пары от V. \en Calculate U-pairs by V. + virtual size_t GetVPairs( double u, SArray & v ) const; // \ru Вычислить V-пары от U. \en Calculate V-pairs by U. + virtual void CalculateMesh( const MbStepData & stepData, const MbFormNote & note, MbMesh & mesh ) const; // \ru Построить полигональную копию mesh. \en Build polygonal copy mesh. + virtual void CalculateSurfaceWire( const MbStepData & stepData, size_t beg, MbMesh & mesh, + size_t uMeshCount = c3d::WIRE_MAX, size_t vMeshCount = c3d::WIRE_MAX ) const; // \ru Рассчитать сетку. \en Calculate mesh. + // \ru Аппроксимация поверхности треугольными пластинами. \en Approximation of a surface by triangular plates. + virtual void CalculateSurfaceGrid( const MbStepData & stepData, bool sense, MbGrid & grid ) const; + // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; + // \ru Пересчитать нормали в вершинах. \en Normals Calculation on vertex. + virtual void Normalize(); + + size_t GetBoundariesCount() const { return boundary.size(); } // \ru Выдать количество граничных двумерных кривых. \en Get the two-dimensional boundary curves count. + virtual MbContour & MakeContour( bool sense ) const; // \ru Выдать граничных двумерный контур. \en Get the two-dimensional boundary contour. + virtual MbCurve & MakeSegment( size_t i, bool sense ) const; // \ru Дать граничную двумерную кривую. \en Get the two-dimensional boundary curve. + + /// \ru Инициализация объекта по другому такому же. \en Initialization of a object by same other object. + void Init( const MbGridSurface & init ); + + /// \ru Выдать количество точек. \en Get the number of points. + size_t PointsCount() const { return points.size(); } + /// \ru Выдать количество нормалей. \en Get the number of normals. + size_t NormalsCount() const { return normals.size(); } + /// \ru Выдать количество параметров. \en Get the number of parameters. + size_t ParamsCount() const { return params.size(); } + // \ru Выдать количество треугольников. \en Get the number of triangles. + size_t TrianglesCount() const { return triangles.size(); } + // \ru Выдать количество граничных кривых. \en Get the number of boundary curves. + size_t BoundariesCount() const { return boundary.size(); } + + // \ru Добавить в контейнер параметры в опорных точках поверхности. \en Get the parameters to container. + void GetParams( std::vector & paramsVector ) const; + // \ru Добавить в контейнер опорные точки. \en Get the points to container. + void GetPoints( std::vector & pointsVector ) const; + // \ru Добавить в контейнер нормали в опорных точках. \en Add the normals to container. + void GetNormals( std::vector & normalsVector ) const; + // \ru Добавить в контейнер треугольники. \en Add the triangles to container. + void GetTriangles( std::vector & tVector ) const; + // \ru Добавить в контейнер треугольники. \en Add the triangles to container. + void GetTriangles( std::vector & tVector ) const; + // \ru Добавить в контейнер граничные кривые. \en Add the boundary curves of surface parameters region. + void GetBoundaries( std::vector & bVector ) const; + + /// \ru Создание поверхности. \en Creatying of surface. + template + static MbGridSurface * Create( const Params & _params + , const Points & _points + , const Normals & _normals + , const Triangles & _triangles + , const Bounds & _bounds ) + { + MbGridSurface * surface = NULL; + + const size_t itemsCnt = _params.size(); + + if ( (itemsCnt > 2) && (itemsCnt == _points.size()) && (_triangles.size() > 0) ) { + if ( (itemsCnt == _normals.size()) || (_normals.size() == 1) ) + surface = new MbGridSurface( _params, _points, _normals, _triangles, _bounds ); + } + return surface; + } + +private: + /// \ru Инициализация. \en Initialization. + void Init( bool bound = true ); + // \ru Инициализация граничных кривых. \en Initialization of boundary curves. + void MakeBoundary(); + // \ru Выдать треугольник. \en Get triangle. + MbTrigon & GetTriangle( size_t i ) { return triangles[i]; } + void PointOn ( double & u, double & v, bool ext, MbCartPoint3D & p ) const; // \ru Точка на поверхности \en Point on the surface + void DeriveU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по u \en First derivative with respect to u + void DeriveV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveUU ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по u \en Second derivative with respect to u + void DeriveVV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по v \en Second derivative with respect to v + void DeriveUV ( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + void DeriveUUU( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveUUV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveUVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + void DeriveVVV( double & u, double & v, bool ext, MbVector3D & der ) const; // \ru Третья производная \en Third derivative + // \ru Выставить взаимные связи триангуляции. \en Set mutual connections of triangulation. + bool SetTrigonNeihbours(); + // \ru Поиск ближайшего треугольника для инициализации данных ячейки. \en Search nearest triangle for initialization of data of cell. + void FindNearest( size_t i, size_t j, std::vector & indecies, + double uDelta, double vDelta, double u, double v ); + // \ru Добавить ближайший треугольник в ячейку. \en Add nearest triangle to cell. + bool AddNearest( size_t i, size_t j, size_t ind ); + // \ru Вычислить индккс ближайшего треугольника и барицентрические координаты точки для него. \en Calculate barycentric coordinates of the nearest trianle. + size_t FindIndex( const double & u, const double & v, double & a, double & b, double & c, double & d ) const; + // \ru Расстояние до треугольника. \en The distance to a triangle. + double RangeToTriangle( size_t ind, const double & u, const double & v, double eps, + double & a, double & b, double & c, double & d ) const; + // \ru Расстояние до треугольника. \en The distance to a triangle. + double DistanceToTriangle( size_t ind, const double & u, const double & v, double eps, + MbCartPoint & p ) const; + // \ru Проверка параметров. \en Check parameters. + void CheckParam( double & u, double & v ) const; + // \ru Выдать данные триангуляции. \en Get triangulation data. + void GetTriangleData( size_t tIndex, + size_t & index1, size_t & index2, size_t & index3, + size_t & neigh1, size_t & neigh2, size_t & neigh3, + MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, + MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, + MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; + // \ru Выдать данные триангуляции соседнего треугольника. \en Get neighbour triangulation data. + bool GetNeighbourData( double u, double v, + size_t neigh1, size_t neigh2, size_t neigh3, + double & aCalc, double & bCalc, double & cCalc, double & deter, double & portion, + MbCartPoint & param1, MbCartPoint & param2, MbCartPoint & param3, + MbCartPoint3D & point1, MbCartPoint3D & point2, MbCartPoint3D & point3, + MbVector3D & normal1, MbVector3D & normal2, MbVector3D & normal3 ) const; + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. + void operator = ( const MbGridSurface & ); + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbGridSurface ) +}; // MbGridSurface + +IMPL_PERSISTENT_OPS( MbGridSurface ) + + +#endif // __SURF_GRID_SURFACE_H diff --git a/C3d/Include/surf_join_surface.h b/C3d/Include/surf_join_surface.h index f49b465..f8cae00 100644 --- a/C3d/Include/surf_join_surface.h +++ b/C3d/Include/surf_join_surface.h @@ -1,421 +1,421 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность соединения. - \en The surface of the joint. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_JOIN_SURFACE_H -#define __SURF_JOIN_SURFACE_H - - -#include -#include -#include - - -class MATH_CLASS MbSurfaceCurve; -class MATH_CLASS MbProperties; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность соединения. - \en The surface of the joint. \~ - \details \ru Поверхность представляет собой сплайновую поверхность, - натянутую на набор заданных однонаправленных кривых. - Кривые не должны пересекаться или касаться друг друга. - Касание или пересечение кривых допустимо только в конечных точках. - Координата u изменяется вдоль заданных кривых в соответствии с параметризацией каждой кривой. - Значение координаты v вдоль каждой кривой постоянно. - В направлении координаты v поверхность строится аналогично NURBS кривой с заданной степенью, узловым вектором и - использующей в качестве узлов точки заданных кривых, вычисленных с одинаковыми параметрами u. - Поверхность используется для гладкого соединения краёв двух поверхностей. - \en The surface is spline surface - tensed on a set of the given unidirectional curves. - Curves shouldn't be intersected or concerned each other. - Tangency or intersection of curves is acceptable only at the end points. - Coordinate u is changed along given curves according to parameterization of each curve. - Value of coordinate v along each curve is constant. - In the direction of v coordinate the surface is constructed similar to NURBS curve with the given degree, a nodal vector and - points of the given curves calculated with identical parameters u are used as knots. - Surface is used for smooth connection of boundaries of two surfaces. \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbJoinSurface : public MbSurface { -protected: - RPArray curves; ///< \ru Набор кривых для построения поверхности. \en Set of curves to construct surface. - SArray knots; ///< \ru Значения узлов для сплайна по v. \en Knot values for spline by v. - ptrdiff_t degree; ///< \ru Степень сплайна по v. \en Order of spline by v. - double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. - double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. - bool closedU; ///< \ru Замкнутость по u. \en Closedness by u. - bool closedV; ///< \ru Замкнутость по V. \en Closedness by V. - bool isPoleUmin; ///< \ru Полюс при u == umin. \en Pole at u == umin. - bool isPoleUmax; ///< \ru Полюс при u == umax. \en Pole at u == umax. - bool isPoleVmin; ///< \ru Полюс при u == vmin. \en Pole at u == vmin. - bool isPoleVmax; ///< \ru Полюс при u == vmax. \en Pole at u == vmax. - -private: - //------------------------------------------------------------------------------ - /** \brief \ru Вспомогательные данные. - \en Auxiliary data. \~ - \details \ru Вспомогательные данные служат для ускорения работы объекта. - \en Auxiliary data are used for fast calculations. \n \~ - */ - // --- - class MbJoinSurfaceAuxiliaryData : public AuxiliaryData { - public: - double calcU; ///< \ru Последнее обработанное значение u. \en Last processed value of u. - double calcV; ///< \ru Последнее обработанное значение v. \en Last processed value of v. - ptrdiff_t lastIndex; ///< \ru Левый индекс узлового вектора из последних вычислений. \en Left index of knot vector from last calculations. - double ** points; ///< \ru 2-х мерный массив для хранения данных по точкам для текущих вычислений. \en Two-dimensional array to store points data for current calculations. - double ** nMatrix; ///< \ru Матрица коэффициентов для NURBS. \en Matrix of coefficients for NURBS. - SArray tempPoints; ///< \ru Множество рабочих точек. \en Set of working points. - SArray tempVectors; ///< \ru Множество рабочих векторов. \en Set of working vectors. - SArray readyData; ///< \ru Множество для хранения вычисленных значений точки и производных. \en Set to store calculated values of point and derivatives. - - // \ru Рабочие указатели для создания базисных сплайнов \en Working pointers for creation of basis splines - double * m_left; ///< \ru Рабочие указатели для создания базисных сплайнов. \en Working pointers for creation of basis splines. - double * m_right; ///< \ru Рабочие указатели для создания базисных сплайнов. \en Working pointers for creation of basis splines. - ptrdiff_t *degree; ///< \ru Степень сплайна по v. \en Order of spline by v. - MbJoinSurfaceAuxiliaryData(); - MbJoinSurfaceAuxiliaryData( const MbJoinSurfaceAuxiliaryData & init ); - virtual ~MbJoinSurfaceAuxiliaryData(); - void CreateVars(); - void InitVars (); - void FreeVars (); - private: - void operator = ( const MbJoinSurfaceAuxiliaryData & ); - }; - mutable CacheManager cache; - -protected: - /// \ru Конструктор копирования. \en Copy-constructor. - MbJoinSurface( const MbJoinSurface &, MbRegDuplicate * ); -private: - MbJoinSurface( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. -public: - /** \brief \ru Конструктор поверхности соединения. - \en Constructor of surface of the joint. \~ - \details \ru Конструктор поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n - В конструкторе этот факт не проверяется.\n - \en Constructor of surface of the joint by set of curves. Curves shouldn't be intersected.\n - In constructor this fact doesn't checked.\n \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - MbJoinSurface( const RPArray & initCurves, bool sameCurves ); - /** \brief \ru Конструктор поверхности соединения. - \en Constructor of surface of the joint. \~ - \details \ru Конструктор поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n - В конструкторе этот факт не проверяется. - \en Constructor of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n - In constructor this fact doesn't checked. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v. - \en Surface order by v. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - MbJoinSurface( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); - /** \brief \ru Конструктор поверхности соединения. - \en Constructor of surface of the joint. \~ - \details \ru Конструктор поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n - Кривые должны быть непересекающиеся. В конструкторе этот факт не проверяется. - \en Constructor of surface of the joint by set of curves, order of surface and knot vector.\n - Curves shouldn't be intersected. In constructor this fact doesn't checked. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v. - \en Surface order by v. \~ - \param[in] initKnots - \ru Узловой вектор по v. - \en A knot vector by v. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - MbJoinSurface( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); - -public: - virtual ~MbJoinSurface(); - -public: - VISITING_CLASS( MbJoinSurface ); - -public: - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n - Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves. Curves shouldn't be intersected.\n - This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - void Init( const RPArray & initCurves, bool sameCurves ); - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n - Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n - This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v.\n - \en Surface order by v.\n \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - bool Init( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); - /** \brief \ru Инициализация поверхности соединения. - \en Initialization of surface of the joint. \~ - \details \ru Инициализация поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n - Кривые должны быть непересекающиеся. Этот факт в функции не проверяется. Порядок поверхности не изменяется. - \en Initialization of surface of the joint by set of curves, order of surface and knot vector.\n - Curves shouldn't be intersected. This fact isn't checked in the function. Surface order doesn't changed. \~ - \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. - \en List of of curves which the surface is tensed on. \~ - \param[in] initDegree - \ru Порядок поверхности по v. - \en Surface order by v. \~ - \param[in] initKnots - \ru Узловой вектор по v. - \en A knot vector by v. \~ - \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n - true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n - false - использовать копии кривых. - \en Determines whether to copy curves:\n - true - use curves given in the constructor in object without copying,\n - false - use copies of curves. \~ - */ - bool Init( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); - - /** \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 Сделать копию элемента \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 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; // \ru Минимальное значение параметра u \en Minimal value of parameter u - virtual double GetVMin() const; // \ru Минимальное значение параметра v \en Minimal value of parameter v - virtual double GetUMax() const; // \ru Максимальное значение параметра u \en Maximal value of parameter u - virtual double GetVMax() const; // \ru Максимальное значение параметра v \en Maximal value of parameter v - 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. - 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 & ) const; // \ru Точка на поверхности \en Point on the surface - virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная \en The second derivative - virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative - virtual void Normal ( double & u, double & v, MbVector3D & ) 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 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 & ) 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 angle ) const; // \ru Вычисление шага параметра u по углу отклонения нормали \en Calculation of parameter u step by the angle of deviation of normal - virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага параметра v по углу отклонения нормали \en Calculation of parameter v step by the angle of deviation of normal - virtual double MetricStepU ( double u, double v, double length ) const; // \ru Вычисление шага параметра u по заданной метрической длине \en Calculation of parameter u step by the given metric length - virtual size_t GetUCount() const; // \ru Количество разбиений по параметру u для проверки событий \en Count of splittings by parameter u to check for events - virtual size_t GetVCount() const; // \ru Количество разбиений по параметру v для проверки событий \en Count of splittings by parameter v to check for events - /** \} */ - - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - virtual void Refresh (); ///< \ru Cбросить все временные данные. \en Reset all temporary data. - - virtual MbSplineSurface * NurbsSurface( double u1, double u2, double v1, double v2, bool bmatch = false ) const; - virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; - virtual MbSurface * Offset( double d, bool same ) const; // \ru Построить смещенную поверхность \en Create a shifted surface - - /// \ru Изменение степени NURBS кривой по v. \en Change degree of NURBS curve by v. - void ChangeDegree ( ptrdiff_t newDegree ); - /// \ru Получить количество базовых кривых. \en Get count of base curves. - size_t GetCurvesCount () const; - /// \ru Получить кривую с индeксом num. \en Get curve with 'num' index. - const MbCurve3D * GetCurve( size_t k ) const; - const SArray & GetKnots() const { return knots; } ///< \ru Получить значения узлов для сплайна по v. \en Get knot values for spline by v. - - /** \brief \ru Получить список начальных или конечных базовых точек кривых. - \en Get list of start or end base points of curves. \~ - \details \ru Получить список начальных или конечных базовых точек кривых.\n - \en Get list of start or end base points of curves.\n \~ - \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n - \en Determines start or end points were requested: true - start, false - end.\n \~ - \param[in] points - \ru Список, в который помещаются найденные точки. \n - Порядок точек соответствует порядку кривых в списке curves. - \en List to store found points. \n - Order of points corresponds to order of curves in 'curves' list. \~ - \return \ru false и список points остается пустым,\n - если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). - \en False then 'points' list remains empty,\n - if at least one curve has no base points (not segment and not curve given by points). \~ - */ - bool GetCurvesBasePoints( bool isFirstPoints, SArray & points ) const; - /** \brief \ru Изменить крайние базовые точки кривых. - \en Change end base points of curves. \~ - \details \ru Базовые точки можно изменить в том случае, если все кривые, на которые натянута поверхность,\n - являются отрезками или кривыми, заданными точками. - \en Base points can be changed in case of all curves which the surface is tensed on\n - are segments or curves given by points. \~ - \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n - \en Determines start or end points were requested: true - start, false - end.\n \~ - \param[in] points - \ru Список, в который помещаются новые значения базовых точек.\n - Порядок точек соответствует порядку кривых в списке curves. - \en List to store new values of base points.\n - Order of points corresponds to order of curves in 'curves' list. \~ - \return \ru false и список points остается пустым,\n - если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). - \en False then 'points' list remains empty,\n - if at least one curve has no base points (not segment and not curve given by points). \~ - */ - bool SetCurvesBasePoints( bool isFirstPoints, SArray & points ); - /** \} */ - - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinSurface ) - -private: - void operator = ( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. - - void ResetTCalc(); - bool CheckData ( const SArray & newKnots, ptrdiff_t newDegree ); // \ru Проверить корректность данных для NURBS \en Check correctness of data for NURBS - void ChangeKnots ( const ptrdiff_t newDegree, const bool closed, SArray & newKnots ); // \ru Изменить массив узлов, если изменилась степень сплайна \en Change array of knots if degree of spline was changed - void CreateTempVars( MbJoinSurfaceAuxiliaryData * ucache ) const; - void InitTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; - void FreeTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; - void PreparePointsData( ptrdiff_t lIndex, ptrdiff_t derNum, MbJoinSurfaceAuxiliaryData * ucache ) const; - void PreparePointList ( const double u, ptrdiff_t derNumberU, MbJoinSurfaceAuxiliaryData * ucache ) const; - void CheckPointData ( const MbeSurfaceDerivativeType derUVNumber, double & u, double & v, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; - ptrdiff_t GetUDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; - ptrdiff_t GetVDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; - void CheckPole(); - void CheckParams ( double & u, double & v ) const; - void PoleDerive ( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV ) const; - double DeviationStep( double u, double v, double angle ) const; - double StepD ( double u, double v, double sag, bool checkAngle, double angle ) const; - // \ru Вычисление точки и производных поверхности. \en Calculation of the point and derivatives of the surface. \~ - void ExploreVector( SArray & points, SArray & vectors, - ptrdiff_t lIndex, ptrdiff_t derNum, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; - -}; - -IMPL_PERSISTENT_OPS( MbJoinSurface ) - -//------------------------------------------------------------------------------ -// \ru Проверить параметры и в случае захода за полюс загнать в полюсную область \en Check parameters and if it is out of pole, then drive it to pole region -// --- -inline void MbJoinSurface::CheckParams( double & u, double & v ) const -{ - if ( isPoleUmin ) { - if ( u < umin ) - u = umin; - } - if ( isPoleUmax ) { - if ( u > umax ) - u = umax; - } - if ( isPoleVmin ) { - const double & vmin = knots[degree - 1]; - if ( v < vmin ) - v = vmin; - } - if ( isPoleVmax ) { - const double & vmax = knots[knots.MaxIndex() - degree + 1]; - if ( v > vmax ) - v = vmax; - } -} - - -#endif // __SURF_JOIN_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность соединения. + \en The surface of the joint. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_JOIN_SURFACE_H +#define __SURF_JOIN_SURFACE_H + + +#include +#include +#include + + +class MATH_CLASS MbSurfaceCurve; +class MATH_CLASS MbProperties; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность соединения. + \en The surface of the joint. \~ + \details \ru Поверхность представляет собой сплайновую поверхность, + натянутую на набор заданных однонаправленных кривых. + Кривые не должны пересекаться или касаться друг друга. + Касание или пересечение кривых допустимо только в конечных точках. + Координата u изменяется вдоль заданных кривых в соответствии с параметризацией каждой кривой. + Значение координаты v вдоль каждой кривой постоянно. + В направлении координаты v поверхность строится аналогично NURBS кривой с заданной степенью, узловым вектором и + использующей в качестве узлов точки заданных кривых, вычисленных с одинаковыми параметрами u. + Поверхность используется для гладкого соединения краёв двух поверхностей. + \en The surface is spline surface + tensed on a set of the given unidirectional curves. + Curves shouldn't be intersected or concerned each other. + Tangency or intersection of curves is acceptable only at the end points. + Coordinate u is changed along given curves according to parameterization of each curve. + Value of coordinate v along each curve is constant. + In the direction of v coordinate the surface is constructed similar to NURBS curve with the given degree, a nodal vector and + points of the given curves calculated with identical parameters u are used as knots. + Surface is used for smooth connection of boundaries of two surfaces. \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbJoinSurface : public MbSurface { +protected: + RPArray curves; ///< \ru Набор кривых для построения поверхности. \en Set of curves to construct surface. + SArray knots; ///< \ru Значения узлов для сплайна по v. \en Knot values for spline by v. + ptrdiff_t degree; ///< \ru Степень сплайна по v. \en Order of spline by v. + double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. + double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. + bool closedU; ///< \ru Замкнутость по u. \en Closedness by u. + bool closedV; ///< \ru Замкнутость по V. \en Closedness by V. + bool isPoleUmin; ///< \ru Полюс при u == umin. \en Pole at u == umin. + bool isPoleUmax; ///< \ru Полюс при u == umax. \en Pole at u == umax. + bool isPoleVmin; ///< \ru Полюс при u == vmin. \en Pole at u == vmin. + bool isPoleVmax; ///< \ru Полюс при u == vmax. \en Pole at u == vmax. + +private: + //------------------------------------------------------------------------------ + /** \brief \ru Вспомогательные данные. + \en Auxiliary data. \~ + \details \ru Вспомогательные данные служат для ускорения работы объекта. + \en Auxiliary data are used for fast calculations. \n \~ + */ + // --- + class MbJoinSurfaceAuxiliaryData : public AuxiliaryData { + public: + double calcU; ///< \ru Последнее обработанное значение u. \en Last processed value of u. + double calcV; ///< \ru Последнее обработанное значение v. \en Last processed value of v. + ptrdiff_t lastIndex; ///< \ru Левый индекс узлового вектора из последних вычислений. \en Left index of knot vector from last calculations. + double ** points; ///< \ru 2-х мерный массив для хранения данных по точкам для текущих вычислений. \en Two-dimensional array to store points data for current calculations. + double ** nMatrix; ///< \ru Матрица коэффициентов для NURBS. \en Matrix of coefficients for NURBS. + SArray tempPoints; ///< \ru Множество рабочих точек. \en Set of working points. + SArray tempVectors; ///< \ru Множество рабочих векторов. \en Set of working vectors. + SArray readyData; ///< \ru Множество для хранения вычисленных значений точки и производных. \en Set to store calculated values of point and derivatives. + + // \ru Рабочие указатели для создания базисных сплайнов \en Working pointers for creation of basis splines + double * m_left; ///< \ru Рабочие указатели для создания базисных сплайнов. \en Working pointers for creation of basis splines. + double * m_right; ///< \ru Рабочие указатели для создания базисных сплайнов. \en Working pointers for creation of basis splines. + ptrdiff_t *degree; ///< \ru Степень сплайна по v. \en Order of spline by v. + MbJoinSurfaceAuxiliaryData(); + MbJoinSurfaceAuxiliaryData( const MbJoinSurfaceAuxiliaryData & init ); + virtual ~MbJoinSurfaceAuxiliaryData(); + void CreateVars(); + void InitVars (); + void FreeVars (); + private: + void operator = ( const MbJoinSurfaceAuxiliaryData & ); + }; + mutable CacheManager cache; + +protected: + /// \ru Конструктор копирования. \en Copy-constructor. + MbJoinSurface( const MbJoinSurface &, MbRegDuplicate * ); +private: + MbJoinSurface( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. +public: + /** \brief \ru Конструктор поверхности соединения. + \en Constructor of surface of the joint. \~ + \details \ru Конструктор поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n + В конструкторе этот факт не проверяется.\n + \en Constructor of surface of the joint by set of curves. Curves shouldn't be intersected.\n + In constructor this fact doesn't checked.\n \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + MbJoinSurface( const RPArray & initCurves, bool sameCurves ); + /** \brief \ru Конструктор поверхности соединения. + \en Constructor of surface of the joint. \~ + \details \ru Конструктор поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n + В конструкторе этот факт не проверяется. + \en Constructor of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n + In constructor this fact doesn't checked. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v. + \en Surface order by v. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + MbJoinSurface( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); + /** \brief \ru Конструктор поверхности соединения. + \en Constructor of surface of the joint. \~ + \details \ru Конструктор поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n + Кривые должны быть непересекающиеся. В конструкторе этот факт не проверяется. + \en Constructor of surface of the joint by set of curves, order of surface and knot vector.\n + Curves shouldn't be intersected. In constructor this fact doesn't checked. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v. + \en Surface order by v. \~ + \param[in] initKnots - \ru Узловой вектор по v. + \en A knot vector by v. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + MbJoinSurface( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); + +public: + virtual ~MbJoinSurface(); + +public: + VISITING_CLASS( MbJoinSurface ); + +public: + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых. Кривые должны быть непересекающиеся.\n + Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves. Curves shouldn't be intersected.\n + This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + void Init( const RPArray & initCurves, bool sameCurves ); + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых и порядку поверхности. Кривые должны быть непересекающиеся.\n + Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves and order of surface. Curves shouldn't be intersected.\n + This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v.\n + \en Surface order by v.\n \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + bool Init( const RPArray & initCurves, ptrdiff_t initDegree, bool sameCurves ); + /** \brief \ru Инициализация поверхности соединения. + \en Initialization of surface of the joint. \~ + \details \ru Инициализация поверхности соединения по набору кривых, порядку поверхности и узловому вектору.\n + Кривые должны быть непересекающиеся. Этот факт в функции не проверяется. Порядок поверхности не изменяется. + \en Initialization of surface of the joint by set of curves, order of surface and knot vector.\n + Curves shouldn't be intersected. This fact isn't checked in the function. Surface order doesn't changed. \~ + \param[in] initCurves - \ru Список кривых, на которых натягивается поверхность. + \en List of of curves which the surface is tensed on. \~ + \param[in] initDegree - \ru Порядок поверхности по v. + \en Surface order by v. \~ + \param[in] initKnots - \ru Узловой вектор по v. + \en A knot vector by v. \~ + \param[in] sameCurves - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + */ + bool Init( const RPArray & initCurves, ptrdiff_t initDegree, const SArray & initKnots, bool sameCurves ); + + /** \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 Сделать копию элемента \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 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; // \ru Минимальное значение параметра u \en Minimal value of parameter u + virtual double GetVMin() const; // \ru Минимальное значение параметра v \en Minimal value of parameter v + virtual double GetUMax() const; // \ru Максимальное значение параметра u \en Maximal value of parameter u + virtual double GetVMax() const; // \ru Максимальное значение параметра v \en Maximal value of parameter v + 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. + 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 & ) const; // \ru Точка на поверхности \en Point on the surface + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная \en The second derivative + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная \en Third derivative + virtual void Normal ( double & u, double & v, MbVector3D & ) 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 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 & ) 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 angle ) const; // \ru Вычисление шага параметра u по углу отклонения нормали \en Calculation of parameter u step by the angle of deviation of normal + virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага параметра v по углу отклонения нормали \en Calculation of parameter v step by the angle of deviation of normal + virtual double MetricStepU ( double u, double v, double length ) const; // \ru Вычисление шага параметра u по заданной метрической длине \en Calculation of parameter u step by the given metric length + virtual size_t GetUCount() const; // \ru Количество разбиений по параметру u для проверки событий \en Count of splittings by parameter u to check for events + virtual size_t GetVCount() const; // \ru Количество разбиений по параметру v для проверки событий \en Count of splittings by parameter v to check for events + /** \} */ + + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + virtual void Refresh (); ///< \ru Cбросить все временные данные. \en Reset all temporary data. + + virtual MbSplineSurface * NurbsSurface( double u1, double u2, double v1, double v2, bool bmatch = false ) const; + virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; + virtual MbSurface * Offset( double d, bool same ) const; // \ru Построить смещенную поверхность \en Create a shifted surface + + /// \ru Изменение степени NURBS кривой по v. \en Change degree of NURBS curve by v. + void ChangeDegree ( ptrdiff_t newDegree ); + /// \ru Получить количество базовых кривых. \en Get count of base curves. + size_t GetCurvesCount () const; + /// \ru Получить кривую с индeксом num. \en Get curve with 'num' index. + const MbCurve3D * GetCurve( size_t k ) const; + const SArray & GetKnots() const { return knots; } ///< \ru Получить значения узлов для сплайна по v. \en Get knot values for spline by v. + + /** \brief \ru Получить список начальных или конечных базовых точек кривых. + \en Get list of start or end base points of curves. \~ + \details \ru Получить список начальных или конечных базовых точек кривых.\n + \en Get list of start or end base points of curves.\n \~ + \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n + \en Determines start or end points were requested: true - start, false - end.\n \~ + \param[in] points - \ru Список, в который помещаются найденные точки. \n + Порядок точек соответствует порядку кривых в списке curves. + \en List to store found points. \n + Order of points corresponds to order of curves in 'curves' list. \~ + \return \ru false и список points остается пустым,\n + если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). + \en False then 'points' list remains empty,\n + if at least one curve has no base points (not segment and not curve given by points). \~ + */ + bool GetCurvesBasePoints( bool isFirstPoints, SArray & points ) const; + /** \brief \ru Изменить крайние базовые точки кривых. + \en Change end base points of curves. \~ + \details \ru Базовые точки можно изменить в том случае, если все кривые, на которые натянута поверхность,\n + являются отрезками или кривыми, заданными точками. + \en Base points can be changed in case of all curves which the surface is tensed on\n + are segments or curves given by points. \~ + \param[in] isFirstPoints - \ru Определяет конечные или начальные точки запрошены: true - начальные, false - конечные.\n + \en Determines start or end points were requested: true - start, false - end.\n \~ + \param[in] points - \ru Список, в который помещаются новые значения базовых точек.\n + Порядок точек соответствует порядку кривых в списке curves. + \en List to store new values of base points.\n + Order of points corresponds to order of curves in 'curves' list. \~ + \return \ru false и список points остается пустым,\n + если хотя бы одна кривая не имеет базовых точек (не отрезок и не кривая, заданная точками). + \en False then 'points' list remains empty,\n + if at least one curve has no base points (not segment and not curve given by points). \~ + */ + bool SetCurvesBasePoints( bool isFirstPoints, SArray & points ); + /** \} */ + + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbJoinSurface ) + +private: + void operator = ( const MbJoinSurface & ); // \ru Не реализовано. \en Not implemented. + + void ResetTCalc(); + bool CheckData ( const SArray & newKnots, ptrdiff_t newDegree ); // \ru Проверить корректность данных для NURBS \en Check correctness of data for NURBS + void ChangeKnots ( const ptrdiff_t newDegree, const bool closed, SArray & newKnots ); // \ru Изменить массив узлов, если изменилась степень сплайна \en Change array of knots if degree of spline was changed + void CreateTempVars( MbJoinSurfaceAuxiliaryData * ucache ) const; + void InitTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; + void FreeTempVars ( MbJoinSurfaceAuxiliaryData * ucache ) const; + void PreparePointsData( ptrdiff_t lIndex, ptrdiff_t derNum, MbJoinSurfaceAuxiliaryData * ucache ) const; + void PreparePointList ( const double u, ptrdiff_t derNumberU, MbJoinSurfaceAuxiliaryData * ucache ) const; + void CheckPointData ( const MbeSurfaceDerivativeType derUVNumber, double & u, double & v, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; + ptrdiff_t GetUDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; + ptrdiff_t GetVDerNumber( const MbeSurfaceDerivativeType derUVNumber ) const; + void CheckPole(); + void CheckParams ( double & u, double & v ) const; + void PoleDerive ( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV ) const; + double DeviationStep( double u, double v, double angle ) const; + double StepD ( double u, double v, double sag, bool checkAngle, double angle ) const; + // \ru Вычисление точки и производных поверхности. \en Calculation of the point and derivatives of the surface. \~ + void ExploreVector( SArray & points, SArray & vectors, + ptrdiff_t lIndex, ptrdiff_t derNum, MbVector3D & vect, MbJoinSurfaceAuxiliaryData * ucache ) const; + +}; + +IMPL_PERSISTENT_OPS( MbJoinSurface ) + +//------------------------------------------------------------------------------ +// \ru Проверить параметры и в случае захода за полюс загнать в полюсную область \en Check parameters and if it is out of pole, then drive it to pole region +// --- +inline void MbJoinSurface::CheckParams( double & u, double & v ) const +{ + if ( isPoleUmin ) { + if ( u < umin ) + u = umin; + } + if ( isPoleUmax ) { + if ( u > umax ) + u = umax; + } + if ( isPoleVmin ) { + const double & vmin = knots[degree - 1]; + if ( v < vmin ) + v = vmin; + } + if ( isPoleVmax ) { + const double & vmax = knots[knots.MaxIndex() - degree + 1]; + if ( v > vmax ) + v = vmax; + } +} + + +#endif // __SURF_JOIN_SURFACE_H diff --git a/C3d/Include/surf_lofted_surface.h b/C3d/Include/surf_lofted_surface.h index 6060c09..7cebd25 100644 --- a/C3d/Include/surf_lofted_surface.h +++ b/C3d/Include/surf_lofted_surface.h @@ -1,664 +1,706 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность, проходящая через заданное семейство кривых. - \en Lofted surface. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_LOFTED_SURFACE_H -#define __SURF_LOFTED_SURFACE_H - -#include -#include -#include -#include - - -class MATH_CLASS MbSurfaceContiguousData; - -#define LOFT_NUMB 4 ///< \ru Вспомогательный параметр для поверхности MbLoftedSurface. Используется для определения количества элементов в массивах, где хранится точка и первые три производные в этой точке. \en Auxiliary parameter for MbLoftedSurface surface. Used for determination of count of elements in arrays of points and first three derivatives at this point. -const VERSION LOFTED_SURFACE_VERSION1 = 0x0F000013L; ///< \ru Корректировка коэффициентов уравнения поверхности. \en Correction of surface equation coefficients. -const VERSION LOFTED_SURFACE_VERSION2 = 0x13000015L; ///< \ru Возможность устанавливать нормали на торцевых сечениях в виде точки. \en Ability to set normals on end sections as a point. - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность, проходящая через заданное семейство кривых. - \en Lofted surface passing through given family of curves. \~ - \details \ru Поверхность, проходящая через заданное семейство кривых, построена аналогично сплайну Эрмита MbHermit3D, - проходящего через заданное семейство точек. - Первый параметр поверхности пропорционален параметрам кривых семейства. - Вдоль второго параметра поверхность изменяется по закону сплайна Эрмита MbHermit3D, точками которого служат точки кривых семейства. - Производные по второму параметру в точках кривых вычисляются как производные параболы, - построенной по трём точкам и значениям параметров в них. - На каждом участке между двумя соседними кривыми семейства поверхность описывается кубическим полиномом - с заданными точками и производными на краях. - Поверхность проходит через кривые семейства при значениях параметра из множества vParams. - \en The surface passing through given family of curves is constructed similar to MbHermit3D Hermite spline - passing through given family of points. - First parameter of surface is proportional to parameters of curves of family. - Along the second parameter the surface changes under the law of MbHermit3D Hermite spline, which points are points of curves of family. - Derivatives by second parameter at points of curves are calculated as derivatives of parabola - constructed by three points and values of parameters at this points. - On each region between two neighboring curves of family the surface is described by the cubic polynomial - with given points and derivatives at the edges. - Surface passes through curves of family for parameter values from vParams set. \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbLoftedSurface : public MbSurface { -protected: - RPArray uCurves; ///< \ru Множество кривых семейства. \en Set of curves of family. - SArray vParams; ///< \ru Множество параметров v для кривых. \en Set of parameters v for curves. - SArray vLabels; ///< \ru Множество признаков одинаковых кривых. \en Set of attributes of similar curves. - double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. - double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. - double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. - double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. - bool uclosed; ///< \ru Признак замкнутости по параметру u. \en Attribute of closedness by parameter u. - bool vclosed; ///< \ru Признак замкнутости по параметру v. \en Attribute of closedness by parameter v. - MbVector3D derive1; ///< \ru Направление производной в начале незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the beginning of the open surface. If it isn't set, then its length is zero. - MbVector3D derive2; ///< \ru Направление производной в конце незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the end of the open surface. If it isn't set, then its length is zero. - bool setNormal1; ///< \ru Установлена нормаль в начальном сечении. \en The normal is set in initial section. - bool setNormal2; ///< \ru Установлена нормаль в конечном сечении. \en The normal is set in end section. - VERSION surfaceVersion; ///< \ru Версия расчета коэффициентов уравнения поверхности. \en Version of coefficient calculation of surface equation. - -protected: - //------------------------------------------------------------------------------ - /** \brief \ru Вспомогательные данные. - \en Auxiliary data. \~ - \details \ru Вспомогательные данные служат для ускорения работы объекта. - \en Auxiliary data are used for fast calculations. \n \~ - */ - // --- - class MbLoftedSurfaceAuxiliaryData : public AuxiliaryData { - public: - DPtr data; ///< \ru Дополнительные данные о поверхности. \en Additional data about a surface. - MbLoftedSurfaceAuxiliaryData(); - MbLoftedSurfaceAuxiliaryData( const MbLoftedSurfaceAuxiliaryData & init ); - virtual ~MbLoftedSurfaceAuxiliaryData(); - }; - - mutable CacheManager cache; - -public: - /** \brief \ru Конструктор поверхности. - \en Constructor of surface. \~ - \details \ru Конструктор поверхности по массиву профильных кривых, направляющим векторам и замкнутости по v. - \en Constructor of surface by array of profile curves, guide vectors and closedness by v. \~ - \param[in] initCurves - \ru Множество задающих кривых. - \en Set of driving curves. \~ - \param[in] vc - \ru Замкнутость поверхности по v. - \en Surface closedness by v. \~ - \param[in] v1 - \ru Направляющий вектор. - \en Guide vector. \~ - \param[in] v2 - \ru Направляющий вектор. - \en Guide vector. \~ - \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. - \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ - \param[in] version - \ru Версия, по умолчанию - последняя. - \en Version, last by default. \~ - */ - MbLoftedSurface( const RPArray & initCurves, - bool vc, const MbVector3D & v1, const MbVector3D & v2, bool same, - VERSION version = Math::DefaultMathVersion() ); - /** \brief \ru Конструктор поверхности. - \en Constructor of surface. \~ - \details \ru Конструктор поверхности по массиву профильных кривых, массиву параметров, направляющим векторам и замкнутости по v. - \en Constructor of surface by array of profile curves, array of parameters, guide vectors and closedness by v. \~ - \param[in] initCurves - \ru Множество задающих кривых. - \en Set of driving curves. \~ - \param[in] initParams - \ru Множество параметров, соответствующих задающим кривым. - \en Set of parameters corresponding to driving curves. \~ - \param[in] vc - \ru Замкнутость поверхности по v. - \en Surface closedness by v. \~ - \param[in] v1 - \ru Направляющий вектор. - \en Guide vector. \~ - \param[in] v2 - \ru Направляющий вектор. - \en Guide vector. \~ - \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. - \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ - \param[in] version - \ru Версия, по умолчанию - последняя. - \en Version, last by default. \~ - */ - MbLoftedSurface( const RPArray & initCurves, const SArray & initParams, - bool vc, const MbVector3D & v1, const MbVector3D & v2, bool setNormal1, bool setNormal2, bool same, - VERSION version = Math::DefaultMathVersion() ); -protected: // \ru Конструкторы для наследников \en Constructors for inheritors - /** \brief \ru Конструктор поверхности. - \en Constructor of surface. \~ - \details \ru Конструктор поверхности по набору профильных кривых. - \en Constructor of surface by family of profile curves. \~ - \param[in] initCurves - \ru Множество задающих кривых. - \en Set of driving curves. \~ - \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. - \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ - \param[in] version - \ru Версия, по умолчанию - последняя. - \en Version, last by default. \~ - */ - MbLoftedSurface( const RPArray & initCurves, bool same, VERSION version = Math::DefaultMathVersion() ); - /** \brief \ru Конструктор поверхности. - \en Constructor of surface. \~ - \details \ru Конструктор поверхности по массиву профильных кривых и массиву параметров. - \en Constructor of surface by array of profile curves and array of parameters. \~ - \param[in] initParams - \ru Множество параметров, соответствующих задающим кривым. - \en Set of parameters corresponding to driving curves. \~ - \param[in] initCurves - \ru Множество задающих кривых. - \en Set of driving curves. \~ - \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. - \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ - \param[in] version - \ru Версия, по умолчанию - последняя. - \en Version, last by default. \~ - */ - MbLoftedSurface( const SArray & initParams, const RPArray & initCurves, bool same, VERSION version = Math::DefaultMathVersion() ); - /// \ru Конструктор-копия. \en Copy constructor. - MbLoftedSurface( const MbLoftedSurface &, MbRegDuplicate * reg ); -private: - MbLoftedSurface( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. -public: - virtual ~MbLoftedSurface(); - -public: - VISITING_CLASS( MbLoftedSurface ); - - /** \ru \name Общие функции геометрического объекта - \en \name Common functions of a geometric object - \{ */ - 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 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 Refresh(); - - 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 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; // \ru Вернуть минимальное значение параметра u \en Return the minimum value of parameter u - virtual double GetVMin () const; // \ru Вернуть минимальное значение параметра v \en Return the minimum value of parameter v - virtual double GetUMax () const; // \ru Вернуть максимальное значение параметра u \en Return the maximum value of parameter u - virtual double GetVMax () const; // \ru Вернуть максимальное значение параметра v \en Return the maximum value of parameter v - 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. - virtual double GetUPeriod() const; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. - virtual size_t GetUCount() const; - virtual size_t GetVCount() const; - // \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 & ) const; // \ru Точка на поверхности \en Point on the surface - virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по u \en Third derivative with respect to u - virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по v \en Third derivative with respect to v - virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv - virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv - /** \} */ - - /** \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 & ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная по u \en Third derivative with respect to u - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная по v \en Third derivative with respect to v - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv - /** \} */ - /** \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 Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of step of approximation with consideration of curvature radius - virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of step of approximation with consideration of curvature radius - virtual double DeviationStepU( double u, double v, double sag ) const; // \ru Вычисление шага по u при пересечении поверхностей \en Calculation of step by u while intersecting surfaces - virtual double DeviationStepV( double u, double v, double sag ) const; // \ru Вычисление шага по u при пересечении поверхностей \en Calculation of step by u while intersecting surfaces - /** \} */ - - /** \ru \name Общие функции поверхности - \en \name Common functions of surface - \{ */ - virtual bool IsPlanar() 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 - - // \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 - - // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей \en Construct tangent and normal placements of constructive planes - virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; - virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; - virtual bool GetCylinderAxis( MbAxis3D & axis ) const; // \ru Дать ось вращения для поверхности \en Get a rotation axis of a surface - - 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 a shifted surface - - 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 - - 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 Определение разбивки параметрической области поверхности вертикалями и горизонталями \en Determine splitting of parametric region of surface by vertical and horizontal lines - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - 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; - // \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 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 - - // \ru Проверить параметры и загнать в область определения, если параметр вышел за полюс. - // Аналог глобальной функции _CheckParams, оптимизированный под использование кэшей. - // \en Check parameters and move them inside domain if parameter is out of pole. - // \en Check parameters. Analogue of the global function _CheckParams, optimized for caches usage. - // \param[in] surface - \ru Поверхность. \en Surface. - // \param[in] u - \ru Первый параметр. \en First parameter. - // \param[in] v - \ru Второй параметр. \en Second parameter. - virtual void CheckSurfParams( double & u, double & v ) const; - - /// \ru Получить количество кривых, на которых построена поверхность \en Get count of curves which the surface is constructed by - ptrdiff_t CurvesCount() const { return (ptrdiff_t)uCurves.Count(); } - - /** \brief \ru Получить кривую по номеру. - \en Get curve by an index. \~ - \details \ru Получить кривую по номеру. \n - \en Get curve by an index. \n \~ - \param[in] ind - \ru Порядковый номер кривой в массиве кривых uCurves. - \en Index of curve in uCurves array of curves. \~ - \return \ru Константная кривая. - \en The constant curve. \~ - */ - const MbCurve3D * GetCurve( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } - /** \brief \ru Получить кривую для редактирования по номеру. - \en Get curve for editing by an index. \~ - \details \ru Получить кривую для редактирования по номеру. \n - \en Get curve for editing by an index. \n \~ - \param[in] ind - \ru Порядковый номер кривой в массиве кривых uCurves. - \en Index of curve in uCurves array of curves. \~ - \return \ru Кривая. - \en A curve. \~ - */ - MbCurve3D * SetCurve( ptrdiff_t ind ) { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } - /** \brief \ru Получить параметр по номеру. - \en Get parameter by an index. \~ - \details \ru Получить параметр по номеру.\n - \en Get parameter by an index.\n \~ - \param[in] ind - \ru Порядковый номер параметра в массиве параметров vParams. - \en Index of parameter in vParams array of parameters. \~ - \return \ru Значение параметра. - \en A parameter value. \~ - */ - double GetParam( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)vParams.Count()) ? vParams[ind] : 0.0; } - /** \brief \ru Заполнить массив параметрами. - \en Fill an array by parameters. \~ - \details \ru Заполнить массив параметрами. \n - \en Fill an array by parameters. \n \~ - \param[in,out] params - \ru Множество для заполнения параметрами. - \en A set to fill by parameters. \~ - */ - void GetParams( SArray & params ) const { params = vParams; } - /** \brief \ru Заполнить массив признаков одинаковых кривых. - \en Fill array of attributes of similar curves. \~ - \details \ru Заполнить массив признаков одинаковых кривых. \n - \en Fill array of attributes of similar curves. \n \~ - \param[in,out] labels - \ru Множество для заполнения. - \en A set to fill. \~ - */ - void GetLabels( SArray & labels ) const { labels = vLabels; } - - /// \ru Направление производной в начале незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the beginning of the open surface. If it isn't set, then its length is zero. - const MbVector3D & GetDerive1() const { return derive1; } - ///< \ru Направление производной в конце незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the end of the open surface. If it isn't set, then its length is zero. - const MbVector3D & GetDerive2() const { return derive2; } - - bool IsEqualLabels() const; ///< \ru Определить, есть ли одинаковые кривые. \en Determine whether there are similar curves. - /** \brief \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. - \en Determine whether there are curves similar to curve with 'ind' index. \~ - \details \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. \n - \en Determine whether there are curves similar to curve with 'ind' index. \n \~ - \param[in] ind - \ru Номер кривой для сравнения. - \en An index of curve for comparison. \~ - \return \ru true - Если в массиве есть кривые, одинаковые с кривой под номером ind. - \en True - If there are curves similar to curve with 'ind' index in array. \~ - */ - bool IsEqualLabels( ptrdiff_t ind ) const; - - - /** \brief \ru Определить, можно ли создать эквидистантную поверхность. - \en Determine whether it is possible to create an offset surface. \~ - \details \ru Определить, можно ли создать эквидистантную поверхность.\n - \en Determine whether it is possible to create an offset surface.\n \~ - \param[in] h - \ru Величина смещения. - \en The offset distance. \~ - \param[in] uLimBeg - \ru Нижняя граница по u области, к которой надо построить эквидистантную поверхность. - \en Lower bound of region by u which offset surface is necessary to construct to. \~ - \param[in] uLimEnd - \ru Верхняя граница по u области, к которой надо построить эквидистантную поверхность. - \en Upper bound of region by u which offset surface is necessary to construct to. \~ - \param[in] vLimBeg - \ru Нижняя граница по v области, к которой надо построить эквидистантную поверхность. - \en Lower bound of region by v which offset surface is necessary to construct to. \~ - \param[in] vLimEnd - \ru Верхняя граница по v области, к которой надо построить эквидистантную поверхность. - \en Upper bound of region by v which offset surface is necessary to construct to. \~ - \return \ru true - Если в можно создать эквидистантную поверхность. - \en True - If it is possible to create an offset surface. \~ - */ - bool IsPossibleCreateThin( double h, - double uLimBeg, double uLimEnd, - double vLimBeg, double vLimEnd ) const; - /** \brief \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. - \en Match arrays of attributes of similarity of curves between adjacent surfaces. \~ - \details \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. \n - \en Match arrays of attributes of similarity of curves between adjacent surfaces. \n \~ - \param[in] surf - \ru Смежная поверхность. - \en Adjacent surface. \~ - \return \ru true - Если есть изменения в массиве признаков кривых хотя бы одной поверхности. - \en True - If there are changes in array of attributes of curves of at least one surface. \~ - */ - bool AgreeLabels( MbLoftedSurface & surf ); - /** \} */ - -protected: - void CheckParam( double & u, bool ext ) const; // \ru Корректировка параметров. \en Correct parameters. \~ - /** \brief \ru Определение местных координат области поверхности. - \en Determination of local coordinates of a surface region. \~ - \details \ru Определение местных координат области поверхности. \n - \en Determination of local coordinates of a surface region. \n \~ - \param[in] v - \ru Координата v на поверхности. - \en V coordinate on the surface. \~ - \param[in,out] j1 - \ru Номер ближайшей кривой с параметром, меньшим v. - \en Index of nearest curve with parameter less than v. \~ - \param[in,out] j2 - \ru Номер ближайшей кривой с параметром, большим v. - \en Index of nearest curve with parameter greater than v. \~ - \param[in,out] y1 - \ru Параметрическое расстояние от точки с координатой v до кривой j1, при условии, что расстояние между кривыми j1 и j2 равно 1. - \en Parametric distance from point with v coordinate to j1 curve provided that distance between j1 and j2 curves is equal to 1. \~ - \param[in,out] y2 - \ru Параметрическое расстояние от точки с координатой v до кривой j2, при условии, что расстояние между кривыми j1 и j2 равно 1. - \en Parametric distance from point with v coordinate to j2 curve provided that distance between j1 and j2 curves is equal to 1. \~ - \param[in,out] t1 - \ru Значение параметра для кривой j1. - \en Value of parameter for j1 curve. \~ - \param[in,out] t2 - \ru Значение параметра для кривой j2. - \en Value of parameter for j2 curve. \~ - */ - void LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, double & y1, double & y2, double & t1, double & t2 ) const; - /** \brief \ru Определение массива векторов кривой. - \en Determination of the array of curve vectors. \~ - \details \ru Определение массива векторов кривой. \n - \en Determination of the array of curve vectors. \n \~ - \param[in] i - \ru Номер кривой. - \en Index of curve. \~ - \param[in] u - \ru Координата u на поверхности. - \en U coordinate on the surface. \~ - \param[in] der - \ru Ссылка на массив векторов для хранения вычисленной точки и производных. - \en Reference to array of vectors to store calculated point and derivatives. \~ - \param[in] ext - \ru Можно ли продолжить кривую за границы области определения ее параметра. - \en Whether it is possible to extend curve out of its parametric domain bounds. \~ - */ - void CalculateCurve( ptrdiff_t i, double u, MbVector3D & point, bool ext, size_t numb ) const; - void CalculateCurve( ptrdiff_t i, double u, MbVector3D & pnt, MbVector3D & fir, MbVector3D * sec, bool ext ) const; - /** \brief \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). - \en Determination of array of vectors of u parameter for point on surface with coordinates (u, v). \~ - \details \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). \n - \en Determination of array of vectors of u parameter for point on surface with coordinates (u, v). \n \~ - \param[in] u - \ru Координата u на поверхности. - \en U coordinate on the surface. \~ - \param[in] j1 - \ru Номер ближайшей кривой с параметром, меньшим v. - \en Index of nearest curve with parameter less than v. \~ - \param[in] j2 - \ru Номер ближайшей кривой с параметром, большим v. - \en Index of nearest curve with parameter greater than v. \~ - \param[in] t1 - \ru Значение параметра для кривой j1. - \en Value of parameter for j1 curve. \~ - \param[in] t2 - \ru Значение параметра для кривой j2. - \en Value of parameter for j2 curve. \~ - \param[in] ext - \ru Можно ли продолжить поверхность за границы области определения ее параметров. - \en Whether it is possible to extend surface out of its parametric domain bounds. \~ - */ - void CalculateSurface( double & u, ptrdiff_t j1, ptrdiff_t j2, - double t1, double t2, bool ext, size_t numb, - MbVector3D & point1, MbVector3D & point2, - MbVector3D & vector1, MbVector3D & vector2, bool correctVectors = true ) const; - void CalculateExplore( double & u, ptrdiff_t j1, ptrdiff_t j2, - double t1, double t2, bool ext, bool boolsecond, - MbVector3D * point1, MbVector3D * point2, - MbVector3D * vector1, MbVector3D * vector2, - double * tLoft ) const; - - void ParamPoint ( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamFirst ( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const; - void ParamThird ( double t1, double t2, double * tLoft ) 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. \~ - */ - bool CheckPoles( MbLoftedSurfaceAuxiliaryData * ) const; // \ru Проверка полюсов на кривых \en Check poles on curves - -private: - void Init( bool close ); - bool IsSimilarCurves( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых \en Determination of similar curves - bool IsSimilarLabels( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых по меткам. \en Determination of similar curves by labels. - void InitLabels(); // \ru Инициализация признаков одинаковых кривых. \en Initialization of attributes of similar curves. - - MbVector3D DirByGivenNormal( bool isStart, const MbVector3D & point1, const MbVector3D & point2 ) const; // \ru Определить вектор направления с заданной нормалью. \en Determine the direction vector with a given normal. - - void operator = ( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLoftedSurface ) -}; - -IMPL_PERSISTENT_OPS( MbLoftedSurface ) - -//------------------------------------------------------------------------------ -// \ru Корректировка параметров. \en Correct parameters. \~ -// --- -inline void MbLoftedSurface::CheckParam( double & u, bool ext ) const -{ - if ( !ext ) { - if ( uclosed ) { // переписана на ::floor(), т.к. подвисала на while - if ( (u < umin) || (u > umax) ) { - double pRgn = ( umax - umin ); - u -= ( ::floor((u - umin) / pRgn) * pRgn ); - } - } - else if ( u < umin ) { - u = umin; - } - else if ( u > umax ) { - u = umax; - } - } - else { - if ( u < umin && GetPoleUMin() ) { - u = umin; - } - else if ( u > umax && GetPoleUMax() ) { - u = umax; - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Определение местных координат области поверхности \en Determination of local coordinates in a surface region -// --- -inline void MbLoftedSurface::LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, - double & y1, double & y2, - double & t1, double & t2 ) const -{ - if ( v < vmin || v > vmax ) { // \ru Параметр вне границ \en Parameter is out of bounds - if ( vclosed ) { - double tmp = vmax - vmin; - v -= ::floor((v - vmin) / tmp) * tmp; - } - else { - if ( v < vmin ) - v = vmin; - else - v = vmax; - } - } - - j1 = 0; - j2 = vParams.MaxIndex(); - - ptrdiff_t ind, delta = j2; // \ru Диапазон \en A range - - // \ru Поиск половинным делением \en Search by bisection - while ( delta > 1 ) { - ind = j1 + ( delta / (ptrdiff_t)2 ); // \ru Индекс в середине \en The index in the middle - if ( v < vParams[ind] ) // \ru Если v меньше серединного параметра \en If v is less than the middle parameter - j2 = ind; // \ru Изменить правую границу \en Change the right bound - else - j1 = ind; // \ru Изменить левую границу \en Change the left bound - delta = j2 - j1; // \ru Диапазон \en A range - } - - t1 = vParams[j1]; - t2 = vParams[j2]; - double dt = t2 - t1; - double antiDt = 1.0; - if ( dt > NULL_EPSILON ) - antiDt /= dt; - y1 = (t2 - v) * antiDt; - y2 = (v - t1) * antiDt; -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметрa точки \en Determination of array of degrees of point parameter -// --- -inline void MbLoftedSurface::ParamPoint( double y1, double y2, double t1, double t2, double * tLoft ) const -{ - double y1pow2 = y1 * y1; - double y2pow2 = y2 * y2; - double y1pow3 = y1pow2 * y1; - double y2pow3 = y2pow2 * y2; - tLoft[0] = 3.0 * y1pow2 - 2.0 * y1pow3; - tLoft[1] = 3.0 * y2pow2 - 2.0 * y2pow3; - tLoft[2] = (y1pow3 - y1pow2) * (t1-t2); - tLoft[3] = (y2pow3 - y2pow2) * (t2-t1); -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметрa производной \en Determination of array of degrees of derivative parameter -// --- -inline void MbLoftedSurface::ParamFirst( double y1, double y2, double t1, double t2, double * tLoft ) const -{ - double y1pow2 = y1 * y1; - double y2pow2 = y2 * y2; - double kdt1 = 1.0 / (t1 - t2); - double kdt2 = -kdt1; - tLoft[0] = 6.0 * (y1 - y1pow2) * kdt1; - tLoft[1] = 6.0 * (y2 - y2pow2) * kdt2; - tLoft[2] = (3.0 * y1pow2 - 2.0 * y1); - tLoft[3] = (3.0 * y2pow2 - 2.0 * y2); -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметрa второй производной \en Determination of array of degrees of second derivative parameter -// --- -inline void MbLoftedSurface::ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const { - double d1 = 1 / (t1-t2); - double d2 = -d1; - tLoft[0] = (6 - 12 * y1) * d1 * d1; - tLoft[1] = (6 - 12 * y2) * d2 * d2; - tLoft[2] = (6 * y1 - 2) * d1; - tLoft[3] = (6 * y2 - 2) * d2; -} - - -//------------------------------------------------------------------------------ -// \ru Определение массива степеней параметрa третьей производной \en Determination of array of degrees of third derivative parameter -// --- -inline void MbLoftedSurface::ParamThird( double t1, double t2, double * tLoft ) const { - double d1 = 1 / (t1-t2); - double d2 = -d1; - double d1pow2 = d1 * d1; - double d2pow2 = d2 * d2; - tLoft[0] = -12 * d1pow2 * d1; - tLoft[1] = -12 * d2pow2 * d2; - tLoft[2] = 6 * d1pow2; - tLoft[3] = 6 * d2pow2; -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Наполнить массив v-параметров и весовых центров заданных кривых. - \en Fill array of v-parameters and weight centers of given curves. \~ - \details \ru Если все профильные кривые плоские, параметры вычисляются функцией CreateElevationParam. - Иначе параметр для каждой кривой вычисляется как координата вдоль направляющей проекции центра масс кривой на направляющую. - \en If all the profile curves are planar, then parameters are calculated by CreateElevationParam function. - Otherwise parameter for each curve is calculated as coordinate along guide projection of center of mass of curve to guide. \~ - \param[in] uCurves - \ru Множество профильных кривых. - \en Set of profile curves. \~ - \param[in] vcls - \ru Замкнута ли поверхность по параметру v. - \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] version - \ru Версия. - \en Version. \~ - \return \ru true - если массив параметров успешно создан. - \en True - if the array of parameters successfully created. \~ - \ingroup Algorithms_3D -*/ -// --- -bool CreateLoftedParams( const RPArray & uCurves, - bool vcls, - SArray & vParams, - SArray * tiePnts, - VERSION version ); - - -#endif // __SURF_LOFTED_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность, проходящая через заданное семейство кривых. + \en Lofted surface. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_LOFTED_SURFACE_H +#define __SURF_LOFTED_SURFACE_H + +#include +#include +#include +#include + + +class MATH_CLASS MbSurfaceContiguousData; + +const_expr size_t LOFT_NUMB = 4; ///< \ru Вспомогательный параметр для поверхности MbLoftedSurface. Используется для определения количества элементов в массивах, где хранится точка и первые три производные в этой точке. \en Auxiliary parameter for MbLoftedSurface surface. Used for determination of count of elements in arrays of points and first three derivatives at this point. +const_expr VERSION LOFTED_SURFACE_VERSION1 = 0x0F000013L; ///< \ru Корректировка коэффициентов уравнения поверхности. \en Correction of surface equation coefficients. +const_expr VERSION LOFTED_SURFACE_VERSION2 = 0x13000015L; ///< \ru Возможность устанавливать нормали на торцевых сечениях в виде точки. \en Ability to set normals on end sections as a point. +const_expr VERSION LOFTED_SURFACE_VERSION3 = 0x13000019L; ///< \ru Введены множители производной в случае установки нормали на торцевых сечениях. \en Factors of the derivative are added in the case of setting the normal on the end sections. +const_expr VERSION LOFTED_SURFACE_VERSION4 = 0x1300001BL; ///< \ru Добавлен вектор направлени движение повехности в случае установки нормали. Необходимо для тела с операцией Купол. \en The direction vector of the surface progress is added in the case of setting the normal. Necessary for the body with the operation Dome. + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность, проходящая через заданное семейство кривых. + \en Lofted surface passing through given family of curves. \~ + \details \ru Поверхность, проходящая через заданное семейство кривых, построена аналогично сплайну Эрмита MbHermit3D, + проходящего через заданное семейство точек. + Первый параметр поверхности пропорционален параметрам кривых семейства. + Вдоль второго параметра поверхность изменяется по закону сплайна Эрмита MbHermit3D, точками которого служат точки кривых семейства. + Производные по второму параметру в точках кривых вычисляются как производные параболы, + построенной по трём точкам и значениям параметров в них. + На каждом участке между двумя соседними кривыми семейства поверхность описывается кубическим полиномом + с заданными точками и производными на краях. + Если крайние кривые семейства представлены точками, то возможно установить производную на краях с ортогональным направлением + относительно нормали плоскости XoY лежащей в локальной системе координат начальной или конечной точечной кривой. Величина производной + зависит от расстояния между точечной кривой и ближайшей к ней. Для возможности изменения величины производной введены неотрицательные + множители, по умолчанию равные 1.0. + Поверхность проходит через кривые семейства при значениях параметра из множества vParams. + \en The surface passing through given family of curves is constructed similar to MbHermit3D Hermite spline + passing through given family of points. + First parameter of surface is proportional to parameters of curves of family. + Along the second parameter the surface changes under the law of MbHermit3D Hermite spline, which points are points of curves of family. + Derivatives by second parameter at points of curves are calculated as derivatives of parabola + constructed by three points and values of parameters at this points. + On each region between two neighboring curves of family the surface is described by the cubic polynomial + with given points and derivatives at the edges. + If the first or last curves of the family are represented by points, then it is possible to define the derivative at the edges + with the orthogonal direction relative to the normal of the XoY plane in the local coordinate system of the initial or final edges. + The value of the derivative depends on the distance between the point curve and the one closest to it. In order to change + the value of the derivative, non-negative factor are introduced by default equal to 1.0. + Surface passes through curves of family for parameter values from vParams set. \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbLoftedSurface : public MbSurface { +protected: + struct MbLoftedBorder { + MbVector3D derive; ///< \ru Направление производной незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative of the open surface. If it isn't set, then its length is zero. + bool setNormal; ///< \ru Установлена нормаль. Направление производной выбирается ортогонально нормали крайнего сечения. \en The normal is set. The direction of the derivative is chosen orthogonally to the normal of the ends section. + double derFactor; ///< \ru Множитель величины производной при установке нормали. По умолчанию 1.0. \en Factor of the derivative when setting the normal. The default is 1.0. + MbVector3D directSurf; ///< \ru Ось направления движения поверхности у концевого участка при установке нормали. По умолчанию соединяет центры концевого и ближайшего сечений. \en Direction axis of the surface progress near the end curve when setting the normal. By default, it connects the centers of the end curve and the nearest curve. + + MbLoftedBorder(); /// \ru Конструктор по умолчанию. \en Default constructor. + MbLoftedBorder( const MbLoftedBorder & obj ); /// \ru Конструктор копирования. \en Copy-constructor. + MbLoftedBorder & operator = ( const MbLoftedBorder & obj ); /// \ru Оператор присваивания. \en Assignment operator. + }; + + RPArray uCurves; ///< \ru Множество кривых семейства. \en Set of curves of family. + SArray vParams; ///< \ru Множество параметров v для кривых. \en Set of parameters v for curves. + SArray vLabels; ///< \ru Множество признаков одинаковых кривых. \en Set of attributes of similar curves. + double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. + double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. + double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. + double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. + bool uclosed; ///< \ru Признак замкнутости по параметру u. \en Attribute of closedness by parameter u. + bool vclosed; ///< \ru Признак замкнутости по параметру v. \en Attribute of closedness by parameter v. + MbLoftedBorder border1; ///< \ru Условия примыкания поверхности к начальной кривой семейства. \en The adjacency conditions of the surface to the starting curve of family. + MbLoftedBorder border2; ///< \ru Условия примыкания поверхности к конечной кривой семейства. \en The adjacency conditions of the surface to the ending curve of family. + VERSION surfaceVersion; ///< \ru Версия расчета коэффициентов уравнения поверхности. \en Version of coefficient calculation of surface equation. + +protected: + //------------------------------------------------------------------------------ + /** \brief \ru Вспомогательные данные. + \en Auxiliary data. \~ + \details \ru Вспомогательные данные служат для ускорения работы объекта. + \en Auxiliary data are used for fast calculations. \n \~ + */ + // --- + class MbLoftedSurfaceAuxiliaryData : public AuxiliaryData { + public: + DPtr data; ///< \ru Дополнительные данные о поверхности. \en Additional data about a surface. + MbLoftedSurfaceAuxiliaryData(); + MbLoftedSurfaceAuxiliaryData( const MbLoftedSurfaceAuxiliaryData & init ); + virtual ~MbLoftedSurfaceAuxiliaryData(); + }; + + mutable CacheManager cache; + +public: + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по массиву профильных кривых, направляющим векторам и замкнутости по v. + \en Constructor of surface by array of profile curves, guide vectors and closedness by v. \~ + \param[in] initCurves - \ru Множество задающих кривых. + \en Set of driving curves. \~ + \param[in] vc - \ru Замкнутость поверхности по v. + \en Surface closedness by v. \~ + \param[in] v1 - \ru Направляющий вектор. + \en Guide vector. \~ + \param[in] v2 - \ru Направляющий вектор. + \en Guide vector. \~ + \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. + \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ + \param[in] version - \ru Версия, по умолчанию - последняя. + \en Version, last by default. \~ + */ + MbLoftedSurface( const RPArray & initCurves, + bool vc, const MbVector3D & v1, const MbVector3D & v2, bool same, + VERSION version = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по массиву профильных кривых, массиву параметров, направляющим векторам и замкнутости по v. + \en Constructor of surface by array of profile curves, array of parameters, guide vectors and closedness by v. \~ + \param[in] initCurves - \ru Множество задающих кривых. + \en Set of driving curves. \~ + \param[in] initParams - \ru Множество параметров, соответствующих задающим кривым. + \en Set of parameters corresponding to driving curves. \~ + \param[in] vc - \ru Замкнутость поверхности по v. + \en Surface closedness by v. \~ + \param[in] v1 - \ru Направляющий вектор. + \en Guide vector. \~ + \param[in] v2 - \ru Направляющий вектор. + \en Guide vector. \~ + \param[in] setNormal1 - \ru Установить нормаль поверхности в начале ортогонально плоскости XoY локальной системы координат первой кривой семейства, если кривая точечная. + \en Set the surface normal at the beginning orthogonal to the XoY plane in the local coordinate system of the first family curve, if it is point curve. \~ + \param[in] setNormal2 - \ru Установить нормаль поверхности в конце ортогонально плоскости XoY локальной системы координат последней кривой семейства, если кривая точечная. + \en Set the surface normal at the end orthogonal to the XoY plane in the local coordinate system of the last family curve, if it is point curve. \~ + \param[in] derFactor1 - \ru Множитель длины производной в начале, если первая кривая семейства точечная. По умолчанию 1.0. + \en The derivative length factor at the beginning, if the first family curve is point curve. The default is 1.0. \~ + \param[in] derFactor2 - \ru Множитель длины производной в конце, если последняя кривая семейства точечная. По умолчанию 1.0. + \en The derivative length factor at the end, if the last family curve is point curve. The default is 1.0. \~ + \param[in] directSurf1 - \ru Ось направления движения поверхности на начальном участке при установке нормали. По умолчанию соединяет центры концевого и ближайшего сечений. + \en Direction axis of the surface progress in the initial section when setting the normal. By default, it connects the centers of the end curve and the nearest curve. \~ + \param[in] directSurf2 - \ru Ось направления движения поверхности на конечном участке при установке нормали. По умолчанию соединяет центры концевого и ближайшего сечений. + \en Direction axis of the surface progress in the final section when setting the normal. By default, it connects the centers of the end curve and the nearest curve. \~ + \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. + \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ + \param[in] version - \ru Версия, по умолчанию - последняя. + \en Version, last by default. \~ + */ + MbLoftedSurface( const RPArray & initCurves, const SArray & initParams, bool vc, + const MbVector3D & v1, const MbVector3D & v2, bool setNormal1, bool setNormal2, double derFactor1, double derFactor2, + const MbVector3D & directSurf1, const MbVector3D & directSurf2, bool same, VERSION version = Math::DefaultMathVersion() ); +protected: // \ru Конструкторы для наследников \en Constructors for inheritors + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по набору профильных кривых. + \en Constructor of surface by family of profile curves. \~ + \param[in] initCurves - \ru Множество задающих кривых. + \en Set of driving curves. \~ + \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. + \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ + \param[in] version - \ru Версия, по умолчанию - последняя. + \en Version, last by default. \~ + */ + MbLoftedSurface( const RPArray & initCurves, bool same, VERSION version = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор поверхности. + \en Constructor of surface. \~ + \details \ru Конструктор поверхности по массиву профильных кривых и массиву параметров. + \en Constructor of surface by array of profile curves and array of parameters. \~ + \param[in] initParams - \ru Множество параметров, соответствующих задающим кривым. + \en Set of parameters corresponding to driving curves. \~ + \param[in] initCurves - \ru Множество задающих кривых. + \en Set of driving curves. \~ + \param[in] same - \ru Определяет, надо ли копировать профильные кривые: true - использовать полученные кривые без копирования, false - использовать копии. + \en Determines whether to copy profile curves: true - use obtained curves without copying, false - use copies. \~ + \param[in] version - \ru Версия, по умолчанию - последняя. + \en Version, last by default. \~ + */ + MbLoftedSurface( const SArray & initParams, const RPArray & initCurves, bool same, VERSION version = Math::DefaultMathVersion() ); + /// \ru Конструктор-копия. \en Copy constructor. + MbLoftedSurface( const MbLoftedSurface &, MbRegDuplicate * reg ); +private: + MbLoftedSurface( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. +public: + virtual ~MbLoftedSurface(); + +public: + VISITING_CLASS( MbLoftedSurface ); + + /** \ru \name Общие функции геометрического объекта + \en \name Common functions of a geometric object + \{ */ + 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 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 Refresh(); + + 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 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; // \ru Вернуть минимальное значение параметра u \en Return the minimum value of parameter u + virtual double GetVMin () const; // \ru Вернуть минимальное значение параметра v \en Return the minimum value of parameter v + virtual double GetUMax () const; // \ru Вернуть максимальное значение параметра u \en Return the maximum value of parameter u + virtual double GetVMax () const; // \ru Вернуть максимальное значение параметра v \en Return the maximum value of parameter v + 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. + virtual double GetUPeriod() const; // \ru Период для замкнутой поверхности или 0. \en Period for closed surface or 0. + virtual size_t GetUCount() const; + virtual size_t GetVCount() const; + // \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 & ) const; // \ru Точка на поверхности \en Point on the surface + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по u \en Third derivative with respect to u + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по v \en Third derivative with respect to v + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv + /** \} */ + + /** \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 & ) const; // \ru Точка на расширенной поверхности \en Point on the extended surface + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u \en First derivative with respect to u + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v \en First derivative with respect to v + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u \en Second derivative with respect to u + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v \en Second derivative with respect to v + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; // \ru Третья производная по u \en Third derivative with respect to u + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; // \ru Третья производная по v \en Third derivative with respect to v + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; // \ru Третья производная по uv \en Third derivative with respect to uv + /** \} */ + /** \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 Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of step of approximation with consideration of curvature radius + virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага аппроксимации с учетом радиуса кривизны \en Calculation of step of approximation with consideration of curvature radius + virtual double DeviationStepU( double u, double v, double sag ) const; // \ru Вычисление шага по u при пересечении поверхностей \en Calculation of step by u while intersecting surfaces + virtual double DeviationStepV( double u, double v, double sag ) const; // \ru Вычисление шага по u при пересечении поверхностей \en Calculation of step by u while intersecting surfaces + /** \} */ + + /** \ru \name Общие функции поверхности + \en \name Common functions of surface + \{ */ + virtual bool IsPlanar() 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 + + // \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 + + // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей \en Construct tangent and normal placements of constructive planes + virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; + virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; + virtual bool GetCylinderAxis( MbAxis3D & axis ) const; // \ru Дать ось вращения для поверхности \en Get a rotation axis of a surface + + 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 a shifted surface + + 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 + + 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 Определение разбивки параметрической области поверхности вертикалями и горизонталями \en Determine splitting of parametric region of surface by vertical and horizontal lines + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + 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; + // \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 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 + + // \ru Проверить параметры и загнать в область определения, если параметр вышел за полюс. + // Аналог глобальной функции _CheckParams, оптимизированный под использование кэшей. + // \en Check parameters and move them inside domain if parameter is out of pole. + // \en Check parameters. Analogue of the global function _CheckParams, optimized for caches usage. + // \param[in] surface - \ru Поверхность. \en Surface. + // \param[in] u - \ru Первый параметр. \en First parameter. + // \param[in] v - \ru Второй параметр. \en Second parameter. + virtual void CheckSurfParams( double & u, double & v ) const; + + /// \ru Получить количество кривых, на которых построена поверхность \en Get count of curves which the surface is constructed by + ptrdiff_t CurvesCount() const { return (ptrdiff_t)uCurves.Count(); } + + /** \brief \ru Получить кривую по номеру. + \en Get curve by an index. \~ + \details \ru Получить кривую по номеру. \n + \en Get curve by an index. \n \~ + \param[in] ind - \ru Порядковый номер кривой в массиве кривых uCurves. + \en Index of curve in uCurves array of curves. \~ + \return \ru Константная кривая. + \en The constant curve. \~ + */ + const MbCurve3D * GetCurve( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } + /** \brief \ru Получить кривую для редактирования по номеру. + \en Get curve for editing by an index. \~ + \details \ru Получить кривую для редактирования по номеру. \n + \en Get curve for editing by an index. \n \~ + \param[in] ind - \ru Порядковый номер кривой в массиве кривых uCurves. + \en Index of curve in uCurves array of curves. \~ + \return \ru Кривая. + \en A curve. \~ + */ + MbCurve3D * SetCurve( ptrdiff_t ind ) { return (ind >= 0 && ind < (ptrdiff_t)uCurves.Count()) ? uCurves[ind] : NULL; } + /** \brief \ru Получить параметр по номеру. + \en Get parameter by an index. \~ + \details \ru Получить параметр по номеру.\n + \en Get parameter by an index.\n \~ + \param[in] ind - \ru Порядковый номер параметра в массиве параметров vParams. + \en Index of parameter in vParams array of parameters. \~ + \return \ru Значение параметра. + \en A parameter value. \~ + */ + double GetParam( ptrdiff_t ind ) const { return (ind >= 0 && ind < (ptrdiff_t)vParams.Count()) ? vParams[ind] : 0.0; } + /** \brief \ru Заполнить массив параметрами. + \en Fill an array by parameters. \~ + \details \ru Заполнить массив параметрами. \n + \en Fill an array by parameters. \n \~ + \param[in,out] params - \ru Множество для заполнения параметрами. + \en A set to fill by parameters. \~ + */ + void GetParams( SArray & params ) const { params = vParams; } + /** \brief \ru Заполнить массив признаков одинаковых кривых. + \en Fill array of attributes of similar curves. \~ + \details \ru Заполнить массив признаков одинаковых кривых. \n + \en Fill array of attributes of similar curves. \n \~ + \param[in,out] labels - \ru Множество для заполнения. + \en A set to fill. \~ + */ + void GetLabels( SArray & labels ) const { labels = vLabels; } + + /// \ru Направление производной в начале незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the beginning of the open surface. If it isn't set, then its length is zero. + const MbVector3D & GetDerive1() const { return border1.derive; } + ///< \ru Направление производной в конце незамкнутой поверхности. Если не задано, то нулевой длины. \en The direction of derivative at the end of the open surface. If it isn't set, then its length is zero. + const MbVector3D & GetDerive2() const { return border2.derive; } + + bool IsEqualLabels() const; ///< \ru Определить, есть ли одинаковые кривые. \en Determine whether there are similar curves. + /** \brief \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. + \en Determine whether there are curves similar to curve with 'ind' index. \~ + \details \ru Определить, есть ли кривые, одинаковые с кривой под номером ind. \n + \en Determine whether there are curves similar to curve with 'ind' index. \n \~ + \param[in] ind - \ru Номер кривой для сравнения. + \en An index of curve for comparison. \~ + \return \ru true - Если в массиве есть кривые, одинаковые с кривой под номером ind. + \en True - If there are curves similar to curve with 'ind' index in array. \~ + */ + bool IsEqualLabels( ptrdiff_t ind ) const; + + + /** \brief \ru Определить, можно ли создать эквидистантную поверхность. + \en Determine whether it is possible to create an offset surface. \~ + \details \ru Определить, можно ли создать эквидистантную поверхность.\n + \en Determine whether it is possible to create an offset surface.\n \~ + \param[in] h - \ru Величина смещения. + \en The offset distance. \~ + \param[in] uLimBeg - \ru Нижняя граница по u области, к которой надо построить эквидистантную поверхность. + \en Lower bound of region by u which offset surface is necessary to construct to. \~ + \param[in] uLimEnd - \ru Верхняя граница по u области, к которой надо построить эквидистантную поверхность. + \en Upper bound of region by u which offset surface is necessary to construct to. \~ + \param[in] vLimBeg - \ru Нижняя граница по v области, к которой надо построить эквидистантную поверхность. + \en Lower bound of region by v which offset surface is necessary to construct to. \~ + \param[in] vLimEnd - \ru Верхняя граница по v области, к которой надо построить эквидистантную поверхность. + \en Upper bound of region by v which offset surface is necessary to construct to. \~ + \return \ru true - Если в можно создать эквидистантную поверхность. + \en True - If it is possible to create an offset surface. \~ + */ + bool IsPossibleCreateThin( double h, + double uLimBeg, double uLimEnd, + double vLimBeg, double vLimEnd ) const; + /** \brief \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. + \en Match arrays of attributes of similarity of curves between adjacent surfaces. \~ + \details \ru Согласовать массивы признаков одинаковости кривых у смежных поверхностей. \n + \en Match arrays of attributes of similarity of curves between adjacent surfaces. \n \~ + \param[in] surf - \ru Смежная поверхность. + \en Adjacent surface. \~ + \return \ru true - Если есть изменения в массиве признаков кривых хотя бы одной поверхности. + \en True - If there are changes in array of attributes of curves of at least one surface. \~ + */ + bool AgreeLabels( MbLoftedSurface & surf ); + /** \brief \ru Установлена ли нормаль на конце. + \en Is the normal set at the end. \~ + \details \ru Установлена ли нормаль на конце. \n + \en Is the normal set at the end. \n \~ + \param[in] atStart - \ru Проверить в начале иначе в конце. + \en Check at the beginning otherwise at the end. \~ + \return \ru true - Нормаль установлена. + \en True - The Normal installed. \~ + */ + bool IsSetNormal( bool atStart ) { return atStart ? border1.setNormal : border2.setNormal; } + /** \} */ + +protected: + void CheckParam( double & u, bool ext ) const; // \ru Корректировка параметров. \en Correct parameters. \~ + /** \brief \ru Определение местных координат области поверхности. + \en Determination of local coordinates of a surface region. \~ + \details \ru Определение местных координат области поверхности. \n + \en Determination of local coordinates of a surface region. \n \~ + \param[in] v - \ru Координата v на поверхности. + \en V coordinate on the surface. \~ + \param[in,out] j1 - \ru Номер ближайшей кривой с параметром, меньшим v. + \en Index of nearest curve with parameter less than v. \~ + \param[in,out] j2 - \ru Номер ближайшей кривой с параметром, большим v. + \en Index of nearest curve with parameter greater than v. \~ + \param[in,out] y1 - \ru Параметрическое расстояние от точки с координатой v до кривой j1, при условии, что расстояние между кривыми j1 и j2 равно 1. + \en Parametric distance from point with v coordinate to j1 curve provided that distance between j1 and j2 curves is equal to 1. \~ + \param[in,out] y2 - \ru Параметрическое расстояние от точки с координатой v до кривой j2, при условии, что расстояние между кривыми j1 и j2 равно 1. + \en Parametric distance from point with v coordinate to j2 curve provided that distance between j1 and j2 curves is equal to 1. \~ + \param[in,out] t1 - \ru Значение параметра для кривой j1. + \en Value of parameter for j1 curve. \~ + \param[in,out] t2 - \ru Значение параметра для кривой j2. + \en Value of parameter for j2 curve. \~ + */ + void LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, double & y1, double & y2, double & t1, double & t2 ) const; + /** \brief \ru Определение массива векторов кривой. + \en Determination of the array of curve vectors. \~ + \details \ru Определение массива векторов кривой. \n + \en Determination of the array of curve vectors. \n \~ + \param[in] i - \ru Номер кривой. + \en Index of curve. \~ + \param[in] u - \ru Координата u на поверхности. + \en U coordinate on the surface. \~ + \param[in] der - \ru Ссылка на массив векторов для хранения вычисленной точки и производных. + \en Reference to array of vectors to store calculated point and derivatives. \~ + \param[in] ext - \ru Можно ли продолжить кривую за границы области определения ее параметра. + \en Whether it is possible to extend curve out of its parametric domain bounds. \~ + */ + void CalculateCurve( ptrdiff_t i, double u, MbVector3D & point, bool ext, size_t numb ) const; + void CalculateCurve( ptrdiff_t i, double u, MbVector3D & pnt, MbVector3D & fir, MbVector3D * sec, bool ext ) const; + /** \brief \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). + \en Determination of array of vectors of u parameter for point on surface with coordinates (u, v). \~ + \details \ru Определение массива векторов параметрa u для точки на поверхности с координатами (u, v). \n + \en Determination of array of vectors of u parameter for point on surface with coordinates (u, v). \n \~ + \param[in] u - \ru Координата u на поверхности. + \en U coordinate on the surface. \~ + \param[in] j1 - \ru Номер ближайшей кривой с параметром, меньшим v. + \en Index of nearest curve with parameter less than v. \~ + \param[in] j2 - \ru Номер ближайшей кривой с параметром, большим v. + \en Index of nearest curve with parameter greater than v. \~ + \param[in] t1 - \ru Значение параметра для кривой j1. + \en Value of parameter for j1 curve. \~ + \param[in] t2 - \ru Значение параметра для кривой j2. + \en Value of parameter for j2 curve. \~ + \param[in] ext - \ru Можно ли продолжить поверхность за границы области определения ее параметров. + \en Whether it is possible to extend surface out of its parametric domain bounds. \~ + */ + void CalculateSurface( double & u, ptrdiff_t j1, ptrdiff_t j2, + double t1, double t2, bool ext, size_t numb, + MbVector3D & point1, MbVector3D & point2, + MbVector3D & vector1, MbVector3D & vector2, bool correctVectors = true ) const; + void CalculateExplore( double & u, ptrdiff_t j1, ptrdiff_t j2, + double t1, double t2, bool ext, bool boolsecond, + MbVector3D * point1, MbVector3D * point2, + MbVector3D * vector1, MbVector3D * vector2, + double * tLoft ) const; + + void ParamPoint ( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamFirst ( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const; + void ParamThird ( double t1, double t2, double * tLoft ) 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. \~ + */ + bool CheckPoles( MbLoftedSurfaceAuxiliaryData * ) const; // \ru Проверка полюсов на кривых \en Check poles on curves + +private: + void Init( bool close ); + bool IsSimilarCurves( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых \en Determination of similar curves + bool IsSimilarLabels( ptrdiff_t i1, ptrdiff_t i2 ) const; // \ru Определение одинаковых кривых по меткам. \en Determination of similar curves by labels. + void InitLabels(); // \ru Инициализация признаков одинаковых кривых. \en Initialization of attributes of similar curves. + + void InitNormalCondition( double derFactor, const MbVector3D & directSurf, bool isStart); // \ru Инициализация структуры граничных условий в случае установки нормали. \en Initialization structure of boundary conditions in the case of the normal setup. + MbVector3D DirByGivenNormal ( bool isStart, const MbVector3D & point1, const MbVector3D & point2 ) const; // \ru Определить вектор направления с заданной нормалью. \en Determine the direction vector with a given normal. + + void operator = ( const MbLoftedSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLoftedSurface ) +}; + +IMPL_PERSISTENT_OPS( MbLoftedSurface ) + +//------------------------------------------------------------------------------ +// \ru Корректировка параметров. \en Correct parameters. \~ +// --- +inline void MbLoftedSurface::CheckParam( double & u, bool ext ) const +{ + if ( !ext ) { + if ( uclosed ) { // переписана на ::floor(), т.к. подвисала на while + if ( (u < umin) || (u > umax) ) { + double pRgn = ( umax - umin ); + u -= ( ::floor((u - umin) / pRgn) * pRgn ); + } + } + else if ( u < umin ) { + u = umin; + } + else if ( u > umax ) { + u = umax; + } + } + else { + if ( u < umin && GetPoleUMin() ) { + u = umin; + } + else if ( u > umax && GetPoleUMax() ) { + u = umax; + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Определение местных координат области поверхности \en Determination of local coordinates in a surface region +// --- +inline void MbLoftedSurface::LocalCoordinate( double & v, ptrdiff_t & j1, ptrdiff_t & j2, + double & y1, double & y2, + double & t1, double & t2 ) const +{ + if ( v < vmin || v > vmax ) { // \ru Параметр вне границ \en Parameter is out of bounds + if ( vclosed ) { + double tmp = vmax - vmin; + v -= ::floor((v - vmin) / tmp) * tmp; + } + else { + if ( v < vmin ) + v = vmin; + else + v = vmax; + } + } + + j1 = 0; + j2 = vParams.MaxIndex(); + + ptrdiff_t ind, delta = j2; // \ru Диапазон \en A range + + // \ru Поиск половинным делением \en Search by bisection + while ( delta > 1 ) { + ind = j1 + ( delta / (ptrdiff_t)2 ); // \ru Индекс в середине \en The index in the middle + if ( v < vParams[ind] ) // \ru Если v меньше серединного параметра \en If v is less than the middle parameter + j2 = ind; // \ru Изменить правую границу \en Change the right bound + else + j1 = ind; // \ru Изменить левую границу \en Change the left bound + delta = j2 - j1; // \ru Диапазон \en A range + } + + t1 = vParams[j1]; + t2 = vParams[j2]; + double dt = t2 - t1; + double antiDt = 1.0; + if ( dt > NULL_EPSILON ) + antiDt /= dt; + y1 = (t2 - v) * antiDt; + y2 = (v - t1) * antiDt; +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметрa точки \en Determination of array of degrees of point parameter +// --- +inline void MbLoftedSurface::ParamPoint( double y1, double y2, double t1, double t2, double * tLoft ) const +{ + double y1pow2 = y1 * y1; + double y2pow2 = y2 * y2; + double y1pow3 = y1pow2 * y1; + double y2pow3 = y2pow2 * y2; + tLoft[0] = 3.0 * y1pow2 - 2.0 * y1pow3; + tLoft[1] = 3.0 * y2pow2 - 2.0 * y2pow3; + tLoft[2] = (y1pow3 - y1pow2) * (t1-t2); + tLoft[3] = (y2pow3 - y2pow2) * (t2-t1); +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметрa производной \en Determination of array of degrees of derivative parameter +// --- +inline void MbLoftedSurface::ParamFirst( double y1, double y2, double t1, double t2, double * tLoft ) const +{ + double y1pow2 = y1 * y1; + double y2pow2 = y2 * y2; + double kdt1 = 1.0 / (t1 - t2); + double kdt2 = -kdt1; + tLoft[0] = 6.0 * (y1 - y1pow2) * kdt1; + tLoft[1] = 6.0 * (y2 - y2pow2) * kdt2; + tLoft[2] = (3.0 * y1pow2 - 2.0 * y1); + tLoft[3] = (3.0 * y2pow2 - 2.0 * y2); +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметрa второй производной \en Determination of array of degrees of second derivative parameter +// --- +inline void MbLoftedSurface::ParamSecond( double y1, double y2, double t1, double t2, double * tLoft ) const { + double d1 = 1 / (t1-t2); + double d2 = -d1; + tLoft[0] = (6 - 12 * y1) * d1 * d1; + tLoft[1] = (6 - 12 * y2) * d2 * d2; + tLoft[2] = (6 * y1 - 2) * d1; + tLoft[3] = (6 * y2 - 2) * d2; +} + + +//------------------------------------------------------------------------------ +// \ru Определение массива степеней параметрa третьей производной \en Determination of array of degrees of third derivative parameter +// --- +inline void MbLoftedSurface::ParamThird( double t1, double t2, double * tLoft ) const { + double d1 = 1 / (t1-t2); + double d2 = -d1; + double d1pow2 = d1 * d1; + double d2pow2 = d2 * d2; + tLoft[0] = -12 * d1pow2 * d1; + tLoft[1] = -12 * d2pow2 * d2; + tLoft[2] = 6 * d1pow2; + tLoft[3] = 6 * d2pow2; +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Наполнить массив v-параметров и весовых центров заданных кривых. + \en Fill array of v-parameters and weight centers of given curves. \~ + \details \ru Если все профильные кривые плоские, параметры вычисляются функцией CreateElevationParam. + Иначе параметр для каждой кривой вычисляется как координата вдоль направляющей проекции центра масс кривой на направляющую. + \en If all the profile curves are planar, then parameters are calculated by CreateElevationParam function. + Otherwise parameter for each curve is calculated as coordinate along guide projection of center of mass of curve to guide. \~ + \param[in] uCurves - \ru Множество профильных кривых. + \en Set of profile curves. \~ + \param[in] vcls - \ru Замкнута ли поверхность по параметру v. + \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] version - \ru Версия. + \en Version. \~ + \return \ru true - если массив параметров успешно создан. + \en True - if the array of parameters successfully created. \~ + \ingroup Algorithms_3D +*/ +// --- +bool CreateLoftedParams( const RPArray & uCurves, + bool vcls, + SArray & vParams, + SArray * tiePnts, + VERSION version ); + + +#endif // __SURF_LOFTED_SURFACE_H diff --git a/C3d/Include/surf_mesh_surface.h b/C3d/Include/surf_mesh_surface.h index ff22843..66e3075 100644 --- a/C3d/Include/surf_mesh_surface.h +++ b/C3d/Include/surf_mesh_surface.h @@ -23,6 +23,8 @@ class MATH_CLASS MbFunction; class MATH_CLASS MbSurfaceContiguousData; class MbPatchWorkingData; +typedef std::map MapCurveParam; +typedef std::map MapCrosses; //------------------------------------------------------------------------------ /** \brief \ru Версия реализации поверхности на сетке кривых. @@ -99,7 +101,7 @@ private: RPArray tvParams; ///< \ru Множество функций перехода к параметрам второго семейства. \en Set of transformations to parameters of second set. SArray uParams; ///< \ru Множество параметров u для задающих кривых. \en Set of parameters u for driving curves. SArray vParams; ///< \ru Множество параметров v для задающих кривых. \en Set of parameters v for driving curves. - + SArray tuCurve; ///< \ru Множество параметров uCurves[i] точек пересечения кривых. \en Set of parameters of uCurves[i] intersection points of curves. SArray tvCurve; ///< \ru Множество параметров vCurves[j] точек пересечения кривых. \en Set of parameters of vCurves[j] intersection points of curves. @@ -137,7 +139,12 @@ private: uint type3; ///< \ru Вид сопряжения, заданный на curvesV[nv-1]. \en Type of conjugation given on curvesV[nv-1]. MbeMeshSurfaceVersion version; ///< \ru Версия реализации определяет форму поверхности. \en Version of implementation determines a shape of surface. - + + MbCurve3D * extCurves[4]; ///< \ru Дополнительные кривые с соседних патчей. \en Additional curves from adjacent patches. + double extParams[4]; ///< \ru Параметры поверхности для дополнительных кривых с соседних патчей. \en Surface parameters for additional curves from adjacent patches. + bool extFlags [4]; ///< \ru Есть ли соседний патч через границу. \en Is there a adjacent patch across the border. + MbFunction * extFuncs [4]; ///< \ru Функция перехода к параметрам кривых соседних патчей. \en Mapping functions for curves from adjacent patches. + private: //------------------------------------------------------------------------------ /** \brief \ru Вспомогательные данные. @@ -185,7 +192,7 @@ public: MbMeshSurface( RPArray & initU, RPArray & initV, bool uClosed, bool vClosed, bool same, const SArray * types = NULL, - MbeMeshSurfaceVersion vers = msv_Ver1 ); + MbeMeshSurfaceVersion vers = msv_Ver3 ); /** \brief \ru Конструктор поверхности. \en Constructor of surface. \~ \details \ru Конструктор поверхности по двум семействам кривых. Каждая кривая семейства U должна пересекаться или @@ -219,7 +226,44 @@ public: SArray & parsU, SArray & parsV, bool uClosed, bool vClosed, bool same, const SArray * types = NULL, - MbeMeshSurfaceVersion vers = msv_Ver1 ); + MbeMeshSurfaceVersion vers = msv_Ver3 ); + +private: + friend class CompositeMeshShellCreator; + friend class CompositeMeshShellCreatorV19; + /** \brief \ru Конструктор поверхности с дополнительными задающими кривыми. + \en Surface constructor with additional defining curves. \~ + \details \ru Конструктор вызывается из генератора CompositeMeshShellCreator для создания + фрагментов составной поверхности по сети кривых с возможностью тангенциального + сопряжения их между собой. + \en The constructor is called from the CompositeMeshShellCreator generator to create + fragments of the composite surface by mesh of curves with the possibility of + tangential mating between them. \~ + \param[in] initU, initV - \ru Множество кривых в направлении параметра u и v. + \en Set of curves at direction of parameter u and v. \~ + \param[in] parsU, parsV - \ru Множество параметров u и v для задающих кривых. + \en Set of parameters u and v for driving curves. \~ + \param[in] uClosed, vclosed - \ru Замкнута ли поверхность по параметру u и v. + \en Whether the surface is closed by parameter u and v. \~ + \param[in] adjPatch - \ru Признаки сопряжения с соседними фрагментами через соответствующие границы. + \en Flags of mating with neighboring fragments through the corresponding borders. + \param[in] same - \ru Определяет, надо ли делать копии кривых:\n + true - использовать в объекте пришедшие в конструктор кривые не дублируя,\n + false - использовать копии кривых. + \en Determines whether to copy curves:\n + true - use curves given in the constructor in object without copying,\n + false - use copies of curves. \~ + \param[in] types - \ru Ссылка на массив с типами сопряжений на границах. + \en Reference to array with types of conjugations at boundaries. \~ + \param[in] vers - \ru Версия реализации поверхности. + \en Version of surface implementation. \~ + */ + MbMeshSurface( c3d::SpaceCurvesSPtrVector & initU, c3d::SpaceCurvesSPtrVector & initV, + c3d::DoubleVector & parsU, c3d::DoubleVector & parsV, + bool uClosed, bool vClosed, + const bool (&adjPatch)[4], + const MbeMatingType( &types )[4], + MbeMeshSurfaceVersion vers ); protected: /// \ru Конструктор-копия. \en Copy constructor. MbMeshSurface( const MbMeshSurface &, MbRegDuplicate * ); @@ -426,6 +470,19 @@ public: */ void GetVParams( SArray & params ) const { params = vParams; } + /** \brief \ru Проверить выставленный тип сопряжения. + \en Check mating type. \~ + \details \ru Проверить выставленный тип сопряжения. \n + \en Check mating type.\n \~ + \param[in] t - \ru Проверяемый тип сопряжения. + \en Mating type to check. \~ + \param[in] n - \ru Номер сопряжения (от 0 до 3). + \en Mating type number (0 to 3). \~ + \return \ru Возвращает true, если такой тип сопряжения установлен. + \en Returns true if this mating type is set. \~ + */ + bool IsMatingType( MbeMatingType t, size_t n ) const; + /** \brief \ru Получить версию алгоритма расчета поверхности. \en Get version of the algorithm for calculating the surface. \~ \details \ru Получить версию алгоритма расчета поверхности.\n @@ -438,11 +495,33 @@ public: private: void AddCurvesRef(); void ReleaseCurves(); - void Init(); + void Init( bool calcParams, bool callFromMultiPatchGenerator = false ); bool CheckPoles( MbMeshSurfaceAuxiliaryData * ) const; // \ru Инициализировать полюсы на границе параметрической области. \en Initialize poles on the border of parameters area. + + // \ru Аналоги публичных функций для внутреннего использования (используют присланный кэш). \en Analongs of public functions for internal use (use the sent cache). + bool GetPoleUMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleUMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleVMin( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + bool GetPoleVMax( MbMeshSurfaceAuxiliaryData * ) const; // \ru Существует ли полюс на границе параметрической области \en Whether there is pole on boundary of parametric region + void _DeriveU( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u + void _DeriveV( double u, double v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по u \en First derivative with respect to u + void DeriveV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Первая производная по v \en First derivative with respect to v + void DeriveUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по u \en Second derivative with respect to u + void DeriveVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по v \en Second derivative with respect to v + void DeriveUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Вторая производная по uv \en Second derivative with respect to uv + void DeriveUUU( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveUUV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveUVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + void DeriveVVV( double & u, double & v, MbVector3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Третья производная \en Third derivative + bool IsLineU( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по U выше первой равны нулю \en If true, then all the derivatives by U higher the first one are equal to zero + bool IsLineV( MbMeshSurfaceAuxiliaryData * ) const; // \ru Если true все производные по V выше первой равны нулю \en If true, then all the derivatives by V higher the first one are equal to zero + void _PointOn( double u, double v, MbCartPoint3D & p, MbMeshSurfaceAuxiliaryData * ) const; // \ru Точка на поверхности \en Point on the surface + 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_v2( double u, double v, double & ul, double & vl, size_t & i0, size_t & j0, size_t ord, MbMeshSurfaceAuxiliaryData * ucache ) 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; void CalculateAlongU_v2( const double & u, const size_t & j0, const size_t & j1, size_t indP, MbMeshSurfaceAuxiliaryData * ucache ) const; @@ -456,11 +535,17 @@ private: void AdditionalCalculateVertex( size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Создать массив смешанных производных. \en Create an array of mixed derivatives. void CreateTwists (); - void CreateTwists_v1(); + void CreateTwists_v1( const MapCrosses & crosses, const MapCrosses & outCrosses ); // \ru Аппроксимировать смешанную производную. \en Approximate mixed derivative. void ApproxTwistBilinear ( size_t iL, size_t iR, size_t jD, size_t jU, size_t iCent, size_t jCent, MbVector3D & resTwist ); void ApproxTwistBilinear_v1( size_t iCent, size_t jCent, MbVector3D & resTwist ); void ApproximateOneCornerTwist_v1( size_t iL, size_t iR, size_t jD, size_t jU, size_t corner, MbVector3D & resTwist ) const; + void ApproxTwistBilinear_v3( ptrdiff_t i, ptrdiff_t j, MbVector3D & resTwist, const MapCrosses & crosses, const MapCrosses & outCrosses ); + // \ru Рассчитать частную производную в вершине ячейки. \en Calculate the partial derivative at the top of the cell. + void CalculateCellDerivative_v3( MbVector3D & res, bool dirU, ptrdiff_t uind, ptrdiff_t vind, bool isOut, + const MapCrosses & crosses, const MapCrosses & outCrosses ) const; + // \ru Рассчитать координаты вершины ячейки. \en Calculate cell vertex coordinates. + void CalculateCellPoint_v3( MbCartPoint3D & res, ptrdiff_t uind, ptrdiff_t vind, const MapCrosses & crosses ) const; // \ru Вычислить вспомогательные массивы трансверсальных производных. \en Calculate auxiliary arrays of transversal derivatives. void CalculateTransDiffs ( double ul, double vl, size_t i0, size_t j0, size_t i1, size_t j1, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Вычислить выводящую производную с линии V = const и ее первые производные по U. \en Calculate leading out derivative from 'V = const'-line and its first derivatives by U. @@ -568,26 +653,28 @@ private: double & t1min, double & t1max, double & t3min, double & t3max, bool dir = true ) const; - void ExactNormal( double u, double v, const MbVector3D & uDer, const MbVector3D & vDer, MbVector3D & nor ) const; + void ExactNormal( double u, double v, const MbVector3D & uDer, const MbVector3D & vDer, MbVector3D & nor, MbMeshSurfaceAuxiliaryData * ) const; // \ru Проверить параметры и в случае выхода за пределы загнать в область определения. // \en Check parameters and if it is out of limits, then drive it to domain void CheckParams( double & u, double & v ) const; // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. // \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. - void CheckParamsEx( double & u, double & v ) const; - - // \ru Нормализовать семейство кривых по параметрической длине \en Normalize family of curves by parametric length - void CreateReparamCurves( const MbCurve3D & curveBeg, - const MbCurve3D & curveEnd, - double tBeg, - double tEnd, - bool closed, - RPArray & curves ) ; + void CheckParamsEx( double & u, double & v, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Попытаться вычислить шаг по U, исходя из шагов по соответствующим операторам Loft-ов \en Try to calculate step by U through steps of corresponding Loft operators bool SurfDeviationStepU( double & u, double & v, double ang, double & resStep, MbMeshSurfaceAuxiliaryData * ucache ) const; // \ru Попытаться вычислить шаг по V, исходя из шага по соответствующим операторам Loft-ов \en Try to calculate step by V through steps of corresponding Loft operators bool SurfDeviationStepV( double & u, double & v, double ang, double & resStepv, MbMeshSurfaceAuxiliaryData * ucache ) const; + // \ru Создать таблицу пересечений для дополнительных кривых. \en Create an intersection table for additional curves. + void CreateCurvesCrossTable( MapCrosses & crosses, MapCrosses & outCrosses ); + // \ru Создать функции перехода к параметрам кривых. \en Create functions for mapping to curve parameters. + void CreateParamFunctions( bool dirU, const MapCrosses & crosses ); + // \ru Расчет производных в точке для образующей кривой. \en Calculation of derivatives at a point for a generating curve. + 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 ); + /** \} */ DECLARE_PERSISTENT_CLASS_NEW_DEL( MbMeshSurface ) @@ -627,24 +714,24 @@ inline void MbMeshSurface::CheckParams( double & u, double & v ) const //------------------------------------------------------------------------------ // \ru Проверить параметры и в случае захода за полюс или выходе за период загнать в область определения. \en Check parameters and if it is out of pole or it is out of period, then drive it to the domain region. // --- -inline void MbMeshSurface::CheckParamsEx( double & u, double & v ) const +inline void MbMeshSurface::CheckParamsEx( double & u, double & v, MbMeshSurfaceAuxiliaryData * ucache ) const { - if ( GetPoleUMin() ) { + if ( GetPoleUMin( ucache ) ) { const double & umin_ = uParams[0]; if ( u < umin_ ) u = umin_; } - if ( GetPoleUMax() ) { + if ( GetPoleUMax( ucache ) ) { const double & umax_ = uParams[uParams.MaxIndex()]; if ( u > umax_ ) u = umax_; } - if ( GetPoleVMin() ) { + if ( GetPoleVMin( ucache ) ) { const double & vmin_ = vParams[0]; if ( v < vmin_ ) v = vmin_; } - if ( GetPoleVMax() ) { + if ( GetPoleVMax( ucache ) ) { const double & vmax_ = vParams[vParams.MaxIndex()]; if ( v > vmax_ ) v = vmax_; @@ -665,21 +752,67 @@ inline void MbMeshSurface::CheckParamsEx( double & u, double & v ) const //------------------------------------------------------------------------------ -// \ru Пересечение MbMeshSurface с MbMeshSurface. \en Intersection of MbMeshSurface with MbMeshSurface. +// \ru Получить граничные кривые MbMeshSurface. \en Get boundary curves of MbMeshSurface. // --- -inline void GetBoundCurves( const MbMeshSurface & mesh, RPArray & meshCurves ) //-V801 +template +void GetBoundCurves( const MbMeshSurface & mesh, ConstCurvesVector & meshCurves ) //-V801 { // \ru Не менять порядок выдачи кривых \en Not to change an order of output of curves + meshCurves.reserve( meshCurves.size() + 4 ); + c3d::ConstSpaceCurveSPtr meshCurve; + size_t cnt = mesh.GetUCurvesCount(); if ( cnt > 0 ) { - meshCurves.Add( mesh.GetUCurve( 0 ) ); - if ( cnt > 1 ) - meshCurves.Add( mesh.GetUCurve( --cnt ) ); + meshCurve = mesh.GetUCurve( 0 ); + meshCurves.push_back( meshCurve ); + if ( cnt > 1 ) { + meshCurve = mesh.GetUCurve( --cnt ); + meshCurves.push_back( meshCurve ); + } } cnt = mesh.GetVCurvesCount(); if ( cnt > 0 ) { - meshCurves.Add( mesh.GetVCurve( 0 ) ); - if ( cnt > 1 ) - meshCurves.Add( mesh.GetVCurve( --cnt ) ); + meshCurve = mesh.GetVCurve( 0 ); + meshCurves.push_back( meshCurve ); + if ( cnt > 1 ) { + meshCurve = mesh.GetVCurve( --cnt ); + meshCurves.push_back( meshCurve ); + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Получить граничные кривые MbMeshSurface. \en Get boundary curves of MbMeshSurface. +// --- +template +void GetBoundCurves( const MbMeshSurface & mesh, ConstCurvesVector & meshCurves, c3d::BoolVector & tangentMatingFlags ) //-V801 +{ // \ru Не менять порядок выдачи кривых \en Not to change an order of output of curves + meshCurves.reserve( meshCurves.size() + 4 ); + tangentMatingFlags.reserve( tangentMatingFlags.size() + 4 ); + c3d::ConstSpaceCurveSPtr meshCurve; + + size_t cnt = mesh.GetUCurvesCount(); + if ( cnt > 0 ) { + meshCurve = mesh.GetUCurve( 0 ); + meshCurves.push_back( meshCurve ); + tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 0 ) ); + + if ( cnt > 1 ) { + meshCurve = mesh.GetUCurve( --cnt ); + meshCurves.push_back( meshCurve ); + tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 2 ) ); + } + } + cnt = mesh.GetVCurvesCount(); + if ( cnt > 0 ) { + meshCurve = mesh.GetVCurve( 0 ); + meshCurves.push_back( meshCurve ); + tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 1 ) ); + if ( cnt > 1 ) { + meshCurve = mesh.GetVCurve( --cnt ); + meshCurves.push_back( meshCurve ); + tangentMatingFlags.push_back( mesh.IsMatingType( trt_Tangent, 3 ) ); + } } } @@ -702,4 +835,33 @@ inline void GetBoundCurves( const MbMeshSurface & mesh, RPArray bool MakeMonotoneParams( SArray & params, double period ); +/** \brief \ru Расчет параметризации поверхности. \en Calculate mesh surface parameters. + \details \ru Расчет параметров поверхности для выбранного направления. + \en Calculation of surface parameters for the selected direction.\~ + \param[in] dirU - \ru Выбранное направление поверхности. + \en Selected surface direction. \~ + \param[in] cls - \ru Замкнутость поверхности в направлении dirU. + \en Is the surface closed in the direction dirU. \~ + \param[in] curves - \ru Семейство кривых dirU. + \en Curves family dirU. \~ + \param[in] tcurves- \ru Семейство кривых !dirU. + \en Curves family !dirU. \~ + \param[in] tCurve - \ru Таблица пересечений кривых u и v. + \en The table of intersection of the curves u and v. \~ + \param[out] sParams - \ru Расчитанный набор параметров. + \en The calculated set of parameters. \~ +*/ +void SetParams_v3( bool dirU, bool cls, const RPArray & curves, const RPArray & tcurves, + const SArray & tCurve, SArray & sParams ); + + +/** \brief \ru Какую версию поверхности создавать в зависимости от версии математики. + \en Which version of the surface to create depending on the version of mathematics. \~ + \param[in] mathVers - \ru Версия математики. + \en Version of mathematics. \~ + \return \ru Версия поверхности по сети кривых. + \en Mesh surface version. \~ +*/ +MbeMeshSurfaceVersion GetMeshSurfaceVersion( const VERSION & mathVers ); + #endif // __SURF_MESH_SURFACE_H diff --git a/C3d/Include/surf_offset_surface.h b/C3d/Include/surf_offset_surface.h index b9ab675..b784f34 100644 --- a/C3d/Include/surf_offset_surface.h +++ b/C3d/Include/surf_offset_surface.h @@ -27,7 +27,7 @@ class MATH_CLASS MbSurfaceContiguousData; Параметры offsetUminVmin, offsetUmaxVmin, offsetUminVmax, offsetUmaxVmax могут быть как больше нуля, так и меньше нуля. Область определения параметров эквидистантной поверхности может отличаться от область определения параметров базовой поверхности basisSurface. Это отличие задано параметрами deltaUmin, deltaUmax, deltaVmin, deltaVmax. - Радиус-вектор эквидистантной поверхности описывается векторной функцией \n + Радиус-вектор эквидистантной поверхности описывается векторной функцией \n r(u,v) = basisSurface(u,v) + (Offset0(u,v) * basisSurface->Normal(u,v)). \n Базовой поверхностью для эквидистантной поверхности не может служить другая эквидистантная поверхность. В подобной ситуации выполняется переход к первичной базовой поверхности. @@ -35,7 +35,7 @@ class MATH_CLASS MbSurfaceContiguousData; 'offsetUminVmin, offsetUmaxVmin, offsetUminVmax, offsetUmaxVmax' parameters can be both greater than zero and less than zero. Domain of parameters of the offset surface can differs from domain of parameters of basisSurface base surface. This difference is given by the parameters deltaUmin, deltaUmax, deltaVmin, deltaVmax. - Radius-vector of offset surface is described by the vector function \n + Radius-vector of offset surface is described by the vector function \n r(u,v) = basisSurface(u,v) + (Offset0(u,v) * basisSurface->Normal(u,v)). \n Base surface for offset surface can't be other offset surface. In this situation it changes to the initial base surface. \~ @@ -363,7 +363,8 @@ public: // \ru Постоянное ли смещение точек? \en Is const the offset type? bool IsConstOffset() const { return ( (type == off_Empty) || (type == off_Const) ); } // \ru Величина смещения. \en The offset distance. - double GetDistance( size_t i = 0 ) const { + double GetDistance( size_t i ) const { + i = i % 4; if ( i == 1 ) return offsetUmaxVmin; else if ( i == 2 ) return offsetUminVmax; @@ -371,14 +372,18 @@ public: if ( i == 3 ) return offsetUmaxVmax; return offsetUminVmin; } + // \ru Средняя величина смещения. \en The average offset distance. + double GetDistance() const { return ( offsetUminVmin + offsetUmaxVmin + offsetUminVmax + offsetUmaxVmax ) / 4; } /** \brief \ru Установить величины смещения. \en Set offset distances. \~ \param[in] d - \ru Новая величина смещения \en New offset distance \~ */ - void SetDistance( double d, size_t i = 0 ); - + void SetDistance( double d, size_t i ); + // \ru Установить постоянную величину смещения. Set new constant offset distance. + void SetDistance( double d ); + /** \brief \ru Проверить корректность точки поверхности. \en Check the correctness of the point of a surface. \~ \details \ru Проверить корректность точки поверхности по кривизне подложки.\n diff --git a/C3d/Include/surf_plane.h b/C3d/Include/surf_plane.h index 7565580..e8642bb 100644 --- a/C3d/Include/surf_plane.h +++ b/C3d/Include/surf_plane.h @@ -27,7 +27,7 @@ class MATH_CLASS MbLine3D; Плоскость ведёт себя как бесконечная поверхность, хотя в своих данных имеет граничные значения параметров umin, umax и vmin, vmax. В отличие от других поверхностей Функции PointOn и Derive... плоскости не корректируют параметры при выходе их за пределы прямоугольной области определения параметров. \n - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = position.origin + (u position.axisX) + (v position.axisY). \n \en A plane is located on the XY coordinate plane of the local coordinate system 'position'. \n Parameters of plane are calculated from the coordinates origin 'position.origin'. @@ -35,7 +35,7 @@ class MATH_CLASS MbLine3D; A plane behaves like an infinite surface, although it has boundary parameter values umin, umax and vmin, vmax. In contrast to other surfaces functions PointOn and Derive.. of plane don't correct parameters when getting out of rectangular domain bounds. \n \n - Radius-vector of the surface is described by the vector function \n + Radius-vector of the surface is described by the vector function \n r(u,v) = position.origin + (u position.axisX) + (v position.axisY). \n \~ \ingroup Surfaces */ // --- @@ -326,7 +326,7 @@ public: // \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; - // \ru Пересечения с линией. \en Intersection with a line. + // \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. virtual void CurveIntersection ( const MbCurve3D &, SArray & uv, SArray & tt, diff --git a/C3d/Include/surf_polysurface.h b/C3d/Include/surf_polysurface.h index 4ba7549..01da7de 100644 --- a/C3d/Include/surf_polysurface.h +++ b/C3d/Include/surf_polysurface.h @@ -200,9 +200,9 @@ public: \{ */ /** \brief \ru Получить узловой вектор по выбранному параметру. - \en Get a knot vector by the chosen parameter. \~ + \en Get a knots vector by the chosen parameter. \~ \details \ru Получить узловой вектор по выбранному параметру.\n - \en Get a knot vector by the chosen parameter.\n \~ + \en Get a knots vector by the chosen parameter.\n \~ \param[in] isU - \ru Определяет, по какой координате запрашивается узловой вектор: true - по u, false - по v. \en Determines the requested coordinate of a knot vector: true - u, false - v. \~ \param[in,out] knots - \ru Матрица для хранения узлового вектора. diff --git a/C3d/Include/surf_revolution_surface.h b/C3d/Include/surf_revolution_surface.h index 99521bf..e43466d 100644 --- a/C3d/Include/surf_revolution_surface.h +++ b/C3d/Include/surf_revolution_surface.h @@ -26,14 +26,14 @@ class MATH_CLASS MbOffsetSurface; \en Revolution surface. \~ \details \ru Поверхность вращения является кинематической поверхностью с образующей в форме дуги окружности. Поверхность вращения получена путем движения образующей кривой curve по окружности или её дуге. - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = position.origin + M(v)(curve(u) - position.origin), \n где M(v) - матрица поворота точки вокруг оси position.axisZ. \n Первый параметр поверхности совпадает с параметром образующей кривой. Второй параметр поверхности совпадает с углом поворота образующей кривой. \en A revolution surface is a swept surface with generatrix in a circle arc form. A revolution surface is obtained by moving of the generatrix 'curve' along the circle or its arc. - Radius-vector of line surface is described by the vector function \n + Radius-vector of line surface is described by the vector function \n r(u,v) = position.origin + M(v)(curve(u) - position.origin), \n where M(v) - rotate matrix by axis position.axisZ. \n The first surface parameter coincides with the parameter of generatrix. diff --git a/C3d/Include/surf_ruled_surface.h b/C3d/Include/surf_ruled_surface.h index 90117d0..1548bda 100644 --- a/C3d/Include/surf_ruled_surface.h +++ b/C3d/Include/surf_ruled_surface.h @@ -24,13 +24,13 @@ class MATH_CLASS MbExtrusionSurface; /** \brief \ru Линейчатая поверхность. \en Ruled surface. \~ \details \ru Линейчатая поверхность построена по двум кривым путём соединения их соответствующих точек отрезками прямой. - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = (1 - v) curve(u) + v sline(w(u)). \n Первый параметр поверхности совпадает с параметром кривой curve. Параметр w кривой sline пропорционален первому параметру поверхности. Вдоль второго параметра поверхность прямолинейна. \en A ruled surface is constructed on two curves by connection of its corresponding points by linear segments. - Radius-vector of surface is described by the vector function \n + Radius-vector of surface is described by the vector function \n r(u,v) = (1 - v) curve(u) + v sline(w(u)). \n First parameter of surface coincides with parameter of 'curve' curve. Parameter w of 'sline' curve is proportional to first parameter of surface. diff --git a/C3d/Include/surf_section_surface.h b/C3d/Include/surf_section_surface.h new file mode 100644 index 0000000..2aa4992 --- /dev/null +++ b/C3d/Include/surf_section_surface.h @@ -0,0 +1,473 @@ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность заметания переменного сечения. + \en The swept mutable section surface. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_SECTION_SURFACE_H +#define __SURF_SECTION_SURFACE_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define _RO_MIN_ 0.05 // \ru Минимальный параметр переменного сечения. \en The minimum parameter of the swept 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. + + +class MATH_CLASS MbSurfaceWorkingData; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность заметания переменного сечения. + \en The swept mutable section surface. \~ + \details \ru Поверхность переменного (конического) сечения образуется путем движения плоской кривой, являющейся коническим сечением, вдоль опорной кривой. + В процессе движения форма плоской кривой меняется в соответствии с дискриминантом конического сечения. + Начало плоской кривой располагается на начальной направляющей кривой, а конец - на конечной направляющей кривой. + Плоскость переменного сечения сохраняет ортогональность опорной кривой в процессе движения. + Первый параметр поверхности совпадает с параметром опорной кривой. + Второй параметр поверхности совпадает с параметром плоской кривой. + \en The swept (conic) 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. + First parameter of surface coincides with the parameter of reference curve. + Second parameter of surface coincides with the parameter of conic section curve. \~ + \ingroup Surfaces +*/ +// --- +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). + 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). + MbeSectionShape form; ///< \ru Форма сечения поверхности при фиксированном втором параметре. \en The surface cross-section shape with the second parameter fixed. + double umin; ///< \ru Минимальное значение первого параметра u. \en Minimal value of parameter u. + double umax; ///< \ru Максимальное значение первого параметра u. \en Maximal value of parameter u. + double vmin; ///< \ru Минимальное значение второго параметра v. \en Minimal value of parameter v. + double vmax; ///< \ru Максимальное значение второго параметра v. \en Maximal value of parameter v. + bool uclosed; ///< \ru Признак замкнутости поверхности по параметру u. \en An attribute of closedness in u-parameter direction. + bool vclosed; ///< \ru Признак замкнутости поверхности по параметру v. \en An attribute of closedness in v-parameter direction. + bool poleVMin; ///< \ru Наличие полюса поверхности при vmin. \en Existence of a pole at vmin. + bool poleVMax; ///< \ru Наличие полюса поверхности при vmax. \en Existence of a pole at vmax. + + //------------------------------------------------------------------------------ + /// \ru Вспомогательные данные служат для ускорения работы объекта. \en Auxiliary data are used for fast calculations. \n \~ + // --- + class MbSectionSurfaceAuxiliaryData : public AuxiliaryData { + public: + DPtr wData; ///< \ru Рабочие данные для расчета поверхности. \en Working data for the calculation of a surface. + MbPlacement3D wPlace; ///< \ru Плоскость XY локальной системы, перпендикулярная опорной кривой в текущей точке. \en The XY plane of local coordinate system perpendicular to the reference curve at its current points. + MbCartPoint wPnt0; ///< \ru Точка на плоскости от её пересечения с первой направляющей кривой. \en The point on plane of its intersection with first guide curve on surface. + MbCartPoint wPnt1; ///< \ru Точка на плоскости от её пересечения с первой направляющей кривой. \en The point on plane of its intersection with first guide curve on surface. + MbCartPoint wPnt2; ///< \ru Точка на плоскости от её пересечения со второй направляющей кривой. \en The point on plane of its intersection with second guide curve on surface. + MbVector wVec1; ///< \ru Вектор на плоскости от её пересечения с поверхностью первой направляющей. \en The vector on plane of its intersection with surface of first guide curve. + MbVector wVec2; ///< \ru Вектор на плоскости от её пересечения с поверхностью второй направляющей. \en The vector on plane of its intersection with surface of second guide curve. + double wPar0; ///< \ru Параметр первой направляющей кривой её пересечения с плоскости. \en The parameter of the first guide curve. + double wPar1; ///< \ru Параметр первой направляющей кривой её пересечения с плоскости. \en The parameter of the first guide curve. + double wPar2; ///< \ru Параметр второй направляющей кривой её пересечения с плоскости. \en The parameter of the second guide curve. + double wPar; ///< \ru Параметр v, для которого вычислена плоскость wPlace. \en The parameter v for which was calculated the plane wPlace. + MbVector3D wOrig1; ///< \ru Первая производная по v начала координат плоскости. \en The first derivative of the v origin of the wPlace. + MbVector3D wOrig2; ///< \ru Вторая производная по v начала координат плоскости. \en The second derivative of the v origin of the wPlace. + MbVector3D wDerv1; ///< \ru Первая производная по v оси axisX плоскости. \en The first derivative of the v axisX of wPlace. + MbVector3D wDerv2; ///< \ru Первая производная по v оси axisY плоскости. \en The first derivative of the v axisY of wPlace. + MbVector3D wSecn1; ///< \ru Вторая производная по v оси axisX плоскости. \en The second derivative of the v axisX of wPlace. + MbVector3D wSecn2; ///< \ru Вторая производная по v оси axisY плоскости. \en The second derivative of the v axisY of wPlace. + std::vector wSplns; ///< \ru Рабочее множество В-сплайнов. \en The work set of B-splines. + std::vector wxy; ///< \ru Рабочее множество точек. \en The work set of the points. + std::vector wxyV; ///< \ru Рабочее множество первых производных по V. \en The work set of the firsf derivatives. + std::vector wxyVV; ///< \ru Рабочее множество вторых производных по V. \en The work set of the second derivatives. + std::vector wxyVVV; ///< \ru Рабочее множество третьих производных по V. \en The work set of the third derivatives. + double wVal; ///< \ru Параметр v, для которого вычислены производные начала и орт плоскости wPlace. \en The parameter v for which was calculated the plane origin derivative and axises derivatives. + + MbSectionSurfaceAuxiliaryData(); + MbSectionSurfaceAuxiliaryData( const MbSectionSurfaceAuxiliaryData & ); + virtual ~MbSectionSurfaceAuxiliaryData(); + + void Init(); // \ru Инициализация данных. \en Init data. + void Init( const MbSectionSurfaceAuxiliaryData & ); + void Move( const MbVector3D & ); // \ru Сдвиг. \en Move. + }; + + mutable CacheManager cache; + +protected: + /** \brief \ru Конструктор поверхности переменного сечения. + \en Swept mutable section surface constructor. \~ + \details \ru Конструктор поверхности переменного сечения по опорной кривой и двум направляющим. + \en Swept section surface constructor by reference curve and guide curves. \~ + \param[in] sp - \ru Опорная кривая. + \en The reference curve (spine). \~ + \param[in] c1 - \ru Первая направляющая кривая. + \en The first guide curve. \~ + \param[in] c2 - \ru Вторая направляющая кривая. + \en The second guide curve. \~ + \param[in] cs - \ru Дополнительные направляющие кривые (могут отсутствовать). + \en The additional guide curves (may be empty). \~ + \param[in] f - \ru Форма сечения поверхности. + \en The form of the surface section. \~ + \param[in] uBeg - \ru Минимальное значение первого параметра поверхности. + \en The minimum value of the first surface parameter. \~ + \param[in] uEnd - \ru Максимальное значение первого параметра поверхности. + \en The maximum value of the first surface parameter. \~ + \param[in] func - \ru Функция управления сечением поверхности. + \en Section control function. \~ + \param[in] patt - \ru Образующая кривая при form==cs_Shape. + \en Forming curve for form==cs_Shape. \~ + \param[in] sh - \ru Описание сечения при form==cs_Shape (пуст в других случаях). + \en Description of shape cross-section for form==cs_Shape. \~ + */ + MbSectionSurface( MbSpine & sp, MbCurve3D & c1, MbCurve3D & c2, + std::vector cs, MbeSectionShape f, + double uBeg, double uEnd, MbFunction * func, + MbPolyCurve * patt, std::vector & sh ); + + /** \brief \ru Конструктор поверхности переменного сечения. + \en Swept mutable section surface constructor. \~ + \details \ru Конструктор поверхности переменного сечения по осевой кривой и закону изменения радиуса вращения. + \en Swept mutable section surface constructor with axis curve and radius law. \~ + \param[in] sp - \ru Опорная кривая. + \en The reference curve (spine). \~ + \param[in] c0 - \ru Осевая кривая. + \en The axis curve. \~ + \param[in] f - \ru Форма сечения поверхности (cs_Round). + \en The form of the surface section (cs_Round). \~ + \param[in] uBeg - \ru Минимальное значение первого параметра поверхности (uBeg & ); // \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; // \ru Вернуть минимальное значение параметра u. \en Get the minimum value of u. + virtual double GetVMin() const; // \ru Вернуть минимальное значение параметра v. \en Get the minimum value of v. + virtual double GetUMax() const; // \ru Вернуть максимальное значение параметра u. \en Get the maximum value of u. + virtual double GetVMax() const; // \ru Вернуть максимальное значение параметра v. \en Get the maximum value of v. + virtual bool IsUClosed() const; // \ru Проверка замкнутости по параметру u. \en Check of surface closedness in u direction. + virtual bool IsVClosed() const; // \ru Проверка замкнутости по параметру v. \en Check of surface closedness in v direction. + + /** \} */ + /** \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 & ) const; // \ru Точка на поверхности. \en The point on the surface. + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; + /** \} */ + /** \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 & ) const; // \ru Точка на расширенной поверхности. \en The point on the extended surface. + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; + + // \ru Функции доступа к группе данных для работы внутри и вне области определения параметров поверхности. + // \en 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 the parameter step in u direction by the sag. + virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. + virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. + virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. + virtual double MetricStepU ( double u, double v, double length ) const; // \ru Вычисление шага по u по заданной длине. \en Calculation of the parameter step in u direction by the given length. + virtual double MetricStepV ( double u, double v, double length ) const; // \ru Вычисление шага по v по заданной длине. \en Calculation of the parameter step in v direction by the given length. + virtual size_t GetUCount() const; + virtual size_t GetVCount() const; + virtual bool GetPoleVMin() const; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. + virtual bool GetPoleVMax() const; // \ru Существует ли полюс на границе параметрической области. \en Whether a pole exists on parametric region boundary. + virtual bool IsPole( double u, double v ) const; // \ru Является ли точка полюсом. \en Whether the point is a pole. + + /** \} */ + /** \ru \name Общие функции поверхности + \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 void ChangeCarrier( const MbSpaceItem & item, MbSpaceItem & init ); // \ru Изменение носителя. \en Changing of carrier. + + virtual void CalculateGabarit( MbCube & ) const; // \ru Выдать габарит. \en Get the bounding box. + virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; // \ru Рассчитать габарит относительно л.с.к. \en Calculate bounding box relative to the local coordinate system. + + virtual MbSplineSurface * NurbsSurface( double, double, double, double, bool bmatch = false ) const; // \ru NURBS копия поверхности. \en NURBS copy of a surface. + virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; // \ru NURBS копия поверхности. \en NURBS copy of a surface. + virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности. \en Create an offset surface. + + // \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 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. + + // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. + virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; + virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; + // \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 Determine whether the surface is convex. + virtual ThreeStates Salient() const; + + // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine splitting of parametric region of surface by vertical and horizontal lines. + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; + //virtual bool IsSpinePeriodic() const; // \ru Периодичность направляющей. \en Periodicity of a reference curve. + + 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 \name Функции поверхности заметания переменного сечения. + \en \name Functions of the swept mutable section surface. + \{ */ + + /// \ru Направляющая. \en Guide curve. + const MbSpine & GetSpine() const { return *spine; } + /// \ru Направляющая кривая. \en The spine (reference) curve. + const MbCurve3D & GetSpineCurve() const { return spine->GetCurve(); } + /// \ru Первая направляющая кривая на первой поверхности (может быть NULL). \en The first guide curve on the first surface (may be NULL). + const MbCurve3D * GetGuide1() const { return guide1; } + /// \ru Вторая направляющая кривая на второй поверхности (может быть NULL). \en The second guide curve on the second surface (may be 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). + const MbFunction * GetFunction() const { return function; } + /// \ru Образующая кривая при form==cs_Shape (для других форм NULL). \en Forming curve for form==cs_Shape (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; + + /** \} */ + +protected : + void Init(); // \ru Инициализация данных. \en Data init. + void CacheInit(); // \ru Инициализация вспомогательных данных. \en Auxiliary data init. + // \ru Проверить и изменить при необходимости параметры поверхности. \en Check and correct parameters of the surface. + void CheckParams( double & u, double & v, bool ext ) const; + // \ru Вычисление пересечений направляющих с плоскостью сечения поверхности. \ en Calculating the intersections of guides with the surface cross -section plane. + bool SectionData( const MbCurve3D * curve0, const double & v, MbPlacement3D & place, + MbCartPoint & xy0, double & t0, + MbCartPoint & xy1, MbVector & vec1, double & t1, + MbCartPoint & xy2, MbVector & vec2, double & t2 ) const; + // \ru Расчет двумерных точек и их производных на плоском сечении поверхности. \en Calculation of two-dimension points and their derivatives on the surface plane section. + void Round( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Linea( const double & u, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Conic( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Cubic( const double & u, const double & v, std::vector & bSplines, + const std::vector & xy, const std::vector & xyV, + const std::vector & xyVV, const std::vector & xyVVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + void Shape( const double & u, const double & v, + const MbCartPoint & xy1, const MbVector & xy1V, const MbVector & xy1VV, const MbVector & xy1VVV, + const MbCartPoint & xy2, const MbVector & xy2V, const MbVector & xy2VV, const MbVector & xy2VVV, + const MbCartPoint & xy0, const MbVector & xy0V, const MbVector & xy0VV, const MbVector & xy0VVV, + MbCartPoint & p, MbVector & pU, MbVector & pV, MbVector * pUU, MbVector * pUV, MbVector * pVV, + MbVector * pUUU, MbVector * pUUV, MbVector * pUVV, MbVector * pVVV ) const; + ptrdiff_t B_Splanes( double & u, std::vector & bSplanes ) const; // \ru Вычисление B-сплайнов.\en B_splines calculation. + // \ru Вычисление радиуса-вектора точки его производных поверхности. \en The surface radius-vector and it derivatives calculation. + void Section ( const double & u, const double & v, MbCartPoint3D & pnt, + MbVector3D * uDer, MbVector3D * vDer, + MbVector3D * uuDer, MbVector3D * uvDer, MbVector3D * vvDer, + MbVector3D * uuuDer, MbVector3D * uuvDer, MbVector3D * uvvDer, MbVector3D * vvvDer ) const; + void PointOn ( double & v, double & u, bool ext, MbCartPoint3D & p ) const; // \ru Вычисления точки поверхности. \en Calculate surface point. + void DeriveU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по u. \en The first derivative with respect to u. + void DeriveV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Первая производная по v. \en The first derivative with respect to v. + void DeriveUU ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по u. \en The second derivative with respect to u. + void DeriveUV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по uv. \en The second derivative with respect to uv. + void DeriveVV ( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Вторая производная по v. \en The second derivative with respect to v. + void DeriveUUU( double & u, double & v, bool ext, MbVector3D & ) const; // \ru Третья производная по uuu. \en The third derivative with respect to uuu. + 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; + +private: + void operator = ( const MbSectionSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSectionSurface ) +}; + + +IMPL_PERSISTENT_OPS( MbSectionSurface ) + + +#endif // __SURF_SECTION_SURFACE_H diff --git a/C3d/Include/surf_sector_surface.h b/C3d/Include/surf_sector_surface.h index 27a4291..a560b7a 100644 --- a/C3d/Include/surf_sector_surface.h +++ b/C3d/Include/surf_sector_surface.h @@ -22,13 +22,13 @@ \en Sectorial surface. \~ \details \ru Секториальная поверхность построена по кривой и точке. Секториальная поверхность является частным случаем линейчатой поверхности с вырожденной в точку второй кривой. - Радиус-вектор поверхности описывается векторной функцией \n + Радиус-вектор поверхности описывается векторной функцией \n r(u,v) = (1 - v) curve(u) + v origin. \n Первый параметр поверхности совпадает с параметром кривой curve. Вдоль второго параметра поверхность прямолинейна. \en Sectorial surface is created by curve and point. Sectorial surface is special case of ruled surface with a second curve degenerated to a point. - Radius-vector of line surface is described by the vector function \n + Radius-vector of line surface is described by the vector function \n r(u,v) = (1 - v) curve(u) + v origin. \n The first surface parameter coincides with the parameter of curve 'curve'. A surface is rectilinear along the second parameter. \~ diff --git a/C3d/Include/surf_smooth_surface.h b/C3d/Include/surf_smooth_surface.h index 301b469..ea81c37 100644 --- a/C3d/Include/surf_smooth_surface.h +++ b/C3d/Include/surf_smooth_surface.h @@ -1,410 +1,410 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Поверхность сопряжения. - \en Smooth surface. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_SMOOTH_SURFACE_H -#define __SURF_SMOOTH_SURFACE_H - - -#include - - -#define _EVEN_ false // \ru Неравномерная параметризация по дуге при u = const \en Uneven parameterization along an arc where u = const - - -class MATH_CLASS MbSurfaceCurve; -class MATH_CLASS MbSurfaceIntersectionCurve; - - -//------------------------------------------------------------------------------ -/** \brief \ru Поверхность сопряжения. - \en Smooth surface. \~ - \details \ru Поверхность сопряжения соединяет две кривые curve1 и curve2 на сопрягаемых поверхностях. - Поверхность сопряжения является родительским классом поверхности скругления MbFilletSurface и поверхности фаски MbCamferSurface. - В отличие от других поверхностей Функции PointOn и Derive... поверхностей сопряжения не корректируют - первый параметр (u) при его выходе за пределы определения параметров (umin umax). - \en A smooth surface connects two curves ('curve1' and 'curve2') on interfacing surfaces. - Smooth surface is the parent class of fillet surface (MbFilletSurface) and chamfer surface (MbChamferSurface). - In contrast to other surfaces functions PointOn and Derive.. of smooth surface don't correct - the first parameter (u) when getting out of domain bounds (umin and umax). \~ - \ingroup Surfaces -*/ -// --- -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). - 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. - double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. - double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. - double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. - double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. - bool uclosed; ///< \ru Признак замкнутости по параметру u. \en An attribute of closedness in u-parameter direction. - bool poleMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin. - bool poleMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax. - -protected: - - /** \brief \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and conjugation type. \~ - \details \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and conjugation type. \~ - \param[in] crv1 - \ru Опорная кривая на первой поверхности - \en Support curve on the first surface. \~ - \param[in] crv2 - \ru Опорная кривая на второй поверхности - \en Support curve on the second surface. \~ - \param[in] fm - \ru Тип сопряжения (0 - скругление, 1 - фаска) - \en Conjugation type (0 - fillet, 1 - chamfer) \~ - */ - MbSmoothSurface( MbSurfaceCurve & crv1, MbSurfaceCurve & crv2, MbeSmoothForm fm, double d1, double d2 ); - - /** \brief \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and conjugation type. \~ - \details \ru Конструктор по двум кривым и типу сопряжения. - \en Constructor by two curves and conjugation type. \~ - \param[in] surf1 - \ru Первая поверхность - \en First surface. \~ - \param[in] curv1 - \ru Кривая в области определения первой поверхности - \en A curve in domain of the first surface \~ - \param[in] surf2 - \ru Вторая поверхность - \en Second surface. \~ - \param[in] curv2 - \ru Кривая в области определения второй поверхности - \en A curve in domain of the second surface \~ - \param[in] fm - \ru Тип сопряжения (0 - скругление, 1 - фаска) - \en Conjugation type (0 - fillet, 1 - chamfer) \~ - */ - MbSmoothSurface( MbSurface &surf1, MbCurve &curv1, MbSurface &surf2, MbCurve &curv2, MbeSmoothForm fm, double d1, double d2 ); - /// \ru Конструктор копирования. \en Copy-constructor. - MbSmoothSurface( const MbSmoothSurface &, MbRegDuplicate * ); - /// \ru Конструктор копирования с теми же опорными поверхностями. \en Copy constructor with the same support surfaces. - MbSmoothSurface( const MbSmoothSurface * ); // \ru Для CurvesDuplicate() \en For CurvesDuplicate() -private: - MbSmoothSurface( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. -public: - virtual ~MbSmoothSurface(); - -public: - VISITING_CLASS( MbSmoothSurface ); - - /** \ru \name Функции инициализации - \en \name Initialization functions - \{ */ - - /** \brief \ru Коррекция средней линии поверхности скругления. - \en Correction of the middle line of fillet surface. \~ - \details \ru Коррекция средней линии поверхности скругления. - \en Correction of the middle line of fillet surface. \~ - \param[in] tmin - \ru Новый минимальный параметр средней линии - \en New minimal parameter of the middle line. \~ - \param[in] tmax - \ru Новый максимальный параметр средней линии - \en New maximal parameter of the middle line. \~ - \param[in] insertPoints - \ru Увеличить число контрольных точек средней кривоф. - \en Insert control points for middle cerve0. \~ - */ - virtual void Init0( double tmin, double tmax, bool insertPoints = true ) = 0; - - /** \} */ - /** \ru \name Общие функции геометрического объекта - \en \name Common functions of a geometric object - \{ */ - 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 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 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. - /** \} */ - /** \ru \name Функции описания области определения поверхности - \en \name Functions for surface domain description - \{ */ - virtual double GetUMin() const; // \ru Вернуть минимальное значение параметра u. \en Get the minimum value of u. - virtual double GetUMax() const; // \ru Вернуть максимальное значение параметра u. \en Get the maximum value of u. - virtual double GetVMin() const; // \ru Вернуть минимальное значение параметра v. \en Get the minimum value of v. - virtual double GetVMax() const; // \ru Вернуть максимальное значение параметра v. \en Get the maximum value of v. - virtual bool IsUClosed() const; // \ru Проверка замкнутости по параметру u. \en Check of surface closedness in u direction. - virtual bool IsVClosed() const; // \ru Проверка замкнутости по параметру v. \en Check of surface closedness in v direction. - virtual double GetUPeriod() const; // \ru Вернуть период. \en Return period. - - // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. - 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 singular. - /** \} */ - /** \ru \name Функции для работы в области определения поверхности - Функции PointOn и Derive... поверхностей сопряжения не корректируют - первый параметр при его выходе за пределы определения параметров. - \en \name Functions for working at surface domain - Functions PointOn and Derive... of smooth surfaces don't correct - the first parameter when getting out of domain bounds. - \{ */ - virtual void PointOn ( double &u, double &v, MbCartPoint3D & ) const = 0; // \ru Точка на поверхности. \en A point on surface. - virtual void DeriveU ( double &u, double &v, MbVector3D & ) const = 0; // \ru Первая производная по u. \en First derivative with respect to u. - virtual void DeriveV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Первая производная по v. \en First derivative with respect to v. - virtual void DeriveUU ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по u. \en Second derivative with respect to u. - virtual void DeriveVV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по v. \en Second derivative with respect to v. - virtual void DeriveUV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. - virtual void DeriveUUU( double &u, double &v, MbVector3D & ) const = 0; - virtual void DeriveUUV( double &u, double &v, MbVector3D & ) const = 0; - virtual void DeriveUVV( double &u, double &v, MbVector3D & ) const = 0; - virtual void DeriveVVV( double &u, double &v, MbVector3D & ) const = 0; - /** \} */ - /** \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 = 0; - /** \} */ - /** \ru \name Функции движения по поверхности - \en \name Functions of moving over the surface - \{ */ - virtual size_t GetUCount() const; - virtual size_t GetVCount() const; - /** \} */ - /** \ru \name Общие функции поверхности - \en \name Common functions of surface. - \{ */ - // \ru Определениe точки пересечения поверхности и кривой. \en Determination of a point of intersection between a surface and a curve. - virtual MbeNewtonResult CurveIntersectNewton( const MbCurve3D &, double funcEpsilon, size_t iterLimit, - double &u0, double &v0, double &t1, bool ext0, bool ext1 ) const; - // \ru Дать максимальное приращение параметра. \en Get the maximum increment of parameter. - virtual double GetParamDelta() const; - // \ru Дать мимнимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. - virtual double GetParamPrice() const; - // \ru Построить NURBS-копию поверхности. \en Construct a NURBS copy of a surface. - virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; - - /** \} */ - /** \ru \name Функции поверхности сопряжения - \en \name Functions of smooth surface - \{ */ - /// \ru Копия с теми же опорными поверхностям. \en A copy with the same support surfaces. - virtual MbSmoothSurface & CurvesDuplicate() const = 0; - /// \ru Сделать полное копирование поверхности. \en Perform a full copying of a surface. - MbSurface & TotalDuplicate() const; - /// \ru Дать радиус. \en Get radius. - virtual double GetSmoothRadius() const = 0; - /// \ru Дать радиусы со знаком. \en Get radii with a sign. - virtual void GetDistances( double u, double &d1, double &d2 ) const = 0; - /// \ru Дать радиус со знаком. \en Get radius with a sign. - virtual double GetDistance( bool s ) const = 0; - - /** \brief \ru Объединить поверхности путём включения поверхности init в данную поверхность. - \en Combine surfaces by inclusion of the surface 'init' into the given surface. \~ - \details \ru Объединить поверхности путём включения поверхности init в данную поверхность. - \en Combine surfaces by inclusion of the surface 'init' into the given surface. \~ - \param[in] edge - \ru Кривая разделяющего ребра - \en A curve of the splitting edge. \~ - \param[in] init - \ru Поверхность, которую нужно добавить в данную - \en A surface which should be added into the given one \~ - \param[in] add - \ru Добавить в конец (true), добавить в начало (false) - \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) \~ - */ - virtual bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, - const MbSurface & init, bool add, MbMatrix & matr, - const MbSurfaceIntersectionCurve * seam ); - - /// \ru Дать коэффициент для радиуса. \en Get coefficient for radius. - virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; - - /// \ru Опорная кривая на первой поверхности. \en Support curve on the first surface. - const MbSurfaceCurve & GetCurve1() const { return *curve1; } - /// \ru Опорная кривая на второй поверхности. \en Support curve on the second surface. - const MbSurfaceCurve & GetCurve2() const { return *curve2; } - /// \ru Дать опорную кривую на первой поверхности для изменения. \en Get the support curve on the first surface for changing. - MbSurfaceCurve & SetCurve1() const { return *curve1; } - /// \ru Дать опорную кривую на второй поверхности для изменения. \en Get the support curve on the second surface for changing. - MbSurfaceCurve & SetCurve2() const { return *curve2; } - - /** \brief \ru Построить граничную кривую вдоль поверхности (V = const). - \en Construct boundary curve along a surface (V = const). \~ - \details \ru Построить граничную кривую вдоль поверхности (V = const). - \en Construct boundary curve along a surface (V = const). \~ - \param[in] s - \ru Если true, то вдоль минимального значения V,\n - если false, то вдоль максимального значения V - \en If it equals true then construct along the minimal value of V,\n - otherwise construct along the maximal value of V \~ - */ - MbCurve * CreateBound( bool s ) const; - - /** \brief \ru Вид опорных кривых. - \en Type of support curves. \~ - \details \ru Вид опорных кривых. - \en Type of support curves. \~ - \return \ru cbt_Specific если кривые построены по отдельным точкам\n - cbt_Ordinary если кривые аналитические - \en Cbt_Specific if the curves have been constructed by the separate points\n - cbt_Ordinary if the curves are analytical \~ - */ - MbeCurveBuildType GetBuildType() const; - - /** \brief \ru Форма поверхности. - \en Form of a surface. \~ - \details \ru Форма поверхности. - \en Form of a surface. \~ - \return \ru 0 в случае поверхности скругления\n - 1 в случае поверхности фаски - \en 0 in a case of fillet\n - 1 in a case of chamfer \~ - */ - MbeSmoothForm Form() const { return form; } - - /** \brief \ru Добавить точку в опорные кривые границы. - \en Add a point to the support curves of the boundary. \~ - \details \ru Добавить точку в опорные кривые границы.\n - Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. - \en Add a point to the support curves of the boundary.\n - A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ - \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) - \en Parameter of a point on the first curve (if add1 equals true) \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую - \en Whether to add a point to the first curve \~ - \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) - \en Parameter of a point on the second curve (if add2 equals true) \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую - \en Whether to add a point to the second curve \~ - */ - virtual bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, - double & t2, const MbCartPoint & p2, bool add2 ); - - /** \brief \ru Продлить поверхность. - \en Prolong surface. \~ - \details \ru Построить и добавить точки в опорные кривые до или после границы, удлиннив поверхность.\n - Точки будут построены и добавлены в кривые, если они имеют тип pt_Hermit. - \en Build and add points to the support curves of the boundary.\n - A points will be builded and added into curves if they have a type pt_Hermit. \~ - \param[in] t - \ru Первый параметр поверхности - \en First parameter of surface \~ - \param[in] p1 - \ru Точка на первой кривой - \en Point on the first curve \~ - \param[in] p2 - \ru Точка на второй кривой - \en Point on the second curve \~ - \param[in] anyCase - \ru Штатная работа со значением false (true исключение). - \en Regular work with the value false (true exception). \~ - */ - bool ProlongSurface( double u, const MbCartPoint & p1, const MbCartPoint & p2, bool anyCase ); - - /** \brief \ru Скорректировать кривые. - \en Correct curves. \~ - \details \ru Скорректировать опорные кривые после вставки точек.\n - Кривая будет скорректирована, если поверхность имеет полюс на краю, опорная кривая имеет тип pt_Hermit и содержит опорную точку с заданным параметром. - Корректируется опорная точка кривой, ближайшая к точке с заданным параметром со стороны полюса поверхности. - \en Correct the support curves after inserting of the points.\n - A curve will be corrected if the surface has a pole on the boundary, a support curve has the type pt_Hermit and contains the support point with the given parameter. - The curve support point which is the nearest to the point with the given parameter from the side of the surface pole is corrected. \~ - \param[in] t1 - \ru Параметр точки на первой опорной кривой. - \en Parameter of a point on the first support curve. \~ - \param[in] t2 - \ru Параметр точки на второй опорной кривой. - \en Parameter of a point on the second support curve. \~ - */ - bool CurveStraighten( double t1, double t2 ); - /// \ru Дать свойства объекта. \en Get the object properties. - void AddProperties( MbProperties &properties ); - /// \ru Проверить полюса. \en Check poles. - void SetPole(); - /** \} */ -protected: - /// \ru Корректировка параметров. \en Correction of parameters. - inline void CheckParam ( double &u, double &v ) const; - - void InitSmoothSurface ( const MbSmoothSurface & ); - void Init ( const MbSmoothSurface & ); - -private: - // \ru Определениe точки пересечения края поверхности и кривой на смежной поверхности. \en Determination of intersection point between the surface boundary and the adjacent surface. - MbeNewtonResult TangentIntersection( const MbSurfaceIntersectionCurve &, - size_t iterLimit, double &u, double &v, double &t, bool ext0, bool ext1 ) const; - MbeNewtonResult CurveTangentIntersection( const MbCurve3D &, double funcEpsilon, size_t iterLimit, - double &u, double &v, double &t, bool ext0, bool ext1 ) const; - bool IsSameSurface( const MbCurve3D &, double &u, double &v, double &t ) const; // \ru Идентификация кривой. \en Identification of a curve. - - void operator = ( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS( MbSmoothSurface ) -}; - -IMPL_PERSISTENT_OPS( MbSmoothSurface ) - -//------------------------------------------------------------------------------ -// \ru Корректировка параметров \en Correction of parameters -// --- -inline void MbSmoothSurface::CheckParam( double &u, double &v ) const { - if ( v < vmin ) - v = vmin; - else - if ( v > vmax ) - v = vmax; - - if ( uclosed ) { - if ( (u < umin) || (u > umax ) ) { - double tmp = umax - umin; - u -= ::floor((u - umin) / tmp) * tmp; - } - } - else { - if ( poleMin && uumax ) - u = umax; - } -} - - -//------------------------------------------------------------------------------ -// Скорректировать крайние точки контейнеров, если они лежат в полюсах поверхности. -// --- -void CorrectPolePoins(const MbSurface & surface, SArray & points ); - - -//------------------------------------------------------------------------------ -// \ru Наполнить массив параметров для кривых на поверхностях \en Fill an array of parameters for the curves on surfaces -// --- -void CreateParams( const MbSurface & surface1, SArray & points1, - const MbSurface & surface2, SArray & points2, - SArray * values, SArray * valuesDerive, - bool °enerate1, bool °enerate2, ptrdiff_t & begN, ptrdiff_t & endN, - SArray & params ); - - -//------------------------------------------------------------------------------ -// \ru Создать кривые на поверхности \en Create curves on a surface. -// --- -void CreateSurfaceCurves( const MbSurface & surface1, SArray & points1, - const MbSurface & surface2, SArray & points2, - MbeSmoothForm form, bool firstFree, double distance1, double distance2, - bool insert, ptrdiff_t begN, ptrdiff_t endN, VERSION version, - MbSurfaceCurve *& curve1, MbSurfaceCurve *& curve2 ); - - -//------------------------------------------------------------------------------ -// \ru Создать поверхность \en Create a surface -// --- -MbSmoothSurface * CreateSmoothSurface( const MbSurface & surface1, SArray & points1, - const MbSurface & surface2, SArray & points2, - MbeSmoothForm form, bool firstFree, double distance1, double distance2, - double conic, bool even, ptrdiff_t begN, ptrdiff_t endN, VERSION version ); - - -#endif // __SURF_SMOOTH_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Поверхность сопряжения. + \en Smooth surface. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_SMOOTH_SURFACE_H +#define __SURF_SMOOTH_SURFACE_H + + +#include + + +const_expr bool _EVEN_ = false; // \ru Неравномерная параметризация по дуге при u = const \en Uneven parameterization along an arc where u = const + + +class MATH_CLASS MbSurfaceCurve; +class MATH_CLASS MbSurfaceIntersectionCurve; + + +//------------------------------------------------------------------------------ +/** \brief \ru Поверхность сопряжения. + \en Smooth surface. \~ + \details \ru Поверхность сопряжения соединяет две кривые curve1 и curve2 на сопрягаемых поверхностях. + Поверхность сопряжения является родительским классом поверхности скругления MbFilletSurface и поверхности фаски MbCamferSurface. + В отличие от других поверхностей Функции PointOn и Derive... поверхностей сопряжения не корректируют + первый параметр (u) при его выходе за пределы определения параметров (umin umax). + \en A smooth surface connects two curves ('curve1' and 'curve2') on interfacing surfaces. + Smooth surface is the parent class of fillet surface (MbFilletSurface) and chamfer surface (MbChamferSurface). + In contrast to other surfaces functions PointOn and Derive.. of smooth surface don't correct + the first parameter (u) when getting out of domain bounds (umin and umax). \~ + \ingroup Surfaces +*/ +// --- +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). + 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. + double umin; ///< \ru Минимальное значение параметра u. \en Minimal value of parameter u. + double umax; ///< \ru Максимальное значение параметра u. \en Maximal value of parameter u. + double vmin; ///< \ru Минимальное значение параметра v. \en Minimal value of parameter v. + double vmax; ///< \ru Максимальное значение параметра v. \en Maximal value of parameter v. + bool uclosed; ///< \ru Признак замкнутости по параметру u. \en An attribute of closedness in u-parameter direction. + bool poleMin; ///< \ru Наличие полюса при umin. \en Existence of a pole at umin. + bool poleMax; ///< \ru Наличие полюса при umax. \en Existence of a pole at umax. + +protected: + + /** \brief \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and conjugation type. \~ + \details \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and conjugation type. \~ + \param[in] crv1 - \ru Опорная кривая на первой поверхности + \en Support curve on the first surface. \~ + \param[in] crv2 - \ru Опорная кривая на второй поверхности + \en Support curve on the second surface. \~ + \param[in] fm - \ru Тип сопряжения (0 - скругление, 1 - фаска) + \en Conjugation type (0 - fillet, 1 - chamfer) \~ + */ + MbSmoothSurface( MbSurfaceCurve & crv1, MbSurfaceCurve & crv2, MbeSmoothForm fm, double d1, double d2 ); + + /** \brief \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and conjugation type. \~ + \details \ru Конструктор по двум кривым и типу сопряжения. + \en Constructor by two curves and conjugation type. \~ + \param[in] surf1 - \ru Первая поверхность + \en First surface. \~ + \param[in] curv1 - \ru Кривая в области определения первой поверхности + \en A curve in domain of the first surface \~ + \param[in] surf2 - \ru Вторая поверхность + \en Second surface. \~ + \param[in] curv2 - \ru Кривая в области определения второй поверхности + \en A curve in domain of the second surface \~ + \param[in] fm - \ru Тип сопряжения (0 - скругление, 1 - фаска) + \en Conjugation type (0 - fillet, 1 - chamfer) \~ + */ + MbSmoothSurface( MbSurface &surf1, MbCurve &curv1, MbSurface &surf2, MbCurve &curv2, MbeSmoothForm fm, double d1, double d2 ); + /// \ru Конструктор копирования. \en Copy-constructor. + MbSmoothSurface( const MbSmoothSurface &, MbRegDuplicate * ); + /// \ru Конструктор копирования с теми же опорными поверхностями. \en Copy constructor with the same support surfaces. + MbSmoothSurface( const MbSmoothSurface * ); // \ru Для CurvesDuplicate() \en For CurvesDuplicate() +private: + MbSmoothSurface( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. +public: + virtual ~MbSmoothSurface(); + +public: + VISITING_CLASS( MbSmoothSurface ); + + /** \ru \name Функции инициализации + \en \name Initialization functions + \{ */ + + /** \brief \ru Коррекция средней линии поверхности скругления. + \en Correction of the middle line of fillet surface. \~ + \details \ru Коррекция средней линии поверхности скругления. + \en Correction of the middle line of fillet surface. \~ + \param[in] tmin - \ru Новый минимальный параметр средней линии + \en New minimal parameter of the middle line. \~ + \param[in] tmax - \ru Новый максимальный параметр средней линии + \en New maximal parameter of the middle line. \~ + \param[in] insertPoints - \ru Увеличить число контрольных точек средней кривоф. + \en Insert control points for middle cerve0. \~ + */ + virtual void Init0( double tmin, double tmax, bool insertPoints = true ) = 0; + + /** \} */ + /** \ru \name Общие функции геометрического объекта + \en \name Common functions of a geometric object + \{ */ + 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 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 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. + /** \} */ + /** \ru \name Функции описания области определения поверхности + \en \name Functions for surface domain description + \{ */ + virtual double GetUMin() const; // \ru Вернуть минимальное значение параметра u. \en Get the minimum value of u. + virtual double GetUMax() const; // \ru Вернуть максимальное значение параметра u. \en Get the maximum value of u. + virtual double GetVMin() const; // \ru Вернуть минимальное значение параметра v. \en Get the minimum value of v. + virtual double GetVMax() const; // \ru Вернуть максимальное значение параметра v. \en Get the maximum value of v. + virtual bool IsUClosed() const; // \ru Проверка замкнутости по параметру u. \en Check of surface closedness in u direction. + virtual bool IsVClosed() const; // \ru Проверка замкнутости по параметру v. \en Check of surface closedness in v direction. + virtual double GetUPeriod() const; // \ru Вернуть период. \en Return period. + + // \ru Существует ли полюс на границе параметрической области сплайновой кривой. \en Whether a pole exists on parametric region boundary of spline curve. + 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 singular. + /** \} */ + /** \ru \name Функции для работы в области определения поверхности + Функции PointOn и Derive... поверхностей сопряжения не корректируют + первый параметр при его выходе за пределы определения параметров. + \en \name Functions for working at surface domain + Functions PointOn and Derive... of smooth surfaces don't correct + the first parameter when getting out of domain bounds. + \{ */ + virtual void PointOn ( double &u, double &v, MbCartPoint3D & ) const = 0; // \ru Точка на поверхности. \en A point on surface. + virtual void DeriveU ( double &u, double &v, MbVector3D & ) const = 0; // \ru Первая производная по u. \en First derivative with respect to u. + virtual void DeriveV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Первая производная по v. \en First derivative with respect to v. + virtual void DeriveUU ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по u. \en Second derivative with respect to u. + virtual void DeriveVV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по v. \en Second derivative with respect to v. + virtual void DeriveUV ( double &u, double &v, MbVector3D & ) const = 0; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. + virtual void DeriveUUU( double &u, double &v, MbVector3D & ) const = 0; + virtual void DeriveUUV( double &u, double &v, MbVector3D & ) const = 0; + virtual void DeriveUVV( double &u, double &v, MbVector3D & ) const = 0; + virtual void DeriveVVV( double &u, double &v, MbVector3D & ) const = 0; + /** \} */ + /** \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 = 0; + /** \} */ + /** \ru \name Функции движения по поверхности + \en \name Functions of moving over the surface + \{ */ + virtual size_t GetUCount() const; + virtual size_t GetVCount() const; + /** \} */ + /** \ru \name Общие функции поверхности + \en \name Common functions of surface. + \{ */ + // \ru Определениe точки пересечения поверхности и кривой. \en Determination of a point of intersection between a surface and a curve. + virtual MbeNewtonResult CurveIntersectNewton( const MbCurve3D &, double funcEpsilon, size_t iterLimit, + double &u0, double &v0, double &t1, bool ext0, bool ext1 ) const; + // \ru Дать максимальное приращение параметра. \en Get the maximum increment of parameter. + virtual double GetParamDelta() const; + // \ru Дать мимнимально различимую величину параметра. \en Get the minimum distinguishable value of parameter. + virtual double GetParamPrice() const; + // \ru Построить NURBS-копию поверхности. \en Construct a NURBS copy of a surface. + virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; + + /** \} */ + /** \ru \name Функции поверхности сопряжения + \en \name Functions of smooth surface + \{ */ + /// \ru Копия с теми же опорными поверхностям. \en A copy with the same support surfaces. + virtual MbSmoothSurface & CurvesDuplicate() const = 0; + /// \ru Сделать полное копирование поверхности. \en Perform a full copying of a surface. + MbSurface & TotalDuplicate() const; + /// \ru Дать радиус. \en Get radius. + virtual double GetSmoothRadius() const = 0; + /// \ru Дать радиусы со знаком. \en Get radii with a sign. + virtual void GetDistances( double u, double &d1, double &d2 ) const = 0; + /// \ru Дать радиус со знаком. \en Get radius with a sign. + virtual double GetDistance( bool s ) const = 0; + + /** \brief \ru Объединить поверхности путём включения поверхности init в данную поверхность. + \en Combine surfaces by inclusion of the surface 'init' into the given surface. \~ + \details \ru Объединить поверхности путём включения поверхности init в данную поверхность. + \en Combine surfaces by inclusion of the surface 'init' into the given surface. \~ + \param[in] edge - \ru Кривая разделяющего ребра + \en A curve of the splitting edge. \~ + \param[in] init - \ru Поверхность, которую нужно добавить в данную + \en A surface which should be added into the given one \~ + \param[in] add - \ru Добавить в конец (true), добавить в начало (false) + \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) \~ + */ + virtual bool SurfacesCombine( const MbSurfaceIntersectionCurve & edge, + const MbSurface & init, bool add, MbMatrix & matr, + const MbSurfaceIntersectionCurve * seam ); + + /// \ru Дать коэффициент для радиуса. \en Get coefficient for radius. + virtual double DistanceRatio( bool firstCurve, MbCartPoint3D & p, double distance ) const; + + /// \ru Опорная кривая на первой поверхности. \en Support curve on the first surface. + const MbSurfaceCurve & GetCurve1() const { return *curve1; } + /// \ru Опорная кривая на второй поверхности. \en Support curve on the second surface. + const MbSurfaceCurve & GetCurve2() const { return *curve2; } + /// \ru Дать опорную кривую на первой поверхности для изменения. \en Get the support curve on the first surface for changing. + MbSurfaceCurve & SetCurve1() const { return *curve1; } + /// \ru Дать опорную кривую на второй поверхности для изменения. \en Get the support curve on the second surface for changing. + MbSurfaceCurve & SetCurve2() const { return *curve2; } + + /** \brief \ru Построить граничную кривую вдоль поверхности (V = const). + \en Construct boundary curve along a surface (V = const). \~ + \details \ru Построить граничную кривую вдоль поверхности (V = const). + \en Construct boundary curve along a surface (V = const). \~ + \param[in] s - \ru Если true, то вдоль минимального значения V,\n + если false, то вдоль максимального значения V + \en If it equals true then construct along the minimal value of V,\n + otherwise construct along the maximal value of V \~ + */ + MbCurve * CreateBound( bool s ) const; + + /** \brief \ru Вид опорных кривых. + \en Type of support curves. \~ + \details \ru Вид опорных кривых. + \en Type of support curves. \~ + \return \ru cbt_Specific если кривые построены по отдельным точкам\n + cbt_Ordinary если кривые аналитические + \en Cbt_Specific if the curves have been constructed by the separate points\n + cbt_Ordinary if the curves are analytical \~ + */ + MbeCurveBuildType GetBuildType() const; + + /** \brief \ru Форма поверхности. + \en Form of a surface. \~ + \details \ru Форма поверхности. + \en Form of a surface. \~ + \return \ru 0 в случае поверхности скругления\n + 1 в случае поверхности фаски + \en 0 in a case of fillet\n + 1 in a case of chamfer \~ + */ + MbeSmoothForm Form() const { return form; } + + /** \brief \ru Добавить точку в опорные кривые границы. + \en Add a point to the support curves of the boundary. \~ + \details \ru Добавить точку в опорные кривые границы.\n + Точка будет добавлена в кривую, если она имеет тип pt_LineSegment, pt_CubicSpline или pt_Hermit. + \en Add a point to the support curves of the boundary.\n + A point will be added into a curve if it has a type pt_LineSegment, pt_CubicSpline or pt_Hermit. \~ + \param[out] t1 - \ru Параметр точки на первой кривой (если add1 = true) + \en Parameter of a point on the first curve (if add1 equals true) \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] add1 - \ru Нужно ли добавлять точку в первую кривую + \en Whether to add a point to the first curve \~ + \param[out] t2 - \ru Параметр точки на второй кривой (если add2 = true) + \en Parameter of a point on the second curve (if add2 equals true) \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] add2 - \ru Нужно ли добавлять точку во вторую кривую + \en Whether to add a point to the second curve \~ + */ + virtual bool InsertPoints( double & t1, const MbCartPoint & p1, bool add1, + double & t2, const MbCartPoint & p2, bool add2 ); + + /** \brief \ru Продлить поверхность. + \en Prolong surface. \~ + \details \ru Построить и добавить точки в опорные кривые до или после границы, удлиннив поверхность.\n + Точки будут построены и добавлены в кривые, если они имеют тип pt_Hermit. + \en Build and add points to the support curves of the boundary.\n + A points will be builded and added into curves if they have a type pt_Hermit. \~ + \param[in] t - \ru Первый параметр поверхности + \en First parameter of surface \~ + \param[in] p1 - \ru Точка на первой кривой + \en Point on the first curve \~ + \param[in] p2 - \ru Точка на второй кривой + \en Point on the second curve \~ + \param[in] anyCase - \ru Штатная работа со значением false (true исключение). + \en Regular work with the value false (true exception). \~ + */ + bool ProlongSurface( double u, const MbCartPoint & p1, const MbCartPoint & p2, bool anyCase ); + + /** \brief \ru Скорректировать кривые. + \en Correct curves. \~ + \details \ru Скорректировать опорные кривые после вставки точек.\n + Кривая будет скорректирована, если поверхность имеет полюс на краю, опорная кривая имеет тип pt_Hermit и содержит опорную точку с заданным параметром. + Корректируется опорная точка кривой, ближайшая к точке с заданным параметром со стороны полюса поверхности. + \en Correct the support curves after inserting of the points.\n + A curve will be corrected if the surface has a pole on the boundary, a support curve has the type pt_Hermit and contains the support point with the given parameter. + The curve support point which is the nearest to the point with the given parameter from the side of the surface pole is corrected. \~ + \param[in] t1 - \ru Параметр точки на первой опорной кривой. + \en Parameter of a point on the first support curve. \~ + \param[in] t2 - \ru Параметр точки на второй опорной кривой. + \en Parameter of a point on the second support curve. \~ + */ + bool CurveStraighten( double t1, double t2 ); + /// \ru Дать свойства объекта. \en Get the object properties. + void AddProperties( MbProperties &properties ); + /// \ru Проверить полюса. \en Check poles. + void SetPole(); + /** \} */ +protected: + /// \ru Корректировка параметров. \en Correction of parameters. + inline void CheckParam ( double &u, double &v ) const; + + void InitSmoothSurface ( const MbSmoothSurface & ); + void Init ( const MbSmoothSurface & ); + +private: + // \ru Определениe точки пересечения края поверхности и кривой на смежной поверхности. \en Determination of intersection point between the surface boundary and the adjacent surface. + MbeNewtonResult TangentIntersection( const MbSurfaceIntersectionCurve &, + size_t iterLimit, double &u, double &v, double &t, bool ext0, bool ext1 ) const; + MbeNewtonResult CurveTangentIntersection( const MbCurve3D &, double funcEpsilon, size_t iterLimit, + double &u, double &v, double &t, bool ext0, bool ext1 ) const; + bool IsSameSurface( const MbCurve3D &, double &u, double &v, double &t ) const; // \ru Идентификация кривой. \en Identification of a curve. + + void operator = ( const MbSmoothSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS( MbSmoothSurface ) +}; + +IMPL_PERSISTENT_OPS( MbSmoothSurface ) + +//------------------------------------------------------------------------------ +// \ru Корректировка параметров \en Correction of parameters +// --- +inline void MbSmoothSurface::CheckParam( double &u, double &v ) const { + if ( v < vmin ) + v = vmin; + else + if ( v > vmax ) + v = vmax; + + if ( uclosed ) { + if ( (u < umin) || (u > umax ) ) { + double tmp = umax - umin; + u -= ::floor((u - umin) / tmp) * tmp; + } + } + else { + if ( poleMin && uumax ) + u = umax; + } +} + + +//------------------------------------------------------------------------------ +// Скорректировать крайние точки контейнеров, если они лежат в полюсах поверхности. +// --- +void CorrectPolePoins(const MbSurface & surface, SArray & points ); + + +//------------------------------------------------------------------------------ +// \ru Наполнить массив параметров для кривых на поверхностях \en Fill an array of parameters for the curves on surfaces +// --- +void CreateParams( const MbSurface & surface1, SArray & points1, + const MbSurface & surface2, SArray & points2, + SArray * values, SArray * valuesDerive, + bool °enerate1, bool °enerate2, ptrdiff_t & begN, ptrdiff_t & endN, + SArray & params ); + + +//------------------------------------------------------------------------------ +// \ru Создать кривые на поверхности \en Create curves on a surface. +// --- +void CreateSurfaceCurves( const MbSurface & surface1, SArray & points1, + const MbSurface & surface2, SArray & points2, + MbeSmoothForm form, bool firstFree, double distance1, double distance2, + bool insert, ptrdiff_t begN, ptrdiff_t endN, VERSION version, + MbSurfaceCurve *& curve1, MbSurfaceCurve *& curve2 ); + + +//------------------------------------------------------------------------------ +// \ru Создать поверхность \en Create a surface +// --- +MbSmoothSurface * CreateSmoothSurface( const MbSurface & surface1, SArray & points1, + const MbSurface & surface2, SArray & points2, + MbeSmoothForm form, bool firstFree, double distance1, double distance2, + double conic, bool even, ptrdiff_t begN, ptrdiff_t endN, VERSION version ); + + +#endif // __SURF_SMOOTH_SURFACE_H diff --git a/C3d/Include/surf_spine.h b/C3d/Include/surf_spine.h index db0cdb6..75dadc3 100644 --- a/C3d/Include/surf_spine.h +++ b/C3d/Include/surf_spine.h @@ -21,10 +21,19 @@ const VERSION SPINE_ALG_VERSION1 = 0x0A000000L; // \ru Добавлена option const VERSION SPINE_ALG_VERSION2 = 0x0D000023L; // \ru Добавлено создание optionalCurve в общем случае \en Added creation of "optionalCurve" in general case +class MATH_CLASS MbSpine; + +namespace c3d // namespace C3D +{ +typedef SPtr SpineSPtr; +typedef SPtr ConstSpineSPtr; +} + + //------------------------------------------------------------------------------ /** \brief \ru Криволинейная направляющая для кинематической поверхности. \en Curvilinear spine for sweep surface. \~ - \details \ru Криволинейная направляющая для кинематической поверхности (поверхности заметания) служит для расчёта в каждой точке направляющей кривой локальной система координат. \n + \details \ru Криволинейная направляющая для кинематической поверхности (поверхности заметания) служит для расчёта в каждой точке направляющей кривой локальной системы координат. \n Локальная ось 0 ориентирована по касательной кривой "curve". \n Локальная ось 1 ориентирована в сторону вектора "direction" или в сторону кривой "optionalCurve". \n Локальная ось 2 дополняет локальную систему до правой системы координат. @@ -37,27 +46,27 @@ const VERSION SPINE_ALG_VERSION2 = 0x0D000023L; // \ru Добавлено соз class MATH_CLASS MbSpine : public MbRefItem, public TapeBase { public: /// \ru Способы движения локальной системы координат вдоль направляющей кривой "curve". \en Methods of movement of the local coordinate system along the guide curve "curve". - enum LocalAxises { + enum LocalAxes { la_planeParallel = 0, ///< \ru Плоскопараллельный, сохраняющий исходную ориентацию осей. \en Plane-parallel, preserving the original orientation of the axes. - la_culcDirection = 1, ///< \ru Вектор "direction" рассчитан объектом. Ось 0 ориентирована по касательной кривой "curve", ось 1 - в сторону вектора "direction". \en Vector "direction" was calculated by object. Axis 0 is oriented along the tangent of the curve "curve", the axis 1 in the direction of the vector "direction". + la_calcDirection = 1, ///< \ru Вектор "direction" рассчитан объектом. Ось 0 ориентирована по касательной кривой "curve", ось 1 - в сторону вектора "direction". \en Vector "direction" was calculated by object. Axis 0 is oriented along the tangent of the curve "curve", the axis 1 in the direction of the vector "direction". la_userDirection = 2, ///< \ru Вектор "direction" задан конструктору. Ось 0 ориентирована по касательной кривой "curve", ось 1 - в сторону вектора "direction". \en Vector "direction" was sent to conctructor. Axis 0 is oriented along the tangent of the curve "curve", the axis 1 in the direction of the vector "direction". la_surfaceNormal = 3, ///< \ru Ось 0 ориентирована по касательной кривой на поверхности "curve", ось 1 - по нормали поверхности кривой "curve". \en The 0 axis is oriented along the tangent curve on the curve surface, the 1 axis is oriented along the normal of the curve surface. la_optionalCurve = 4, ///< \ru Ось 0 ориентирована по касательной кривой "curve", ось 1 - в сторону кривой "optionalCurve". \en Axis 0 is oriented along the tangent of the curve "curve", the axis 1 in the direction of the curve "optionalCurve". }; private: - MbCurve3D * curve; ///< \ru Направляющая кривая - всегда не NULL. \en Spine curve - it is always not NULL. - MbVector3D direction; ///< \ru Вектор ориентации матрицы преобразования. \en Vector of transformation matrix orientation. - MbCurve3D * optionalCurve; ///< \ru Кривая векторa ориентации матрицы преобразования (может быть NULL для простой траектории). \en A curve of the transformation matrix orientation (it may be NULL for a simple trajectory). - MbSurface * spineSurface; ///< \ru Поверхность направляющей кривой, если "curve" - кривая на поверхности, или NULL. \en The surface of the "curve", if it is curve on surface, or NULL. - MbCurve * featureCurve; ///< \ru Двумерная кривая, если "curve" - кривая на поверхности, или NULL. \en Two-dimensional curve of the "curve", if it is curve on surface, or NULL. - LocalAxises localAxises; ///< \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. - MbVector3D ort0; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. - MbVector3D ort1; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. - MbVector3D ort2; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. - VERSION version; ///< \ru Версия расчета вектора direction. \en Version of vector "direction" calculation. + SPtr curve; ///< \ru Направляющая кривая - всегда не NULL. \en Spine curve - it is always not 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. + 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. + MbVector3D ort0; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. + MbVector3D ort1; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. + MbVector3D ort2; ///< \ru Вектор базиса в точке ortParam направляющей. \en A basis vector in the point ortParam of the spine. + VERSION version; ///< \ru Версия расчета вектора direction. \en Version of vector "direction" calculation. //------------------------------------------------------------------------------ /** \brief \ru Вспомогательные данные. @@ -133,17 +142,17 @@ protected: */ MbSpine( const MbCurve3D & cur, bool same, const MbVector3D & dir, bool par, VERSION vers = Math::DefaultMathVersion() ); - /** \brief \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования. + /** \brief \ru Конструктор по направляющей кривой и кривой вектора ориентации матрицы преобразования. \en Constructor by spine curve and a curve of the vector of transformation matrix orientation. \~ - \details \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования.\n - \en Constructor by spine curve and a curve of the vector of transformation matrix orientation.\n \~ + \details \ru Конструктор по направляющей кривой и кривой вектора ориентации матрицы преобразования.\n + \en Constructor by spine curve and a curve of the vector of transformation matrix orientation.\n \~ \param[in] cur - \ru Направляющая кривая \en A spine curve \~ \param[in] same - \ru Признак использования оригинала направляющей кривой, а не ее копии \en Attribute of using the original of spine curve instead of its copy \~ - \param[in] opt - \ru Кривая векторa ориентации матрицы преобразования + \param[in] opt - \ru Кривая вектора ориентации матрицы преобразования \en A curve of the vector of transformation matrix orientation \~ - \param[in] sameO - \ru Признак использования оригинала кривой векторa ориентации матрицы преобразования, а не ее копии + \param[in] sameO - \ru Признак использования оригинала кривой вектора ориентации матрицы преобразования, а не ее копии \en Attribute of using the original of a curve of the vector of transformation matrix orientation instead of its copy \~ \param[in] par - \ru Признак параллельного переноса. \en Attribute of parallel translation. \~ @@ -151,6 +160,8 @@ protected: \en Version of calculation the local coordinate system. \~ */ MbSpine( const MbCurve3D & cur, bool same, const MbCurve3D & opt, bool sameO, bool par, VERSION vers = Math::DefaultMathVersion() ); + // \ru Конструктор по направляющей кривой и поверхности, на которой лежит направляющая кривая. \en Constructor by spine curve and the surface on which the spine curve lies. \~ + MbSpine( const MbCurve3D & spineCurve, bool sameSpine, const MbSurface & surface, bool sameSurface, const MbCurve & pCurve, bool sameCurve, VERSION ver ); protected: MbSpine( const MbSpine &, MbRegDuplicate * ); @@ -160,6 +171,81 @@ public: public: VISITING_CLASS( MbSpine ); + /** \brief \ru Конструктор по направляющей кривой. + \en Constructor by spine curve. \~ + \details \ru Конструктор по направляющей кривой.\n + \en Constructor by spine curve.\n \~ + \param[in] c - \ru Направляющая кривая + \en A spine curve \~ + \param[in] parallel - \ru Признак параллельного переноса + \en Attribute of parallel translation. \~ + \param[in] same - \ru Признак использования оригинала направляющей кривой, а не ее копии + \en Attribute of using the original of spine curve instead of its copy \~ + \param[in] vers - \ru Версия вычисления осей локальной системы координат. + \en Version of calculation the local coordinate system. \~ + */ + static MbSpine & Create( const MbCurve3D & c, bool parallel, bool same, + VERSION vers = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор по направляющей кривой и вектору ориентации матрицы преобразования. + \en Constructor by spine curve and a vector of transformation matrix orientation. \~ + \details \ru Конструктор по направляющей кривой и вектору ориентации матрицы преобразования.\n + \en Constructor by spine curve and a vector of transformation matrix orientation.\n \~ + \param[in] c - \ru Направляющая кривая + \en A spine curve \~ + \param[in] same - \ru Признак использования оригинала направляющей кривой, а не ее копии + \en Attribute of using the original of spine curve instead of its copy \~ + \param[in] direction - \ru Вектор ориентации матрицы преобразования. + \en Vector of transformation matrix orientation. \~ + \param[in] parallel - \ru Признак параллельного переноса + \en Attribute of parallel translation. \~ + \param[in] vers - \ru Версия вычисления осей локальной системы координат. + \en Version of calculation the local coordinate system. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbSpine * Create( const MbCurve3D & c, bool same, const MbVector3D & dir, bool parallel, + VERSION vers = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования. + \en Constructor by spine curve and a curve of the vector of transformation matrix orientation. \~ + \details \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования.\n + \en Constructor by spine curve and a curve of the vector of transformation matrix orientation.\n \~ + \param[in] sp - \ru Направляющая кривая + \en A spine curve \~ + \param[in] sameS - \ru Признак использования оригинала направляющей кривой, а не ее копии + \en Attribute of using the original of spine curve instead of its copy \~ + \param[in] dc - \ru Кривая векторa ориентации матрицы преобразования + \en A curve of the vector of transformation matrix orientation \~ + \param[in] sameD - \ru Признак использования оригинала кривой векторa ориентации матрицы преобразования, а не ее копии + \en Attribute of using the original of a curve of the vector of transformation matrix orientation instead of its copy \~ + \param[in] parallel - \ru Признак параллельного переноса + \en Attribute of parallel translation. \~ + \param[in] vers - \ru Версия вычисления осей локальной системы координат. + \en Version of calculation the local coordinate system. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbSpine * Create( const MbCurve3D & sp, bool sameS, const MbCurve3D & dc, bool sameD, bool parallel, + VERSION vers = Math::DefaultMathVersion() ); + /** \brief \ru Конструктор по направляющей кривой на кривой, связанной с поверхностью. + \en Constructor by spine curve on a curve associated with a surface. \~ + \details \ru Конструктор по направляющей кривой и поверхности, на которой лежит направляющая кривая.\n + \en Constructor by spine curve and the surface on which the spine curve lies.\n \~ + \param[in] sp - \ru Направляющая кривая + \en A spine curve \~ + \param[in] sameS - \ru Признак использования оригинала направляющей кривой, а не ее копии + \en Attribute of using the original of spine curve instead of its copy \~ + \param[in] surf - \ru Поверхность направляющей кривой. + \en The surface of the sp, it should be curve on surface. \~ + \param[in] pCrv - \ru Двумерная кривая на поверхности направляющей кривой. + \en The two-dimensional curve on the surface of the guide curve. \~ + \param[in] vers - \ru Версия вычисления осей локальной системы координат. + \en Version of calculation the local coordinate system. \~ + \return \ru Возвращает указатель на созданный объект или нулевой указатель в случае неудачи. + \en Returns pointer to the created object or null pointer in case of failure. \~ + */ + static MbSpine * Create( const MbCurve3D & sp, bool sameS, const MbSurface & surf, const MbCurve * pCrv, + VERSION vers ); + /** \} */ /** \ru \name Базовые функции \en \name Base functions @@ -192,7 +278,7 @@ public: double GetTMax() const { return curve->GetTMax(); } /// \ru Вернуть минимальное значение параметра. \en Get the minimum value of parameter. double GetTMin() const { return curve->GetTMin(); } - /// \ru Проверка замкнутости кривой. \en Check for curve closedness + /// \ru Проверка замкнутости кривой. \en Check for curve closeness bool IsClosed() const { return curve->IsClosed(); } /** \} */ /** \ru \name Функции для работы в области определения направляющей кривой @@ -272,7 +358,7 @@ public: \return \ru Вектор \en A vector \~ */ - const MbVector3D & GetOrt0() const { return ort0; } + const MbVector3D & GetOrt0() const { return ort0; } /** \brief \ru Вычисление матриц преобразования. \en Calculation of transformation matrices. \~ @@ -293,14 +379,6 @@ public: // \ru Вычисление матрицы преобразования второй производной радиуса-вектора. \en Calculation of transformation matrix for second derivative of radius vector. \~ void CalculateMatrix2( double & v, bool ext, MbMatrix3D & matrix2 ) const; - /** \brief \ru Построить плейсмент в заданной точке. - \en Construct placement in the given point. \~ - \details \ru Построить плейсмент в заданной точке.\n - \en Construct placement in the given point.\n \~ - \param[in] v - \ru Параметр на направляющей кривой - \en Parameter on spine curve \~ - */ - MbPlacement3D GetPlacement( double v ) const; /// \ru Направляющая кривая. \en The spine curve. const MbCurve3D & GetCurve() const { return *curve; } /// \ru Дать направляющую кривую для изменения. \en Get spine curve for editing. @@ -313,28 +391,53 @@ public: VERSION GetVersion() const { return version; } /// \ru Изменить направляющую кривую. \en Change the spine curve. - void ChangeCurve( const MbCurve3D & c ); + void ChangeCurve( const MbCurve3D & ); /// \ru Изменить ориентирующую кривую. \en Change the direction curve. - void ChangeOptionalCurve( const MbCurve3D * d ); + void ChangeOptionalCurve( const MbCurve3D & ); /// \ru Вектор ориентации матрицы преобразования. \en Vector of transformation matrix orientation. const MbVector3D & GetDirection() const { return direction; } /// \ru Изменить вектор ориентации матрицы преобразования. \en Change the vector of transformation matrix orientation. bool SetDirection( const MbVector3D & d, bool checkBySpineCurve = false ); - /// \ru Лать способ ориентации локальной системы координат. \en Пуе еhe method of orientation of the local coordinate system. \~ - LocalAxises GetLocalAxisMethod() const { return localAxises; } - /// \ru Лать способ ориентации локальной системы координат. \en Пуе еhe method of orientation of the local coordinate system. \~ - void SetLocalAxisMethod( LocalAxises la ) { localAxises = la; } + /// \ru Дать способ ориентации локальной системы координат. \en Get the method of orientation of the local coordinate system. \~ + LocalAxes GetLocalAxisMethod() const { return localAxes; } + /// \ru Дать способ ориентации локальной системы координат. \en Get the method of orientation of the local coordinate system. \~ + void SetLocalAxisMethod( LocalAxes la ) { localAxes = la; } /// \ru Признак параллельного переноса. \en Attribute of plane-parallel translation. - bool IsParallel() const { return localAxises == MbSpine::la_planeParallel; } + bool IsParallel() const { return localAxes == la_planeParallel; } /// \ru Признак пользовательского направления. \en Attribute of user direction. - bool IsUserDirection() const { return ( localAxises >= MbSpine::la_userDirection ); } - - /// \ru Параметр кривой, для которой расчитан базис направляющей. \en Parameter of a curve with calculated basis of spine. + bool IsUserDirection() const { return ( localAxes == la_userDirection ); } + /// \ru Признак направления по нормали к поверхности. \en Attribute of direction as surface normal. + bool BySurfaceNormal() const { return ( localAxes == la_surfaceNormal ); } + /// \ru Признак направления по вспомогательной кривой. \en Attribute of direction by optional curve. + bool ByOptionalCurve() const { return ( localAxes == la_optionalCurve ); } + /// \ru Параметр кривой, для которой рассчитан базис направляющей. \en Parameter of a curve with calculated basis of spine. double GetOrtParam() const { return ortParam; } - /// \ru Установить параметр кривой, для которой расчитан базис направляющей. \en Set the parameter of a curve with calculated basis of spine. - void SetOrtParam( double t ); + /// \ru Установить параметр кривой, для которой рассчитан базис направляющей. \en Set the parameter of a curve with calculated basis of spine. + void SetOrtParam( double t ); + /// \ru Вычисление ортов для матриц преобразования. \ en The basis vectors calculation for matrix. + void BaseVectors0( double & v, bool ext, MbCartPoint3D & origin, + MbVector3D & vector0, MbVector3D & vector1, MbVector3D & vector2 ) const; + /// \ru Вычисление ортов и их первых производных. \ en Calculation of the basis vectors and their first derivatives. + void BaseVectors1( double & v, bool ext, MbVector3D & origin1, + MbVector3D & vector0, MbVector3D & vector1, MbVector3D & vector2, + MbVector3D & derive0, MbVector3D & derive1, MbVector3D & derive2 ) const; + /// \ru Вычисление ортов и их первых и вторых производных. \ en Calculation of the basis vectors and their first and second derivatives. + void BaseVectors2( double & v, bool ext, MbVector3D & origin1, MbVector3D & origin2, + MbVector3D & vector0, MbVector3D & vector1, MbVector3D & vector2, + MbVector3D & derive0, MbVector3D & derive1, MbVector3D & derive2, + MbVector3D & second0, MbVector3D & second1, MbVector3D & second2 ) const; + /** \brief \ru Построить плейсмент в заданной точке. + \en Construct placement in the given point. \~ + \details \ru Построить плейсмент в заданной точке.\n + \en Construct placement in the given point.\n \~ + \param[in] v - \ru Параметр на направляющей кривой + \en Parameter on spine curve \~ + */ + MbPlacement3D GetPlacement( double v ) const; + /// \ru Инициализировать плейсмент для заданной точке. \en Initialize placement for the given point. \~ + void GetPlacement( double v, MbPlacement3D & pl ) const; /// \ru Количество сегментов направляющей кривой. \en The number of segments of the spine curve. size_t GetSegmentsCount() const; @@ -344,78 +447,25 @@ public: \details \ru Функция регистрации по количеству ссылок для предотвращения многократной записи.\n \en Function of registration by the number of references to avoid multiple writing.\n \~ */ - void PrepareWrite() { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( (GetUseCount() > 1) ? registrable : noRegistrable ); } + + const MbSurface * GetSpineSurface() const { return spineSurface; } ///< \ru Поверхность направляющей кривой, если "curve" - кривая на поверхности. \en The surface of the "curve", if it is curve on surface. + const MbCurve * GetFeatureCurve() const { return featureCurve; } ///< \ru Двумерная кривая, если "curve" - кривая на поверхности. \en Two-dimensional curve of the "curve", if it is curve on surface. + /** \} */ - /** \brief \ru Конструктор по направляющей кривой. - \en Constructor by spine curve. \~ - \details \ru Конструктор по направляющей кривой.\n - \en Constructor by spine curve.\n \~ - \param[in] c - \ru Направляющая кривая - \en A spine curve \~ - \param[in] parallel - \ru Признак параллельного переноса - \en Attribute of parallel translation. \~ - \param[in] same - \ru Признак использования оригинала направляющей кривой, а не ее копии - \en Attribute of using the original of spine curve instead of its copy \~ - \param[in] vers - \ru Версия вычисления осей локальной системы координат. - \en Version of calculation the local coordinate system. \~ - */ - static MbSpine & Create( const MbCurve3D & c, bool parallel, bool same, VERSION vers = Math::DefaultMathVersion() ); - /** \brief \ru Конструктор по направляющей кривой и вектору ориентации матрицы преобразования. - \en Constructor by spine curve and a vector of transformation matrix orientation. \~ - \details \ru Конструктор по направляющей кривой и вектору ориентации матрицы преобразования.\n - \en Constructor by spine curve and a vector of transformation matrix orientation.\n \~ - \param[in] c - \ru Направляющая кривая - \en A spine curve \~ - \param[in] same - \ru Признак использования оригинала направляющей кривой, а не ее копии - \en Attribute of using the original of spine curve instead of its copy \~ - \param[in] direction - \ru Вектор ориентации матрицы преобразования. - \en Vector of transformation matrix orientation. \~ - \param[in] parallel - \ru Признак параллельного переноса - \en Attribute of parallel translation. \~ - \param[in] vers - \ru Версия вычисления осей локальной системы координат. - \en Version of calculation the local coordinate system. \~ - */ - static MbSpine * Create( const MbCurve3D & c, bool same, const MbVector3D & dir, bool parallel, VERSION vers = Math::DefaultMathVersion() ); - /** \brief \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования. - \en Constructor by spine curve and a curve of the vector of transformation matrix orientation. \~ - \details \ru Конструктор по направляющей кривой и кривой векторa ориентации матрицы преобразования.\n - \en Constructor by spine curve and a curve of the vector of transformation matrix orientation.\n \~ - \param[in] sp - \ru Направляющая кривая - \en A spine curve \~ - \param[in] sameS - \ru Признак использования оригинала направляющей кривой, а не ее копии - \en Attribute of using the original of spine curve instead of its copy \~ - \param[in] dc - \ru Кривая векторa ориентации матрицы преобразования - \en A curve of the vector of transformation matrix orientation \~ - \param[in] sameD - \ru Признак использования оригинала кривой векторa ориентации матрицы преобразования, а не ее копии - \en Attribute of using the original of a curve of the vector of transformation matrix orientation instead of its copy \~ - \param[in] parallel - \ru Признак параллельного переноса - \en Attribute of parallel translation. \~ - \param[in] vers - \ru Версия вычисления осей локальной системы координат. - \en Version of calculation the local coordinate system. \~ - */ - static MbSpine * Create( const MbCurve3D & sp, bool sameS, const MbCurve3D & dc, bool sameD, bool parallel, VERSION vers = Math::DefaultMathVersion() ); - private: - void InitDirection(); // \ru Вычисление direction; разбор частных случаев типа плоских кривых, дуг окружности и т.п. \en Calculation of "direction"; analysis of such special cases as planar curves, circle arcs etc. - bool CalculateSurface(); // \ru Для кривой на поверхности вять поверхность и двумерную кривую. \en Get "spineSurface" and "featureCurve" if "curve" is a curve on surface. void CheckParam( double & v ) const ; // \ru Функция переносит параметр v в область определения направляющей кривой. \en The function moves the parameter v inside the spine curve domain. - void CalculateVector1( double & v, bool ext, - MbVector3D & vector0, MbVector3D & vector1, MbVector3D & vector2, - MbVector3D & derive0, MbVector3D & derive1, MbVector3D & derive2 ) const; // \ru Вычисление векторов для матриц преобразования. \ en Vectors сalculation for matrix. - void CalculateVector2( double & v, bool ext, - MbVector3D & vector0, MbVector3D & vector1, MbVector3D & vector2, - MbVector3D & derive0, MbVector3D & derive1, MbVector3D & derive2, - MbVector3D & second0, MbVector3D & second1, MbVector3D & second2 ) const; // \ru Вычисление векторов для матриц преобразования. \ en Vectors сalculation for matrix. + void InitDirection(); // \ru Вычисление direction; разбор частных случаев типа плоских кривых, дуг окружности и т.п. \en Calculation of "direction"; analysis of such special cases as planar curves, circle arcs etc. + bool CalculateSpineSurface(); // \ru Для кривой на поверхности выделить поверхность и двумерную кривую. \en Get "spineSurface" and "featureCurve" if "curve" is a curve on surface. void CalculateDirection( double v, MbVector3D & direct ) const; // \ru Вектор ориентации матрицы преобразования. \en Vector of transformation matrix orientation. - bool InitOptionalCurve( bool exactOnly ); // \ru Вычисление optionalCurve; использовать, если нетривиальный случай. \en Calculation of "optionalCurve"; use if the case is nontrivial. void Multiplication( const MbVector3D & vector0, const MbVector3D & vector1, const MbVector3D & vector2, MbMatrix3D & matrix ) const; // \ru Определение матрицы преобразования. \en Determination of transformation matrix. DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpine ) OBVIOUS_PRIVATE_COPY( MbSpine ) -}; +}; // MbSpine IMPL_PERSISTENT_OPS( MbSpine ) @@ -478,7 +528,17 @@ MATH_FUNC (void) MakeSpines( const MbSpine & sp, SArray & items ); \param[in,out] items - \ru Массив направляющих. \en An array of spines. \~ */ // --- -MATH_FUNC (void) DeleteNonUsedSpines( SArray & items ); +template +void DeleteNonUsedSpines( SpineDataVector & spineDataItems ) +{ + if ( !spineDataItems.empty() ) { + for ( size_t i = spineDataItems.size(); i--; ) { + MbSpine * spine = &spineDataItems[i].spine; + ::DeleteItem( spine ); + } + spineDataItems.clear(); + } +} //------------------------------------------------------------------------------ @@ -511,10 +571,12 @@ MATH_FUNC (ThreeStates) InitSpineDirection( const MbCurve3D & curve, MbVector3D \en A curve. \~ \param[in] direction - \ru Вектор, который не должен совпадать с касательной к кривой. \en A vector which must not be coincident with the curve tangent. \~ + \param[in] version - \ru Версия. + \en Version. \~ \return \ru true, если вектор не совпадает с касательной к кривой. \en It equals true if the vector is not coincident with the curve tangent. \~ */ // --- -MATH_FUNC (bool) CheckSpineDirection( const MbCurve3D & curve, const MbVector3D & direction ); +MATH_FUNC (bool) CheckSpineDirection( const MbCurve3D & curve, const MbVector3D & direction, VERSION version = Math::DefaultMathVersion() ); #endif //__SURF_SPINE_H diff --git a/C3d/Include/surf_spiral_surface.h b/C3d/Include/surf_spiral_surface.h index e1f9bf2..762bc71 100644 --- a/C3d/Include/surf_spiral_surface.h +++ b/C3d/Include/surf_spiral_surface.h @@ -1,400 +1,401 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Спиральная поверхность. - \en Spiral surface. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SURF_SPIRAL_SURFACE_H -#define __SURF_SPIRAL_SURFACE_H - - -#include -#include -#include - - -class MATH_CLASS MbConeSpiral; - - -//------------------------------------------------------------------------------ -/** \brief \ru Спиральная поверхность. - \en Spiral surface. \~ - \details \ru Спиральная поверхность получена путем движения образующей кривой curve по цилиндрической спирали. - Спиральная поверхность является частным случаем кинематической поверхности. - Ось спирали направлена вдоль оси Z локальной системы координат. - Второй параметр поверхности отсчитывается от оси position.axisX локальной системы координат. - Радиус-вектор поверхности описывается векторной функцией \n - r(u,v) = position.origin + (M(v) (curve(u) - origin)), \n - где M(v) - матрица вращения. \n - Первый параметр поверхности совпадает с параметром образующей кривой. - Второй параметр поверхности совпадает с углом поворота точки спирали вокруг её оси. - \en A spiral surface is obtained by moving of a generating curve along a cylindrical spiral. - Spiral surface is a special case of sweep surface. - A spiral axis is directed along the Z-axis of the local coordinate system. - The second parameter of a surface is measured from the axis "position.axisX" of the local coordinate system. - Radius-vector of the surface is described by the vector function \n - r(u,v) = position.origin + (M(v) (curve(u) - origin)), \n - where M(v) is rotation matrix. \n - The first surface parameter coincides with the parameter of generatrix. - The second surface parameter coincides with rotation angle of a spiral point around its axis. \~ - \ingroup Surfaces -*/ -// --- -class MATH_CLASS MbSpiralSurface : public MbSweptSurface { -private: - MbPlacement3D position; ///< \ru Местная система координат (position.axisZ - ось спирали). \en Local coordinate system ('position.axisZ' is axis of spiral). - double radius; ///< \ru Радиус спирали. \en A spiral radius. - double step; ///< \ru Шаг спирали. \en A pitch of spiral. - MbCartPoint3D origin; ///< \ru Центр тяжести образующей. \en Center of gravity of generatrix. - MbMatrix3D into; ///< \ru Матрица преобразования в систему position. \en Matrix of transformation to the system 'position'. - MbMatrix3D from; ///< \ru Матрица преобразования из системы position. \en Matrix of transformation from the system 'position'. - double stepd2pi; ///< \ru Шаг приходящийся на период. \en A step corresponding to period. - -public: - - /** \brief \ru Конструктор по образующей, локальной системе координат, радиусу спирали, шагу спирали. - \en Constructor by generatrix, local coordinate system, spiral radius and spiral pitch. \~ - \details \ru Конструктор по образующей, локальной системе координат, радиусу спирали, шагу спирали. - \en Constructor by generatrix, local coordinate system, spiral radius and spiral pitch. \~ - \param[in] c - \ru Образующая - \en Generatrix \~ - \param[in] pos - \ru Локальная система координат - \en Local coordinate system \~ - \param[in] r - \ru Радиус спирали - \en Spiral radius \~ - \param[in] s - \ru Шаг спирали - \en Spiral pitch \~ - \param[in] t1 - \ru Начальный параметр спирали - \en Start parameter of spiral \~ - \param[in] t2 - \ru Конечный параметр спирали - \en End parameter of spiral \~ - \param[in] sameCurve - \ru Признак использования оригинала образующей, а не ее копии - \en Attribute of using the original of generatrix instead of its copy. \~ - */ - MbSpiralSurface( const MbCurve3D & c, const MbPlacement3D & pos, double r, double s, double t1, double t2, - bool sameCurve ); - - /** \brief \ru Конструктор по образующей и спирали. - \en Constructor by generatrix and spiral. \~ - \details \ru Конструктор по образующей и спирали. - \en Constructor by generatrix and spiral. \~ - \param[in] c - \ru Образующая - \en Generatrix \~ - \param[in] s - \ru Спираль - \en Spiral \~ - \param[in] sameCurve - \ru Признак использования оригинала образующей, а не ее копии - \en Attribute of using the original of generatrix instead of its copy. \~ - */ - MbSpiralSurface( const MbCurve3D & c, const MbConeSpiral & s, bool sameCurve ); - -protected: - MbSpiralSurface( const MbSpiralSurface &, MbRegDuplicate * ); -private: - MbSpiralSurface( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. -public: - virtual ~MbSpiralSurface(); - -public: - VISITING_CLASS( MbSpiralSurface ); - - /** \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 Сделать копию элемента. \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 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 Функции для работы в области определения поверхности - Функции PointOn, Derive... поверхностей корректируют параметры - при выходе их за пределы прямоугольной области определения параметров. - \en \name Functions for working at surface domain - Functions PointOn, Derive... correct parameters - when getting out of rectangular domain bounds. - \{ */ - virtual void PointOn ( double & u, double & v, MbCartPoint3D & ) const; // \ru Точка на поверхности. \en A point on surface. - virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u. \en First derivative with respect to u. - virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v. \en First derivative with respect to v. - virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. - virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. - virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. - virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; - virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; - virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; - virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; - /** \} */ - /** \ru \name Функции для работы внутри и вне области определения поверхности - функции _PointOn, _Derive... поверхностей не корректируют - параметры при выходе их за пределы прямоугольной области определения параметров. - \en \name Functions for working inside and outside the surface domain. - functions _PointOn, _Derive... of surfaces don't correct - parameters when getting out of rectangular domain bounds. - \{ */ - virtual void _PointOn ( double u, double v, MbCartPoint3D & ) const; // \ru Точка на расширенной поверхности. \en A point on extended surface. - virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en First derivative with respect to u. - virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en First derivative with respect to v. - virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. - virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. - virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. - virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; - virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; - virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; - virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; - /** \} */ - /** \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 on surface - \{ */ - virtual double StepU ( double u, double v, double sag ) const; // \ru Вычисление шага по u по заданной стрелке прогиба. \en Calculation of the parameter step in u direction by the sag. - virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. - virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. - virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. - virtual double MetricStepU ( double u, double v, double length ) const; // \ru Вычисление шага по u по заданной длине. \en Calculation of the parameter step in u direction by the given length. - virtual double MetricStepV ( double u, double v, double length ) const; // \ru Вычисление шага по v по заданной длине. \en Calculation of the parameter step in v direction by the given length. - virtual size_t GetUCount() const; - virtual size_t GetVCount() const; - /** \} */ - /** \ru \name Общие функции поверхности - \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 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. - virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности \en Creation of an offset surface - - 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 the projection of a point onto the surface. - virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; - - // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. - virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; - virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; - - // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces are similar to merge. - 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 region to the parametric region of 'surf'. - virtual bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const; - - // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. - virtual void GetTesselation( const MbStepData & stepData, - double u1, double u2, double v1, double v2, - SArray & uu, SArray & vv ) const; - - virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. - virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. - - virtual bool IsLineU() const; // \ru Если true все производные по U выше первой равны нулю. \en If it equals true then all derivatives with respect to u which have more than first order are equal to null. - /** \} */ - /** \ru \name Функции спиральной поверхности - \en \name Functions of spiral surface - \{ */ - - /** \brief \ru Определение матрицы переноса для образующей. - \en Determination of a transfer matrix for generatrix. \~ - \details \ru Определение матрицы при переносе образующей - из параметра vmin в параметр v. - \en Determination of matrix when transferring the generatrix - from the parameter vmin to the parameter v. \~ - \param[in] v - \ru Новый параметр на спирали - \en A new parameter on the spiral \~ - \param[out] matr - \ru Матрица-резцультат - \en A matrix - the result \~ - */ - void TransformMatrix( double v, MbMatrix3D & matr ) const; - - /// \ru Внутренний радиус витков. \en Internal radius of coils. - double GetSpiralR() const { return radius; } - /// \ru Внутренний шаг витков. \en Internal pitch of coils. - double GetStep() const { return step; } - - /// \ru Физический радиус витков. \en Physical radius of coils. - double GetSpiralRadius() const; - /// \ru Физический шаг витков. \en Physical pitch of coils. - double GetSpiralStep() const; - - /// \ru Местная система координат (ось position.axisZ - ось спирали). \en Local coordinate system ('position.axisZ' is axis of spiral). - const MbPlacement3D & GetPlacement() const { return position; } - /// \ru Центр тяжести образующей. \en Center of gravity of generatrix. - const MbCartPoint3D & GetOrigin() const { return origin; } - - /// \ru Построить спираль. \en Construct a spiral. - MbConeSpiral & CreateSpiral() const; - - /// \ru Является ли локальная система координат поверхности ортонормированной. \en Whether the local coordinate system of a surface is orthonormalized. - bool IsPositionNormal() const { return ( position.IsNormal() ); } - /// \ru Является ли локальная система координат поверхности ортогональной с равными по длине осями X,Y. \en Whether the local coordinate system of a surface is orthogonal with X and Y axes equal by length. - bool IsPositionCircular() const { return ( position.IsCircular() ); } - /// \ru Является ли локальная система координат поверхности ортогональной и изотропной по осям. \en Whether the local coordinate system of a surface is orthogonal and isotropic by the axes. - bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } - /// \ru Является ли образующая кривая окружностью. \en Whether a generatrix is a circle. - bool IsCircleType() const; - - /// \ru Оценить рабочий диапазон для проецирования. \en Estimate the projection range along V. - bool GetProjectionRange( const MbCartPoint3D & pnt, bool ext, const MbRect2D * userRange, MbRect2D & resRange ) const; - /// \ru Скорректировать разбивку для проецирования точки. \en Correct the number of splittings by v-parameter for point projection. - bool CorrectVCount( double vbeg, double vend, size_t & cntv ) const; - /** \} */ -private: - - void Init(); // \ru Инициализация. \en Initialization. - inline void CheckParam ( double & v ) const; - inline void RotateVector ( const double & sin_V, const double & cos_V, MbVector3D & ) const; - inline void RotateDeriveV ( const double & sin_V, const double & cos_V, MbVector3D & ) const; - inline void RotateDeriveVV ( const double & sin_V, const double & cos_V, MbVector3D & ) const; - inline void RotateDeriveVVV( const double & sin_V, const double & cos_V, MbVector3D & ) const; - inline void DirectrixPointOn ( const double & v, const double & sinV, const double & cosV, MbCartPoint3D & ) const; - inline void DirectrixDeriveV ( const double & sinV, const double & cosV, MbVector3D & ) const; - inline void DirectrixDeriveVV ( const double & sinV, const double & cosV, MbVector3D & ) const; - inline void DirectrixDeriveVVV( const double & sinV, const double & cosV, MbVector3D & ) const; - - void operator = ( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. - - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpiralSurface ) -}; - -IMPL_PERSISTENT_OPS( MbSpiralSurface ) - -//------------------------------------------------------------------------------ -// \ru Проверить параметр \en Check parameter -// --- -inline void MbSpiralSurface::CheckParam( double & v ) const -{ - if ( v < vmin ) - v = vmin; - else - if ( v > vmax ) - v = vmax; -} - - -//------------------------------------------------------------------------------ -// \ru Выдать физический радиус спирали \en Get physical radius of spiral -// --- -inline double MbSpiralSurface::GetSpiralStep() const -{ - if ( position.IsNormal() ) - return step; - else if ( position.IsOrthogonal() ) { - return (step * position.GetAxisZ().Length()); - } - return 0.0; -} - - -//------------------------------------------------------------------------------ -// \ru Поворот вектора вокруг оси спирали \en Rotation of vector around spiral axis -// --- -inline void MbSpiralSurface::RotateVector( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const -{ - _vector.Transform( into ); - double x = (_vector.x * cos_V) - (_vector.y * sin_V); - double y = (_vector.x * sin_V) + (_vector.y * cos_V); - _vector.x = x; - _vector.y = y; - _vector.Transform( from ); -} - - -//------------------------------------------------------------------------------- -// \ru Первая производная поворота вектора вокруг оси спирали \en First derivative of vector rotation around the spiral axis -// --- -inline void MbSpiralSurface::RotateDeriveV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const -{ - _vector.Transform( into ); - double x = - (_vector.x * sin_V) - (_vector.y * cos_V); - double y = (_vector.x * cos_V) - (_vector.y * sin_V); - _vector.x = x; - _vector.y = y; - _vector.z = 0.0; - _vector.Transform( from ); -} - - -//------------------------------------------------------------------------------- -// \ru Вторая производная поворота вектора вокруг оси спирали \en Second derivative of vector rotation around spiral axis -// --- -inline void MbSpiralSurface::RotateDeriveVV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const -{ - _vector.Transform( into ); - double x = - (_vector.x * cos_V) + (_vector.y * sin_V); - double y = - (_vector.x * sin_V) - (_vector.y * cos_V); - _vector.x = x; - _vector.y = y; - _vector.z = 0.0; - _vector.Transform( from ); -} - - -//------------------------------------------------------------------------------- -// \ru Третья производная поворота вектора вокруг оси спирали \en Third derivative of vector rotation around spiral axis -// --- -inline void MbSpiralSurface::RotateDeriveVVV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const -{ - _vector.Transform( into ); - double x = (_vector.x * sin_V) + (_vector.y * cos_V); - double y = - (_vector.x * cos_V) + (_vector.y * sin_V); - _vector.x = x; - _vector.y = y; - _vector.z = 0.0; - _vector.Transform( from ); -} - - -//------------------------------------------------------------------------------ -// \ru Точка спирали \en A point of spiral -// --- -inline void MbSpiralSurface::DirectrixPointOn( const double & v, const double & sinV, const double & cosV, MbCartPoint3D & p ) const { - p = position.GetOrigin(); - p.Add( position.GetAxisZ(), (stepd2pi * v), position.GetAxisX(), (radius * cosV), position.GetAxisY(), (radius * sinV) ); -} - - -//------------------------------------------------------------------------------- -// \ru Первая производная спирали \en First derivative of spiral -// --- -inline void MbSpiralSurface::DirectrixDeriveV( const double & sinV, const double & cosV, MbVector3D & d ) const { - d.Set( position.GetAxisZ(), stepd2pi, position.GetAxisX(), -(radius * sinV), position.GetAxisY(), (radius * cosV) ); -} - - -//------------------------------------------------------------------------------- -// \ru Вторая производная спирали \en Second derivative of spiral -// --- -inline void MbSpiralSurface::DirectrixDeriveVV( const double & sinV, const double & cosV, MbVector3D & d ) const { - d.Set( position.GetAxisX(), -(radius * cosV), position.GetAxisY(), -(radius * sinV) ); -} - - -//------------------------------------------------------------------------------- -// \ru Третья производная спирали \en Third derivative of spiral -// --- -inline void MbSpiralSurface::DirectrixDeriveVVV( const double & sinV, const double & cosV, MbVector3D & d ) const { - d.Set( position.GetAxisX(), (radius * sinV), position.GetAxisY(), -(radius * cosV) ); -} - - -#endif // __SURF_SPIRAL_SURFACE_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Спиральная поверхность. + \en Spiral surface. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SURF_SPIRAL_SURFACE_H +#define __SURF_SPIRAL_SURFACE_H + + +#include +#include +#include +#include + + +class MATH_CLASS MbConeSpiral; + + +//------------------------------------------------------------------------------ +/** \brief \ru Спиральная поверхность. + \en Spiral surface. \~ + \details \ru Спиральная поверхность получена путем движения образующей кривой curve по цилиндрической спирали. + Спиральная поверхность является частным случаем кинематической поверхности. + Ось спирали направлена вдоль оси Z локальной системы координат. + Второй параметр поверхности отсчитывается от оси position.axisX локальной системы координат. + Радиус-вектор поверхности описывается векторной функцией \n + r(u,v) = position.origin + (M(v) (curve(u) - origin)), \n + где M(v) - матрица вращения. \n + Первый параметр поверхности совпадает с параметром образующей кривой. + Второй параметр поверхности совпадает с углом поворота точки спирали вокруг её оси. + \en A spiral surface is obtained by moving of a generating curve along a cylindrical spiral. + Spiral surface is a special case of sweep surface. + A spiral axis is directed along the Z-axis of the local coordinate system. + The second parameter of a surface is measured from the axis "position.axisX" of the local coordinate system. + Radius-vector of the surface is described by the vector function \n + r(u,v) = position.origin + (M(v) (curve(u) - origin)), \n + where M(v) is rotation matrix. \n + The first surface parameter coincides with the parameter of generatrix. + The second surface parameter coincides with rotation angle of a spiral point around its axis. \~ + \ingroup Surfaces +*/ +// --- +class MATH_CLASS MbSpiralSurface : public MbSweptSurface { +private: + MbPlacement3D position; ///< \ru Местная система координат (position.axisZ - ось спирали). \en Local coordinate system ('position.axisZ' is axis of spiral). + double radius; ///< \ru Радиус спирали. \en A spiral radius. + double step; ///< \ru Шаг спирали. \en A pitch of spiral. + MbCartPoint3D origin; ///< \ru Центр тяжести образующей. \en Center of gravity of generatrix. + MbMatrix3D into; ///< \ru Матрица преобразования в систему position. \en Matrix of transformation to the system 'position'. + MbMatrix3D from; ///< \ru Матрица преобразования из системы position. \en Matrix of transformation from the system 'position'. + double stepd2pi; ///< \ru Шаг приходящийся на период. \en A step corresponding to period. + +public: + + /** \brief \ru Конструктор по образующей, локальной системе координат, радиусу спирали, шагу спирали. + \en Constructor by generatrix, local coordinate system, spiral radius and spiral pitch. \~ + \details \ru Конструктор по образующей, локальной системе координат, радиусу спирали, шагу спирали. + \en Constructor by generatrix, local coordinate system, spiral radius and spiral pitch. \~ + \param[in] c - \ru Образующая + \en Generatrix \~ + \param[in] pos - \ru Локальная система координат + \en Local coordinate system \~ + \param[in] r - \ru Радиус спирали + \en Spiral radius \~ + \param[in] s - \ru Шаг спирали + \en Spiral pitch \~ + \param[in] t1 - \ru Начальный параметр спирали + \en Start parameter of spiral \~ + \param[in] t2 - \ru Конечный параметр спирали + \en End parameter of spiral \~ + \param[in] sameCurve - \ru Признак использования оригинала образующей, а не ее копии + \en Attribute of using the original of generatrix instead of its copy. \~ + */ + MbSpiralSurface( const MbCurve3D & c, const MbPlacement3D & pos, double r, double s, double t1, double t2, + bool sameCurve ); + + /** \brief \ru Конструктор по образующей и спирали. + \en Constructor by generatrix and spiral. \~ + \details \ru Конструктор по образующей и спирали. + \en Constructor by generatrix and spiral. \~ + \param[in] c - \ru Образующая + \en Generatrix \~ + \param[in] s - \ru Спираль + \en Spiral \~ + \param[in] sameCurve - \ru Признак использования оригинала образующей, а не ее копии + \en Attribute of using the original of generatrix instead of its copy. \~ + */ + MbSpiralSurface( const MbCurve3D & c, const MbConeSpiral & s, bool sameCurve ); + +protected: + MbSpiralSurface( const MbSpiralSurface &, MbRegDuplicate * ); +private: + MbSpiralSurface( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. +public: + virtual ~MbSpiralSurface(); + +public: + VISITING_CLASS( MbSpiralSurface ); + + /** \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 Сделать копию элемента. \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 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 Функции для работы в области определения поверхности + Функции PointOn, Derive... поверхностей корректируют параметры + при выходе их за пределы прямоугольной области определения параметров. + \en \name Functions for working at surface domain + Functions PointOn, Derive... correct parameters + when getting out of rectangular domain bounds. + \{ */ + virtual void PointOn ( double & u, double & v, MbCartPoint3D & ) const; // \ru Точка на поверхности. \en A point on surface. + virtual void DeriveU ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по u. \en First derivative with respect to u. + virtual void DeriveV ( double & u, double & v, MbVector3D & ) const; // \ru Первая производная по v. \en First derivative with respect to v. + virtual void DeriveUU ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. + virtual void DeriveVV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. + virtual void DeriveUV ( double & u, double & v, MbVector3D & ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. + virtual void DeriveUUU( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUUV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; + virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; + /** \} */ + /** \ru \name Функции для работы внутри и вне области определения поверхности + функции _PointOn, _Derive... поверхностей не корректируют + параметры при выходе их за пределы прямоугольной области определения параметров. + \en \name Functions for working inside and outside the surface domain. + functions _PointOn, _Derive... of surfaces don't correct + parameters when getting out of rectangular domain bounds. + \{ */ + virtual void _PointOn ( double u, double v, MbCartPoint3D & ) const; // \ru Точка на расширенной поверхности. \en A point on extended surface. + virtual void _DeriveU ( double u, double v, MbVector3D & ) const; // \ru Первая производная по u. \en First derivative with respect to u. + virtual void _DeriveV ( double u, double v, MbVector3D & ) const; // \ru Первая производная по v. \en First derivative with respect to v. + virtual void _DeriveUU ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. + virtual void _DeriveVV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по v. \en Second derivative with respect to v. + virtual void _DeriveUV ( double u, double v, MbVector3D & ) const; // \ru Вторая производная по uv. \en Second derivative with respect to u and v. + virtual void _DeriveUUU( double u, double v, MbVector3D & ) const; + virtual void _DeriveUUV( double u, double v, MbVector3D & ) const; + virtual void _DeriveUVV( double u, double v, MbVector3D & ) const; + virtual void _DeriveVVV( double u, double v, MbVector3D & ) const; + /** \} */ + /** \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 on surface + \{ */ + virtual double StepU ( double u, double v, double sag ) const; // \ru Вычисление шага по u по заданной стрелке прогиба. \en Calculation of the parameter step in u direction by the sag. + virtual double StepV ( double u, double v, double sag ) const; // \ru Вычисление шага по v по заданной стрелке прогиба. \en Calculation of the parameter step in v direction by the sag. + virtual double DeviationStepU( double u, double v, double angle ) const; // \ru Вычисление шага по u по заданному углу отклонения. \en Calculation of the parameter step in u direction by the deviation angle. + virtual double DeviationStepV( double u, double v, double angle ) const; // \ru Вычисление шага по v по заданному углу отклонения. \en Calculation of the parameter step in v direction by the deviation angle. + virtual double MetricStepU ( double u, double v, double length ) const; // \ru Вычисление шага по u по заданной длине. \en Calculation of the parameter step in u direction by the given length. + virtual double MetricStepV ( double u, double v, double length ) const; // \ru Вычисление шага по v по заданной длине. \en Calculation of the parameter step in v direction by the given length. + virtual size_t GetUCount() const; + virtual size_t GetVCount() const; + /** \} */ + /** \ru \name Общие функции поверхности + \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 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. + virtual MbSurface * Offset( double d, bool same ) const; // \ru Создание эквидистантной поверхности \en Creation of an offset surface + + 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 the projection of a point onto the surface. + virtual bool NearPointProjection ( const MbCartPoint3D & pnt, double & u, double & v, bool ext, MbRect2D * uvRange = NULL ) const; + + // \ru Построить касательные и нормальные плейсменты конструктивных плоскостей. \en Construct tangent and normal placements of constructive planes. + virtual bool CreateNormalPlacements ( const MbVector3D & axisZ, double angle, SArray & places ) const; + virtual bool CreateTangentPlacements( const MbVector3D & axisZ, SArray & places ) const; + + // \ru Подобные ли поверхности для объединения (слива). \en Whether the surfaces are similar to merge. + 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 region to the parametric region of 'surf'. + virtual bool GetMatrixToSurface( const MbSurface & surf, MbMatrix & matr, VERSION version, double precision = METRIC_PRECISION ) const; + + // \ru Определение разбивки параметрической области поверхности вертикалями и горизонталями. \en Determine a splitting of parametric region of a surface by verticals and horizontals. + virtual void GetTesselation( const MbStepData & stepData, + double u1, double u2, double v1, double v2, + SArray & uu, SArray & vv ) const; + + virtual size_t GetUMeshCount() const; // \ru Выдать количество полигонов по u. \en Get the number of polygons in u-direction. + virtual size_t GetVMeshCount() const; // \ru Выдать количество полигонов по v. \en Get the number of polygons in v-direction. + + virtual bool IsLineU() const; // \ru Если true все производные по U выше первой равны нулю. \en If it equals true then all derivatives with respect to u which have more than first order are equal to null. + /** \} */ + /** \ru \name Функции спиральной поверхности + \en \name Functions of spiral surface + \{ */ + + /** \brief \ru Определение матрицы переноса для образующей. + \en Determination of a transfer matrix for generatrix. \~ + \details \ru Определение матрицы при переносе образующей + из параметра vmin в параметр v. + \en Determination of matrix when transferring the generatrix + from the parameter vmin to the parameter v. \~ + \param[in] v - \ru Новый параметр на спирали + \en A new parameter on the spiral \~ + \param[out] matr - \ru Матрица-резцультат + \en A matrix - the result \~ + */ + void TransformMatrix( double v, MbMatrix3D & matr ) const; + + /// \ru Внутренний радиус витков. \en Internal radius of coils. + double GetSpiralR() const { return radius; } + /// \ru Внутренний шаг витков. \en Internal pitch of coils. + double GetStep() const { return step; } + + /// \ru Физический радиус витков. \en Physical radius of coils. + double GetSpiralRadius() const; + /// \ru Физический шаг витков. \en Physical pitch of coils. + double GetSpiralStep() const; + + /// \ru Местная система координат (ось position.axisZ - ось спирали). \en Local coordinate system ('position.axisZ' is axis of spiral). + const MbPlacement3D & GetPlacement() const { return position; } + /// \ru Центр тяжести образующей. \en Center of gravity of generatrix. + const MbCartPoint3D & GetOrigin() const { return origin; } + + /// \ru Построить спираль. \en Construct a spiral. + MbConeSpiral * CreateSpiral() const { return MbConeSpiral::Create( radius, step, position, vmin, vmax ); } + + /// \ru Является ли локальная система координат поверхности ортонормированной. \en Whether the local coordinate system of a surface is orthonormalized. + bool IsPositionNormal() const { return ( position.IsNormal() ); } + /// \ru Является ли локальная система координат поверхности ортогональной с равными по длине осями X,Y. \en Whether the local coordinate system of a surface is orthogonal with X and Y axes equal by length. + bool IsPositionCircular() const { return ( position.IsCircular() ); } + /// \ru Является ли локальная система координат поверхности ортогональной и изотропной по осям. \en Whether the local coordinate system of a surface is orthogonal and isotropic by the axes. + bool IsPositionIsotropic() const { return ( position.IsIsotropic() ); } + /// \ru Является ли образующая кривая окружностью. \en Whether a generatrix is a circle. + bool IsCircleType() const; + + /// \ru Оценить рабочий диапазон для проецирования. \en Estimate the projection range along V. + bool GetProjectionRange( const MbCartPoint3D & pnt, bool ext, const MbRect2D * userRange, MbRect2D & resRange ) const; + /// \ru Скорректировать разбивку для проецирования точки. \en Correct the number of splittings by v-parameter for point projection. + bool CorrectVCount( double vbeg, double vend, size_t & cntv ) const; + /** \} */ +private: + + void Init(); // \ru Инициализация. \en Initialization. + inline void CheckParam ( double & v ) const; + inline void RotateVector ( const double & sin_V, const double & cos_V, MbVector3D & ) const; + inline void RotateDeriveV ( const double & sin_V, const double & cos_V, MbVector3D & ) const; + inline void RotateDeriveVV ( const double & sin_V, const double & cos_V, MbVector3D & ) const; + inline void RotateDeriveVVV( const double & sin_V, const double & cos_V, MbVector3D & ) const; + inline void DirectrixPointOn ( const double & v, const double & sinV, const double & cosV, MbCartPoint3D & ) const; + inline void DirectrixDeriveV ( const double & sinV, const double & cosV, MbVector3D & ) const; + inline void DirectrixDeriveVV ( const double & sinV, const double & cosV, MbVector3D & ) const; + inline void DirectrixDeriveVVV( const double & sinV, const double & cosV, MbVector3D & ) const; + + void operator = ( const MbSpiralSurface & ); // \ru Не реализовано. \en Not implemented. + + DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSpiralSurface ) +}; + +IMPL_PERSISTENT_OPS( MbSpiralSurface ) + +//------------------------------------------------------------------------------ +// \ru Проверить параметр \en Check parameter +// --- +inline void MbSpiralSurface::CheckParam( double & v ) const +{ + if ( v < vmin ) + v = vmin; + else + if ( v > vmax ) + v = vmax; +} + + +//------------------------------------------------------------------------------ +// \ru Выдать физический радиус спирали \en Get physical radius of spiral +// --- +inline double MbSpiralSurface::GetSpiralStep() const +{ + if ( position.IsNormal() ) + return step; + else if ( position.IsOrthogonal() ) { + return (step * position.GetAxisZ().Length()); + } + return 0.0; +} + + +//------------------------------------------------------------------------------ +// \ru Поворот вектора вокруг оси спирали \en Rotation of vector around spiral axis +// --- +inline void MbSpiralSurface::RotateVector( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const +{ + _vector.Transform( into ); + double x = (_vector.x * cos_V) - (_vector.y * sin_V); + double y = (_vector.x * sin_V) + (_vector.y * cos_V); + _vector.x = x; + _vector.y = y; + _vector.Transform( from ); +} + + +//------------------------------------------------------------------------------- +// \ru Первая производная поворота вектора вокруг оси спирали \en First derivative of vector rotation around the spiral axis +// --- +inline void MbSpiralSurface::RotateDeriveV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const +{ + _vector.Transform( into ); + double x = - (_vector.x * sin_V) - (_vector.y * cos_V); + double y = (_vector.x * cos_V) - (_vector.y * sin_V); + _vector.x = x; + _vector.y = y; + _vector.z = 0.0; + _vector.Transform( from ); +} + + +//------------------------------------------------------------------------------- +// \ru Вторая производная поворота вектора вокруг оси спирали \en Second derivative of vector rotation around spiral axis +// --- +inline void MbSpiralSurface::RotateDeriveVV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const +{ + _vector.Transform( into ); + double x = - (_vector.x * cos_V) + (_vector.y * sin_V); + double y = - (_vector.x * sin_V) - (_vector.y * cos_V); + _vector.x = x; + _vector.y = y; + _vector.z = 0.0; + _vector.Transform( from ); +} + + +//------------------------------------------------------------------------------- +// \ru Третья производная поворота вектора вокруг оси спирали \en Third derivative of vector rotation around spiral axis +// --- +inline void MbSpiralSurface::RotateDeriveVVV( const double & sin_V, const double & cos_V, MbVector3D & _vector ) const +{ + _vector.Transform( into ); + double x = (_vector.x * sin_V) + (_vector.y * cos_V); + double y = - (_vector.x * cos_V) + (_vector.y * sin_V); + _vector.x = x; + _vector.y = y; + _vector.z = 0.0; + _vector.Transform( from ); +} + + +//------------------------------------------------------------------------------ +// \ru Точка спирали \en A point of spiral +// --- +inline void MbSpiralSurface::DirectrixPointOn( const double & v, const double & sinV, const double & cosV, MbCartPoint3D & p ) const { + p = position.GetOrigin(); + p.Add( position.GetAxisZ(), (stepd2pi * v), position.GetAxisX(), (radius * cosV), position.GetAxisY(), (radius * sinV) ); +} + + +//------------------------------------------------------------------------------- +// \ru Первая производная спирали \en First derivative of spiral +// --- +inline void MbSpiralSurface::DirectrixDeriveV( const double & sinV, const double & cosV, MbVector3D & d ) const { + d.Set( position.GetAxisZ(), stepd2pi, position.GetAxisX(), -(radius * sinV), position.GetAxisY(), (radius * cosV) ); +} + + +//------------------------------------------------------------------------------- +// \ru Вторая производная спирали \en Second derivative of spiral +// --- +inline void MbSpiralSurface::DirectrixDeriveVV( const double & sinV, const double & cosV, MbVector3D & d ) const { + d.Set( position.GetAxisX(), -(radius * cosV), position.GetAxisY(), -(radius * sinV) ); +} + + +//------------------------------------------------------------------------------- +// \ru Третья производная спирали \en Third derivative of spiral +// --- +inline void MbSpiralSurface::DirectrixDeriveVVV( const double & sinV, const double & cosV, MbVector3D & d ) const { + d.Set( position.GetAxisX(), (radius * sinV), position.GetAxisY(), -(radius * cosV) ); +} + + +#endif // __SURF_SPIRAL_SURFACE_H diff --git a/C3d/Include/surf_spline_surface.h b/C3d/Include/surf_spline_surface.h index 0fe4664..3c5190b 100644 --- a/C3d/Include/surf_spline_surface.h +++ b/C3d/Include/surf_spline_surface.h @@ -31,7 +31,7 @@ class MbSplineWorkingData; \en Weights of a NURBS surface. \~ \ingroup Data_Structures */ // --- -class MbWeightMatrix { +class MATH_CLASS MbWeightMatrix { private: size_t linesCnt; ///< \ru Количество строк матрицы. \en A number of matrix lines. size_t columnsCnt; ///< \ru Количество столбцов матрицы. \en A number of matrix columns. @@ -44,52 +44,52 @@ public: MbWeightMatrix( const MbWeightMatrix & wm ); ~MbWeightMatrix() {} public: - // Количество строк. + /// \ru Количество строк. \en Number of lines. size_t Lines() const { return linesCnt; } - // Количество столбцов. + /// \ru Количество столбцов. \en Number of columns. size_t Columns() const { return columnsCnt; } - // Общий вес? + /// \ru Общий вес? \en Is it used a common weight? bool IsCommonWeight() const; - // Инициализация по общему весу. + /// \ru Инициализация по общему весу. \en Initialize by common weight. bool InitWeights( double wt, size_t linesCnt, size_t columnsCnt ); - // Инициализация по матрице весов. + /// \ru Инициализация по матрице весов. \en Initialize by weights array. bool InitWeights( const Array2 & wts ); - // Инициализация по матрице весов. + /// \ru Инициализация по матрице весов. \en Initialize by weights array. void InitWeights( const MbWeightMatrix & wm ); - // Получить веса. + /// \ru Получить веса. \en . void GetWeights( Array2 & wts ) const; - // Установить веса. + /// \ru Установить веса. \en Get weights array. bool SetWeights( const Array2 & wts ) { return InitWeights( wts ); } - // Получить вес. + /// \ru Получить вес. \en Get a weight by indices. double GetWeight( size_t lineIndex, size_t columnIndex ) const; - // Установить вес. + /// \ru Установить вес. \en Set weight. bool SetWeight( size_t lineIndex, size_t columnIndex, double wt ); - // Вставить строку. + /// \ru Вставить строку. \en Insert a line. void InsertLine ( size_t k, double wt = 1.0 ); - // Вставить столбец. + /// \ru Вставить столбец \en Insert a column. void InsertColumn( size_t k, double wt = 1.0 ); - // Добавить строку. + /// \ru Добавить строку. \en Add a line. void AddLine( double wt = 1.0 ) { InsertLine( linesCnt, wt ); } - // Добавить столбец. + /// \ru Добавить столбец. \en Add a column. void AddColumn( double wt = 1.0 ) { InsertColumn( columnsCnt, wt ); }; - // Удалить строку. + /// \ru Удалить строку. \en Delete line by line index. void RemoveLine( size_t k ); - // Удалить столбец. + /// \ru Удалить столбец. \en Delete column by column index. void RemoveColumn( size_t k ); - // Получить указатель на строку, если не используется общий вес. Иначе возвращает NULL. + /// \ru Получить указатель на строку, если не используется общий вес. Иначе возвращает нулевой указатель. \en Get a pointer to a string if the common weight is not used. Otherwise returns a null pointer. const double * _GetLine( size_t k ) const; - // Можно ли оптимизировать расход памяти. + /// \ru Можно ли оптимизировать расход памяти? \en Is it possible to adjust memory of weights array? bool CanAdjust( const Array2 & wts ) const; - // Оптимизировать расход памяти. + /// \ru Оптимизировать расход памяти. \en Adjust memory of weights array. bool Adjust(); - // Оператор присваивания. + /// \ru Оператор присваивания. \en Assignment operator. MbWeightMatrix & operator = ( const MbWeightMatrix & wm ) { InitWeights( wm ); return *this; } - // Оператор присваивания. + /// \ru Оператор присваивания. \en Assignment operator. MbWeightMatrix & operator = ( const Array2 & wm ) { InitWeights( wm ); return *this; } protected: - // Сформировать полную матрицу весов, если используется общий вес. + /// \ru Сформировать полную матрицу весов, если используется общий вес. \en Fill full weights array if common weight is used. bool FillArray2(); private: MbWeightMatrix( const Array2 & ); // не реализовано, запрещено @@ -181,8 +181,13 @@ public: \param[in] initVKnots - \ru Узловой вектор по v. \en A knot vector by V. \~ */ - MbSplineSurface( size_t uDeg, size_t vDeg, bool uCls, bool vCls, const Array2 & initPoints, - const SArray & initUKnots, const SArray & initVKnots ); + MbSplineSurface( size_t uDeg, + size_t vDeg, + bool uCls, + bool vCls, + const Array2 & initPoints, + const SArray & initUKnots, + const SArray & initVKnots ); /** \brief \ru Конструктор NURBS поверхности. \en Constructor of NURBS surface. \~ @@ -205,8 +210,14 @@ public: \param[in] initVKnots - \ru Узловой вектор по v. \en A knot vector by V. \~ */ - MbSplineSurface( size_t uDeg, size_t vDeg, bool uCls, bool vCls, const Array2 & initPoints, const Array2 & initWeights, - const SArray & initUKnots, const SArray & initVKnots ); + MbSplineSurface( size_t uDeg, + size_t vDeg, + bool uCls, + bool vCls, + const Array2 & initPoints, + const Array2 & initWeights, + const SArray & initUKnots, + const SArray & initVKnots ); /** \brief \ru Конструктор NURBS поверхности по четырем углам при обходе против часовой стрелки. \en Constructor of NURBS surface by four angles of counterclockwise traverse. \~ @@ -256,7 +267,7 @@ public: \en Matrix of point weights. \~ */ bool Init( const Array2 & cPoints, - const Array2 & pWeights ); + const Array2 & pWeights ); /** \brief \ru Инициализация заполненной поверхности. \en Initialization of filled surface. \~ \details \ru Инициализация заполненной поверхности.\n @@ -316,24 +327,24 @@ public: \param[in] scl - \ru Коэффициент масштабирования. \en Scale factor. \~ */ - bool InitParasolid( bool uCls, - bool vCls, - bool brational, - size_t uDgr, - size_t vDgr, - ptrdiff_t uCnt, - ptrdiff_t vCnt, - const CcArray & vcs, - ptrdiff_t vcsCnt, - const CcArray & uKMul, - ptrdiff_t uKMulCnt, - const CcArray & vKMul, - ptrdiff_t vKMulCnt, - const CcArray & uKnt, - ptrdiff_t uKntCnt, - const CcArray & vKnt, - ptrdiff_t vKntCnt, - double scl ); + bool InitParasolid( bool uCls, + bool vCls, + bool brational, + size_t uDgr, + size_t vDgr, + ptrdiff_t uCnt, + ptrdiff_t vCnt, + const CcArray & vcs, + ptrdiff_t vcsCnt, + const CcArray & uKMul, + ptrdiff_t uKMulCnt, + const CcArray & vKMul, + ptrdiff_t vKMulCnt, + const CcArray & uKnt, + ptrdiff_t uKntCnt, + const CcArray & vKnt, + ptrdiff_t vKntCnt, + double scl ); /** \ru \name Общие функции геометрического объекта. \en \name Common functions of geometric object. @@ -393,6 +404,9 @@ public: virtual void DeriveUVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по uvv. \en Third derivative with respect to uvv. virtual void DeriveVVV( double & u, double & v, MbVector3D & ) const; // \ru Третья производная по v. \en Third derivative with respect to v. virtual void Normal ( double & u, double & v, MbVector3D & ) const; // \ru Нормаль. \en Normal. + // \ru Точка и производные по u и по v в пределах области определения. \en Point and derivatives of object for parameters inside surface parameters domain. + virtual void Explore ( double & u, double & v, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer ) const; /** \} */ /** \ru \name Функции для работы внутри и вне области определения поверхности @@ -464,7 +478,7 @@ public: \param[in] u - \ru Первый параметр. \en First parameter. \~ \param[in] v - \ru Второй параметр. \en Second parameter. \~ */ - virtual void CheckSurfParams( double & u, double & v ) const; + virtual void CheckSurfParams( double & u, double & v ) const; /** \brief \ru Построить усеченную поверхность. \en Construct a trimmed surface. \~ @@ -556,7 +570,7 @@ public: \return \ru Значение веса. \en A value of weight. \~ */ - double GetWeight( ptrdiff_t i, ptrdiff_t j ) const { return weights.GetWeight( i, j ); } + double GetWeight( ptrdiff_t i, ptrdiff_t j ) const { return weights.GetWeight( i, j ); } // \ru Получить матрицу весов вершин. \en Get the matrix of vertices weights. virtual void GetWeights( Array2 & wts ) const { weights.GetWeights( wts ); } @@ -572,7 +586,7 @@ public: */ size_t GetKnotsCount( bool isU ) const { return (isU ? uknots.Count() : vknots.Count()); } - // \ru Получить узловой вектор по выбранному параметру. \en Get a knot vector by the chosen parameter. + // \ru Получить узловой вектор по выбранному параметру. \en Get a knots vector by the chosen parameter. virtual void GetKnots( bool isU, SArray & knots ) const { knots = (isU ? uknots : vknots); } /** \brief \ru Получить значение одного узла. \en Get the value of one knot. \~ @@ -771,23 +785,18 @@ public: */ void DirectParallelRects( const MbVector3D & direction, std::vector & parallelRects ) const; -private: - bool CheckPoles( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов. \en Check poles existence. + /// \ru Может ли быть поверхность замкнутой по первому параметру? \en Can the surface be closed by the first parameter? + bool CheckUTouch( double precision ) const; + /// \ru Может ли быть поверхность замкнутой по второму параметру? \en Can the surface be closed by the second parameter? + bool CheckVTouch( double precision ) const; +private: void SetClosed( bool isU, bool cls ); // \ru Установить признак замкнутости. \en Set attribute of closedness. void SetKnots ( size_t degree, ptrdiff_t count, bool close, SArray & knots ); // \ru Установка значений узлового вектора \en Setting of knot vector values. void OpenKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots ); // \ru Переопределение базисного узлового вектора из Close в Open. \en Redetermination of the basis knot vector from Close to Open. void CloseKnotsVector ( size_t degree, ptrdiff_t count, SArray & knots, double ); // \ru Переопределение базисного узлового вектора из Open в Close. \en Redetermination of the basis knot vector from Open to Close. - bool InitPatch ( MbSplineSurfaceAuxiliaryData * ) const; - void CalculatePatch ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; - void CalculateSpline ( int, MbSplineSurfaceAuxiliaryData * ) const; // \ru Расчет вектора точки и его первых, вторых и третьих производных. \en Calculation of the point vector and its first, second and third derivatives - void CalculateSplineWeight( int, MbSplineSurfaceAuxiliaryData * ) const; - - bool CatchMemory( MbSplineSurfaceAuxiliaryData * ) const; - void FreeMemory ( MbSplineSurfaceAuxiliaryData * ) const; - void ResetCache(); void operator = ( const MbSplineSurface & ); // \ru Не реализовано. \en Not implemented. @@ -795,7 +804,18 @@ private: double GetMeanParam( bool isU, double, double ) const; // \ru Получить среднее расстояние между band-ами. \en Get the middle distance between 'band'-s. double GetKoef( bool isU ) const; // \ru Получить коэффициент пересчета из длины в параметры. \en Get a coefficient of recalculation of the length to the parameters. - // \ru Служебные аналоги публичных функций, которые используют заданный кэш. \en Service analogs of public functions that use a given cache. + //--- + // \ru Служебные функции, которые используют заданный кэш (должен быть != NULL). \en Service functions that use a given cache (must != NULL). + bool CheckPoles( MbSplineSurfaceAuxiliaryData * ) const; // \ru Проверить наличие полюсов. \en Check poles existence. + + bool CatchMemory( MbSplineSurfaceAuxiliaryData * ) const; + void FreeMemory ( MbSplineSurfaceAuxiliaryData * ) const; + + bool InitPatch ( MbSplineSurfaceAuxiliaryData * ) const; + void CalculatePatch ( double & u, double & v, MbSplineSurfaceAuxiliaryData * ) const; + void CalculateSpline ( int, MbSplineSurfaceAuxiliaryData * ) const; // \ru Расчет вектора точки и его первых, вторых и третьих производных. \en Calculation of the point vector and its first, second and third derivatives + void CalculateSplineWeight( int, MbSplineSurfaceAuxiliaryData * ) const; + void DeriveU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по u. \en First derivative with respect to u. void DeriveV ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Первая производная по v. \en First derivative with respect to v. void DeriveUU ( double & u, double & v, MbVector3D &, MbSplineSurfaceAuxiliaryData * ) const; // \ru Вторая производная по u. \en Second derivative with respect to u. @@ -827,6 +847,15 @@ private: double DeviationStep ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; double DeviationStepPlus ( bool isU, double u, double v, double angle, MbSplineSurfaceAuxiliaryData * ) const; void TypedStepPlus ( double u, double v, bool alongU, const MbStepData & stepData, double & step, MbSplineSurfaceAuxiliaryData * ) const; + + void PoleDerive( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV, MbSplineSurfaceAuxiliaryData * ) const; + + void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, + MbSplineSurfaceAuxiliaryData * ) const; + void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, MbVector3D & tttDer, + MbSplineSurfaceAuxiliaryData * ) const; + //--- + double GetMinStep ( bool isU, const double * pRng = NULL ) const; bool ApproxAsPlane() const; // \ru Можно ли аппроксимировать поверхность как плоскость. \en Whether a surface can be approximated by a plane. @@ -834,8 +863,6 @@ private: MbSplineSurface * CalcApproxAsPlane( size_t nUDegree, size_t nVDegree, ptrdiff_t nUCount, ptrdiff_t nVCount ) const; bool UseMultiplKnots() const; - void PoleDerive( double u, double v, MbVector3D & vDerU, MbVector3D & vDerV, MbSplineSurfaceAuxiliaryData * ) const; - inline void CheckParam( const SArray & knots, const ptrdiff_t & degree, const bool & closed, double & t ) const; // \ru Создать двумерную кривую, если пространственная кривая является границей поверхности. \en Create a two-dimensional curve if a space curve is surface boundary. @@ -843,12 +870,7 @@ private: MbCurve * IsPartSplineBorder( const MbCurve3D & curve ) const; void GetVertecisRects( const MbVector3D & direction, bool u, - std::vector > & vertecesRects ) const; - private: - void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, - MbSplineSurfaceAuxiliaryData * ) const; - void CalculateDerivativesAlong( double & u, double & v, bool isU, MbVector3D & tDer, MbVector3D & ttDer, MbVector3D & tttDer, - MbSplineSurfaceAuxiliaryData * ) const; + std::vector & vertecesRects ) const; DECLARE_PERSISTENT_CLASS_NEW_DEL( MbSplineSurface ) }; diff --git a/C3d/Include/surface.h b/C3d/Include/surface.h index a7d178a..b510365 100644 --- a/C3d/Include/surface.h +++ b/C3d/Include/surface.h @@ -91,7 +91,7 @@ typedef std::pair ConstSurfacesSetRet; \ingroup Surfaces */ // --- -class MATH_CLASS MbSurface : public MbSpaceItem { +class MATH_CLASS MbSurface : public MbSpaceItem, public MbNestSyncItem { protected : /** \brief \ru Габаритный куб поверхности. \en Bounding box of surface. \~ @@ -308,6 +308,25 @@ public: virtual void NormalU ( double & u, double & v, MbVector3D & ) const; /// \ru Вычислить производную нормали по V. \en Calculate derivative of normal with respect to V. virtual void NormalV ( double & u, double & v, MbVector3D & ) const; + /** \brief \ru Вычислить значения точки и первых производных по u и по v. + \en Calculate point and first derivatives with respect to u and with respect to v. \~ + \details \ru Скорректировать параметры при выходе их за пределы прямоугольной области определения и вычислить значения точки и первых производных по u и по v. + \en Correct parameters when getting out of rectangular domain bounds and calculate point and first derivatives with respect to u and with respect to v. \~ + \param[in] u - \ru Параметр. + \en Parameter. \~ + \param[in] v - \ru Параметр. + \en Parameter. \~ + \param[out] pnt - \ru Точка. + \en Point. \~ + \param[out] uDer - \ru Производная по u. + \en Derivative with respect to u. \~ + \param[out] vDer - \ru Производная по v. + \en Derivative with respect to v. \~ + \ingroup Surfaces + */ + virtual void Explore( double & u, double & v, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer ) const; + /** \} */ /** \ru \name Функции для работы внутри и вне области определения поверхности @@ -833,6 +852,24 @@ public: */ virtual MbSplineSurface * NurbsSurface( double u1, double u2, double v1, double v2, bool bmatch = false ) const; + // \ru Построить NURBS-копию поверхности. \en Construct a NURBS copy of a surface. + /** \brief \ru Построить NURBS копию поверхности. + \en Construct a NURBS copy of a surface. \~ + \details \ru Строит NURBS поверхность, аппроксимирующую исходную с заданными параметрами по каждому направлению. + В параметрах можно задать степень и количество узлов сплайна, диапазон изменения параметра кривой. + Если в параметрах не задан флаг точной аппроксимации, то строит NURBS без кратных узлов. + \en Constructs a NURBS surface which approximates a given surface with the given parameters in each direction. + In parameters the degree and the number of knots of a spline and the range of curve's parameters changing may be set. + If the flag of accurate approximation is not set in parameters then NURBS without multiple knots is constructed. \~ + \param[in] uParam - \ru Параметры построения по направлению u. + \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. \~ + */ + virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; + /** \brief \ru Подготовить параметры для преобразования в NURBS поверхность. \en Prepare parameters for the transformation to NURBS surface. \~ \details \ru Подготовить параметры для преобразования в NURBS поверхность. @@ -930,23 +967,7 @@ public: */ void CheckApproxPointParamsClosed( bool isU, double par, size_t degree, size_t pCount, SArray & tList, SArray & aKnots ) const; - // \ru Построить NURBS-копию поверхности. \en Construct a NURBS copy of a surface. - /** \brief \ru Построить NURBS копию поверхности. - \en Construct a NURBS copy of a surface. \~ - \details \ru Строит NURBS поверхность, аппроксимирующую исходную с заданными параметрами по каждому направлению. - В параметрах можно задать степень и количество узлов сплайна, диапазон изменения параметра кривой. - Если в параметрах не задан флаг точной аппроксимации, то строит NURBS без кратных узлов. - \en Constructs a NURBS surface which approximates a given surface with the given parameters in each direction. - In parameters the degree and the number of knots of a spline and the range of curve's parameters changing may be set. - If the flag of accurate approximation is not set in parameters then NURBS without multiple knots is constructed. \~ - \param[in] uParam - \ru Параметры построения по направлению u. - \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. \~ - */ - virtual MbSurface * NurbsSurface( const MbNurbsParameters & uParam, const MbNurbsParameters & vParam ) const; + // \ru Построить эквидистантую поверхность. \en Create an offset surface. /** \brief \ru Построить эквидистантую поверхность. \en Create an offset surface. \~ @@ -1044,7 +1065,7 @@ public: /** \brief \ru Определить точки пересечения кривoй с контурами поверхности. \en Determine points of intersections between the curve and the surface contours. \~ \details \ru Определить точки пересечения кривoй с границами поверхности - для нахождение частей кривой в пределах поверхности + для нахождения частей кривой в пределах поверхности и векторов для их сдвига в пределы поверхности. Вектор сдвига определен для каждой точки пересечения. Если вектор сдвига найти нельзя, то в массив сохраняется вектор нулевой длины. @@ -1079,7 +1100,7 @@ public: /** \brief \ru Определить точки пересечения кривoй с контурами поверхности. \en Determine points of intersections between the curve and the surface contours. \~ \details \ru Определить точки пересечения кривoй с границами поверхности - для нахождение частей кривой в пределах поверхности + для нахождения частей кривой в пределах поверхности и векторов для их сдвига в пределы поверхности. Вектор сдвига определен для каждой точки пересечения. Если вектор сдвига найти нельзя, то в массив сохраняется вектор нулевой длины. @@ -1153,12 +1174,12 @@ public: \en A given point. \~ \param[in] vect - \ru Вектор направления. \en A direction vector. \~ - \param[in,out] uv - \ru Множество точек проекции. - \en A set of projection points. \~ - \param[in] ext - \ru Флаг, определяющий, искать ли проекцию на продолжении кривой (если true, то искать). - \en A flag defining whether to seek projection on the extension of the curve. \~ - \param[in] uvRange - \ru Диапазон изменения параметров, в котором надо найти решение. - \en A range of parameters changing in which the solution should be found. \~ + \param[out] uv - \ru Множество точек проекции в области определения поверхности. + \en A set of projection points in the area of surface definition. \~ + \param[in] ext - \ru Флаг, определяющий, искать ли проекцию на продолжении поверхности (если true, то искать). + \en A flag defining whether to seek projection on the extension of the surface. \~ + \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; @@ -1407,7 +1428,7 @@ public: \param[out] uv - \ru Множество параметров точек с искомой касательной. \en A set of parameters of points for the required tangent. \~ */ - virtual void GetIsoclinal( const MbVector3D & nor, SArray & uv ) const; + virtual void GetIsoclinal( const MbVector3D & nor, SArray & uv ) const; /// \ru Рассчитать габарит поверхности. Рекомендуется использовать GetGabarit. \en Calculate bounding box of surface. It is recommended to use GetGabarit. virtual void CalculateGabarit( MbCube & cube ) const; @@ -1415,7 +1436,7 @@ public: virtual void CalculateLocalGabarit( const MbMatrix3D & into, MbCube & cube ) const; /// \ru Рассчитать габаритный куб поверхности. \en Calculate bounding box of surface. - const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube; } + const MbCube & GetGabarit() const { if ( cube.IsEmpty() ) { MbCube tmp; CalculateGabarit( tmp ); } return cube; } /// \ru Вернуть сохраненный габаритный куб. Он должен быть пустой. Рекомендуется использовать GetGabarit. \en Return saved bounding box. It should be empty. It is recommended to use GetGabarit. const MbCube & Cube() const { return cube; } /// \ru Сделать габарит пустым. Для внутреннего использования. \en Make the bounding box empty. For internal use only. @@ -1432,7 +1453,7 @@ public: */ void CopyGabarit( const MbSurface & s, const MbVector3D * to = NULL ) { cube = s.cube; if ( (to != NULL) && !cube.IsEmpty() ) { cube.Move( *to ); } } /// \ru Вычислить диагональ габаритного куба. \en Calculate the diagonal of the bounding box. - double GetGabDiagonal() const { if ( cube.IsEmpty() ) CalculateGabarit( cube ); return cube.GetDiagonal(); } + double GetGabDiagonal() const { if ( cube.IsEmpty() ) { MbCube tmp; CalculateGabarit( tmp ); } return cube.GetDiagonal(); } /** \brief \ru Вычислить прямоугольный габарит поверхности в заданной плоскости. \en Calculate the rectangular bounding box of a surface in the given plane. \~ @@ -1443,7 +1464,7 @@ public: \param[out] rect - \ru Вычисленный прямоугольник. \en Calculated rectangle. \~ */ - void CalculateRect( const MbPlacement3D & place, MbRect & rect ) const; + void CalculateRect( const MbPlacement3D & place, MbRect & rect ) const; /** \brief \ru Вернуть граничный двумерный контур. \en Return the bounding two-dimensional contour. \~ @@ -1525,6 +1546,10 @@ public: virtual double GetUParamToUnit( double u, double v ) const; /// \ru Дать приращение параметра v, соответствующее единичной длине в пространстве. \en Get increment of v-parameter, corresponding to the unit length in space. virtual double GetVParamToUnit( double u, double v ) const; + /// \ru Дать приращение параметра u, соответствующее единичной длине в пространстве. \en Get increment of u-parameter, corresponding to the unit length in space. + double GetUParamToUnit( const MbCartPoint & uv ) const { return GetUParamToUnit( uv.x, uv.y ); } + /// \ru Дать приращение параметра v, соответствующее единичной длине в пространстве. \en Get increment of v-parameter, corresponding to the unit length in space. + double GetVParamToUnit( const MbCartPoint & uv ) const { return GetVParamToUnit( uv.x, uv.y ); } /// \ru Дать приращение параметра 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; @@ -1696,7 +1721,7 @@ public: \param[in] u - \ru Первый параметр. \en First parameter. \~ \param[in] v - \ru Второй параметр. \en Second parameter. \~ */ - virtual void CheckSurfParams( double & u, double & v ) const; + virtual void CheckSurfParams( double & u, double & v ) const; /// \ru Дать плоскость (или только возможность ее выдачи). \en Get a plane (or only a possibility of getting a plane) bool GetPlacement ( MbPlacement3D * place, bool exact = false ) const; @@ -1752,7 +1777,7 @@ public: /** \} */ // \ru Функции унификации объекта и вектора объектов в шаблонных функциях. \en Functions for compatibility of a object and a vector of objects in template functions. - size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. + size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. const MbSurface * operator [] ( size_t ) const { return this; } ///< \ru Оператор доступа. \en An access operator. protected: @@ -1784,6 +1809,7 @@ private: IMPL_PERSISTENT_OPS( MbSurface ) + //------------------------------------------------------------------------------ // \ru Вычислить точку на поверхности. \en Calculate a point on a surface. // --- @@ -1792,6 +1818,18 @@ inline void MbSurface::PointOn( MbCartPoint & uv, MbCartPoint3D & p ) const { } +//------------------------------------------------------------------------------ +// \ru Вычислить значения точки и производных для параметров в пределах области определения. +// \en Calculate point and derivatives of object for parameters inside the surface's domain of parameters. \~ +// --- +inline void MbSurface::Explore( double & u, double & v, + MbCartPoint3D & pnt, MbVector3D & uDer, MbVector3D & vDer ) const { + PointOn( u, v, pnt ); + DeriveU( u, v, uDer ); + DeriveV( u, v, vDer ); +} + + //------------------------------------------------------------------------------ // \ru Вычислить точку на продолженной поверхности. \en Calculate a point on a surface extension. // --- diff --git a/C3d/Include/system_atomic.h b/C3d/Include/system_atomic.h index 90eaea1..8eef130 100644 --- a/C3d/Include/system_atomic.h +++ b/C3d/Include/system_atomic.h @@ -1,205 +1,279 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Системозависимые атомарные операции. - Если требуются атомарные операции, должен использоваться этот файл ( не использовать!!!). - \en System-dependent atomic operations. - If atomic operations are required, this file should used ( must not be used!!!).\~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SYSTEM_ATOMIC_H -#define __SYSTEM_ATOMIC_H - -#include -#include -#include - -//------------------------------------------------------------------------------ -// \ru Использование атомарных операций согласно стандарту C++11. -// \en Using atomic operations according to C++11 standard. -// -//--- - -#ifdef STANDARD_C11 -#ifndef _NOT_USE_ATOMIC -#define STANDARD_C11_ATOMIC -#endif -#endif - -#ifdef STANDARD_C11_ATOMIC - -#include - -typedef std::atomic_ptrdiff_t use_count_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. -typedef std::atomic_size_t serial_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. -typedef std::atomic atomic_bool; // \ru Потокобезопасный логический тип. \en Thread-safe boolean type. - -//------------------------------------------------------------------------------ -/** \ru Получить значение. \en Get value. -*/ -//--- -template -Type LoadTypeValue( const AtomicType & v ) { - return v.load(); -} - -//------------------------------------------------------------------------------ -/** \ru Установить значение. \en Get value. -*/ -//--- -template -void StoreTypeValue( const AtomicType & src, AtomicType & dst ) { - dst.store( src.load() ); -} - -//------------------------------------------------------------------------------ -/** \ru Установить значение. \en Get value. -*/ -//--- -template -void StoreTypeValue( const Type src, AtomicType & dst ) { - dst.store( src ); -} - -//------------------------------------------------------------------------------ -/** \ru Получить значение. \en Get value. -*/ -//--- -inline serial_type SerialTypeValue( const serial_type & v ) { - return v.load(); -} -inline use_count_type UseCountValue( const use_count_type & v ) { - return v.load(); -} - -#else - -//------------------------------------------------------------------------------ -// \ru Шаблонный класс, работающий с целочисленными типами данных. Базовый класс для потокобезопасных счётчиков. -// \en Template class working with integer data types. Base class for thread-safe counters. -//-- -template< class Type > -class atomic_itype -{ -protected: - CommonMutex m_lock; - Type m_value; -public: - atomic_itype() {} - atomic_itype( const atomic_itype & t ) : m_value( t.m_value ) {} - atomic_itype( const Type t ) : m_value( t ) {} - - // \ru Операторы присваивания. \en Assignment operators. - atomic_itype & operator = ( const atomic_itype & t ) { ScopedLock l( &m_lock ); m_value = t.m_value; return *this; } - atomic_itype & operator = ( Type t ) { ScopedLock l( &m_lock ); m_value = t; return *this; } - - // \ru Операторы инкремента и декремента. \en Increment and decrement operators. - atomic_itype & operator ++ () { ScopedLock l( &m_lock ); ++m_value; return *this; } // prefix ++ - atomic_itype & operator -- () { ScopedLock l( &m_lock ); --m_value; return *this; } // prefix -- - Type operator ++ ( int ) { // postfix ++ - Type t = m_value; - { - ScopedLock l( &m_lock ); - ++m_value; - } - return t; - } - Type operator -- ( int ) { // postfix -- - Type t = m_value; - { - ScopedLock l( &m_lock ); - --m_value; - } - return t; - } - - // \ru Операторы сравнения. \en Comparison operators. - bool operator == ( const atomic_itype & t ) const { return m_value == t.m_value; } - bool operator != ( const atomic_itype & t ) const { return m_value != t.m_value; } - bool operator < ( const atomic_itype & t ) const { return m_value < t.m_value; } - bool operator > ( const atomic_itype & t ) const { return m_value > t.m_value; } - bool operator <= ( const atomic_itype & t ) const { return m_value <= t.m_value; } - bool operator >= ( const atomic_itype & t ) const { return m_value >= t.m_value; } - - // \ru Доступ к данным. \en Data access. - Type operator()() const { return m_value; } - -}; - -//------------------------------------------------------------------------------ -// \ru Потокобезопасный логический тип. \en Thread-safe boolean type. -//-- -class atomic_bool : public atomic_itype -{ -public: - atomic_bool() {} - - atomic_bool( const atomic_bool & t ) : atomic_itype( t.m_value ) {} - atomic_bool( const bool t ) : atomic_itype( t ? 1 : 0 ) {} - atomic_bool( const int t ) : atomic_itype( t != 0 ? 1 : 0 ) {} - - // \ru Операторы присваивания. \en Assignment operators. - atomic_bool & operator = ( const atomic_bool & t ) { ScopedLock l( &m_lock ); m_value = t.m_value; return *this; } - atomic_bool & operator = ( bool t ) { ScopedLock l( &m_lock ); m_value = t ? 1 : 0; return *this; } - atomic_bool & operator = ( int t ) { ScopedLock l( &m_lock ); m_value = t != 0 ? 1 : 0; return *this; } - - bool operator && ( bool t ) { return t == !!m_value; } - bool operator || ( bool t ) { return t || !!m_value; } - - // \ru Доступ к данным. \en Data access. - bool operator()() const { return !!m_value; } - -private: - // \ru Операторы инкремента и декремента не разрешены. \en Increment and decrement operators not allowed. - atomic_bool & operator ++ (); - atomic_bool & operator -- (); - bool operator ++ ( int ); - bool operator -- ( int ); -}; - -typedef atomic_itype serial_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. -typedef atomic_itype use_count_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. - -//------------------------------------------------------------------------------ -/** \ru Получить значение. \en Get value. -*/ -//--- -template -Type LoadTypeValue( const AtomicType & v ) { - return v(); -} - -//------------------------------------------------------------------------------ -/** \ru Установить значение. \en Get value. -*/ -//--- -template -void StoreTypeValue( const AtomicType & src, AtomicType & dst ) { - dst = src; -} - -//------------------------------------------------------------------------------ -/** \ru Установить значение. \en Get value. -*/ -//--- -template -void StoreTypeValue( const Type src, AtomicType & dst ) { - dst = src; -} - -//------------------------------------------------------------------------------ -/** \ru Получить значение. \en Get value. -*/ -//--- -inline size_t SerialTypeValue( const serial_type & v ) { - return v(); -} -inline ptrdiff_t UseCountValue( const use_count_type & v ) { - return v(); -} - -#endif // STANDARD_C11_ATOMIC - - -#endif // __SYSTEM_ATOMIC_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Системозависимые атомарные операции. + Если требуются атомарные операции, должен использоваться этот файл ( не использовать!!!). + \en System-dependent atomic operations. + If atomic operations are required, this file should used ( must not be used!!!).\~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SYSTEM_ATOMIC_H +#define __SYSTEM_ATOMIC_H + +#include +#include +#include + +//------------------------------------------------------------------------------ +// \ru Использование атомарных операций согласно стандарту C++11. +// \en Using atomic operations according to C++11 standard. +// +//--- + +#ifdef C3D_STANDARD_CXX_11_PARTIAL + #ifndef _NOT_USE_ATOMIC + #define C3D_USE_CXX11_ATOMIC + #endif +#endif + +#ifdef C3D_USE_CXX11_ATOMIC + +#include + +typedef std::atomic_ptrdiff_t use_count_type; ///< \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. +typedef std::atomic_size_t serial_type; ///< \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. +typedef std::atomic_schar flag_type; ///< \ru Потокобезопасный тип флага. \en Thread-safe flag type. +typedef std::atomic atomic_bool; ///< \ru Потокобезопасный логический тип. \en Thread-safe boolean type. + +//------------------------------------------------------------------------------ +/** \ru Получить значение. \en Get value. +*/ +//--- +template +Type LoadTypeValue( const AtomicType & v ) { + return v.load(); +} + +//------------------------------------------------------------------------------ +/** \ru Установить значение. \en Get value. +*/ +//--- +template +void StoreTypeValue( const AtomicType & src, AtomicType & dst ) { + dst.store( src.load() ); +} + +//------------------------------------------------------------------------------ +/** \ru Установить значение. \en Get value. +*/ +//--- +template +void StoreTypeValue( const Type src, AtomicType & dst ) { + dst.store( src ); +} + +//------------------------------------------------------------------------------ +/** \ru Получить значение. \en Get value. +*/ +//--- +inline size_t SerialTypeValue( const serial_type & v ) { + return v.load(); +} +inline ptrdiff_t UseCountValue( const use_count_type & v ) { + return v.load(); +} + +//------------------------------------------------------------------------------ +// \ru Шаблонный класс для перечислений (Type - тип перечисления). +// \en Template class for enums (Type - a type of enum). +//-- +template< class Type > +class atomic_enum_type +{ + use_count_type m_value; + +public: + atomic_enum_type() :m_value (0) {} + atomic_enum_type( const Type & val ) : m_value (val) {} + atomic_enum_type( const atomic_enum_type & val ) : m_value( val.m_value.load() ) {} + + // \ru Операторы присваивания. \en Assignment operators. + atomic_enum_type & operator = ( const atomic_enum_type & t ) { m_value.store( t.m_value.load() ); return *this; } + atomic_enum_type & operator = ( const Type & t ) { m_value.store( t ); return *this; } + + // \ru Операторы сравнения. \en Comparison operators. + bool operator == ( const atomic_enum_type & t ) const { return m_value.load() == t.m_value.load(); } + bool operator == ( const Type & t ) const { return m_value.load() == t; } + bool operator != ( const atomic_enum_type & t ) const { return m_value.load() != t.m_value.load(); } + bool operator != ( const Type & t ) const { return m_value.load() != t; } + bool operator < ( const atomic_enum_type & t ) const { return m_value.load() < t.m_value.load(); } + bool operator < ( Type t ) const { return m_value.load() < t; } + bool operator > ( const atomic_enum_type & t ) const { return m_value.load() > t.m_value; } + bool operator > ( const Type & t ) const { return m_value.load() > t; } + bool operator <= ( const atomic_enum_type & t ) const { return m_value.load() <= t.m_value.load(); } + bool operator <= ( const Type & t ) const { return m_value.load() <= t; } + bool operator >= ( const atomic_enum_type & t ) const { return m_value.load() >= t.m_value.load(); } + bool operator >= ( const Type & t ) const { return m_value.load() >= t; } + + // \ru Доступ к данным. \en Data access. + Type operator()() const { return static_cast( m_value.load() ); } +}; + +#else + +//------------------------------------------------------------------------------ +// \ru Шаблонный класс, работающий с целочисленными типами данных. Базовый класс для потокобезопасных счётчиков. +// \en Template class working with integer data types. Base class for thread-safe counters. +//-- +template< class Type > +class atomic_itype +{ +protected: + CommonMutex m_lock; + Type m_value; +public: + atomic_itype() {} + atomic_itype( const atomic_itype & t ) : m_value( t.m_value ) {} + atomic_itype( const Type & t ) : m_value( t ) {} + + // \ru Операторы присваивания. \en Assignment operators. + atomic_itype & operator = ( const atomic_itype & t ) { ScopedLock l( &m_lock ); m_value = t.m_value; return *this; } + atomic_itype & operator = ( Type t ) { ScopedLock l( &m_lock ); m_value = t; return *this; } + + // \ru Операторы инкремента и декремента. \en Increment and decrement operators. + atomic_itype & operator ++ () { ScopedLock l( &m_lock ); ++m_value; return *this; } // prefix ++ + atomic_itype & operator -- () { ScopedLock l( &m_lock ); --m_value; return *this; } // prefix -- + Type operator ++ ( int ) { // postfix ++ + Type t = m_value; + { + ScopedLock l( &m_lock ); + ++m_value; + } + return t; + } + Type operator -- ( int ) { // postfix -- + Type t = m_value; + { + ScopedLock l( &m_lock ); + --m_value; + } + return t; + } + + // \ru Операторы сравнения. \en Comparison operators. + bool operator == ( const atomic_itype & t ) const { return m_value == t.m_value; } + bool operator != ( const atomic_itype & t ) const { return m_value != t.m_value; } + bool operator < ( const atomic_itype & t ) const { return m_value < t.m_value; } + bool operator > ( const atomic_itype & t ) const { return m_value > t.m_value; } + bool operator <= ( const atomic_itype & t ) const { return m_value <= t.m_value; } + bool operator >= ( const atomic_itype & t ) const { return m_value >= t.m_value; } + + // \ru Доступ к данным. \en Data access. + Type operator()() const { return m_value; } + +}; + +//------------------------------------------------------------------------------ +// \ru Потокобезопасный логический тип. \en Thread-safe boolean type. +//-- +class atomic_bool : public atomic_itype +{ +public: + atomic_bool() {} + + atomic_bool( const atomic_bool & t ) : atomic_itype( t.m_value ) {} + atomic_bool( const bool t ) : atomic_itype( t ? 1 : 0 ) {} + atomic_bool( const int t ) : atomic_itype( t != 0 ? 1 : 0 ) {} + + // \ru Операторы присваивания. \en Assignment operators. + atomic_bool & operator = ( const atomic_bool & t ) { ScopedLock l( &m_lock ); m_value = t.m_value; return *this; } + atomic_bool & operator = ( bool t ) { ScopedLock l( &m_lock ); m_value = t ? 1 : 0; return *this; } + atomic_bool & operator = ( int t ) { ScopedLock l( &m_lock ); m_value = t != 0 ? 1 : 0; return *this; } + + bool operator && ( bool t ) { return t == !!m_value; } + bool operator || ( bool t ) { return t || !!m_value; } + + // \ru Доступ к данным. \en Data access. + bool operator()() const { return !!m_value; } + +private: + // \ru Операторы инкремента и декремента не разрешены. \en Increment and decrement operators not allowed. + atomic_bool & operator ++ (); + atomic_bool & operator -- (); + bool operator ++ ( int ); + bool operator -- ( int ); +}; + +typedef atomic_itype serial_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. +typedef atomic_itype use_count_type; // \ru Потокобезопасный тип счётчика ссылок. \en Thread-safe references count type. +typedef atomic_itype flag_type; ///< \ru Потокобезопасный тип флага. \en Thread-safe flag type. + +//------------------------------------------------------------------------------ +/** \ru Получить значение. \en Get value. +*/ +//--- +template +Type LoadTypeValue( const AtomicType & v ) { + return v(); +} + +//------------------------------------------------------------------------------ +/** \ru Установить значение. \en Get value. +*/ +//--- +template +void StoreTypeValue( const AtomicType & src, AtomicType & dst ) { + dst = src; +} + +//------------------------------------------------------------------------------ +/** \ru Установить значение. \en Get value. +*/ +//--- +template +void StoreTypeValue( const Type src, AtomicType & dst ) { + dst = src; +} + +//------------------------------------------------------------------------------ +/** \ru Получить значение. \en Get value. +*/ +//--- +inline size_t SerialTypeValue( const serial_type & v ) { + return v(); +} +inline ptrdiff_t UseCountValue( const use_count_type & v ) { + return v(); +} + +//------------------------------------------------------------------------------ +// \ru Шаблонный класс для перечислений (Type - тип перечисления). +// \en Template class for enums (Type - a type of enum). +//-- +template< class Type > +class atomic_enum_type : public atomic_itype +{ +public: + atomic_enum_type() : atomic_itype() {} + atomic_enum_type( Type & val ) : atomic_itype( val ) {} + atomic_enum_type( const Type & val ) : atomic_itype( val ) {} + atomic_enum_type( const atomic_enum_type & val ) : atomic_itype( val.m_value ) {} + atomic_enum_type( atomic_enum_type & val ) : atomic_itype( val.m_value ) {} + + // \ru Операторы присваивания. \en Assignment operators. + atomic_enum_type & operator = ( const atomic_enum_type & t ) { ScopedLock l( &m_lock ); m_value = t.m_value; return *this; } + atomic_enum_type & operator = ( const Type & t ) { ScopedLock l( &m_lock ); m_value = t; return *this; } + + // \ru Операторы сравнения. \en Comparison operators. + bool operator == ( const atomic_enum_type & t ) const { return m_value == t.m_value; } + bool operator == ( const Type & t ) const { return m_value == t; } + bool operator != ( const atomic_enum_type & t ) const { return m_value != t.m_value; } + bool operator != ( const Type & t ) const { return m_value != t; } + bool operator < ( const atomic_enum_type & t ) const { return m_value < t.m_value; } + bool operator < ( Type t ) const { return m_value < t; } + bool operator > ( const atomic_enum_type & t ) const { return m_value > t.m_value; } + bool operator > ( const Type & t ) const { return m_value > t; } + bool operator <= ( const atomic_enum_type & t ) const { return m_value <= t.m_value; } + bool operator <= ( const Type & t ) const { return m_value <= t; } + bool operator >= ( const atomic_enum_type & t ) const { return m_value >= t.m_value; } + bool operator >= ( const Type & t ) const { return m_value >= t; } + + // \ru Доступ к данным. \en Data access. + Type operator()() const { return static_cast( m_value ); } +}; + +#endif // C3D_USE_CXX11_ATOMIC + + +#endif // __SYSTEM_ATOMIC_H diff --git a/C3d/Include/system_cpp_standard.h b/C3d/Include/system_cpp_standard.h index d04677a..f6481b4 100644 --- a/C3d/Include/system_cpp_standard.h +++ b/C3d/Include/system_cpp_standard.h @@ -1,71 +1,182 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Макросы стандартов C и C++. - \en C\C++ standards. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SYSTEM_CPP_STANDARD_H -#define __SYSTEM_CPP_STANDARD_H - -#include -#include - -// С11 -#if (defined(_MSC_VER) && (_MSC_VER > 1600)) || (defined(__INTEL_C) ) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || (defined(__BORLANDC__)) // BORLAND version? -#define STANDARD_C11 -#endif -// C11 with thread_local support -#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || (defined(__INTEL_C) ) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || (defined(__BORLANDC__)) // BORLAND version? -#define STANDARD_C11_THREAD -#endif - -// С++11 -#if defined(__cplusplus) && (__cplusplus >= 201103L) // С++11 (fully supported) -#define STANDARD_CPP11 -#define STANDARD_C11_THREAD -#endif - -// GCC version (https://sourceforge.net/p/predef/wiki/Compilers/) -#if !defined(C3D_WINDOWS) // _MSC_VER - #if defined(__GNUC__) - #if defined(__GNUC_MINOR__) - #if defined(__GNUC_PATCHLEVEL__) - #define C3D_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) - #else - #define C3D_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) - #endif - #else - #define #define C3D_GCC_VERSION (__GNUC__ * 10000) - #endif - #else - #define C3D_GCC_VERSION 0 - #endif -#else // C3D_WINDOWS - #define C3D_GCC_VERSION 0 -#endif // C3D_WINDOWS - -#if defined(__clang__) // Clang compiler - #define C3D_CLANG_COMPILER -#endif // Clang compiler - -// GNU glibc version. -#if defined(C3D_LINUX) // Linux - #include - #if defined(__GLIBC__) && defined(__GLIBC_MINOR__) - #define C3D_GLIBC_VERSION (__GLIBC__ * 1000 + __GLIBC_MINOR__) - #else - #define C3D_GLIBC_VERSION 0 - #endif -#else - #define C3D_GLIBC_VERSION 0 -#endif - -#if ( defined(STANDARD_C11) || defined(STANDARD_CPP11) ) -#define STANDARD_CPP11_RVALUE_REFERENCES -#endif - - -#endif // __SYSTEM_CPP_STANDARD_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Макросы стандартов C и C++. + \en C\C++ standards. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SYSTEM_CPP_STANDARD_H +#define __SYSTEM_CPP_STANDARD_H + +#include +#include + +// Clang version (https://sourceforge.net/p/predef/wiki/Compilers/) +// LLVM versions of Apple Clang: https://gist.github.com/yamaya/2924292 + https://en.wikipedia.org/wiki/Xcode#Toolchain_versions +#if defined(__clang__) // Clang compiler + #define C3D_CLANG_COMPILER + #if defined(__clang_major__) + #if defined(__clang_minor__) + #define C3D_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) + #else + #define C3D_CLANG_VERSION (__clang_major__ * 100) + #endif + #else + #define C3D_CLANG_VERSION 0 + #endif +#else + #define C3D_CLANG_VERSION 0 +#endif // Clang compiler + +// Intel compiler version (https://sourceforge.net/p/predef/wiki/Compilers/) +#if defined(__INTEL_COMPILER) + #define C3D_ICC_VERSION __INTEL_COMPILER +#else + #define C3D_ICC_VERSION 0 +#endif + +// GCC version (https://sourceforge.net/p/predef/wiki/Compilers/) +#if !defined(C3D_WINDOWS) && C3D_CLANG_VERSION == 0 && C3D_ICC_VERSION == 0 // GCC compiler + #if defined(__GNUC__) + #if defined(__GNUC_MINOR__) + #if defined(__GNUC_PATCHLEVEL__) + #define C3D_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) + #else + #define C3D_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) + #endif + #else + #define C3D_GCC_VERSION (__GNUC__ * 10000) + #endif + #else + #define C3D_GCC_VERSION 0 + #endif +#else + #define C3D_GCC_VERSION 0 +#endif // GCC compiler + +// GNU glibc version. +#if defined(C3D_LINUX) // glibc version. + #include + #if defined(__GLIBC__) && defined(__GLIBC_MINOR__) + #define C3D_GLIBC_VERSION (__GLIBC__ * 1000 + __GLIBC_MINOR__) + #else + #define C3D_GLIBC_VERSION 0 + #endif +#else + #define C3D_GLIBC_VERSION 0 +#endif // glibc version. + +// Available C++ standard to use. +// https://en.cppreference.com/w/cpp/compiler_support +// https://clang.llvm.org/cxx_status.html +// https://gcc.gnu.org/projects/cxx-status.html#cxx11 +// https://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler +// https://software.intel.com/en-us/articles/c14-features-supported-by-intel-c-compiler +// https://software.intel.com/en-us/articles/c17-features-supported-by-intel-c-compiler +#if (defined(_MSC_VER) && (_MSC_VER >= 1914)) || (C3D_GCC_VERSION >= 70000) || (C3D_ICC_VERSION >= 1910) || \ + (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 500) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 901) + #define C3D_STANDARD_CXX 2017 +#elif (defined(_MSC_VER) && (_MSC_VER >= 1910)) || (C3D_GCC_VERSION >= 50000) || (C3D_ICC_VERSION >= 1700) || \ + (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 304) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 501) + #define C3D_STANDARD_CXX 2014 +#elif (defined(_MSC_VER) && (_MSC_VER >= 1900)) || (C3D_GCC_VERSION >= 40801) || (C3D_ICC_VERSION >= 1500) || \ + (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 303) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 500) + #define C3D_STANDARD_CXX 2011 +#else + #define C3D_STANDARD_CXX 2003 +#endif // C++ version + +#if !defined(C3D_STANDARD_CXX_LIMIT) + #define C3D_STANDARD_CXX_LIMIT 99999 +#endif + +#if C3D_STANDARD_CXX_LIMIT >= 2011 && C3D_STANDARD_CXX >= 2011 + #define C3D_STANDARD_CXX_11 +#endif + +#if defined(C3D_STANDARD_CXX_11) || ((defined(_MSC_VER) && (_MSC_VER > 1600)) && C3D_STANDARD_CXX_LIMIT >= 2011) + #define C3D_STANDARD_CXX_11_PARTIAL +#endif + +#if C3D_STANDARD_CXX_LIMIT >= 2014 && C3D_STANDARD_CXX >= 2014 + #define C3D_STANDARD_CXX_14 +#endif + +#if C3D_STANDARD_CXX_LIMIT >= 2017 && C3D_STANDARD_CXX >= 2017 + #define C3D_STANDARD_CXX_17 +#endif + +#if C3D_STANDARD_CXX_LIMIT >= 2020 && C3D_STANDARD_CXX >= 2020 + #define C3D_STANDARD_CXX_20 +#endif + +// Available C standard to use. +// https://en.wikipedia.org/wiki/C99 + https://gcc.gnu.org/c99status.html +// https://gcc.gnu.org/wiki/C11Status + https://en.wikipedia.org/wiki/C11_(C_standard_revision) + https://releases.llvm.org/3.6.0/tools/clang/docs/UsersManual.html#c-language-features +// https://en.wikipedia.org/wiki/C18_(C_standard_revision) +// https://software.intel.com/en-us/articles/c99-support-in-intel-c-compiler + https://software.intel.com/en-us/articles/c11-support-in-intel-c-compiler +#if (C3D_GCC_VERSION >= 80100) || (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 700) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 1000) || (C3D_ICC_VERSION >= 1910) + #define C3D_STANDARD_C 2018 +#elif (C3D_GCC_VERSION >= 40900) || (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 306) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 601) || (C3D_ICC_VERSION >= 1800) + #define C3D_STANDARD_C 2011 +#elif (defined(_MSC_VER) && (_MSC_VER >= 1900)) || (C3D_GCC_VERSION >= 40500) || \ + (!defined(__apple_build_version__) && C3D_CLANG_VERSION >= 301) || \ + (defined(__apple_build_version__) && __apple_build_version__ >= 301) || (C3D_ICC_VERSION >= 1200) + #define C3D_STANDARD_C 1999 +#else + #define C3D_STANDARD_C 1989 +#endif + +#if C3D_STANDARD_C >= 1999 + #define C3D_STANDARD_C99 +#endif + +#if C3D_STANDARD_C >= 2011 + #define C3D_STANDARD_C11 +#endif + +#if C3D_STANDARD_C >= 2018 + #define C3D_STANDARD_C18 +#endif + + +////////////////////////////////////////////////////////////////////////////////////////// +// C++ standard dependent syntax. +////////////////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------ +/// \ru Обертка для override. \en Wrapper for override. +//--- +#if defined(C3D_STANDARD_CXX_11_PARTIAL) + #define c3d_override override +#else + #define c3d_override +#endif + +//------------------------------------------------------------------------------ +/// \ru Обертка для constexpr. \en Wrapper for constexpr. +//--- +#ifdef C3D_STANDARD_CXX_11 + #define const_expr constexpr +#else + #define const_expr const +#endif // C3D_STANDARD_CXX_11 + +//------------------------------------------------------------------------------ +// \ru Нулевой указатель. \en Null pointer. +//--- +#ifdef C3D_STANDARD_CXX_11_PARTIAL + #define C3D_NULL_PTR nullptr +#else + #define C3D_NULL_PTR NULL +#endif // C3D_STANDARD_CXX_11_PARTIAL + + +#endif // __SYSTEM_CPP_STANDARD_H diff --git a/C3d/Include/system_dependency.h b/C3d/Include/system_dependency.h index 8cee41c..c5c227e 100644 --- a/C3d/Include/system_dependency.h +++ b/C3d/Include/system_dependency.h @@ -1,259 +1,249 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Системозависимые функции. - \en System-dependent functions. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __SYSTEM_DEPENDENCY_H -#define __SYSTEM_DEPENDENCY_H - -#include -#include -#include - -#ifdef C3D_WINDOWS //_MSC_VER -#define LOG_PATH _T("C:\\Logs\\") -#else // C3D_WINDOWS -#define LOG_PATH _T("") -#endif // C3D_WINDOWS - -#ifndef C3D_WINDOWS //_MSC_VER - -#include -#include -#include -#include -#include -#include -#include - - -#if (C3D_GLIBC_VERSION >= 2023) // C3D_GLIBC_VERSION - #include - #define c3d_isnan(d) std::isnan(d) -#else // C3D_GLIBC_VERSION - #include - #define c3d_isnan(d) isnan(d) -#endif // C3D_GLIBC_VERSION - -#define _finite std::isfinite - - -//------------------------------------------------------------------------------ -// \ru RGB-цвет. \en RGB color. -// --- -typedef uint32 COLORREF; - - -//------------------------------------------------------------------------------ -// RGBs of int colors from WinApi -// --- -#define RGB(r, g ,b) ((uint32) (((uint8) (r) | ((uint16) (g) << 8)) | (((uint32) (uint8) (b)) << 16))) - - -//------------------------------------------------------------------------------ -// \ru Дать значение красного цвета в пределах 0 - 255. \en Get value of red color in range from 0 to 255. -// --- -inline uint8 GetRValue(COLORREF rgb_color) -{ - return (uint8) (rgb_color); -} - - -//------------------------------------------------------------------------------ -// \ru Дать значение зелёного цвета в пределах 0 - 255. \en Get value of green color in range from 0 to 255. -// --- -inline uint8 GetGValue(COLORREF rgb_color) -{ - return (uint8) (rgb_color >> 8); -} - - -//------------------------------------------------------------------------------ -// \ru Дать значение синего цвета в пределах 0 - 255. \en Get value of blue color in range from 0 to 255. -// --- -inline uint8 GetBValue(COLORREF rgb_color) -{ - return (uint8) (rgb_color >> 16); -} - - -// \ru Вывод сообщений об ошибках пока отключаем в Линуксе \en Output of error messages is temporary disabled in Linux -#define _RPT0(warnlvl, text) -#define _RPT1(a1, a2, a3) // \ru не реализовано \en not implemented -#define _CRT_WARN -#define _CRT_ASSERT - -#else // C3D_WINDOWS - - #define c3d_isnan(d) _isnan(d) - -#ifdef __BORLANDC__ -// \ru Вывод сообщений об ошибках пока отключаем в BORLAND \en Output of error messages is temporary disabled in BORLAND -#define _RPT0(warnlvl, text) -#define _RPT1(a1, a2, a3) // \ru не реализовано \en not implemented -#define _CRT_WARN -#define _CRT_ASSERT - -#else // __BORLANDC__ - -// \ru Одновременное определение _MBCS и _UNICODE недопустимо! \en Simultaneous definition of _MBCS and _UNICODE is not acceptable! -#if defined(_MBCS) && defined(_UNICODE) - #error Multibyte Character Sets (MBCS) not supported -#endif // _MBCS -#endif // __BORLANDC__ - -#endif // C3D_WINDOWS - -#include -#ifdef STANDARD_C11 -#include -// #error is not supported when compiling with /clr or /clr:pure. -// #include -#endif - -#ifndef threadLocal -# if __STDC_VERSION__ >= 201112 && !defined __STDC_NO_THREADS__ -# define threadLocal _Thread_local -# elif defined C3D_WINDOWS && ( \ - defined _MSC_VER || \ - defined __ICL || \ - defined __DMC__ || \ - defined __BORLANDC__ ) -# define threadLocal __declspec(thread) -/* note that ICC (linux) and Clang are covered by __GNUC__ */ -# elif defined __GNUC__ || \ - defined __SUNPRO_C || \ - defined __xlC__ -# define threadLocal __thread -# else -# error "Cannot define thread_local" -# endif -#endif - - -//------------------------------------------------------------------------------ -/** \brief \ru Высокоточный таймер. - \en High resolution timer. \~ - \details \ru Высокоточный таймер. - \en High resolution timer. \~ -\ingroup Base_Tools -*/ -// --- -class MbAccurateTimer { -#ifdef STANDARD_C11 - typedef std::chrono::high_resolution_clock::time_point TimePoint; -#endif -protected: - double lastTime; ///< \ru Время в секундах. \en Time in seconds. -private: -#ifdef STANDARD_C11 - TimePoint begTime; ///< \ru Засечка времени. \en Time stamp. -#endif - -public: - /// \ru Конструктор. \en Constructor. - MbAccurateTimer() : lastTime( 0.0 ) {} - virtual ~MbAccurateTimer() {} - - /// \ru Сброшен ли таймер. \en Is empty timer? - virtual bool IsEmpty () const { return !(lastTime > 0.0); } - /// \ru Сбросить таймер. \en Reset timer. - virtual void SetEmpty() { lastTime = 0.0; } - /// \ru Добавить значение. \en Add time value. - virtual bool SetTime ( double t ) { lastTime = t; return (t >= 0); } - /// \ru Начать отсчет. \en Start time measurement. - virtual void Begin (); - /// \ru Закончить отсчет. \en Finish time measurement. - virtual void End (); - /// \ru Получить значение времени. \en Get time value. - double GetLast() const { return lastTime; } - /// \ru Получить значение частоты. \en Get frequency value. - double PerSec () const { return (lastTime > 0.0 ? 1.0 / lastTime : 0.0); } -}; - - -//------------------------------------------------------------------------------ -// \ru Начать отсчет. \en Start time measurement. -//--- -inline void MbAccurateTimer::Begin() -{ -#ifdef STANDARD_C11 - begTime = std::chrono::high_resolution_clock::now(); -#endif -} - -//------------------------------------------------------------------------------ -// \ru Закончить отсчет. \en Finish time measurement. -// --- -inline void MbAccurateTimer::End() -{ -#ifdef STANDARD_C11 - TimePoint endTime = std::chrono::high_resolution_clock::now(); - double t = std::chrono::duration_cast< std::chrono::duration >(endTime - begTime).count(); - SetTime( t ); -#endif -} - - -//------------------------------------------------------------------------------ -/** \brief \ru Таймер со статистикой. - \en Average timer. \~ - \details \ru Таймер со статистикой. - \en Average timer. \~ -\ingroup Base_Tools -*/ -// --- -class MbAverageTimer : public MbAccurateTimer -{ - double avgTime; ///< \ru Среднее время в секундах. \en Average time in seconds. - double minTime; ///< \ru Минимальное время в секундах. \en Min. time in seconds. - double maxTime; ///< \ru Максимальное время в секундах. \en Max. time in seconds. - uint runCount; ///< \ru Количество запусков. \en Number of samples. - -public: - /// \ru Конструктор. \en Constructor. - MbAverageTimer() : avgTime( 0.0 ), minTime( 0.0 ), maxTime ( 0.0 ), runCount( 0 ) {} - - virtual bool IsEmpty() const { return (runCount == 0); } - virtual void SetEmpty(); - virtual bool SetTime( double ); - double GetAvg() const { return avgTime; } - double GetMin() const { return minTime; } - double GetMax() const { return maxTime; } -}; - -//------------------------------------------------------------------------------ -// \ru Сбросить таймер. \en Reset timer. -//--- -inline void MbAverageTimer::SetEmpty() -{ - MbAccurateTimer::SetEmpty(); - avgTime = minTime = maxTime = 0.0; - runCount = 0; -} - -//------------------------------------------------------------------------------ -// \ru Добавить значение. \en Add value. -//--- -inline bool MbAverageTimer::SetTime( double t ) -{ - bool res = MbAccurateTimer::SetTime( t ); - - if ( IsEmpty() ) - avgTime = minTime = maxTime = t; - else - { - avgTime += (t - avgTime) / (runCount + 1); - minTime = (std::min)( minTime, t ); - maxTime = (std::max)( maxTime, t ); - } - - runCount++; - return res; -} - -#endif // __SYSTEM_DEPENDENCY_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Системозависимые функции. + \en System-dependent functions. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __SYSTEM_DEPENDENCY_H +#define __SYSTEM_DEPENDENCY_H + +#include +#include +#include + +#ifdef C3D_WINDOWS //_MSC_VER +#define LOG_PATH _T("C:\\Logs\\") +#else // C3D_WINDOWS +#define LOG_PATH _T("") +#endif // C3D_WINDOWS + +#ifndef C3D_WINDOWS //_MSC_VER + +#include +#include +#include +#include +#include +#include +#include + + +#if (C3D_GLIBC_VERSION >= 2023) // C3D_GLIBC_VERSION + #include + #define c3d_isnan(d) std::isnan(d) +#else // C3D_GLIBC_VERSION + #include + #define c3d_isnan(d) isnan(d) +#endif // C3D_GLIBC_VERSION + +#define _finite std::isfinite + + +//------------------------------------------------------------------------------ +// \ru RGB-цвет. \en RGB color. +// --- +typedef uint32 COLORREF; + + +//------------------------------------------------------------------------------ +// RGBs of int colors from WinApi +// --- +#define RGB(r, g ,b) ((uint32) (((uint8) (r) | ((uint16) (g) << 8)) | (((uint32) (uint8) (b)) << 16))) + + +//------------------------------------------------------------------------------ +// \ru Дать значение красного цвета в пределах 0 - 255. \en Get value of red color in range from 0 to 255. +// --- +inline uint8 GetRValue(COLORREF rgb_color) +{ + return (uint8) (rgb_color); +} + + +//------------------------------------------------------------------------------ +// \ru Дать значение зелёного цвета в пределах 0 - 255. \en Get value of green color in range from 0 to 255. +// --- +inline uint8 GetGValue(COLORREF rgb_color) +{ + return (uint8) (rgb_color >> 8); +} + + +//------------------------------------------------------------------------------ +// \ru Дать значение синего цвета в пределах 0 - 255. \en Get value of blue color in range from 0 to 255. +// --- +inline uint8 GetBValue(COLORREF rgb_color) +{ + return (uint8) (rgb_color >> 16); +} + + +// \ru Вывод сообщений об ошибках пока отключаем в Линуксе \en Output of error messages is temporary disabled in Linux +#define _RPT0(warnlvl, text) +#define _RPT1(a1, a2, a3) // \ru не реализовано \en not implemented +#define _CRT_WARN +#define _CRT_ASSERT + +#else // C3D_WINDOWS + + #define c3d_isnan(d) _isnan(d) + +// \ru Одновременное определение _MBCS и _UNICODE недопустимо! \en Simultaneous definition of _MBCS and _UNICODE is not acceptable! +#if defined(_MBCS) && defined(_UNICODE) + #error Multibyte Character Sets (MBCS) not supported +#endif // _MBCS + +#endif // C3D_WINDOWS + +#include + +#ifdef C3D_STANDARD_CXX_11_PARTIAL + #include + // #error is not supported when compiling with /clr or /clr:pure. + // #include +#endif + +#ifndef threadLocal +# if (__STDC_VERSION__ >= 201112) && !defined(__STDC_NO_THREADS__) +# define threadLocal _Thread_local +# elif defined C3D_WINDOWS && ( \ + defined _MSC_VER || \ + defined __ICL || \ + defined __DMC__ ) +# define threadLocal __declspec(thread) +/* note that ICC (linux) and Clang are covered by __GNUC__ */ +# elif defined __GNUC__ || \ + defined __SUNPRO_C || \ + defined __xlC__ +# define threadLocal __thread +# else +# error "Cannot define thread_local" +# endif +#endif + + +//------------------------------------------------------------------------------ +/** \brief \ru Высокоточный таймер. + \en High resolution timer. \~ + \details \ru Высокоточный таймер. + \en High resolution timer. \~ +\ingroup Base_Tools +*/ +// --- +class MbAccurateTimer { +#ifdef C3D_STANDARD_CXX_11_PARTIAL + typedef std::chrono::high_resolution_clock::time_point TimePoint; +#endif +protected: + double lastTime; ///< \ru Время в секундах. \en Time in seconds. +private: +#ifdef C3D_STANDARD_CXX_11_PARTIAL + TimePoint begTime; ///< \ru Засечка времени. \en Time stamp. +#endif + +public: + /// \ru Конструктор. \en Constructor. + MbAccurateTimer() : lastTime( 0.0 ) {} + virtual ~MbAccurateTimer() {} + + /// \ru Сброшен ли таймер. \en Is empty timer? + virtual bool IsEmpty () const { return !(lastTime > 0.0); } + /// \ru Сбросить таймер. \en Reset timer. + virtual void SetEmpty() { lastTime = 0.0; } + /// \ru Добавить значение. \en Add time value. + virtual bool SetTime ( double t ) { lastTime = t; return (t >= 0); } + /// \ru Начать отсчет. \en Start time measurement. + virtual void Begin (); + /// \ru Закончить отсчет. \en Finish time measurement. + virtual void End (); + /// \ru Получить значение времени. \en Get time value. + double GetLast() const { return lastTime; } + /// \ru Получить значение частоты. \en Get frequency value. + double PerSec () const { return (lastTime > 0.0 ? 1.0 / lastTime : 0.0); } +}; + + +//------------------------------------------------------------------------------ +// \ru Начать отсчет. \en Start time measurement. +//--- +inline void MbAccurateTimer::Begin() +{ +#ifdef C3D_STANDARD_CXX_11_PARTIAL + begTime = std::chrono::high_resolution_clock::now(); +#endif +} + +//------------------------------------------------------------------------------ +// \ru Закончить отсчет. \en Finish time measurement. +// --- +inline void MbAccurateTimer::End() +{ +#ifdef C3D_STANDARD_CXX_11_PARTIAL + TimePoint endTime = std::chrono::high_resolution_clock::now(); + double t = std::chrono::duration_cast< std::chrono::duration >(endTime - begTime).count(); + SetTime( t ); +#endif +} + + +//------------------------------------------------------------------------------ +/** \brief \ru Таймер со статистикой. + \en Average timer. \~ + \details \ru Таймер со статистикой. + \en Average timer. \~ +\ingroup Base_Tools +*/ +// --- +class MbAverageTimer : public MbAccurateTimer +{ + double avgTime; ///< \ru Среднее время в секундах. \en Average time in seconds. + double minTime; ///< \ru Минимальное время в секундах. \en Min. time in seconds. + double maxTime; ///< \ru Максимальное время в секундах. \en Max. time in seconds. + uint runCount; ///< \ru Количество запусков. \en Number of samples. + +public: + /// \ru Конструктор. \en Constructor. + MbAverageTimer() : avgTime( 0.0 ), minTime( 0.0 ), maxTime ( 0.0 ), runCount( 0 ) {} + + virtual bool IsEmpty() const { return (runCount == 0); } + virtual void SetEmpty(); + virtual bool SetTime( double ); + double GetAvg() const { return avgTime; } + double GetMin() const { return minTime; } + double GetMax() const { return maxTime; } +}; + +//------------------------------------------------------------------------------ +// \ru Сбросить таймер. \en Reset timer. +//--- +inline void MbAverageTimer::SetEmpty() +{ + MbAccurateTimer::SetEmpty(); + avgTime = minTime = maxTime = 0.0; + runCount = 0; +} + +//------------------------------------------------------------------------------ +// \ru Добавить значение. \en Add value. +//--- +inline bool MbAverageTimer::SetTime( double t ) +{ + bool res = MbAccurateTimer::SetTime( t ); + + if ( IsEmpty() ) + avgTime = minTime = maxTime = t; + else + { + avgTime += (t - avgTime) / (runCount + 1); + minTime = (std::min)( minTime, t ); + maxTime = (std::max)( maxTime, t ); + } + + runCount++; + return res; +} + +#endif // __SYSTEM_DEPENDENCY_H diff --git a/C3d/Include/system_types.h b/C3d/Include/system_types.h index a63100a..deeb7cc 100644 --- a/C3d/Include/system_types.h +++ b/C3d/Include/system_types.h @@ -78,10 +78,10 @@ typedef uint32 VERSION; ///< \ru Версия. \en Version. \~ // \ru Умный указатель, единолично владеющий объектом. // \en Smart pointer that solely owns the object. //--- -#ifdef STANDARD_C11 -#define std_unique_ptr std::unique_ptr +#ifdef C3D_STANDARD_CXX_11_PARTIAL + #define std_unique_ptr std::unique_ptr #else -#define std_unique_ptr std::auto_ptr + #define std_unique_ptr std::auto_ptr #endif //------------------------------------------------------------------------------ @@ -116,46 +116,46 @@ typedef ptrdiff_t refcount_t; // Возвращаемый тип счет #if defined(PLATFORM_64) /// \ru Максимальное значение uint. \en Maximum value of uint. \~ \ingroup Base_Tools -const uint SYS_MAX_UINT = 0xffffffff; // ((uint)-1) //-V112 +const_expr uint SYS_MAX_UINT = 0xffffffff; // ((uint)-1) //-V112 /// \ru Максимальное значение size_t. \en Maximum value of size_t. \~ \ingroup Base_Tools -const size_t SYS_MAX_T = 0xffffffffffffffff; // ((size_t)-1) //-V112 +const_expr size_t SYS_MAX_T = 0xffffffffffffffff; // ((size_t)-1) //-V112 /// \ru Максимальное значение ptrdiff_t. \en Maximum value of ptrdiff_t. \~ \ingroup Base_Tools -const ptrdiff_t SYS_MAX_ST = 0x7fffffffffffffff; //-V112 +const_expr ptrdiff_t SYS_MAX_ST = 0x7fffffffffffffff; //-V112 /// \ru Минимальное значение ptrdiff_t. \en Minimum value of ptrdiff_t. \~ \ingroup Base_Tools -const ptrdiff_t SYS_MIN_ST = 0x8000000000000000; //-V112 +const_expr ptrdiff_t SYS_MIN_ST = 0x8000000000000000; //-V112 #else // PLATFORM_64 /// \ru Максимальное значение uint. \en Maximum value of uint. \~ \ingroup Base_Tools -const uint SYS_MAX_UINT = 0xffffffff; // ((uint)-1) //-V112 +const_expr uint SYS_MAX_UINT = 0xffffffff; // ((uint)-1) //-V112 /// \ru Максимальное значение size_t. \en Maximum value of size_t. \~ \ingroup Base_Tools -const size_t SYS_MAX_T = 0xffffffff; // ((size_t)-1) //-V112 +const_expr size_t SYS_MAX_T = 0xffffffff; // ((size_t)-1) //-V112 /// \ru Максимальное значение ptrdiff_t. \en Maximum value of ptrdiff_t. \~ \ingroup Base_Tools -const ptrdiff_t SYS_MAX_ST = 0x7fffffff; //-V112 +const_expr ptrdiff_t SYS_MAX_ST = 0x7fffffff; //-V112 /// \ru Минимальное значение ptrdiff_t. \en Minimum value of ptrdiff_t. \~ \ingroup Base_Tools -const ptrdiff_t SYS_MIN_ST = 0x80000000; //-V112 +const_expr ptrdiff_t SYS_MIN_ST = 0x80000000; //-V112 #endif // PLATFORM_64 /// \ru Максимальное значение uint8. \en Maximum value of uint8. \~ \ingroup Base_Tools -const uint8 SYS_MAX_UINT8 = 0xFF; //-V112 +const_expr uint8 SYS_MAX_UINT8 = 0xFF; //-V112 /// \ru Максимальное значение uint16. \en Maximum value of uint16. \~ \ingroup Base_Tools -const uint16 SYS_MAX_UINT16 = 0xFFFF; //-V112 +const_expr uint16 SYS_MAX_UINT16 = 0xFFFF; //-V112 /// \ru Максимальное значение uint32. \en Maximum value of uint32. \~ \ingroup Base_Tools -const uint32 SYS_MAX_UINT32 = 0xFFFFFFFF; //-V112 +const_expr uint32 SYS_MAX_UINT32 = 0xFFFFFFFF; //-V112 /// \ru Максимальное значение uint64. \en Maximum value of uint64. \~ \ingroup Base_Tools -const uint64 SYS_MAX_UINT64 = 0xFFFFFFFFFFFFFFFF; //-V112 +const_expr uint64 SYS_MAX_UINT64 = 0xFFFFFFFFFFFFFFFF; //-V112 /// \ru Максимальное значение int16. \en Maximum value of int16. \~ \ingroup Base_Tools -const int16 SYS_MAX_INT16 = 0x7FFF; //-V112 +const_expr int16 SYS_MAX_INT16 = 0x7FFF; //-V112 /// \ru Максимальное значение int32. \en Maximum value of int32. \~ \ingroup Base_Tools -const int32 SYS_MAX_INT32 = 0x7FFFFFFF; //-V112 +const_expr int32 SYS_MAX_INT32 = 0x7FFFFFFF; //-V112 /// \ru Максимальное значение int64. \en Maximum value of int64. \~ \ingroup Base_Tools -const int64 SYS_MAX_INT64 = 0x7FFFFFFFFFFFFFFF; //-V112 +const_expr int64 SYS_MAX_INT64 = 0x7FFFFFFFFFFFFFFF; //-V112 /// \ru Минимальное значение int16. \en Minimum value of int16. \~ \ingroup Base_Tools -const int16 SYS_MIN_INT16 = (int16)(uint16)0x8000; //-V112 +const_expr int16 SYS_MIN_INT16 = (int16)(uint16)0x8000; //-V112 /// \ru Минимальное значение int32. \en Minimum value of int32. \~ \ingroup Base_Tools -const int32 SYS_MIN_INT32 = (int32)(uint32)0x80000000; //-V112 +const_expr int32 SYS_MIN_INT32 = (int32)(uint32)0x80000000; //-V112 /// \ru Минимальное значение int64. \en Minimum value of int64. \~ \ingroup Base_Tools -const int64 SYS_MIN_INT64 = (int64)(uint64)0x8000000000000000; //-V112 +const_expr int64 SYS_MIN_INT64 = (int64)(uint64)0x8000000000000000; //-V112 //#endif // NOMINMAX @@ -202,12 +202,12 @@ inline int8 HiInt8 ( uint16 u16 ) { return int8(u16 >> 8); } //-V //------------------------------------------------------------------------------ /// \ru Неопределенный размер. \en Undefined size. \~ \ingroup Base_Tools //--- -const size_t NSIZE = SYS_MAX_T; //OV_x64 (size_t)-1; +const_expr size_t NSIZE = SYS_MAX_T; //OV_x64 (size_t)-1; //------------------------------------------------------------------------------ /// \ru Неопределенная позиция (для 32 битных данных). \en Undefined position (for 32-bit data). \~ \ingroup Base_Tools //--- -const uint NPOS32 = (uint)SYS_MAX_UINT32; // \ru КВН x64 -1 для работы с таблицами \en КВН x64 -1 for dealing with tables +const_expr uint NPOS32 = (uint)SYS_MAX_UINT32; // \ru КВН x64 -1 для работы с таблицами \en КВН x64 -1 for dealing with tables //------------------------------------------------------------------------------ @@ -218,7 +218,7 @@ const uint NPOS32 = (uint)SYS_MAX_UINT32; // \ru КВН x64 -1 для работ \ingroup Base_Tools */ //--- -const size_t SIZE_OF_POINTER = sizeof(char *); +const_expr size_t SIZE_OF_POINTER = sizeof(char *); //------------------------------------------------------------------------------ @@ -243,7 +243,7 @@ SignedType abs_t( const SignedType x ) { return ((x >= 0) ? x : -x); } //KYA K13 #pragma warning(disable: 4251) //AP class '1' needs to have dll-interface to be used by clients of class '2' (using non-exported in exported) // have to be disabled -#pragma warning(disable: 4018) // W3: comparison : signed/unsigned mismatch +//#pragma warning(disable: 4018) // W3: comparison : signed/unsigned mismatch #pragma warning(disable: 4201) // W4: nonstandard extension used : nameless struct/union #pragma warning(disable: 4245) // W4: const conversion, signed/unsigned mismatch diff --git a/C3d/Include/templ_array2.h b/C3d/Include/templ_array2.h index a205d26..e1c1156 100644 --- a/C3d/Include/templ_array2.h +++ b/C3d/Include/templ_array2.h @@ -19,11 +19,6 @@ #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - - class reader; class writer; @@ -84,11 +79,11 @@ public: // Общие методы матриц (двумерных массив bool SetSize( size_t n ) { return SetSize( n, n ); } ///< \ru Установить размер. \en Set size. /// \ru Получить элемент массива. \en Get an element of the array. - const Type & GetElem( size_t ln, size_t cn ) const { PRECONDITION( !!parr && ln < l && cn < c ); return parr[ln][cn]; } + const Type & GetElem( size_t ln, size_t cn ) const; /// \ru Установить элемент массива. \en Set an element of the array. - void SetElem( size_t ln, size_t cn, const Type & v ) { PRECONDITION( !!parr && ln < l && cn < c ); parr[ln][cn] = v; } + void SetElem( size_t ln, size_t cn, const Type & v ); /// \ru Оператор доступа по индексам. \en Access by indices operator. - const Type & operator () ( size_t i, size_t j ) const { PRECONDITION( i < l && j < c ); return parr[i][j]; } + const Type & operator () ( size_t i, size_t j ) const; /// \ru Расписать массив нулями. \en Assign zeros to array. Array2 & SetZero() { zero_array( *this ); return *this; } /// \ru Функция присваивания. \en An assignment function. @@ -100,13 +95,13 @@ public: // Общие методы матриц (двумерных массив public: /// \ru Оператор доступа по индексам. \en Access by indices operator. - Type & operator () ( size_t i, size_t j ) { PRECONDITION( i < l && j < c ); return parr[i][j]; } + Type & operator () ( size_t i, size_t j ); /// \ru Выдать адрес начала строки. \en Get an address of the row start. - const Type * GetLine( size_t i = 0 ) const { PRECONDITION( i < l ); return parr[i]; } + const Type * GetLine( size_t i = 0 ) const; /// \ru Выдать адрес начала строки. \en Get an address of the row start. - Type * SetLine( size_t i = 0 ) { PRECONDITION( i < l ); return parr[i]; } + Type * SetLine( size_t i = 0 ); /// \ru Инициировать элемент. \en Initiate an element. - void Init( size_t ln, size_t cn, const Type & v ) { PRECONDITION( !!parr && ln < l && cn < c ); parr[ln][cn] = v; } + void Init( size_t ln, size_t cn, const Type & v ); /// \ru Функции, выделяющие потенциально большие участки памяти, возвращают результат операции (успех/ошибка). /// \en Functions that allocate potentially large memory, return the operation result (success/error). @@ -247,6 +242,74 @@ inline bool Array2::SetSize( size_t lSize, size_t cSize ) { return ::set_array_size( *this, lSize, cSize ); } +//------------------------------------------------------------------------------ +// \ru Получить элемент массива. \en Get an element of the array. +// --- +template +const Type & Array2::GetElem( size_t ln, size_t cn ) const { + PRECONDITION( !!parr && ln < l && cn < c ); + return parr[ln][cn]; +} + +//------------------------------------------------------------------------------ +// \ru Установить элемент массива. \en Set an element of the array. +// --- +template +void Array2::SetElem( size_t ln, size_t cn, const Type & v ) { + PRECONDITION( !!parr && ln < l && cn < c ); + if ( !!parr && ln < l && cn < c ) + parr[ln][cn] = v; +} + +//------------------------------------------------------------------------------ +// \ru Оператор доступа по индексам. \en Access by indices operator. +// --- +template +const Type & Array2::operator() ( size_t i, size_t j ) const { + PRECONDITION( i < l && j < c ); + return parr[i][j]; +} + +/// \ru Оператор доступа по индексам. \en Access by indices operator. +template +Type & Array2::operator() ( size_t i, size_t j ) { + PRECONDITION( i < l && j < c ); + return parr[i][j]; +} + +//------------------------------------------------------------------------------ +// \ru Выдать адрес начала строки. \en Get an address of the row start. +// --- +template +const Type * Array2::GetLine( size_t i ) const { + PRECONDITION( i < l ); + if ( i < l ) + return parr[i]; + return NULL; +} + +//------------------------------------------------------------------------------ +// \ru Выдать адрес начала строки. \en Get an address of the row start. +// --- +template +Type * Array2::SetLine( size_t i ) { + PRECONDITION( i < l ); + if ( i < l ) + return parr[i]; + return NULL; +} + +//------------------------------------------------------------------------------ +// \ru Инициировать элемент. \en Initiate an element. +// --- +template +void Array2::Init( size_t ln, size_t cn, const Type & v ) { + PRECONDITION( !!parr && ln < l && cn < c ); + if ( !!parr && ln < l && cn < c ) + parr[ln][cn] = v; +} + + //------------------------------------------------------------------------------ // \ru Поменять местами строки. \en Swap lines. // --- @@ -396,7 +459,7 @@ inline bool Array2::CatchLinePointers( size_t newCount ) l = newCount; #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldSize * SIZE_OF_POINTER, parr, newCount * SIZE_OF_POINTER, 2/*Array2*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldSize * SIZE_OF_POINTER, parr, newCount * SIZE_OF_POINTER, 2/*Array2*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ } catch ( const std::bad_alloc & ) { @@ -457,7 +520,7 @@ inline bool realloc_line( Type *& line, size_t oldSize, size_t newSize ) #endif // USE_REALLOC_IN_ARRAYS #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldSize * sizeOfType, line, newSize * sizeOfType, 2/*Array2*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldSize * sizeOfType, line, newSize * sizeOfType, 2/*Array2*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ } catch ( const std::bad_alloc & ) { diff --git a/C3d/Include/templ_balance_tree.h b/C3d/Include/templ_balance_tree.h index 0287f1b..82517a6 100644 --- a/C3d/Include/templ_balance_tree.h +++ b/C3d/Include/templ_balance_tree.h @@ -319,7 +319,7 @@ inline void BalanceTreeNode::operator delete ( void * ptr, size_t size ) { // \ru конструктор узла дерева \en constructor of node of tree // --- template -inline BalanceTreeNode::BalanceTreeNode( BalanceTree & parent, Type * content ) : +inline BalanceTreeNode::BalanceTreeNode( BalanceTree & parent, Type * content ) : parent_m ( parent ), left_m ( NULL ), right_m ( NULL ), @@ -366,7 +366,7 @@ inline void BalanceTreeNode::SetRight( BalanceTreeNode * p ){ // \ru конструктор дерева \en constructor of tree // --- template -inline BalanceTree::BalanceTree( Compare_t c_t, Compare_v c_v, bool shouldDelete ) : +inline BalanceTree::BalanceTree( Compare_t c_t, Compare_v c_v, bool shouldDelete ) : root_m ( NULL ), allCount_m ( 0 ), owns_m ( shouldDelete ), @@ -513,7 +513,7 @@ inline void BalanceTree::ForEach( IterFunc f, void *pars ) { // \ru двойной RL-поворот \en double RL-rotation // --- template -inline void BalanceTree::DoubleTurningRL ( BalanceTreeNode *& node, +inline void BalanceTree::DoubleTurningRL ( BalanceTreeNode *& node, BalanceTreeNode * p1, BalanceTreeNode *& p2 ) { p2 = p1->left_m; @@ -533,7 +533,7 @@ inline void BalanceTree::DoubleTurningRL ( BalanceTreeNode *& node, // \ru двойной LR-поворот \en double LR-rotation // --- template -inline void BalanceTree::DoubleTurningLR ( BalanceTreeNode *& node, +inline void BalanceTree::DoubleTurningLR ( BalanceTreeNode *& node, BalanceTreeNode * p1, BalanceTreeNode *& p2 ) { p2 = p1->right_m; @@ -553,7 +553,7 @@ inline void BalanceTree::DoubleTurningLR ( BalanceTreeNode *& node, // \ru Построение идеально сбалансированного дерева \en Creation of ideally balanced tree // --- template -inline bool BalanceTree::AddToBalanceTree( Type & content, BalanceTreeNode *& node, +inline bool BalanceTree::AddToBalanceTree( Type & content, BalanceTreeNode *& node, bool & isBranchGrew ) { bool isAdd = false; if ( !node ) { @@ -646,7 +646,7 @@ inline bool BalanceTree::AddToBalanceTree( Type & content, BalanceTreeNode // \ru Балансировка слева \en Balancing at the left // --- template -inline void BalanceTree::BalanceL( BalanceTreeNode *& node, bool & isBranchGrew ) { +inline void BalanceTree::BalanceL( BalanceTreeNode *& node, bool & isBranchGrew ) { switch ( node->balance_m ) { case ts_negative : node->balance_m = ts_neutral; break; case ts_neutral : node->balance_m = ts_positive; isBranchGrew = false; break; @@ -685,7 +685,7 @@ inline void BalanceTree::BalanceL( BalanceTreeNode *& node, bool & i // \ru Балансировка справа \en Balancing at the right // --- template -inline void BalanceTree::BalanceR( BalanceTreeNode *& node, bool & isBranchGrew ) { +inline void BalanceTree::BalanceR( BalanceTreeNode *& node, bool & isBranchGrew ) { switch ( node->balance_m ) { case ts_positive : node->balance_m = ts_neutral; break; case ts_neutral : node->balance_m = ts_negative; isBranchGrew = false; break; @@ -724,7 +724,7 @@ inline void BalanceTree::BalanceR( BalanceTreeNode *& node, bool & i // \ru Исключение из сбалансированного дерева \en Exclude from balanced tree // --- template -inline bool BalanceTree::DelFromBalanceTree( BalanceTreeNode *& q, BalanceTreeNode *& r, bool & isBranchGrew ) { +inline bool BalanceTree::DelFromBalanceTree( BalanceTreeNode *& q, BalanceTreeNode *& r, bool & isBranchGrew ) { bool res = false; if ( r->right_m ) { res = DelFromBalanceTree( q, r->right_m, isBranchGrew ); @@ -748,7 +748,7 @@ inline bool BalanceTree::DelFromBalanceTree( BalanceTreeNode *& q, B // \ru Исключение из сбалансированного дерева \en Exclude from balanced tree // --- template -inline bool BalanceTree::DeleteFromBalanceTree( Type & content, BalanceTreeNode *& node, +inline bool BalanceTree::DeleteFromBalanceTree( Type & content, BalanceTreeNode *& node, bool & isBranchGrew, DelType del ) { bool res = false; if ( node && node->content_m ) { diff --git a/C3d/Include/templ_c_array.h b/C3d/Include/templ_c_array.h index a83e941..e116a25 100644 --- a/C3d/Include/templ_c_array.h +++ b/C3d/Include/templ_c_array.h @@ -20,10 +20,6 @@ #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - FORVARD_DECL_TEMPLATE_TYPENAME( class CcArray ); FORVARD_DECL_TEMPLATE_TYPENAME( void fill_array( CcArray &, const Type & fillData, size_t cnt ) ); @@ -68,12 +64,7 @@ public : /// \ru Освободить память. \en Free memory. void FreeMemory() { SetArraySize( 0 ); } /// \ru Оператор доступа. \en An access operator. - Type & operator []( size_t idx ) const { -#if defined(C3D_DEBUG) - PRECONDITION( idx < count ); -#endif - return parr[idx]; - } + Type & operator []( size_t idx ) const { PRECONDITION( idx < count ); return parr[idx]; } /// \ru Выделена ли память? \en Is memory allocated? bool IsNull () const { return parr == NULL; } /// \ru Выдать адрес начала массива. \en Get address of the beginning of an array. @@ -134,9 +125,7 @@ inline CcArray::CcArray( size_t _count ) template inline void CcArray::Copy( const void * from, size_t cnt, size_t offset ) { -#if defined(C3D_DEBUG) PRECONDITION( (offset + cnt <= count) && (cnt ? from != NULL : true) ); -#endif memcpy( parr + offset, from, cnt * sizeof(Type) ); } @@ -172,7 +161,7 @@ inline bool CcArray::SetArraySize( size_t newCount ) #if defined(C3D_DEBUG) count = newCount; #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldSize * sizeof(Type), parr, newCount * sizeof(Type), 4/*CcArray*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldSize * sizeof(Type), parr, newCount * sizeof(Type), 4/*CcArray*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ #endif // C3D_DEBUG } @@ -202,9 +191,7 @@ inline bool CcArray::SetArraySize( size_t newCount ) template void fill_array( CcArray & arr, const Type & fillData, size_t cnt ) { -#if defined(C3D_DEBUG) PRECONDITION( cnt <= arr.count ); -#endif for ( size_t i = 0; i < cnt; i++ ) memcpy( &arr[i], &fillData, sizeof(Type) ); } diff --git a/C3d/Include/templ_csp_array.h b/C3d/Include/templ_csp_array.h index 3005fc3..79d43d5 100644 --- a/C3d/Include/templ_csp_array.h +++ b/C3d/Include/templ_csp_array.h @@ -16,8 +16,8 @@ FORVARD_DECL_TEMPLATE_TYPENAME( class CSPArray ); FORVARD_DECL_TEMPLATE_TYPENAME( void qp_sort( CSPArray & arr ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader& CALL_DECLARATION operator >> ( reader& in, CSPArray & ref ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( writer& CALL_DECLARATION operator << ( writer& out, const CSPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, CSPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const CSPArray & ref ) ); //------------------------------------------------------------------------------ @@ -85,8 +85,8 @@ public: Type * RemoveObj( Type * delObject, DelType del ); ///< \ru Удалить элемент. \en Delete element. TEMPLATE_FRIEND void qp_sort TEMPLATE_SUFFIX ( CSPArray & arr ); - TEMPLATE_FRIEND reader& CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader& in, CSPArray & ref ); - TEMPLATE_FRIEND writer& CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer& out, const CSPArray & ref ); + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, CSPArray & ref ); + TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const CSPArray & ref ); private: /// \ru Сортировка с выбором удаляемого элемента из двух одинаковых. \en Sort with the choice of the element to remove from the two identical. @@ -100,7 +100,7 @@ private: // \ru добавление объекта в массив \en adding an object to array // --- template -inline Type* CSPArray::Add( Type * el ) +inline Type * CSPArray::Add( Type * el ) { //::qp_sort( *this ); Sort(); @@ -112,7 +112,7 @@ inline Type* CSPArray::Add( Type * el ) // \ru добавление объекта в массив \en adding an object to array // --- template -inline Type* CSPArray::Add( Type * el, size_t & indexEl ) +inline Type * CSPArray::Add( Type * el, size_t & indexEl ) { //::qp_sort( *this ); Sort(); @@ -124,7 +124,7 @@ inline Type* CSPArray::Add( Type * el, size_t & indexEl ) // \ru поиск объекта в массиве \en search of an element in array // --- template -inline size_t /*OV_x64 int*/ CSPArray::Find( const Type * el ) +inline size_t CSPArray::Find( const Type * el ) { // ::qp_sort( *this ); Sort(); @@ -179,7 +179,8 @@ inline void CSPArray::Sort( LessFuncPtr lessFunc ) // \ru удалить элемент из массива (по указателю) \en delete an element from array (by the pointer) // --- template -inline Type* CSPArray::RemoveObj( Type *delObject, DelType del ) { +inline Type * CSPArray::RemoveObj( Type * delObject, DelType del ) +{ C3D_ASSERT( SPArray::nowDeletedElem == 0 ); // \ru Bременно, для отладки \en Temporarily, for debugging. size_t i = Find( delObject ); return ( i != SYS_MAX_T ) ? RemoveInd(i, del) : 0; diff --git a/C3d/Include/templ_dptr.h b/C3d/Include/templ_dptr.h index 94f46ad..1f59775 100644 --- a/C3d/Include/templ_dptr.h +++ b/C3d/Include/templ_dptr.h @@ -1,186 +1,186 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Автоматический указатель на объекты, не имеющие счетчиков ссылок. - \en Smart pointer to objects without reference counters. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TEMPL_DPTR_H -#define __TEMPL_DPTR_H - - -#ifndef NULL - #define NULL 0 -#endif - - -#include -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Автоматический указатель. - \en Smart pointer. \~ - \details \ru Автоматический указатель на объекты, не имеющие счетчиков ссылок. \n - \en Smart pointer to objects without reference counters. \n \~ - \ingroup Base_Tools_SmartPointers -*/ -// --- -template -class DPtr { -public: - /// \ru Конструктор. \en Constructor. - DPtr(); - /// \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. - DPtr( dtype * obj ); - /// \ru Конструктор по автоматическому указателю на объект. \en Constructor by smart pointer to an object. - DPtr( const DPtr & dptr ); - /// \ru Деструктор. \en Destructor. - ~DPtr(); - -public: - /// \ru Оператор доступа. \en An access operator. - operator dtype* ( void ) const { return m_Ptr; } - /// \ru Оператор доступа. \en An access operator. - dtype & operator * ( void ) const { return *m_Ptr; } - /// \ru Оператор доступа. \en An access operator. - dtype * operator -> ( void ) const { return m_Ptr; } - /// \ru Оператор присваивания. \en The assignment operator. - DPtr & operator = ( dtype * pObj ); - /// \ru Оператор присваивания. \en The assignment operator. - DPtr & operator = ( const DPtr & src ); - /// \ru Оператор равенства. \en The equality operator. - bool operator == ( const DPtr & src ) const { return ( m_Ptr == src.m_Ptr ); } - /// \ru Оператор равенства. \en The equality operator. - bool operator == ( dtype * pObj ) const { return ( m_Ptr == pObj ); } - /// \ru Оператор неравенства. \en The inequality operator. - bool operator != ( const DPtr & src ) const { return ( !(operator == (src )) ); } - /// \ru Оператор неравенства. \en The inequality operator. - bool operator != ( dtype * pObj ) const { return ( !(operator == (pObj)) ); } - -private: - /// \ru Счетчик ссылок на объект. \en A counter of references to an object. - template - struct Owner { - dtype1 * m_Ptr; - uint m_RefCounter; - - Owner( dtype1 * obj ) - : m_Ptr( obj ) - , m_RefCounter(0) - {} - ~Owner() - { - PRECONDITION( m_RefCounter == 0 ); - delete m_Ptr; - } - void Release() - { - if ( m_RefCounter-- == 1 ) - delete this; - } - }; - -private: - dtype * m_Ptr; ///< \ru Указатель на объект. \en A pointer to an object. - Owner * m_Owner; ///< \ru Счетчик ссылок на объект. \en A counter of references to an object. -}; - - -//------------------------------------------------------------------------------- -/// \ru Конструктор. \en Constructor. -// --- -template -DPtr::DPtr() - : m_Ptr ( NULL ) - , m_Owner( NULL ) -{ -} - - -//------------------------------------------------------------------------------- -// \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. -// --- -template -DPtr::DPtr( dtype * obj ) - : m_Ptr ( obj ) - , m_Owner( NULL ) -{ - if ( obj != NULL ) { - m_Owner = new Owner( obj ); - m_Owner->m_RefCounter++; - } -} - - -//------------------------------------------------------------------------------- -// \ru Конструктор копирования. \en Copy constructor. -// --- -template -DPtr::DPtr( const DPtr & dptr ) - : m_Ptr( dptr.m_Ptr ) - , m_Owner( dptr.m_Owner ) -{ - if ( m_Owner != NULL ) - m_Owner->m_RefCounter++; -} - - -//------------------------------------------------------------------------------- -// \ru Оператор присваивания. \en Assignment operator. -// --- -template -DPtr & DPtr::operator = ( dtype * pObj ) -{ - if ( m_Ptr != pObj ) { - m_Ptr = pObj; - if ( m_Owner != NULL ) { - m_Owner->Release(); - m_Owner = NULL; - } - if ( pObj != NULL ) { - m_Owner = new Owner( pObj ); - m_Owner->m_RefCounter++; - } - } - - return *this; -} - - -//------------------------------------------------------------------------------- -// \ru Оператор присваивания. \en Assignment operator. -// --- -template -DPtr & DPtr::operator = ( const DPtr & dptr ) -{ - if ( m_Ptr != dptr.m_Ptr ) { - m_Ptr = dptr.m_Ptr; - if ( m_Owner != NULL ) { - m_Owner->Release(); - m_Owner = NULL; - } - if ( dptr.m_Ptr != NULL ) { - m_Owner = dptr.m_Owner; - m_Owner->m_RefCounter++; - } - } - - return *this; -} - - -//------------------------------------------------------------------------------- -// \ru Деструктор. \en Destructor. -// --- -template -DPtr::~DPtr() -{ - if ( m_Owner ) - m_Owner->Release(); -} - - -#endif // __TEMPL_DPTR_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Автоматический указатель на объекты, не имеющие счетчиков ссылок. + \en Smart pointer to objects without reference counters. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TEMPL_DPTR_H +#define __TEMPL_DPTR_H + + +#ifndef NULL + #define NULL 0 +#endif + + +#include +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Автоматический указатель. + \en Smart pointer. \~ + \details \ru Автоматический указатель на объекты, не имеющие счетчиков ссылок. \n + \en Smart pointer to objects without reference counters. \n \~ + \ingroup Base_Tools_SmartPointers +*/ +// --- +template +class DPtr { +public: + /// \ru Конструктор. \en Constructor. + DPtr(); + /// \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. + DPtr( dtype * obj ); + /// \ru Конструктор по автоматическому указателю на объект. \en Constructor by smart pointer to an object. + DPtr( const DPtr & dptr ); + /// \ru Деструктор. \en Destructor. + ~DPtr(); + +public: + /// \ru Оператор доступа. \en An access operator. + operator dtype* ( void ) const { return m_Ptr; } + /// \ru Оператор доступа. \en An access operator. + dtype & operator * ( void ) const { return *m_Ptr; } + /// \ru Оператор доступа. \en An access operator. + dtype * operator -> ( void ) const { return m_Ptr; } + /// \ru Оператор присваивания. \en The assignment operator. + DPtr & operator = ( dtype * pObj ); + /// \ru Оператор присваивания. \en The assignment operator. + DPtr & operator = ( const DPtr & src ); + /// \ru Оператор равенства. \en The equality operator. + bool operator == ( const DPtr & src ) const { return ( m_Ptr == src.m_Ptr ); } + /// \ru Оператор равенства. \en The equality operator. + bool operator == ( dtype * pObj ) const { return ( m_Ptr == pObj ); } + /// \ru Оператор неравенства. \en The inequality operator. + bool operator != ( const DPtr & src ) const { return ( !(operator == (src )) ); } + /// \ru Оператор неравенства. \en The inequality operator. + bool operator != ( dtype * pObj ) const { return ( !(operator == (pObj)) ); } + +private: + /// \ru Счетчик ссылок на объект. \en A counter of references to an object. + template + struct Owner { + dtype1 * m_Ptr; + uint m_RefCounter; + + Owner( dtype1 * obj ) + : m_Ptr( obj ) + , m_RefCounter(0) + {} + ~Owner() + { + PRECONDITION( m_RefCounter == 0 ); + delete m_Ptr; + } + void Release() + { + if ( m_RefCounter-- == 1 ) + delete this; + } + }; + +private: + dtype * m_Ptr; ///< \ru Указатель на объект. \en A pointer to an object. + Owner * m_Owner; ///< \ru Счетчик ссылок на объект. \en A counter of references to an object. +}; + + +//------------------------------------------------------------------------------- +/// \ru Конструктор. \en Constructor. +// --- +template +DPtr::DPtr() + : m_Ptr ( NULL ) + , m_Owner( NULL ) +{ +} + + +//------------------------------------------------------------------------------- +// \ru Конструктор по указателю на объект. \en Constructor by pointer to an object. +// --- +template +DPtr::DPtr( dtype * obj ) + : m_Ptr ( obj ) + , m_Owner( NULL ) +{ + if ( obj != NULL ) { + m_Owner = new Owner( obj ); + m_Owner->m_RefCounter++; + } +} + + +//------------------------------------------------------------------------------- +// \ru Конструктор копирования. \en Copy constructor. +// --- +template +DPtr::DPtr( const DPtr & dptr ) + : m_Ptr( dptr.m_Ptr ) + , m_Owner( dptr.m_Owner ) +{ + if ( m_Owner != NULL ) + m_Owner->m_RefCounter++; +} + + +//------------------------------------------------------------------------------- +// \ru Оператор присваивания. \en Assignment operator. +// --- +template +DPtr & DPtr::operator = ( dtype * pObj ) +{ + if ( m_Ptr != pObj ) { + m_Ptr = pObj; + if ( m_Owner != NULL ) { + m_Owner->Release(); + m_Owner = NULL; + } + if ( pObj != NULL ) { + m_Owner = new Owner( pObj ); + m_Owner->m_RefCounter++; + } + } + + return *this; +} + + +//------------------------------------------------------------------------------- +// \ru Оператор присваивания. \en Assignment operator. +// --- +template +DPtr & DPtr::operator = ( const DPtr & dptr ) +{ + if ( m_Ptr != dptr.m_Ptr ) { + m_Ptr = dptr.m_Ptr; + if ( m_Owner != NULL ) { + m_Owner->Release(); + m_Owner = NULL; + } + if ( dptr.m_Ptr != NULL ) { + m_Owner = dptr.m_Owner; + m_Owner->m_RefCounter++; + } + } + + return *this; +} + + +//------------------------------------------------------------------------------- +// \ru Деструктор. \en Destructor. +// --- +template +DPtr::~DPtr() +{ + if ( m_Owner ) + m_Owner->Release(); +} + + +#endif // __TEMPL_DPTR_H diff --git a/C3d/Include/templ_fdp_array.h b/C3d/Include/templ_fdp_array.h index 089ed17..f34f6e9 100644 --- a/C3d/Include/templ_fdp_array.h +++ b/C3d/Include/templ_fdp_array.h @@ -18,10 +18,6 @@ #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - FORVARD_DECL_TEMPLATE_TYPENAME( class FDPArray ); FORVARD_DECL_TEMPLATE_TYPENAME( void destroy_array ( FDPArray & ) ); @@ -109,11 +105,11 @@ public: void operator delete ( void *, size_t ); #endif // __DEBUG_MEMORY_ALLOCATE_FREE_ -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: FDPArray( FDPArray && ); ///< \ru Конструктор перемещения массива. \en Constructor of an array moving. FDPArray & operator = ( FDPArray && ); ///< \ru Оператор перемещения массива. \en Operator of an array moving. -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -135,7 +131,7 @@ inline void FDPArray::operator delete( void * ptr, size_t size ) { } #endif // __DEBUG_MEMORY_ALLOCATE_FREE_ -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ // \ru Конструктор перемещения массива. \en Constructor of an array moving. // --- @@ -164,7 +160,7 @@ FDPArray & FDPArray::operator = ( FDPArray && _Right ) } return (*this); } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ // \ru деструктор массива \en destructor of array // --- @@ -222,23 +218,26 @@ template inline Type* FDPArray::RemoveInd( size_t delIndex, DelType del ) { PRECONDITION( delIndex < RPArray::count ); - const Type **d = RPArray::GetAddr() + delIndex; + Type * r = 0; + if ( delIndex < RPArray::count ) { + const Type ** d = RPArray::GetAddr() + delIndex; - Type *r = (Type*) *d; + r = (Type *)*d; - // \ru сначала приведем в порядок массив ... \en put an array in order at first ... - memmove( d, d+1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); - RPArray::count--; + // \ru сначала приведем в порядок массив ... \en put an array in order at first ... + memmove( d, d + 1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); + RPArray::count--; - // \ru ...а потом будем удалять \en ... and then delete - if ( fDestroy && (del==Delete || del==defDelete) ) { - PRECONDITION( !r || nowDeletedElem != r ); - nowDeletedElem = r; + // \ru ...а потом будем удалять \en ... and then delete + if ( fDestroy && ( del == Delete || del == defDelete ) ) { + PRECONDITION( !r || nowDeletedElem != r ); + nowDeletedElem = r; - (*fDestroy)(r); - r = 0; + ( *fDestroy )( r ); + r = 0; - nowDeletedElem = 0; + nowDeletedElem = 0; + } } return r; @@ -264,23 +263,26 @@ template inline Type* FDPArray::DestroyInd( size_t delIndex, typename FDPArray::DestroyFunc fd ) { PRECONDITION( delIndex < RPArray::count ); - const Type **d = RPArray::GetAddr() + delIndex; + Type * r = 0; + if ( delIndex < RPArray::count ) { + const Type ** d = RPArray::GetAddr() + delIndex; - Type *r = (Type*) *d; + r = (Type *)*d; - // \ru сначала приведем в порядок массив ... \en put an array in order at first ... - memmove( d, d+1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); - RPArray::count--; + // \ru сначала приведем в порядок массив ... \en put an array in order at first ... + memmove( d, d + 1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); + RPArray::count--; - // \ru ...а потом будем удалять \en ... and then delete - if ( fd ) { - PRECONDITION( !r || nowDeletedElem != r ); // \ru Bременно, для отладки \en Temporarily, for debugging. - nowDeletedElem = r; + // \ru ...а потом будем удалять \en ... and then delete + if ( fd ) { + PRECONDITION( !r || nowDeletedElem != r ); // \ru Bременно, для отладки \en Temporarily, for debugging. + nowDeletedElem = r; - (*fd)(r); - r = 0; + ( *fd )( r ); + r = 0; - nowDeletedElem = 0; + nowDeletedElem = 0; + } } return r; diff --git a/C3d/Include/templ_ifc_array.h b/C3d/Include/templ_ifc_array.h index 22618be..7138cac 100644 --- a/C3d/Include/templ_ifc_array.h +++ b/C3d/Include/templ_ifc_array.h @@ -37,8 +37,8 @@ class IFC_Array : private RPArray { public: typedef Type * stored_type; ///< \ru Имя для указателя на объект. \en A name of the pointer to the object. - typedef Type * & reference; - typedef Type * const & const_reference; + typedef Type * & reference; + typedef Type * const & const_reference; /// \ru Константный итератор (новые функции можно добавлять по мере необходимости). \en A constant iterator (new functions can be added as necessary) class iterator @@ -152,11 +152,11 @@ private: TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, IFC_Array & ref ); TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const IFC_Array & ref ); -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: IFC_Array( IFC_Array && ); ///< \ru Конструктор перемещения массива. \en Constructor of an array moving. IFC_Array & operator = ( IFC_Array && ); ///< \ru Оператор перемещения массива. \en Operator of an array moving. -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; //------------------------------------------------------------------------------ @@ -172,7 +172,7 @@ inline void IFCArray_Release( Type * & el ) } } -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ // \ru Конструктор перемещения массива. \en Constructor of an array moving. // --- @@ -195,7 +195,7 @@ IFC_Array & IFC_Array::operator = ( IFC_Array && _Right ) } return (*this); } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ // \ru Деструктор массива. \en Destructor of array @@ -258,7 +258,7 @@ inline void IFC_Array::SetAt( stored_type ent, size_t ind ) { //--- template inline void IFC_Array::Exchange( size_t ind1, size_t ind2 ) { - if ( ind1 != ind2 ) { + if ( ind1 != ind2 && ind1 < RPArray::count && ind2 < RPArray::count ) { Type * value = RPArray::operator[](ind2); RPArray::operator[](ind2) = RPArray::operator[](ind1); RPArray::operator[](ind1) = value; @@ -273,14 +273,16 @@ template inline Type * IFC_Array::RemoveInd( size_t delIndex ) { PRECONDITION( delIndex < RPArray::count ); + stored_type r = 0; + if ( delIndex < RPArray::count ) { + stored_type * d = RPArray::begin() + delIndex; - stored_type * d = RPArray::begin() + delIndex; + r = *d; - stored_type r = *d; - - memmove( d, d+1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); - RPArray::count--; - IFCArray_Release( r ); + memmove( d, d + 1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); + RPArray::count--; + IFCArray_Release( r ); + } return r; } diff --git a/C3d/Include/templ_im_array.h b/C3d/Include/templ_im_array.h index 12a79f6..a15a6ae 100644 --- a/C3d/Include/templ_im_array.h +++ b/C3d/Include/templ_im_array.h @@ -133,7 +133,7 @@ inline void IMArray::operator delete ( void * ptr, size_t size ) { // \ru конструктор массива \en constructor of an array // --- template -inline IMArray::IMArray( PArray< Type > & arr, Compare_t c_t, Compare_v c_v, size_t maxCnt, uint16 delt ) +inline IMArray::IMArray( PArray< Type > & arr, Compare_t c_t, Compare_v c_v, size_t maxCnt, uint16 delt ) : SArray< size_t >( maxCnt, delt ), array(arr), compT(c_t), compV(c_v) {} @@ -310,82 +310,86 @@ inline size_t & IMArray::operator ()( size_t myIndex ) const { template Type * add_to_array( IMArray & arr, size_t ind, size_t * myIndex ) { PRECONDITION( ind < arr.array.Count() ); - - Type * el = arr.array[ind]; + + Type * el = 0; size_t mcIArr = SYS_MAX_T; // \ru текущий индекс в IMArray \en the current index in IMArray - if ( el ) { + if ( ind < arr.array.Count() ) { + el = arr.array[ind]; - if ( !arr.count ) { - arr.SArray< size_t >::Add( ind ); - mcIArr = 0; - } - else { - size_t ml = 0; - mcIArr = ml; - size_t mcPArr = arr.GetIndex( mcIArr ); // \ru текущий индекс в PArray \en the current index in PArray - - // \ru проверяем первый эл. \en check the first element - int resL = (el->*arr.compT)( arr.array[mcPArr] ); + if ( el ) { - // \ru если элемент меньше первого, вставляем перед первым \en if an element is less than the first element then place it before the first element - if ( resL < 0 ) - arr.InsertInd( mcIArr, ind ); + if ( !arr.count ) { + arr.SArray< size_t >::Add( ind ); + mcIArr = 0; + } else { - size_t mr = arr.count - 1; - mcIArr = mr; - mcPArr = arr.GetIndex( mcIArr ); + size_t ml = 0; + mcIArr = ml; + size_t mcPArr = arr.GetIndex( mcIArr ); // \ru текущий индекс в PArray \en the current index in PArray - // \ru проверяем последний эл. \en check the last element - int resR = !mcIArr ? resL : (el->*arr.compT)( arr.array[mcPArr] ); + // \ru проверяем первый эл. \en check the first element + int resL = ( el->*arr.compT )( arr.array[mcPArr] ); - // \ru если один объект в массиве или эл. больше или равен последнему, \en if one object in the array or an element is not less than the last element, - // \ru должны попасть сюда \en should be here - if ( !mcIArr || resR >= 0 ) { - arr.SArray< size_t >::Add( ind ); - mcIArr = mr + 1; - } + // \ru если элемент меньше первого, вставляем перед первым \en if an element is less than the first element then place it before the first element + if ( resL < 0 ) + arr.InsertInd( mcIArr, ind ); else { - if ( arr.count == 2 ) - arr.InsertInd( mcIArr, ind ); + size_t mr = arr.count - 1; + mcIArr = mr; + mcPArr = arr.GetIndex( mcIArr ); + + // \ru проверяем последний эл. \en check the last element + int resR = !mcIArr ? resL : ( el->*arr.compT )( arr.array[mcPArr] ); + + // \ru если один объект в массиве или эл. больше или равен последнему, \en if one object in the array or an element is not less than the last element, + // \ru должны попасть сюда \en should be here + if ( !mcIArr || resR >= 0 ) { + arr.SArray< size_t >::Add( ind ); + mcIArr = mr + 1; + } else { + if ( arr.count == 2 ) + arr.InsertInd( mcIArr, ind ); + else { - // \ru сюда попадаем если resL >= 0 и resR < 0 \en this is the case when resL >= 0 and resR < 0 - while ( ml + 1 < mr ) { // \ru пока не нашли - ищем \en seek until do not find + // \ru сюда попадаем если resL >= 0 и resR < 0 \en this is the case when resL >= 0 and resR < 0 + while ( ml + 1 < mr ) { // \ru пока не нашли - ищем \en seek until do not find - if ( !resL ) { - mcIArr = ml; + if ( !resL ) { + mcIArr = ml; -// 68759 do { -// mcIArr++; -// mcPArr = arr.GetIndex( mcIArr ); -// } while ( (el->*arr.compT)( arr.array[mcPArr] ) == 0 ); - mcIArr++; - mcPArr = arr.GetIndex( mcIArr ); + // 68759 do { + // mcIArr++; + // mcPArr = arr.GetIndex( mcIArr ); + // } while ( (el->*arr.compT)( arr.array[mcPArr] ) == 0 ); + mcIArr++; + mcPArr = arr.GetIndex( mcIArr ); - break; - } - else { - size_t md = ( ml + mr ) / 2; - mcPArr = arr.GetIndex( md ); - - int res = (el->*arr.compT)( arr.array[mcPArr] ); - - if ( res > 0 ) - ml = md; - else if ( res < 0 ) { - mr = md; - mcIArr = md; + break; } else { - resL = res; //res = 0 - mcIArr = md + 1; // \ru если ml + 1 < mr не выполнится объект должен добавиться после md \en if ml + 1 is not less than mr then the object should be added after md - ml = md; + size_t md = ( ml + mr ) / 2; + mcPArr = arr.GetIndex( md ); + + int res = ( el->*arr.compT )( arr.array[mcPArr] ); + + if ( res > 0 ) + ml = md; + else if ( res < 0 ) { + mr = md; + mcIArr = md; + } + else { + resL = res; //res = 0 + mcIArr = md + 1; // \ru если ml + 1 < mr не выполнится объект должен добавиться после md \en if ml + 1 is not less than mr then the object should be added after md + ml = md; + } } } - } - arr.InsertInd( mcIArr, ind ); + arr.InsertInd( mcIArr, ind ); + } } } } @@ -502,11 +506,12 @@ size_t find_in_array( const IMArray & arr, const void * val, size_t * myIn template void array_remove_ind( IMArray & arr, size_t delIndex, bool completely ){ PRECONDITION( delIndex < arr.count ); - size_t arrayIndex = arr.GetIndex(delIndex); //arr.parr[ delIndex ]; - arr.SArray< size_t >::RemoveInd( delIndex ); - - if ( completely ) - array_reduction_obj( arr, arrayIndex ); + if ( delIndex < arr.count ) { + size_t arrayIndex = arr.GetIndex( delIndex ); //arr.parr[ delIndex ]; + arr.SArray< size_t >::RemoveInd( delIndex ); + if ( completely ) + array_reduction_obj( arr, arrayIndex ); + } } diff --git a/C3d/Include/templ_iterator.h b/C3d/Include/templ_iterator.h index 065b25a..5292cb1 100644 --- a/C3d/Include/templ_iterator.h +++ b/C3d/Include/templ_iterator.h @@ -1,96 +1,96 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Итератор массива. - \en Iterator of array. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TEMPL_ITERATOR_H -#define __TEMPL_ITERATOR_H - -#include - -//------------------------------------------------------------------------------ -/** \brief \ru Интерфейс итератора. - \en Interface of iterator. \~ - \details \ru Итератор итератора. \n - \en Iterator of iterator. \n \~ - \ingroup Base_Tools_Containers -*/ -// --- -template -class PointersIterator { -public: - /// \ru Деструктор. \en Destructor. - virtual ~PointersIterator() {}; - /// \ru Сброс итератора. \en Reset iterator. - virtual void Restart() = 0; - /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move an iterator to the next. - virtual Type * operator ++(int) = 0; - /// \ru Получить текущий элемент \en Get the current element - virtual Type * operator() () const = 0; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Итератор массива. - \en Iterator of array. \~ - \details \ru Итератор массива указателей. \n - \en Iterator of pointers array. \n \~ - \ingroup Base_Tools_Containers -*/ -// --- -template -class PointersArrayIterator : public PointersIterator { -private: - const Array & items; ///< \ru Ссылка на массив. \en A reference to the array. - size_t index; ///< \ru Текущее положение итератора. \en The current position of iterator. - -public: - /// \ru Конструктор итератора. \en Constructor of iterator. - PointersArrayIterator( const Array & arr ) : items( arr ), index( 0 ) {} - /// \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; } - /// \ru Получить текущий элемент \en Get the current element - virtual Type * operator() () const { return (index < items.Count()) ? items[index] : NULL; } - -private: // \ru не реализовано \en not implemented - PointersArrayIterator & operator = ( const PointersArrayIterator & ); - PointersArrayIterator ( const PointersArrayIterator & ); - PointersArrayIterator (); -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Итератор списка. - \en Iterator of list. \~ - \details \ru Итератор списка указателей. \n - \en Iterator of pointers list. \n \~ - \ingroup Base_Tools_Containers -*/ -// --- -template -struct PointersListIterator : public LIterator, public PointersIterator -{ - /// \ru Конструктор итератора. \en Constructor of iterator. - PointersListIterator( const List & l ) : LIterator( l ) {} - /// \ru Конструктор итератора. \en Constructor of iterator. - PointersListIterator() : LIterator() {} - - /// \ru Сброс итератора. \en Reset iterator. - virtual void Restart() { LIterator::Restart(); } - /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move an iterator to the next. - virtual Type * operator ++(int) { return LIterator::operator++(int()); } - /// \ru Получить текущий элемент \en Get the current element - virtual Type * operator() () const { return LIterator::operator()(); } - -private: // \ru не реализовано \en not implemented - PointersListIterator & operator = ( const PointersListIterator & ); - PointersListIterator ( const PointersListIterator & ); -}; - - -#endif //__TEMPL_ITERATOR_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Итератор массива. + \en Iterator of array. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TEMPL_ITERATOR_H +#define __TEMPL_ITERATOR_H + +#include + +//------------------------------------------------------------------------------ +/** \brief \ru Интерфейс итератора. + \en Interface of iterator. \~ + \details \ru Итератор итератора. \n + \en Iterator of iterator. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class PointersIterator { +public: + /// \ru Деструктор. \en Destructor. + virtual ~PointersIterator() {}; + /// \ru Сброс итератора. \en Reset iterator. + virtual void Restart() = 0; + /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move an iterator to the next. + virtual Type * operator ++(int) = 0; + /// \ru Получить текущий элемент \en Get the current element + virtual Type * operator() () const = 0; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Итератор массива. + \en Iterator of array. \~ + \details \ru Итератор массива указателей. \n + \en Iterator of pointers array. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class PointersArrayIterator : public PointersIterator { +private: + const Array & items; ///< \ru Ссылка на массив. \en A reference to the array. + size_t index; ///< \ru Текущее положение итератора. \en The current position of iterator. + +public: + /// \ru Конструктор итератора. \en Constructor of iterator. + PointersArrayIterator( const Array & arr ) : items( arr ), index( 0 ) {} + /// \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; } + /// \ru Получить текущий элемент \en Get the current element + virtual Type * operator() () const { return (index < items.Count()) ? items[index] : NULL; } + +private: // \ru не реализовано \en not implemented + PointersArrayIterator & operator = ( const PointersArrayIterator & ); + PointersArrayIterator ( const PointersArrayIterator & ); + PointersArrayIterator (); +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Итератор списка. + \en Iterator of list. \~ + \details \ru Итератор списка указателей. \n + \en Iterator of pointers list. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +struct PointersListIterator : public LIterator, public PointersIterator +{ + /// \ru Конструктор итератора. \en Constructor of iterator. + PointersListIterator( const List & l ) : LIterator( l ) {} + /// \ru Конструктор итератора. \en Constructor of iterator. + PointersListIterator() : LIterator() {} + + /// \ru Сброс итератора. \en Reset iterator. + virtual void Restart() { LIterator::Restart(); } + /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move an iterator to the next. + virtual Type * operator ++(int) { return LIterator::operator++(int()); } + /// \ru Получить текущий элемент \en Get the current element + virtual Type * operator() () const { return LIterator::operator()(); } + +private: // \ru не реализовано \en not implemented + PointersListIterator & operator = ( const PointersListIterator & ); + PointersListIterator ( const PointersListIterator & ); +}; + + +#endif //__TEMPL_ITERATOR_H diff --git a/C3d/Include/templ_kdtree.h b/C3d/Include/templ_kdtree.h index cb97bf5..e05b449 100644 --- a/C3d/Include/templ_kdtree.h +++ b/C3d/Include/templ_kdtree.h @@ -1,506 +1,506 @@ -////////////////////////////////////////////////////////////////////////////////// -/** -\file -\brief \ru К-мерное дерево. - \en K-d tree. \~ - -*/ -// \ru К-мерное дерево - это структура данных с разбиением пространства для упорядочивания точек из K-мерного пространства, -// используемая для поиска k ближайших соседей. -// \en K-d tree is a space-partitioning data structure for organizing points in a k-dimensional space, -// using for the k-nearest neighbors (kNN) search -// -//////////////////////////////////////////////////////////////////////////////// -#ifndef __MB_KDTREE_H -#define __MB_KDTREE_H - -#include -#include +////////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief \ru К-мерное дерево. + \en K-d tree. \~ + +*/ +// \ru К-мерное дерево - это структура данных с разбиением пространства для упорядочивания точек из K-мерного пространства, +// используемая для поиска k ближайших соседей. +// \en K-d tree is a space-partitioning data structure for organizing points in a k-dimensional space, +// using for the k-nearest neighbors (kNN) search +// +//////////////////////////////////////////////////////////////////////////////// +#ifndef __MB_KDTREE_H +#define __MB_KDTREE_H + +#include +#include #include -#include -#include - - -//----------------------------------------------------------------------------- -/** \brief \ru Очередь с приоритетом с использованием кучи. - \en Priority queue using a heap. \~ - \details \ru Очередь с приоритетом с использованием кучи. Размер очереди фиксирован. - Производительность этой реализации выше чем у std::priority_queue. \n - \en Priority queue using a heap. Size of queue is fixed. - This implementation perfomance is better in comparsion with std::priority_queue. \n \~ - \ingroup Base_Tools -*/ -// --- -template -class PriorityQueue -{ -protected: - struct Element ///< \ru Элемент очереди. \en Element of queue. - { - Weight weight; ///< \ru Вес элемента. \en Weight of element. - Index index; ///< \ru Индекс элемента. \en Index of element. - }; - Element * elements; ///< \ru Элементы очереди. \en Elements of queue. - Element * offsetedElements; ///< \ru Смещенные элементы очереди. \en Shifted elements of queue. - size_t count; ///< \ru Актуальное число элементов в очереди. \en Actual count of elements in the queue. - size_t maxSize; ///< \ru Максимальное число элементов в очереди. \en Maximal count of elements in the queue. - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - PriorityQueue( const PriorityQueue & ); - -public: - /// \ru Конструктор. \en Constructor. - PriorityQueue( ); - /// \ru Деструктор. \en Destructor. - ~PriorityQueue(); - -public: - /** \ru \name Функции очереди с приоритетом. - \en \name Functions of priority queue. - \{ */ - /// \ru Инициализировать очередь максимальным количеством элементов в очереди. \en Initialize the queue by number of elements. - inline bool Initialize( size_t _maxSize ); - /// \ru Получить количество элементов в очереди. \en Get elements count in the queue. - inline size_t ElementsCount() const { return count; } - /// \ru Получить вес элемента очереди. \en Get weight of element in the queue. - inline Weight GetWeight( size_t i ) const { return elements[i].weight; } - /// \ru Получить индекс элемента очереди. \en Get index of element in the queue. - inline Index GetIndex( size_t i ) const { return elements[i].index; } - /// \ru Получить вес верхнего элемента очереди. \en Get weight of the top element in the queue. - inline Weight GetTopWeight() const { return elements[0].weight; } - /// \ru Вставить элемент с заданным индексом и весом в очередь. \en Insert element with given index and weight in the queue. - inline void Insert( Index index, Weight weight ); - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const PriorityQueue & ); -}; - - -//----------------------------------------------------------------------------- -/** \brief \ru К-d дерево. - \en K-d tree. \~ - \details \ru К-мерное бинарное дерево. \n - \en K-d binary tree. \n \~ - \ingroup Base_Tools -*/ -// --- -template -class KdTree { -public: - struct Node { ///< \ru Структура узла дерева. \en Structure of node of the tree. - union { - struct { ///< \ru Узел дерева. \en Node of tree. - Scalar splitValue; ///< \ru Разделяющее значение. \en Split value. - size_t firstChildId : 24; ///< \ru Индекс первого потомка. \en Index of first child. - size_t dim : 2; ///< \ru Измерение, вдоль которого происходит сравнение [0 = x, 1 = y, 2 = z]. \en The dimension along which node is splitted [0 = x, 1 = y, 2 = z]. - size_t type : 1; ///< \ru Тип узла дерева (0 - узел, 1 - лист). \en Type of node (0 - node, 1 - leaf). - }; - struct { ///< \ru Лист дерева. \en Leaf of tree. - unsigned int start; ///< \ru Индекс первого элемента листа. \en Index of first element of leaf. - unsigned short size; ///< \ru Количество элементов листа. \en Number of elements in the leaf. - }; - }; - }; - - typedef std::vector NodeList; - typedef std::vector PointList; - typedef std::vector IndexList; - typedef PriorityQueue ScalarPriorityQueue; - -protected: - MbCube box; ///< \ru Ограничивающий куб. \en Bounding box. - NodeList nodes; ///< \ru Узлы дерева. \en Nodes of tree. - PointList points; ///< \ru Множество точек. \en Set of points. - IndexList indices; ///< \ru Индексы точек. \en Indices of points. - size_t targetCellSize; ///< \ru Минимальное количество точек в листе дерева. \en Minimal number of point in a tree leaf. - size_t targetMaxDepth; ///< \ru Максимальная глубина дерева. \en Maximal tree depth. - size_t numLevel; ///< \ru Глубина дерева. \en Tree depth. - bool isBalanced; ///< \ru Cбалансированное дерево или нет. \en Three is balanced or unbalanced. - - struct QueryNode { ///< \ru Структура узла для запроса. \en Structure of query node. - QueryNode() {} - QueryNode( size_t id ) : nodeId( id ) {} - size_t nodeId; ///< \ru Id следующего узла. \en Id of next node. - Scalar sq; ///< \ru Квадрат расстояния до следующего узла. \en Squared distance to next node. - }; - -public: - /** - \brief \ru Конструктор. - \en Constructor. \~ - \details \ru Конструктор k-мерного дерева. - \en Constructor of k-d tree. \~ - \param[in] points - \ru Множество точек. - \en Set of points. \~ - \param[in] minLeafSize - \ru Минимальное количество точек в листе дерева (по умолчанию 16). - \en Minimal number of point in a tree leaf (16 by default). \~ - \param[in] maxDepth - \ru Максимальная глубина дерева (по умолчанию 64). - \en Maximal tree depth (64 by default). \~ - \param[in] balanced - \ru Создать сбалансированное дерево или нет (по умолчанию несбалансированное). - \en Create three balanced or unbalanced (unbalanced by default). \~ - */ - KdTree( const PointList & points, size_t minLeafSize = 16, size_t maxDepth = 64, bool balanced = false ); - /// \ru Деструктор. \en Destructor. - ~KdTree(); - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - KdTree( const KdTree & ); - -public: - /** \ru \name Функции очереди с приоритетом. - \en \name Functions of priority queue. - \{ */ - /** - \brief \ru Найти k ближайших соседей для данной точки. - \en Performs the k-nearest neighbors (kNN) query. \~ - \details \ru Найти k ближайших соседей для данной точки. - \en Performs the k-nearest neighbors (kNN) query. \~ - \param[in] queryPoint - \ru Точка, для которой ищутся соседи. - \en The point for which the neighbors are being searched for . \~ - \param[in] neighborCount - \ru Запрашиваемое число соседей . - \en Number of neighbors requested. \~ - \param[in] neighborQueue - \ru Очередь с результатами поиска, в котором верхний элемент является наиболее удаленным от заданной точки - \en Queue with k-nearest neighbors (kNN) query results, where the topmost element [0] is NOT the nearest but the farthest \~ - */ - void GetKNearestNeighbors( const MbCartPoint3D & queryPoint, size_t neighborCount, ScalarPriorityQueue & neighborQueue ); - /// \ru Получить узлы дерева. \en Get tree nodes. - inline const NodeList & GetNodes() { return nodes; } - /// \ru Получить множество точек. \en Get points set. - inline const PointList & GetPoints() { return points; } - /// \ru Получить глубину дерева. \en Get depth of tree. - inline size_t GetNumLevel() { return numLevel; } - /// \ru Получить ограничивающий куб. \en Get axis aligned bounding box. - inline const MbCube & GetAxisAlignedBox() { return box; } - /** \} */ - -private: - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. - void operator = ( const KdTree & ); - // Используется для построения дерева: разделить множество subset [start..end] согласно dim и splitValue, - // и вернуть индекс первого элемента второго множества. - size_t split( size_t start, size_t end, size_t dim, double splitValue ); - // Построение дерева. - size_t createTree( size_t nodeId, size_t start, size_t end, size_t level ); - -}; - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru PriorityQueue - очередь с приоритетом. \en PriorityQueue - priority queue. -// -//////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------- -// \ru Конструктор очереди с приоритетом. \en Constructor of priority queue. -// --- -template -PriorityQueue::PriorityQueue() - : elements( 0 ) - , maxSize ( 0 ) -{ -} - - -//------------------------------------------------------------------------------- -// \ru Деструктор очереди с приоритетом. \en Destructor of priority queue. -// --- -template -PriorityQueue::~PriorityQueue() -{ - if ( elements ) - delete[] elements; -} - - -//------------------------------------------------------------------------------- -// \ru Инициализировать очередь максимальным количеством элементов в очереди. \en Initialize the queue by number of elements. -// --- -template -inline bool PriorityQueue::Initialize( size_t _maxSize ) -{ - if ( maxSize != _maxSize ) { - maxSize = _maxSize; - delete[] elements; - try { - elements = new Element[maxSize]; - } - catch ( ... ) { +#include +#include + + +//----------------------------------------------------------------------------- +/** \brief \ru Очередь с приоритетом с использованием кучи. + \en Priority queue using a heap. \~ + \details \ru Очередь с приоритетом с использованием кучи. Размер очереди фиксирован. + Производительность этой реализации выше чем у std::priority_queue. \n + \en Priority queue using a heap. Size of queue is fixed. + This implementation perfomance is better in comparsion with std::priority_queue. \n \~ + \ingroup Base_Tools +*/ +// --- +template +class PriorityQueue +{ +protected: + struct Element ///< \ru Элемент очереди. \en Element of queue. + { + Weight weight; ///< \ru Вес элемента. \en Weight of element. + Index index; ///< \ru Индекс элемента. \en Index of element. + }; + Element * elements; ///< \ru Элементы очереди. \en Elements of queue. + Element * offsetedElements; ///< \ru Смещенные элементы очереди. \en Shifted elements of queue. + size_t count; ///< \ru Актуальное число элементов в очереди. \en Actual count of elements in the queue. + size_t maxSize; ///< \ru Максимальное число элементов в очереди. \en Maximal count of elements in the queue. + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + PriorityQueue( const PriorityQueue & ); + +public: + /// \ru Конструктор. \en Constructor. + PriorityQueue( ); + /// \ru Деструктор. \en Destructor. + ~PriorityQueue(); + +public: + /** \ru \name Функции очереди с приоритетом. + \en \name Functions of priority queue. + \{ */ + /// \ru Инициализировать очередь максимальным количеством элементов в очереди. \en Initialize the queue by number of elements. + inline bool Initialize( size_t _maxSize ); + /// \ru Получить количество элементов в очереди. \en Get elements count in the queue. + inline size_t ElementsCount() const { return count; } + /// \ru Получить вес элемента очереди. \en Get weight of element in the queue. + inline Weight GetWeight( size_t i ) const { if ( i < count ) return elements[i].weight; return Weight(); } + /// \ru Получить индекс элемента очереди. \en Get index of element in the queue. + inline Index GetIndex( size_t i ) const { if ( i < count ) return elements[i].index; return Index(); } + /// \ru Получить вес верхнего элемента очереди. \en Get weight of the top element in the queue. + inline Weight GetTopWeight() const { if ( count > 0 ) return elements[0].weight; return Weight(); } + /// \ru Вставить элемент с заданным индексом и весом в очередь. \en Insert element with given index and weight in the queue. + inline void Insert( Index index, Weight weight ); + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const PriorityQueue & ); +}; + + +//----------------------------------------------------------------------------- +/** \brief \ru К-d дерево. + \en K-d tree. \~ + \details \ru К-мерное бинарное дерево. \n + \en K-d binary tree. \n \~ + \ingroup Base_Tools +*/ +// --- +template +class KdTree { +public: + struct Node { ///< \ru Структура узла дерева. \en Structure of node of the tree. + union { + struct { ///< \ru Узел дерева. \en Node of tree. + Scalar splitValue; ///< \ru Разделяющее значение. \en Split value. + size_t firstChildId : 24; ///< \ru Индекс первого потомка. \en Index of first child. + size_t dim : 2; ///< \ru Измерение, вдоль которого происходит сравнение [0 = x, 1 = y, 2 = z]. \en The dimension along which node is splitted [0 = x, 1 = y, 2 = z]. + size_t type : 1; ///< \ru Тип узла дерева (0 - узел, 1 - лист). \en Type of node (0 - node, 1 - leaf). + }; + struct { ///< \ru Лист дерева. \en Leaf of tree. + unsigned int start; ///< \ru Индекс первого элемента листа. \en Index of first element of leaf. + unsigned short size; ///< \ru Количество элементов листа. \en Number of elements in the leaf. + }; + }; + }; + + typedef std::vector NodeList; + typedef std::vector PointList; + typedef std::vector IndexList; + typedef PriorityQueue ScalarPriorityQueue; + +protected: + MbCube box; ///< \ru Ограничивающий куб. \en Bounding box. + NodeList nodes; ///< \ru Узлы дерева. \en Nodes of tree. + PointList points; ///< \ru Множество точек. \en Set of points. + IndexList indices; ///< \ru Индексы точек. \en Indices of points. + size_t targetCellSize; ///< \ru Минимальное количество точек в листе дерева. \en Minimal number of point in a tree leaf. + size_t targetMaxDepth; ///< \ru Максимальная глубина дерева. \en Maximal tree depth. + size_t numLevel; ///< \ru Глубина дерева. \en Tree depth. + bool isBalanced; ///< \ru Cбалансированное дерево или нет. \en Three is balanced or unbalanced. + + struct QueryNode { ///< \ru Структура узла для запроса. \en Structure of query node. + QueryNode() {} + QueryNode( size_t id ) : nodeId( id ) {} + size_t nodeId; ///< \ru Id следующего узла. \en Id of next node. + Scalar sq; ///< \ru Квадрат расстояния до следующего узла. \en Squared distance to next node. + }; + +public: + /** + \brief \ru Конструктор. + \en Constructor. \~ + \details \ru Конструктор k-мерного дерева. + \en Constructor of k-d tree. \~ + \param[in] points - \ru Множество точек. + \en Set of points. \~ + \param[in] minLeafSize - \ru Минимальное количество точек в листе дерева (по умолчанию 16). + \en Minimal number of point in a tree leaf (16 by default). \~ + \param[in] maxDepth - \ru Максимальная глубина дерева (по умолчанию 64). + \en Maximal tree depth (64 by default). \~ + \param[in] balanced - \ru Создать сбалансированное дерево или нет (по умолчанию несбалансированное). + \en Create three balanced or unbalanced (unbalanced by default). \~ + */ + KdTree( const PointList & points, size_t minLeafSize = 16, size_t maxDepth = 64, bool balanced = false ); + /// \ru Деструктор. \en Destructor. + ~KdTree(); + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + KdTree( const KdTree & ); + +public: + /** \ru \name Функции очереди с приоритетом. + \en \name Functions of priority queue. + \{ */ + /** + \brief \ru Найти k ближайших соседей для данной точки. + \en Performs the k-nearest neighbors (kNN) query. \~ + \details \ru Найти k ближайших соседей для данной точки. + \en Performs the k-nearest neighbors (kNN) query. \~ + \param[in] queryPoint - \ru Точка, для которой ищутся соседи. + \en The point for which the neighbors are being searched for . \~ + \param[in] neighborCount - \ru Запрашиваемое число соседей . + \en Number of neighbors requested. \~ + \param[in] neighborQueue - \ru Очередь с результатами поиска, в котором верхний элемент является наиболее удаленным от заданной точки + \en Queue with k-nearest neighbors (kNN) query results, where the topmost element [0] is NOT the nearest but the farthest \~ + */ + void GetKNearestNeighbors( const MbCartPoint3D & queryPoint, size_t neighborCount, ScalarPriorityQueue & neighborQueue ); + /// \ru Получить узлы дерева. \en Get tree nodes. + inline const NodeList & GetNodes() { return nodes; } + /// \ru Получить множество точек. \en Get points set. + inline const PointList & GetPoints() { return points; } + /// \ru Получить глубину дерева. \en Get depth of tree. + inline size_t GetNumLevel() { return numLevel; } + /// \ru Получить ограничивающий куб. \en Get axis aligned bounding box. + inline const MbCube & GetAxisAlignedBox() { return box; } + /** \} */ + +private: + // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation, to prevent an assignment by default. + void operator = ( const KdTree & ); + // Используется для построения дерева: разделить множество subset [start..end] согласно dim и splitValue, + // и вернуть индекс первого элемента второго множества. + size_t split( size_t start, size_t end, size_t dim, double splitValue ); + // Построение дерева. + size_t createTree( size_t nodeId, size_t start, size_t end, size_t level ); + +}; + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru PriorityQueue - очередь с приоритетом. \en PriorityQueue - priority queue. +// +//////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------- +// \ru Конструктор очереди с приоритетом. \en Constructor of priority queue. +// --- +template +PriorityQueue::PriorityQueue() + : elements( 0 ) + , maxSize ( 0 ) +{ +} + + +//------------------------------------------------------------------------------- +// \ru Деструктор очереди с приоритетом. \en Destructor of priority queue. +// --- +template +PriorityQueue::~PriorityQueue() +{ + if ( elements ) + delete[] elements; +} + + +//------------------------------------------------------------------------------- +// \ru Инициализировать очередь максимальным количеством элементов в очереди. \en Initialize the queue by number of elements. +// --- +template +inline bool PriorityQueue::Initialize( size_t _maxSize ) +{ + if ( maxSize != _maxSize ) { + maxSize = _maxSize; + delete[] elements; + try { + elements = new Element[maxSize]; + } + catch ( ... ) { elements = NULL; - maxSize = count = 0; + maxSize = count = 0; C3D_CONTROLED_THROW; return false; - } - offsetedElements = ( elements - 1 ); - } - count = 0; - return true; -} - - -//------------------------------------------------------------------------------- -// \ru Вставить элемент с заданным индексом и весом в очередь. \en Insert element with given index and weight in the queue. -// --- -template -inline void PriorityQueue::Insert( Index index, Weight weight ) -{ - if ( count == maxSize ) { - if ( weight < elements[0].weight ) { - size_t j, k; - j = 1; - k = 2; - while ( k <= maxSize ) { - Element* z = &( offsetedElements[k] ); - if ( (k < maxSize) && (z->weight < offsetedElements[k+1].weight) ) - z = &( offsetedElements[++k] ); - - if( weight >= z->weight ) - break; - offsetedElements[j] = *z; - j = k; - k = 2 * j; - } - offsetedElements[j].weight = weight; - offsetedElements[j].index = index; - } - } - else { - size_t i, j; - i = ++count; - while ( i >= 2 ) { - j = i >> 1; - Element& y = offsetedElements[j]; - if( weight <= y.weight ) - break; - offsetedElements[i] = y; - i = j; - } - offsetedElements[i].index = index; - offsetedElements[i].weight = weight; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru К-d дерево. \en PriorityQueue - priority queue. -// -//////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------- -// \ru Конструктор дерева. \en K-d tree. -// --- -template -KdTree::KdTree( const PointList & _points, size_t nofPointsPerCell, size_t maxDepth, bool balanced ) - : points ( _points.size() ) - , indices( _points.size() ) -{ - points[0] = _points[0]; - box.SetEmpty(); - for( size_t i = 1; i < points.size(); ++i ) { - points[i] = _points[i]; - indices[i] = i; - box |= ( points[i] ); - } - - targetMaxDepth = maxDepth; - targetCellSize = nofPointsPerCell; - isBalanced = balanced; - - // Добавление первого узла. Остальные добавляются при вызове createTree (рекурсия). - nodes.resize( 1 ); - nodes.back().type = 0; - numLevel = createTree( 0, 0, points.size(), 1 ); -} - - -//------------------------------------------------------------------------------- -// \ru Деструктор дерева. \en Destructor of tree. -// --- -template -KdTree::~KdTree() -{ -} - - -//------------------------------------------------------------------------------- -// \ru Найти k ближайших соседей для данной точки. Результат операции хранится -// в виде стека neighborQueue, в котором верхний элемент является наиболее -// удаленным от заданной точки. -// (его содержимое не сортировано, но упорядоченно расположено в куче) -// \en Performs the k-nearest neighbors (kNN) query. The result of the query, -// the k-nearest neighbors, are stored into the stack neighborQueue, where the -// topmost element [0] is NOT the nearest but the farthest! -// (they are not sorted but arranged into a heap) -// --- -template -void KdTree::GetKNearestNeighbors( const MbCartPoint3D & queryPoint, size_t k, ScalarPriorityQueue & neighborQueue ) -{ - if ( !neighborQueue.Initialize( k ) ) - return; - - std::vector nodeStack( numLevel + 1 ); - nodeStack[0].nodeId = 0; - nodeStack[0].sq = 0.0; - size_t count = 1; - - while( count ) { - QueryNode & qnode = nodeStack[count - 1]; // Последний вставленный в стек узел. - - // При проходе вниз по дереву qnode.nodeId является ближайшим поддеревом, т.е. - // qnode.nodeId является другим поддеревом, которое будет обрабатываться, - // если фактический ближайший узел будет больше, чем делящее расстояние (split distance). - Node & node = nodes[qnode.nodeId]; // - - // Если расстояние меньше чем верхний элемент neighborQueue, то это может быть один из k ближайших соседей. - if( neighborQueue.ElementsCount() < k || neighborQueue.GetTopWeight() ) { - if( node.type ) { // Достигли листа дерева. - --count; - - // Индекс последнего элемента листа в points. - size_t end = node.start + node.size; - // Добавление элемента листа в очередь. - for( size_t i = node.start; i < end; ++i ) - neighborQueue.Insert( indices[i], ( queryPoint - points[i] )*( queryPoint - points[i] ) ); - } - else { // Не лист дерева. - // Расстояние между найденной точкой и фактической координатой деления. - double new_off = queryPoint[node.dim] - node.splitValue; - - // Левое поддерево. - if( new_off < 0. ) { - nodeStack[count].nodeId = node.firstChildId; - // В родительском nodeId хранится индекс другого поддерева (для прохода в обратном направлении). - qnode.nodeId = node.firstChildId + 1; - } - // Правое поддерево. - else { - nodeStack[count].nodeId = node.firstChildId + 1; - qnode.nodeId = node.firstChildId; - } - // Расстояние наследуется от родителя(при спуске по дереву оно равно 0). - nodeStack[count].sq = qnode.sq; - // Расстояние от родителя - это квадрат расстояния от плоскости деления. - qnode.sq = new_off * new_off; - ++count; - } - } - else { - --count; - } - } -} - - -//------------------------------------------------------------------------------- -// \ru Разделить часть массива между индексами start и end на две части, одна из которых меньше -// чем splitValue, другое с элементами больше или равными чем splitValue. Сравнение элементов -// производится с помощью координаты dim [0 = x, 1 = y, 2 = z]. -// \en Split the array part between start and end in two part, one with the elements less than splitValue, -// the other with the elements greater or equal than splitValue. The elements are compared -// using the "dim" coordinate [0 = x, 1 = y, 2 = z]. -// --- -template -size_t KdTree::split( size_t start, size_t end, size_t dim, double splitValue ) -{ - size_t l( start ), r( end - 1 ); - for( ; l < r; ++l, --r ) { - while( l < end && points[l][dim] < splitValue ) - l++; - while( r >= start && points[r][dim] >= splitValue ) - r--; - if( l > r ) - break; - std::swap( points[l], points[r] ); - std::swap( indices[l], indices[r] ); - } - return ( points[l][dim] < splitValue ? l + 1 : l ); // Вернуть индекс первого элемента во второй части. -} - - -//------------------------------------------------------------------------------- -// \ru Построить k-мерное дерево (рекурсивно). Если количество точек узла меньше чем -// targetCellsize, то делаем этот узел листом, иначе рассчитываем ограничивающий -// куб для точек узла и делим его по среднему значению наибольшего габарита куба. -// \en Build the kdtree recursively. If the number of points in the node is lower than -// targetCellsize then mark this node as leaf, else compute the bounding box of the points -// of the node and split it at the middle of the largest bounding box dimension. -// --- -template -size_t KdTree::createTree( size_t nodeId, size_t start, size_t end, size_t level ) -{ - Node & node = nodes[nodeId]; // Первый узел - MbCube cube; - - for( size_t i = start + 1; i < end; ++i ) - cube |= points[i] ; - - - MbVector3D diag = cube.pmax - cube.pmin; // Диагональ габаритного куба. - - size_t dim; - if( diag.x > diag.y ) - dim = diag.x > diag.z ? 0 : 2; - else - dim = diag.y > diag.z ? 1 : 2; - - node.dim = dim; - if( isBalanced ) // Разделить точки используя среднее значение вдоль направления dim. - { - std::vector tempVector; - for( size_t i = start + 1; i < end; ++i ) - tempVector.push_back( (points[i])[dim] ); - std::sort( tempVector.begin(), tempVector.end() ); - node.splitValue = ( tempVector[int(tempVector.size() / 2.0)] + tempVector[int(tempVector.size() / 2.0) + 1] ) / 2.0; - } - else // Разделить ограничивающий куб на две части на основе среднего значение вдоль направления dim. - node.splitValue = Scalar( 0.5*( cube.pmax[dim] + cube.pmin[dim] ) ); - - size_t midId = split( start, end, dim, node.splitValue ); // Индекс первого элемента во второй части. - - node.firstChildId = nodes.size(); - nodes.resize( nodes.size() + 2 ); - bool flag = ( midId == start ) || ( midId == end ); - size_t leftLevel, rightLevel; - { - // Левый потомок. - size_t childId = nodes[nodeId].firstChildId; - Node & child = nodes[childId]; - if( flag || ( midId - start ) <= targetCellSize || level >= targetMaxDepth ) { - child.type = 1; - child.start = (unsigned int)start; - child.size = (unsigned short)(midId - start); - leftLevel = level; - } - else { - child.type = 0; - leftLevel = createTree( childId, start, midId, level + 1 ); - } - } - - { - // Правый потомок. - size_t childId = nodes[nodeId].firstChildId + 1; - Node & child = nodes[childId]; - if( flag || ( end - midId ) <= targetCellSize || level >= targetMaxDepth ) { - child.type = 1; - child.start = (unsigned int)midId; - child.size = (unsigned short)(end - midId); - rightLevel = level; - } - else { - child.type = 0; - rightLevel = createTree( childId, midId, end, level + 1 ); - } - } - if( leftLevel > rightLevel ) - return leftLevel; - return rightLevel; -} - - + } + offsetedElements = ( elements - 1 ); + } + count = 0; + return true; +} + + +//------------------------------------------------------------------------------- +// \ru Вставить элемент с заданным индексом и весом в очередь. \en Insert element with given index and weight in the queue. +// --- +template +inline void PriorityQueue::Insert( Index index, Weight weight ) +{ + if ( count == maxSize ) { + if ( weight < elements[0].weight ) { + size_t j, k; + j = 1; + k = 2; + while ( k <= maxSize ) { + Element* z = &( offsetedElements[k] ); + if ( (k < maxSize) && (z->weight < offsetedElements[k+1].weight) ) + z = &( offsetedElements[++k] ); + + if( weight >= z->weight ) + break; + offsetedElements[j] = *z; + j = k; + k = 2 * j; + } + offsetedElements[j].weight = weight; + offsetedElements[j].index = index; + } + } + else { + size_t i, j; + i = ++count; + while ( i >= 2 ) { + j = i >> 1; + Element& y = offsetedElements[j]; + if( weight <= y.weight ) + break; + offsetedElements[i] = y; + i = j; + } + offsetedElements[i].index = index; + offsetedElements[i].weight = weight; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru К-d дерево. \en PriorityQueue - priority queue. +// +//////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------- +// \ru Конструктор дерева. \en K-d tree. +// --- +template +KdTree::KdTree( const PointList & _points, size_t nofPointsPerCell, size_t maxDepth, bool balanced ) + : points ( _points.size() ) + , indices( _points.size() ) +{ + points[0] = _points[0]; + box.SetEmpty(); + for( size_t i = 1; i < points.size(); ++i ) { + points[i] = _points[i]; + indices[i] = i; + box |= ( points[i] ); + } + + targetMaxDepth = maxDepth; + targetCellSize = nofPointsPerCell; + isBalanced = balanced; + + // Добавление первого узла. Остальные добавляются при вызове createTree (рекурсия). + nodes.resize( 1 ); + nodes.back().type = 0; + numLevel = createTree( 0, 0, points.size(), 1 ); +} + + +//------------------------------------------------------------------------------- +// \ru Деструктор дерева. \en Destructor of tree. +// --- +template +KdTree::~KdTree() +{ +} + + +//------------------------------------------------------------------------------- +// \ru Найти k ближайших соседей для данной точки. Результат операции хранится +// в виде стека neighborQueue, в котором верхний элемент является наиболее +// удаленным от заданной точки. +// (его содержимое не сортировано, но упорядоченно расположено в куче) +// \en Performs the k-nearest neighbors (kNN) query. The result of the query, +// the k-nearest neighbors, are stored into the stack neighborQueue, where the +// topmost element [0] is NOT the nearest but the farthest! +// (they are not sorted but arranged into a heap) +// --- +template +void KdTree::GetKNearestNeighbors( const MbCartPoint3D & queryPoint, size_t k, ScalarPriorityQueue & neighborQueue ) +{ + if ( !neighborQueue.Initialize( k ) ) + return; + + std::vector nodeStack( numLevel + 1 ); + nodeStack[0].nodeId = 0; + nodeStack[0].sq = 0.0; + size_t count = 1; + + while( count ) { + QueryNode & qnode = nodeStack[count - 1]; // Последний вставленный в стек узел. + + // При проходе вниз по дереву qnode.nodeId является ближайшим поддеревом, т.е. + // qnode.nodeId является другим поддеревом, которое будет обрабатываться, + // если фактический ближайший узел будет больше, чем делящее расстояние (split distance). + Node & node = nodes[qnode.nodeId]; // + + // Если расстояние меньше чем верхний элемент neighborQueue, то это может быть один из k ближайших соседей. + if( neighborQueue.ElementsCount() < k || neighborQueue.GetTopWeight() ) { + if( node.type ) { // Достигли листа дерева. + --count; + + // Индекс последнего элемента листа в points. + size_t end = node.start + node.size; + // Добавление элемента листа в очередь. + for( size_t i = node.start; i < end; ++i ) + neighborQueue.Insert( indices[i], ( queryPoint - points[i] )*( queryPoint - points[i] ) ); + } + else { // Не лист дерева. + // Расстояние между найденной точкой и фактической координатой деления. + double new_off = queryPoint[node.dim] - node.splitValue; + + // Левое поддерево. + if( new_off < 0. ) { + nodeStack[count].nodeId = node.firstChildId; + // В родительском nodeId хранится индекс другого поддерева (для прохода в обратном направлении). + qnode.nodeId = node.firstChildId + 1; + } + // Правое поддерево. + else { + nodeStack[count].nodeId = node.firstChildId + 1; + qnode.nodeId = node.firstChildId; + } + // Расстояние наследуется от родителя(при спуске по дереву оно равно 0). + nodeStack[count].sq = qnode.sq; + // Расстояние от родителя - это квадрат расстояния от плоскости деления. + qnode.sq = new_off * new_off; + ++count; + } + } + else { + --count; + } + } +} + + +//------------------------------------------------------------------------------- +// \ru Разделить часть массива между индексами start и end на две части, одна из которых меньше +// чем splitValue, другое с элементами больше или равными чем splitValue. Сравнение элементов +// производится с помощью координаты dim [0 = x, 1 = y, 2 = z]. +// \en Split the array part between start and end in two part, one with the elements less than splitValue, +// the other with the elements greater or equal than splitValue. The elements are compared +// using the "dim" coordinate [0 = x, 1 = y, 2 = z]. +// --- +template +size_t KdTree::split( size_t start, size_t end, size_t dim, double splitValue ) +{ + size_t l( start ), r( end - 1 ); + for( ; l < r; ++l, --r ) { + while( l < end && points[l][dim] < splitValue ) + l++; + while( r >= start && points[r][dim] >= splitValue ) + r--; + if( l > r ) + break; + std::swap( points[l], points[r] ); + std::swap( indices[l], indices[r] ); + } + return ( points[l][dim] < splitValue ? l + 1 : l ); // Вернуть индекс первого элемента во второй части. +} + + +//------------------------------------------------------------------------------- +// \ru Построить k-мерное дерево (рекурсивно). Если количество точек узла меньше чем +// targetCellsize, то делаем этот узел листом, иначе рассчитываем ограничивающий +// куб для точек узла и делим его по среднему значению наибольшего габарита куба. +// \en Build the kdtree recursively. If the number of points in the node is lower than +// targetCellsize then mark this node as leaf, else compute the bounding box of the points +// of the node and split it at the middle of the largest bounding box dimension. +// --- +template +size_t KdTree::createTree( size_t nodeId, size_t start, size_t end, size_t level ) +{ + Node & node = nodes[nodeId]; // Первый узел + MbCube cube; + + for( size_t i = start + 1; i < end; ++i ) + cube |= points[i] ; + + + MbVector3D diag = cube.pmax - cube.pmin; // Диагональ габаритного куба. + + size_t dim; + if( diag.x > diag.y ) + dim = diag.x > diag.z ? 0 : 2; + else + dim = diag.y > diag.z ? 1 : 2; + + node.dim = dim; + if( isBalanced ) // Разделить точки используя среднее значение вдоль направления dim. + { + std::vector tempVector; + for( size_t i = start + 1; i < end; ++i ) + tempVector.push_back( (points[i])[dim] ); + std::sort( tempVector.begin(), tempVector.end() ); + node.splitValue = ( tempVector[int(tempVector.size() / 2.0)] + tempVector[int(tempVector.size() / 2.0) + 1] ) / 2.0; + } + else // Разделить ограничивающий куб на две части на основе среднего значение вдоль направления dim. + node.splitValue = Scalar( 0.5*( cube.pmax[dim] + cube.pmin[dim] ) ); + + size_t midId = split( start, end, dim, node.splitValue ); // Индекс первого элемента во второй части. + + node.firstChildId = nodes.size(); + nodes.resize( nodes.size() + 2 ); + bool flag = ( midId == start ) || ( midId == end ); + size_t leftLevel, rightLevel; + { + // Левый потомок. + size_t childId = nodes[nodeId].firstChildId; + Node & child = nodes[childId]; + if( flag || ( midId - start ) <= targetCellSize || level >= targetMaxDepth ) { + child.type = 1; + child.start = (unsigned int)start; + child.size = (unsigned short)(midId - start); + leftLevel = level; + } + else { + child.type = 0; + leftLevel = createTree( childId, start, midId, level + 1 ); + } + } + + { + // Правый потомок. + size_t childId = nodes[nodeId].firstChildId + 1; + Node & child = nodes[childId]; + if( flag || ( end - midId ) <= targetCellSize || level >= targetMaxDepth ) { + child.type = 1; + child.start = (unsigned int)midId; + child.size = (unsigned short)(end - midId); + rightLevel = level; + } + else { + child.type = 0; + rightLevel = createTree( childId, midId, end, level + 1 ); + } + } + if( leftLevel > rightLevel ) + return leftLevel; + return rightLevel; +} + + #endif //__MB_KDTREE_H \ No newline at end of file diff --git a/C3d/Include/templ_lis_array.h b/C3d/Include/templ_lis_array.h index 0473359..810a74b 100644 --- a/C3d/Include/templ_lis_array.h +++ b/C3d/Include/templ_lis_array.h @@ -13,10 +13,6 @@ #include #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ // \ru после sys_defs.h !!! \en after sys_defs.h !!! -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - FORVARD_DECL_TEMPLATE_TYPENAME( class LiSArray ); FORVARD_DECL_TEMPLATE_TYPENAME( void set_array_size( LiSArray &, size_t newSize ) ); @@ -249,7 +245,7 @@ void set_array_size( LiSArray & arr, size_t newSize ) // \ru !!! здесь count не изменяется!!! \en !!! 'count' is not changed!! #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldUpper * sizeof(Type), arr.parr, newUpper * sizeof(Type), 3/*LiSArray*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldUpper * sizeof(Type), arr.parr, newUpper * sizeof(Type), 3/*LiSArray*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ } } diff --git a/C3d/Include/templ_multimap.h b/C3d/Include/templ_multimap.h index 4dfad24..0bdf1cd 100644 --- a/C3d/Include/templ_multimap.h +++ b/C3d/Include/templ_multimap.h @@ -1,699 +1,699 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Мультимножество, реализующее основной функционал std::multimap. - \en Multiset implementing the core functionality of std::multimap. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TEMPL_MULTIMAP_H -#define __TEMPL_MULTIMAP_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Ассоциативное множество c дубликатами (мультимножество). - \en Associative set with duplicates (multiset). \~ - \details \ru Ассоциативное множество c дубликатами (мультимножество). \n - Реализует основные функциии std::multimap. Требования к типам данных KeyType и ValType такие же, как в SArray. - Мультимножество задает соответствие (ассоциации) объекта-ключа подмножеству объектов-значений. - Для некоторого объекта типа KeyType задается соответствие подмножеству объектов ValType. - \en Associative set with duplicates (multiset). \n - Implements the core functions of is std::multimap. Requirements to data types KeyType and ValType are the same as in SArray. - Multiset sets the mapping (associations) between a key-object and a subset of value-objects. - For some object of the "KeyType" type there is set a mapping to a subset of objects of the "ValType" type. \~ - \ingroup Base_Tools_Containers -*/ -// --- -template -class MultiMap { -public: - - struct Pair - { - const KeyType m_key; - const ValType m_val; - Pair( const KeyType & key, const ValType & val ) : m_key( key ), m_val( val ) {} - bool operator < ( const Pair & p ) const { - return m_key < p.m_key; - } - bool operator == ( const Pair & p ) const { - return m_key == p.m_key && m_val == p.m_val; - } - Pair & operator = ( const Pair & ); // \ru Не реализовано. \en Not implemented. - }; - -public: - MultiMap(); - virtual ~MultiMap() {} - - class Iterator; - -public: - /// \ru Оператор доступа по ключу. \en Access by key operator. - Iterator operator[] ( const KeyType & key ) const; - /// \ru Получить итератор, указывающий на первый элемент. \en Get an iterator pointing to the first element. - Iterator First() const; - /// \ru Добавить элемент с заданным ключом и значением. \en Add an element with specified key and value. - void Associate( const KeyType & key, const ValType & val ); - /// \ru Удалить заданное значение с заданным ключом. \en Remove an element with specified key and value. - void Dissociate( const KeyType & key, const ValType & val ); - /// \ru Удалить элементы в диапазоне [it1, it2). \en Remove elements in the range [it1, it2). - void Dissociate( Iterator & it1, Iterator & it2 ); - /// \ru Удалить элемент, указанный итератором. \en Remove an element specified by an iterator. - Iterator Dissociate( Iterator & it ); - /// \ru Удалить все элементы из контейнера. \en Removes all elements from the container. - void Flush() { m_Pairs.Flush(); } - /// \ru Существует ли элемент с заданными ключом и значением. \en Is there an element with the specified key and value. - bool IsAssociated( const KeyType & key, const ValType & val ) const; - /// \ru Найти элемент с заданными ключом и значением. \en Find an element with the specified key and value. - Iterator Find( const KeyType & key ) const; - // \ru Итератор, указывающий на первый элемент со значением ключа, не меньшим, чем заданный. \en An iterator pointing to the first element not less than the given key. - Iterator LowerBound( const KeyType & key ) const; - // \ru Итератор, указывающий на первый элемент со значением ключа, большим, чем заданный. \en An iterator pointing to the first element greater than the given key. - Iterator UpperBound( const KeyType & key ) const; - // \ru Диапазон, содержащий все элементы с данным ключом в контейнере. \en A range containing all elements with the given key in the container. - std::pair EqualRange( const KeyType & key ) const; - // \ru Количество элементов в контейнере. \en The number of elements in the container. - size_t Count() const { return m_Pairs.Count(); } - - static size_t UpperBoundEx( const SArray & pairs, const KeyType & key ); - static size_t LowerBoundEx( const SArray & pairs, const KeyType & key ); - static std::pair EqualRangeEx( const SArray & pairs, const KeyType & key ); - -private: - SArray m_Pairs; - - private: // \ru Специфицируем нуль для разных типов. \en Specify null for different types. - template - struct Null { // \ru Нуль тривиальных типов (int, float, double и т.д.). \en Null of trivial types (int, float, double etc.). - static inline T val() { return 0; } - }; - template - struct Null { // \ru Нуль указателей. \en Null of pointers. - static inline T* val() { return NULL; } - }; -// \ru LF_Linux: 25.03.11 g++ выдает ошибку на этот код - не использованы KeyType, ValType в полной специализации шаблона. -// Однако непонятно, зачем нужна эта полная специализация - общая частичная специализация для тривиальных типов вполне подойдет. -// \en LF_Linux: 25.03.11 g++ returns an error in this code - types KeyType and ValType are not used in the full specialization of template. -// But it is not clear what for this specialization is required - the common partial specialization for the trivial types is sufficient. -// template<> -// \ru struct Null { // Нуль вещественных чисел \en struct Null { // Null of real numbers -// static inline double val() { return 0.0; } -// }; - -public: - // \ru Итератор по элементам контейнера. \en Iterator for the container elements. - class Iterator { - private: - Pair * m_Ptr; - Pair * m_MaxPtr; - - public: - Iterator() : m_Ptr( NULL ), m_MaxPtr( 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 ) - { - const size_t count = m_Pairs.Count(); - if ( count > 0 ) { - size_t idx = MultiMap::LowerBoundEx( m_Pairs, pair.m_key ); - size_t temp = idx; - while ( temp < m_Pairs.Count() && m_Pairs[temp].m_key == pair.m_key ) { - if ( m_Pairs[temp] == pair ) { - idx = temp; - break; - } - temp++; - } - m_MaxPtr = &m_Pairs[count-1]; - if ( idx < count ) { - m_Ptr = &m_Pairs[idx]; - } - } - } - Iterator( const SArray & m_Pairs, const Iterator & iter1, const Iterator & iter2 ) // range - : m_Ptr( NULL ), m_MaxPtr( NULL ) - { - const size_t count = m_Pairs.Count(); - if ( count > 0 && iter1.m_Ptr != 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 ) { - if ( m_Pairs[temp] == *iter1.m_Ptr ) { - idx1 = temp; - break; - } - temp++; - } - size_t idx2 = SYS_MAX_T; - if ( iter2.m_Ptr != NULL ) { - idx2 = MultiMap::UpperBoundEx( m_Pairs, iter2.m_Ptr->m_key ); - if ( idx2 < m_Pairs.Count() ) { - if ( idx2 > 0) - idx2--; - else - idx2 = SYS_MAX_T; - } - } - if ( idx2 == SYS_MAX_T ) - idx2 = count - 1; - if ( idx1 < count && idx2 < count ) { - m_Ptr = &m_Pairs[idx1]; - m_MaxPtr = &m_Pairs[idx2]; - } - } - } - - public: - /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move the iterator to the next. - Iterator operator ++( int ) - { - Iterator iter(*this); - if ( m_Ptr && m_Ptr < m_MaxPtr ) - m_Ptr++; - else - m_Ptr = 0; - return iter; - } - /// \ru Оператор равенства. \en An equality operator. - bool operator == ( const Iterator & itr ) const - { - if ( Empty() && itr.Empty() ) - return true; - if ( ( Empty() && !itr.Empty() ) || ( !Empty() && itr.Empty() ) ) - return false; - return m_Ptr == itr.m_Ptr && m_MaxPtr == itr.m_MaxPtr; - } - /// \ru Оператор "!=". \en An "!=" operator. - bool operator != ( const Iterator & itr ) const - { - if ( Empty() && itr.Empty() ) - return false; - if ( ( Empty() && !itr.Empty() ) || ( !Empty() && itr.Empty() ) ) - return true; - return m_Ptr != itr.m_Ptr || m_MaxPtr != itr.m_MaxPtr; - } - /// \ru Оператор "меньше". \en Operator "less". - bool operator < ( const Iterator& itr ) const - { - return m_Ptr < itr.m_Ptr && m_MaxPtr <= itr.m_MaxPtr; - } - /// \ru Пустой ли итератор. \en Is the iterator empty. - bool Empty() const - { - return !( m_Ptr && m_Ptr <= m_MaxPtr ); - } - // \ru Получить текущий ключ элемента. \en Get the current key of the element. - KeyType Key() const - { - return !Empty() ? m_Ptr->m_key : (KeyType)0; - } - // \ru Получить текущее значение элемента. \en Get the current value of the element. - ValType Value() const - { - return !Empty() ? m_Ptr->m_val : (ValType)0; - } - // \ru Получить пару с текущим ключом и текущим кзначением элемента. \en Get the pair with the current key and the current value of the element. - Pair* GetPair() const - { - return m_Ptr; - } - }; -}; - - -//------------------------------------------------------------------------------ -// -// --- -template -size_t MultiMap::LowerBoundEx( const SArray::Pair> & pairs, const KeyType & key ) -{ - if ( pairs.Count() > 11 ) { - size_t end = pairs.Count() - 1; - size_t last = end; - size_t start = 0; - size_t firstNotLess = SYS_MAX_T; - - while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. - size_t middle = ( start + end ) / 2; - Pair& mdE = pairs[middle]; - if ( mdE.m_key < key ) { - start = middle; - } - else if ( key <= mdE.m_key ) { - if ( middle < firstNotLess ) - firstNotLess = middle; - end = middle; - } - // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. - // \en If we are here, then operators of identity check and comparison are not correct. - else { - PRECONDITION( 0 ); - return SYS_MAX_T; - } - } - - // \ru Проверяем ключ между start и end. \en Check a key between start and end. - if ( start + 1 < pairs.Count() - 1 ) { - size_t middle = start + 1; - Pair& mdE = pairs[middle]; - if ( key <= mdE.m_key && middle < firstNotLess ) - firstNotLess = middle; - } - - if ( key <= pairs[0].m_key ) - return 0; - if ( firstNotLess <= last && firstNotLess >= 0 && key <= pairs[firstNotLess].m_key ) - return firstNotLess; - if ( key == pairs[last].m_key ) - return last; - } - else { - if ( pairs.Count() == 1 ) - return key <= pairs[0].m_key ? 0 : SYS_MAX_T; - else if ( pairs.Count() == 2 ) { - if ( key <= pairs[0].m_key ) - return 0; - if ( key <= pairs[1].m_key ) - return 1; - } - else { // 2 < count <= 11 - for( size_t i = 0; i < pairs.Count(); ++i ) - if ( key <= pairs[i].m_key ) - return i; - } - } - return SYS_MAX_T; -} - -//------------------------------------------------------------------------------ -// \ru Итератор, указывающий на первый элемент со значением ключа, не меньшим, чем заданный. -// \en An iterator pointing to the first element not less than the given key. -// --- -template -inline typename MultiMap::Iterator MultiMap::LowerBound( const KeyType & key ) const -{ - size_t idx = LowerBoundEx ( m_Pairs, key ); - return idx < m_Pairs.Count() ? Iterator ( m_Pairs, m_Pairs[idx] ) : Iterator(); -} - -template -size_t MultiMap::UpperBoundEx( const SArray::Pair> & pairs, const KeyType & key ) -{ - if ( pairs.Count() > 11 ) { - size_t end = pairs.Count() - 1; - size_t last = end; - size_t start = 0; - size_t firstGreater = SYS_MAX_T; - - while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. - size_t middle = ( start + end ) / 2; - Pair& mdE = pairs[middle]; - if ( mdE.m_key <= key ) { - start = middle; - } - else if ( key < mdE.m_key ) { - if ( middle < firstGreater ) - firstGreater = middle; - end = middle; - } - // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. - // \en If we are here, then operators of identity check and comparison are not correct. - else { - PRECONDITION( 0 ); - return SYS_MAX_T; - } - } - - if ( key < pairs[0].m_key ) - return 0; - if ( firstGreater <= end && firstGreater >= 0 && key < pairs[firstGreater].m_key ) - return firstGreater; - if ( key < pairs[last].m_key ) - return last; - } - else { - if ( pairs.Count() == 1 ) - return key < pairs[0].m_key ? 0 :SYS_MAX_T; - else if ( pairs.Count() == 2 ) { - if ( key < pairs[0].m_key ) - return 0; - if ( key < pairs[1].m_key ) - return 1; - } - else { // 2 < count <= 11 - for( size_t i = 0; i < pairs.Count(); ++i ) - if ( key < pairs[i].m_key ) - return i; - } - } - return SYS_MAX_T; -} - - -//------------------------------------------------------------------------------ -// \ru Итератор, указывающий на первый элемент со значением ключа, большим, чем заданный. -// \en An iterator pointing to the first element greater than the given key. -// --- -template -inline typename MultiMap::Iterator MultiMap::UpperBound( const KeyType & key ) const -{ - size_t ind = UpperBoundEx ( m_Pairs, key ); - return ind != SYS_MAX_T ? Iterator ( m_Pairs, m_Pairs[ind] ) : Iterator(); -} - - -//------------------------------------------------------------------------------ -// -// --- -template -std::pair MultiMap::EqualRangeEx( const SArray::Pair> & pairs, const KeyType & key ) -{ - if ( pairs.Count() > 11 ) { - size_t end = pairs.Count() - 1; - size_t lastRight = end; - size_t start = 0; - size_t firstNotLess = SYS_MAX_T; - size_t firstGreater = SYS_MAX_T; - - // \ru Проверяем последний элемент. \en Check the last element. - if ( key > pairs[pairs.Count() - 1].m_key ) - return std::pair (SYS_MAX_T, SYS_MAX_T); - - // \ru Проверяем первый элемент. \en Check the first element. - if ( key < pairs[0].m_key ) - return std::pair (0, 0); - - if ( key != pairs[0].m_key ) { - while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. - size_t middle = ( start + end ) / 2; - Pair& mdE = pairs[middle]; - if ( mdE.m_key < key ) { - start = middle; - } - else if ( key <= mdE.m_key ) { - if ( key < mdE.m_key && lastRight > middle ) - lastRight = middle; - if ( middle < firstNotLess ) - firstNotLess = middle; - end = middle; - } - // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. - // \en If we are here, then operators of identity check and comparison are not correct. - else { - PRECONDITION( 0 ); - return std::pair (SYS_MAX_T, SYS_MAX_T); - } - } - } - else - firstNotLess = 0; // key == pairs[0].m_key - - // \ru Проверяем ключ между start и end. \en Check a key between start and end. - if ( start + 1 == end ) { - size_t middle = start + 1; - Pair& mdE = pairs[middle]; - if ( key <= mdE.m_key && middle < firstNotLess ) - firstNotLess = middle; - } - - // \ru Проверяем последний элемент. \en Check the last element. - if ( firstNotLess == SYS_MAX_T && key == pairs[pairs.Count() - 1].m_key ) - return std::pair (pairs.Count() - 1, SYS_MAX_T); - - if ( firstNotLess == SYS_MAX_T ) - return std::pair (SYS_MAX_T, SYS_MAX_T); - - // \ru Теперь начинаем правый поиск. \en Now start right search. - end = lastRight; - start = firstNotLess; - - if ( start == end && pairs[firstNotLess].m_key != key ) - return std::pair ( firstNotLess, firstNotLess ); - - while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. - size_t middle = ( start + end ) / 2; - Pair& mdE = pairs[middle]; - if ( mdE.m_key <= key ) { - start = middle; - } - else if ( key < mdE.m_key ) { - if ( middle < firstGreater ) - firstGreater = middle; - end = middle; - } - // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. - // \en If we are here, then operators of identity check and comparison are not correct. - else { - PRECONDITION( 0 ); - return std::pair ( SYS_MAX_T, SYS_MAX_T ); - } - } - - if ( firstGreater == SYS_MAX_T ) - { - if ( pairs[firstNotLess].m_key != key ) - firstGreater = firstNotLess; - else if ( lastRight > 0 && pairs[lastRight - 1].m_key == key && pairs[lastRight].m_key != key ) - firstGreater = lastRight; - else if ( firstNotLess + 1 < pairs.Count() && pairs[firstNotLess + 1].m_key != key ) - firstGreater = firstNotLess + 1; - } - return std::pair ( firstNotLess, firstGreater ); - } - else { - if ( pairs.Count() == 0 ) - return std::pair ( SYS_MAX_T, SYS_MAX_T ); - if ( pairs.Count() == 1 ) - return key == pairs[0].m_key ? std::pair ( 0, SYS_MAX_T ) : - ( key < pairs[0].m_key ? std::pair ( 0, 0 ) : std::pair ( SYS_MAX_T, SYS_MAX_T ) ); - if ( pairs.Count() == 2 ) { - size_t first = SYS_MAX_T; - if ( key < pairs[0].m_key ) - return std::pair(0, 0); - if ( key > pairs[1].m_key ) - return std::pair(SYS_MAX_T, SYS_MAX_T); - if ( key == pairs[0].m_key ) - first = 0; - else if ( key == pairs[1].m_key ) - first = 1; - else // ( key > pairs[0].m_key && key < pairs[1].m_key ) - return std::pair ( 1, 1 ); - if ( key == pairs[1].m_key ) - return std::pair ( first, SYS_MAX_T ); - return std::pair (first, 1); - } - else { // 2 < count <= 11 - size_t first = SYS_MAX_T, second = SYS_MAX_T; - if ( key < pairs[0].m_key ) - return std::pair ( 0, 0 ); - if ( key > pairs[pairs.Count() - 1].m_key ) - return std::pair ( first, second ); - for( size_t i = 0; i < pairs.Count(); ++i ) { - if ( key == pairs[i].m_key ) { - if ( first == SYS_MAX_T ) - first = i; - } - else { - if ( key < pairs[i].m_key ) { - second = i; - break; - } - } - } - if ( first == SYS_MAX_T ) - first = second; - return std::pair ( first, second ); - } - } -} - - -//------------------------------------------------------------------------------ -// \ru Диапазон, содержащий все элементы с данным ключом в контейнере. -// \en A range containing all elements with the given key in the container. -// --- -template -inline std::pair::Iterator,typename MultiMap::Iterator> - MultiMap::EqualRange ( const KeyType & key ) const -{ - std::pair idx = EqualRangeEx ( m_Pairs, key ); - Iterator first, second; - if ( idx.first < m_Pairs.Count() ) - first = Iterator ( m_Pairs, m_Pairs[idx.first]); - if ( idx.second < m_Pairs.Count() ) - second = Iterator ( m_Pairs, m_Pairs[idx.second]); - return std::pair ( first, second ); -} - - -//------------------------------------------------------------------------------ -/// \ru Найти элемент с заданными ключом и значением. -// \en Find an element with the specified key and value. -// --- -template -inline typename MultiMap::Iterator MultiMap::Find( const KeyType & key ) const -{ - if ( m_Pairs.Count() > 11 ) { - size_t mx = m_Pairs.Count() - 1; - size_t mxc = mx; - size_t mn = 0; - - while ( mn + 1 < mx ) { // \ru Ищем, пока не нашли. \en Seek until find. - size_t md = ( mn + mx ) / 2; - Pair& mdE = m_Pairs[md]; - if ( mdE.m_key < key ) { - mn = md; - } - else if ( key < mdE.m_key ) { - mx = md; - } - else if ( mdE.m_key == key ) - return Iterator ( m_Pairs, mdE ); - // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. - // \en If we are here, then operators of identity check and comparison are not correct. - else { - PRECONDITION( 0 ); - return Iterator(); - } - } - - if ( key == m_Pairs[0].m_key ) - return Iterator ( m_Pairs, m_Pairs[0] ); - if ( key == m_Pairs[mxc].m_key ) - return Iterator ( m_Pairs, m_Pairs[mxc] ); - } - else { - if ( m_Pairs.Count() == 1 ) - return key == m_Pairs[0].m_key ? Iterator ( m_Pairs, m_Pairs[0] ) : Iterator(); - else if ( m_Pairs.Count() == 2 ) { - if ( key == m_Pairs[0].m_key ) - return Iterator ( m_Pairs, m_Pairs[0] ); - if ( key == m_Pairs[1].m_key ) - return Iterator ( m_Pairs, m_Pairs[1] ); - return Iterator(); - } - else { // 2 < count <= 11 - for( size_t i = 0; i < m_Pairs.Count(); ++i ) - if ( key == m_Pairs[i].m_key ) - return Iterator ( m_Pairs, m_Pairs[i] ); - } - } - return Iterator(); -} - - -//------------------------------------------------------------------------------- -// \ru Конструктор. \en Contructor. -// --- -template -MultiMap::MultiMap() - : m_Pairs( 0, 1 ) -{} - - -//------------------------------------------------------------------------------- -/// \ru Добавить элемент с заданным ключом и значением. -// \en Add an element with specified key and value. -// --- -template -inline void MultiMap::Associate( const KeyType & key, const ValType & val ) { - Pair pair( key, val ); - std::pair idx = EqualRangeEx ( m_Pairs, key ); - if ( idx.second < m_Pairs.Count() ) - m_Pairs.InsertInd ( idx.second, pair ); - else - m_Pairs.Add ( pair ); -} - - -//------------------------------------------------------------------------------- -// \ru Существует ли элемент с заданными ключом и значением. -// \en Is there an element with the specified key and value. -// --- -template -inline bool MultiMap::IsAssociated( const KeyType & key, const ValType & val ) const { - return m_Pairs.FindIt( Pair(key, val) ) < m_Pairs.Count(); -} - - -//------------------------------------------------------------------------------- -/// \ru Удалить заданное значение с заданным ключом. \en Remove an element with specified key and value. -// --- -template -inline void MultiMap::Dissociate( const KeyType & key, const ValType & val ) { - Pair pair( key, val ); - size_t idx = m_Pairs.FindIt( pair ); - if ( idx < m_Pairs.Count() ) { - m_Pairs.RemoveInd( idx ); - } -} - - -//------------------------------------------------------------------------------- -/// \ru Удалить элемент, указанный итератором. \en Remove an element specified by an iterator. -// --- -template -inline typename MultiMap::Iterator MultiMap::Dissociate( - typename MultiMap::Iterator & it ) -{ - size_t idx = m_Pairs.FindIt( *it.GetPair() ); - if ( idx < m_Pairs.Count() ) { - m_Pairs.RemoveInd( idx ); - if ( idx < m_Pairs.Count() ) - return Iterator ( m_Pairs, m_Pairs[idx]); - } - return Iterator(); -} - - -//------------------------------------------------------------------------------- -/// \ru Удалить элементы в диапазоне [it1, it2). \en Remove elements in the range [it1, it2). -// --- -template -inline void MultiMap::Dissociate( - typename MultiMap::Iterator & it1, - typename MultiMap::Iterator & it2 ) -{ - if ( m_Pairs.Count() == 0 || it1.Empty() ) - return; - if ( it2.Empty() ) { - // \ru Удаляем с it1 до конца. \en Remove from it1 up to the end. - it2 = Iterator ( m_Pairs, m_Pairs[m_Pairs.Count() - 1] ); - if ( it1 == it2 ) - Dissociate ( it1.Key(), it1.Value() ); // \ru Просто удаляем последний элемент. \en Just remove the last element. - else if ( it1 < it2 ) { - size_t idx = m_Pairs.FindIt( *it1.GetPair() ); - if ( idx != SYS_MAX_T ) - m_Pairs.RemoveInd ( idx, m_Pairs.Count () ); - } - } - else if ( it1 < it2 ) - m_Pairs.Remove ( it1.GetPair(), it2.GetPair() ); -} - - -//------------------------------------------------------------------------------- -/// \ru Оператор доступа по ключу. \en Access by key operator. -// --- -template -inline typename MultiMap::Iterator MultiMap::operator[] ( const KeyType & key ) const { - return Iterator( m_Pairs, Pair(key, Null::val()) ); -} - - -//------------------------------------------------------------------------------- -/// \ru Получить итератор, указывающий на первый элемент. \en Get an iterator pointing to the first element. -// --- -template -inline typename MultiMap::Iterator MultiMap::First() const { - if ( m_Pairs.Count() ) - return Iterator ( m_Pairs, m_Pairs[0] ); - return Iterator(); -} - - -#endif // __TEMPL_MULTIMAP_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Мультимножество, реализующее основной функционал std::multimap. + \en Multiset implementing the core functionality of std::multimap. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TEMPL_MULTIMAP_H +#define __TEMPL_MULTIMAP_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Ассоциативное множество c дубликатами (мультимножество). + \en Associative set with duplicates (multiset). \~ + \details \ru Ассоциативное множество c дубликатами (мультимножество). \n + Реализует основные функциии std::multimap. Требования к типам данных KeyType и ValType такие же, как в SArray. + Мультимножество задает соответствие (ассоциации) объекта-ключа подмножеству объектов-значений. + Для некоторого объекта типа KeyType задается соответствие подмножеству объектов ValType. + \en Associative set with duplicates (multiset). \n + Implements the core functions of is std::multimap. Requirements to data types KeyType and ValType are the same as in SArray. + Multiset sets the mapping (associations) between a key-object and a subset of value-objects. + For some object of the "KeyType" type there is set a mapping to a subset of objects of the "ValType" type. \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class MultiMap { +public: + + struct Pair + { + const KeyType m_key; + const ValType m_val; + Pair( const KeyType & key, const ValType & val ) : m_key( key ), m_val( val ) {} + bool operator < ( const Pair & p ) const { + return m_key < p.m_key; + } + bool operator == ( const Pair & p ) const { + return m_key == p.m_key && m_val == p.m_val; + } + Pair & operator = ( const Pair & ); // \ru Не реализовано. \en Not implemented. + }; + +public: + MultiMap(); + virtual ~MultiMap() {} + + class Iterator; + +public: + /// \ru Оператор доступа по ключу. \en Access by key operator. + Iterator operator[] ( const KeyType & key ) const; + /// \ru Получить итератор, указывающий на первый элемент. \en Get an iterator pointing to the first element. + Iterator First() const; + /// \ru Добавить элемент с заданным ключом и значением. \en Add an element with specified key and value. + void Associate( const KeyType & key, const ValType & val ); + /// \ru Удалить заданное значение с заданным ключом. \en Remove an element with specified key and value. + void Dissociate( const KeyType & key, const ValType & val ); + /// \ru Удалить элементы в диапазоне [it1, it2). \en Remove elements in the range [it1, it2). + void Dissociate( Iterator & it1, Iterator & it2 ); + /// \ru Удалить элемент, указанный итератором. \en Remove an element specified by an iterator. + Iterator Dissociate( Iterator & it ); + /// \ru Удалить все элементы из контейнера. \en Removes all elements from the container. + void Flush() { m_Pairs.Flush(); } + /// \ru Существует ли элемент с заданными ключом и значением. \en Is there an element with the specified key and value. + bool IsAssociated( const KeyType & key, const ValType & val ) const; + /// \ru Найти элемент с заданными ключом и значением. \en Find an element with the specified key and value. + Iterator Find( const KeyType & key ) const; + // \ru Итератор, указывающий на первый элемент со значением ключа, не меньшим, чем заданный. \en An iterator pointing to the first element not less than the given key. + Iterator LowerBound( const KeyType & key ) const; + // \ru Итератор, указывающий на первый элемент со значением ключа, большим, чем заданный. \en An iterator pointing to the first element greater than the given key. + Iterator UpperBound( const KeyType & key ) const; + // \ru Диапазон, содержащий все элементы с данным ключом в контейнере. \en A range containing all elements with the given key in the container. + std::pair EqualRange( const KeyType & key ) const; + // \ru Количество элементов в контейнере. \en The number of elements in the container. + size_t Count() const { return m_Pairs.Count(); } + + static size_t UpperBoundEx( const SArray & pairs, const KeyType & key ); + static size_t LowerBoundEx( const SArray & pairs, const KeyType & key ); + static std::pair EqualRangeEx( const SArray & pairs, const KeyType & key ); + +private: + SArray m_Pairs; + + private: // \ru Специфицируем нуль для разных типов. \en Specify null for different types. + template + struct Null { // \ru Нуль тривиальных типов (int, float, double и т.д.). \en Null of trivial types (int, float, double etc.). + static inline T val() { return 0; } + }; + template + struct Null { // \ru Нуль указателей. \en Null of pointers. + static inline T* val() { return NULL; } + }; +// \ru LF_Linux: 25.03.11 g++ выдает ошибку на этот код - не использованы KeyType, ValType в полной специализации шаблона. +// Однако непонятно, зачем нужна эта полная специализация - общая частичная специализация для тривиальных типов вполне подойдет. +// \en LF_Linux: 25.03.11 g++ returns an error in this code - types KeyType and ValType are not used in the full specialization of template. +// But it is not clear what for this specialization is required - the common partial specialization for the trivial types is sufficient. +// template<> +// \ru struct Null { // Нуль вещественных чисел \en struct Null { // Null of real numbers +// static inline double val() { return 0.0; } +// }; + +public: + // \ru Итератор по элементам контейнера. \en Iterator for the container elements. + class Iterator { + private: + Pair * m_Ptr; + Pair * m_MaxPtr; + + public: + Iterator() : m_Ptr( NULL ), m_MaxPtr( 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 ) + { + const size_t count = m_Pairs.Count(); + if ( count > 0 ) { + size_t idx = MultiMap::LowerBoundEx( m_Pairs, pair.m_key ); + size_t temp = idx; + while ( temp < m_Pairs.Count() && m_Pairs[temp].m_key == pair.m_key ) { + if ( m_Pairs[temp] == pair ) { + idx = temp; + break; + } + temp++; + } + m_MaxPtr = &m_Pairs[count-1]; + if ( idx < count ) { + m_Ptr = &m_Pairs[idx]; + } + } + } + Iterator( const SArray & m_Pairs, const Iterator & iter1, const Iterator & iter2 ) // range + : m_Ptr( NULL ), m_MaxPtr( NULL ) + { + const size_t count = m_Pairs.Count(); + if ( count > 0 && iter1.m_Ptr != 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 ) { + if ( m_Pairs[temp] == *iter1.m_Ptr ) { + idx1 = temp; + break; + } + temp++; + } + size_t idx2 = SYS_MAX_T; + if ( iter2.m_Ptr != NULL ) { + idx2 = MultiMap::UpperBoundEx( m_Pairs, iter2.m_Ptr->m_key ); + if ( idx2 < m_Pairs.Count() ) { + if ( idx2 > 0) + idx2--; + else + idx2 = SYS_MAX_T; + } + } + if ( idx2 == SYS_MAX_T ) + idx2 = count - 1; + if ( idx1 < count && idx2 < count ) { + m_Ptr = &m_Pairs[idx1]; + m_MaxPtr = &m_Pairs[idx2]; + } + } + } + + public: + /// \ru Получить текущий элемент и сдвинуть итератор на следующий. \en Get the current element and move the iterator to the next. + Iterator operator ++( int ) + { + Iterator iter(*this); + if ( m_Ptr && m_Ptr < m_MaxPtr ) + m_Ptr++; + else + m_Ptr = 0; + return iter; + } + /// \ru Оператор равенства. \en An equality operator. + bool operator == ( const Iterator & itr ) const + { + if ( Empty() && itr.Empty() ) + return true; + if ( ( Empty() && !itr.Empty() ) || ( !Empty() && itr.Empty() ) ) + return false; + return m_Ptr == itr.m_Ptr && m_MaxPtr == itr.m_MaxPtr; + } + /// \ru Оператор "!=". \en An "!=" operator. + bool operator != ( const Iterator & itr ) const + { + if ( Empty() && itr.Empty() ) + return false; + if ( ( Empty() && !itr.Empty() ) || ( !Empty() && itr.Empty() ) ) + return true; + return m_Ptr != itr.m_Ptr || m_MaxPtr != itr.m_MaxPtr; + } + /// \ru Оператор "меньше". \en Operator "less". + bool operator < ( const Iterator& itr ) const + { + return m_Ptr < itr.m_Ptr && m_MaxPtr <= itr.m_MaxPtr; + } + /// \ru Пустой ли итератор. \en Is the iterator empty. + bool Empty() const + { + return !( m_Ptr && m_Ptr <= m_MaxPtr ); + } + // \ru Получить текущий ключ элемента. \en Get the current key of the element. + KeyType Key() const + { + return !Empty() ? m_Ptr->m_key : (KeyType)0; + } + // \ru Получить текущее значение элемента. \en Get the current value of the element. + ValType Value() const + { + return !Empty() ? m_Ptr->m_val : (ValType)0; + } + // \ru Получить пару с текущим ключом и текущим кзначением элемента. \en Get the pair with the current key and the current value of the element. + Pair* GetPair() const + { + return m_Ptr; + } + }; +}; + + +//------------------------------------------------------------------------------ +// +// --- +template +size_t MultiMap::LowerBoundEx( const SArray::Pair> & pairs, const KeyType & key ) +{ + if ( pairs.Count() > 11 ) { + size_t end = pairs.Count() - 1; + size_t last = end; + size_t start = 0; + size_t firstNotLess = SYS_MAX_T; + + while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. + size_t middle = ( start + end ) / 2; + Pair& mdE = pairs[middle]; + if ( mdE.m_key < key ) { + start = middle; + } + else if ( key <= mdE.m_key ) { + if ( middle < firstNotLess ) + firstNotLess = middle; + end = middle; + } + // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. + // \en If we are here, then operators of identity check and comparison are not correct. + else { + PRECONDITION( 0 ); + return SYS_MAX_T; + } + } + + // \ru Проверяем ключ между start и end. \en Check a key between start and end. + if ( start + 1 < pairs.Count() - 1 ) { + size_t middle = start + 1; + Pair& mdE = pairs[middle]; + if ( key <= mdE.m_key && middle < firstNotLess ) + firstNotLess = middle; + } + + if ( key <= pairs[0].m_key ) + return 0; + if ( firstNotLess <= last && firstNotLess >= 0 && key <= pairs[firstNotLess].m_key ) + return firstNotLess; + if ( key == pairs[last].m_key ) + return last; + } + else { + if ( pairs.Count() == 1 ) + return key <= pairs[0].m_key ? 0 : SYS_MAX_T; + else if ( pairs.Count() == 2 ) { + if ( key <= pairs[0].m_key ) + return 0; + if ( key <= pairs[1].m_key ) + return 1; + } + else { // 2 < count <= 11 + for( size_t i = 0; i < pairs.Count(); ++i ) + if ( key <= pairs[i].m_key ) + return i; + } + } + return SYS_MAX_T; +} + +//------------------------------------------------------------------------------ +// \ru Итератор, указывающий на первый элемент со значением ключа, не меньшим, чем заданный. +// \en An iterator pointing to the first element not less than the given key. +// --- +template +inline typename MultiMap::Iterator MultiMap::LowerBound( const KeyType & key ) const +{ + size_t idx = LowerBoundEx ( m_Pairs, key ); + return idx < m_Pairs.Count() ? Iterator ( m_Pairs, m_Pairs[idx] ) : Iterator(); +} + +template +size_t MultiMap::UpperBoundEx( const SArray::Pair> & pairs, const KeyType & key ) +{ + if ( pairs.Count() > 11 ) { + size_t end = pairs.Count() - 1; + size_t last = end; + size_t start = 0; + size_t firstGreater = SYS_MAX_T; + + while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. + size_t middle = ( start + end ) / 2; + Pair& mdE = pairs[middle]; + if ( mdE.m_key <= key ) { + start = middle; + } + else if ( key < mdE.m_key ) { + if ( middle < firstGreater ) + firstGreater = middle; + end = middle; + } + // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. + // \en If we are here, then operators of identity check and comparison are not correct. + else { + PRECONDITION( 0 ); + return SYS_MAX_T; + } + } + + if ( key < pairs[0].m_key ) + return 0; + if ( firstGreater <= end && firstGreater >= 0 && key < pairs[firstGreater].m_key ) + return firstGreater; + if ( key < pairs[last].m_key ) + return last; + } + else { + if ( pairs.Count() == 1 ) + return key < pairs[0].m_key ? 0 :SYS_MAX_T; + else if ( pairs.Count() == 2 ) { + if ( key < pairs[0].m_key ) + return 0; + if ( key < pairs[1].m_key ) + return 1; + } + else { // 2 < count <= 11 + for( size_t i = 0; i < pairs.Count(); ++i ) + if ( key < pairs[i].m_key ) + return i; + } + } + return SYS_MAX_T; +} + + +//------------------------------------------------------------------------------ +// \ru Итератор, указывающий на первый элемент со значением ключа, большим, чем заданный. +// \en An iterator pointing to the first element greater than the given key. +// --- +template +inline typename MultiMap::Iterator MultiMap::UpperBound( const KeyType & key ) const +{ + size_t ind = UpperBoundEx ( m_Pairs, key ); + return ind != SYS_MAX_T ? Iterator ( m_Pairs, m_Pairs[ind] ) : Iterator(); +} + + +//------------------------------------------------------------------------------ +// +// --- +template +std::pair MultiMap::EqualRangeEx( const SArray::Pair> & pairs, const KeyType & key ) +{ + if ( pairs.Count() > 11 ) { + size_t end = pairs.Count() - 1; + size_t lastRight = end; + size_t start = 0; + size_t firstNotLess = SYS_MAX_T; + size_t firstGreater = SYS_MAX_T; + + // \ru Проверяем последний элемент. \en Check the last element. + if ( key > pairs[pairs.Count() - 1].m_key ) + return std::pair (SYS_MAX_T, SYS_MAX_T); + + // \ru Проверяем первый элемент. \en Check the first element. + if ( key < pairs[0].m_key ) + return std::pair (0, 0); + + if ( key != pairs[0].m_key ) { + while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. + size_t middle = ( start + end ) / 2; + Pair& mdE = pairs[middle]; + if ( mdE.m_key < key ) { + start = middle; + } + else if ( key <= mdE.m_key ) { + if ( key < mdE.m_key && lastRight > middle ) + lastRight = middle; + if ( middle < firstNotLess ) + firstNotLess = middle; + end = middle; + } + // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. + // \en If we are here, then operators of identity check and comparison are not correct. + else { + PRECONDITION( 0 ); + return std::pair (SYS_MAX_T, SYS_MAX_T); + } + } + } + else + firstNotLess = 0; // key == pairs[0].m_key + + // \ru Проверяем ключ между start и end. \en Check a key between start and end. + if ( start + 1 == end ) { + size_t middle = start + 1; + Pair& mdE = pairs[middle]; + if ( key <= mdE.m_key && middle < firstNotLess ) + firstNotLess = middle; + } + + // \ru Проверяем последний элемент. \en Check the last element. + if ( firstNotLess == SYS_MAX_T && key == pairs[pairs.Count() - 1].m_key ) + return std::pair (pairs.Count() - 1, SYS_MAX_T); + + if ( firstNotLess == SYS_MAX_T ) + return std::pair (SYS_MAX_T, SYS_MAX_T); + + // \ru Теперь начинаем правый поиск. \en Now start right search. + end = lastRight; + start = firstNotLess; + + if ( start == end && pairs[firstNotLess].m_key != key ) + return std::pair ( firstNotLess, firstNotLess ); + + while ( start + 1 < end ) { // \ru Ищем, пока не нашли. \en Seek until find. + size_t middle = ( start + end ) / 2; + Pair& mdE = pairs[middle]; + if ( mdE.m_key <= key ) { + start = middle; + } + else if ( key < mdE.m_key ) { + if ( middle < firstGreater ) + firstGreater = middle; + end = middle; + } + // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. + // \en If we are here, then operators of identity check and comparison are not correct. + else { + PRECONDITION( 0 ); + return std::pair ( SYS_MAX_T, SYS_MAX_T ); + } + } + + if ( firstGreater == SYS_MAX_T ) + { + if ( pairs[firstNotLess].m_key != key ) + firstGreater = firstNotLess; + else if ( lastRight > 0 && pairs[lastRight - 1].m_key == key && pairs[lastRight].m_key != key ) + firstGreater = lastRight; + else if ( firstNotLess + 1 < pairs.Count() && pairs[firstNotLess + 1].m_key != key ) + firstGreater = firstNotLess + 1; + } + return std::pair ( firstNotLess, firstGreater ); + } + else { + if ( pairs.Count() == 0 ) + return std::pair ( SYS_MAX_T, SYS_MAX_T ); + if ( pairs.Count() == 1 ) + return key == pairs[0].m_key ? std::pair ( 0, SYS_MAX_T ) : + ( key < pairs[0].m_key ? std::pair ( 0, 0 ) : std::pair ( SYS_MAX_T, SYS_MAX_T ) ); + if ( pairs.Count() == 2 ) { + size_t first = SYS_MAX_T; + if ( key < pairs[0].m_key ) + return std::pair(0, 0); + if ( key > pairs[1].m_key ) + return std::pair(SYS_MAX_T, SYS_MAX_T); + if ( key == pairs[0].m_key ) + first = 0; + else if ( key == pairs[1].m_key ) + first = 1; + else // ( key > pairs[0].m_key && key < pairs[1].m_key ) + return std::pair ( 1, 1 ); + if ( key == pairs[1].m_key ) + return std::pair ( first, SYS_MAX_T ); + return std::pair (first, 1); + } + else { // 2 < count <= 11 + size_t first = SYS_MAX_T, second = SYS_MAX_T; + if ( key < pairs[0].m_key ) + return std::pair ( 0, 0 ); + if ( key > pairs[pairs.Count() - 1].m_key ) + return std::pair ( first, second ); + for( size_t i = 0; i < pairs.Count(); ++i ) { + if ( key == pairs[i].m_key ) { + if ( first == SYS_MAX_T ) + first = i; + } + else { + if ( key < pairs[i].m_key ) { + second = i; + break; + } + } + } + if ( first == SYS_MAX_T ) + first = second; + return std::pair ( first, second ); + } + } +} + + +//------------------------------------------------------------------------------ +// \ru Диапазон, содержащий все элементы с данным ключом в контейнере. +// \en A range containing all elements with the given key in the container. +// --- +template +inline std::pair::Iterator,typename MultiMap::Iterator> + MultiMap::EqualRange ( const KeyType & key ) const +{ + std::pair idx = EqualRangeEx ( m_Pairs, key ); + Iterator first, second; + if ( idx.first < m_Pairs.Count() ) + first = Iterator ( m_Pairs, m_Pairs[idx.first]); + if ( idx.second < m_Pairs.Count() ) + second = Iterator ( m_Pairs, m_Pairs[idx.second]); + return std::pair ( first, second ); +} + + +//------------------------------------------------------------------------------ +/// \ru Найти элемент с заданными ключом и значением. +// \en Find an element with the specified key and value. +// --- +template +inline typename MultiMap::Iterator MultiMap::Find( const KeyType & key ) const +{ + if ( m_Pairs.Count() > 11 ) { + size_t mx = m_Pairs.Count() - 1; + size_t mxc = mx; + size_t mn = 0; + + while ( mn + 1 < mx ) { // \ru Ищем, пока не нашли. \en Seek until find. + size_t md = ( mn + mx ) / 2; + Pair& mdE = m_Pairs[md]; + if ( mdE.m_key < key ) { + mn = md; + } + else if ( key < mdE.m_key ) { + mx = md; + } + else if ( mdE.m_key == key ) + return Iterator ( m_Pairs, mdE ); + // \ru Если попадаем сюда, значит некорректно написаны операторы "тождественно" и сравнения. + // \en If we are here, then operators of identity check and comparison are not correct. + else { + PRECONDITION( 0 ); + return Iterator(); + } + } + + if ( key == m_Pairs[0].m_key ) + return Iterator ( m_Pairs, m_Pairs[0] ); + if ( key == m_Pairs[mxc].m_key ) + return Iterator ( m_Pairs, m_Pairs[mxc] ); + } + else { + if ( m_Pairs.Count() == 1 ) + return key == m_Pairs[0].m_key ? Iterator ( m_Pairs, m_Pairs[0] ) : Iterator(); + else if ( m_Pairs.Count() == 2 ) { + if ( key == m_Pairs[0].m_key ) + return Iterator ( m_Pairs, m_Pairs[0] ); + if ( key == m_Pairs[1].m_key ) + return Iterator ( m_Pairs, m_Pairs[1] ); + return Iterator(); + } + else { // 2 < count <= 11 + for( size_t i = 0; i < m_Pairs.Count(); ++i ) + if ( key == m_Pairs[i].m_key ) + return Iterator ( m_Pairs, m_Pairs[i] ); + } + } + return Iterator(); +} + + +//------------------------------------------------------------------------------- +// \ru Конструктор. \en Contructor. +// --- +template +MultiMap::MultiMap() + : m_Pairs( 0, 1 ) +{} + + +//------------------------------------------------------------------------------- +/// \ru Добавить элемент с заданным ключом и значением. +// \en Add an element with specified key and value. +// --- +template +inline void MultiMap::Associate( const KeyType & key, const ValType & val ) { + Pair pair( key, val ); + std::pair idx = EqualRangeEx ( m_Pairs, key ); + if ( idx.second < m_Pairs.Count() ) + m_Pairs.InsertInd ( idx.second, pair ); + else + m_Pairs.Add ( pair ); +} + + +//------------------------------------------------------------------------------- +// \ru Существует ли элемент с заданными ключом и значением. +// \en Is there an element with the specified key and value. +// --- +template +inline bool MultiMap::IsAssociated( const KeyType & key, const ValType & val ) const { + return m_Pairs.FindIt( Pair(key, val) ) < m_Pairs.Count(); +} + + +//------------------------------------------------------------------------------- +/// \ru Удалить заданное значение с заданным ключом. \en Remove an element with specified key and value. +// --- +template +inline void MultiMap::Dissociate( const KeyType & key, const ValType & val ) { + Pair pair( key, val ); + size_t idx = m_Pairs.FindIt( pair ); + if ( idx < m_Pairs.Count() ) { + m_Pairs.RemoveInd( idx ); + } +} + + +//------------------------------------------------------------------------------- +/// \ru Удалить элемент, указанный итератором. \en Remove an element specified by an iterator. +// --- +template +inline typename MultiMap::Iterator MultiMap::Dissociate( + typename MultiMap::Iterator & it ) +{ + size_t idx = m_Pairs.FindIt( *it.GetPair() ); + if ( idx < m_Pairs.Count() ) { + m_Pairs.RemoveInd( idx ); + if ( idx < m_Pairs.Count() ) + return Iterator ( m_Pairs, m_Pairs[idx]); + } + return Iterator(); +} + + +//------------------------------------------------------------------------------- +/// \ru Удалить элементы в диапазоне [it1, it2). \en Remove elements in the range [it1, it2). +// --- +template +inline void MultiMap::Dissociate( + typename MultiMap::Iterator & it1, + typename MultiMap::Iterator & it2 ) +{ + if ( m_Pairs.Count() == 0 || it1.Empty() ) + return; + if ( it2.Empty() ) { + // \ru Удаляем с it1 до конца. \en Remove from it1 up to the end. + it2 = Iterator ( m_Pairs, m_Pairs[m_Pairs.Count() - 1] ); + if ( it1 == it2 ) + Dissociate ( it1.Key(), it1.Value() ); // \ru Просто удаляем последний элемент. \en Just remove the last element. + else if ( it1 < it2 ) { + size_t idx = m_Pairs.FindIt( *it1.GetPair() ); + if ( idx != SYS_MAX_T ) + m_Pairs.RemoveInd ( idx, m_Pairs.Count () ); + } + } + else if ( it1 < it2 ) + m_Pairs.Remove ( it1.GetPair(), it2.GetPair() ); +} + + +//------------------------------------------------------------------------------- +/// \ru Оператор доступа по ключу. \en Access by key operator. +// --- +template +inline typename MultiMap::Iterator MultiMap::operator[] ( const KeyType & key ) const { + return Iterator( m_Pairs, Pair(key, Null::val()) ); +} + + +//------------------------------------------------------------------------------- +/// \ru Получить итератор, указывающий на первый элемент. \en Get an iterator pointing to the first element. +// --- +template +inline typename MultiMap::Iterator MultiMap::First() const { + if ( m_Pairs.Count() ) + return Iterator ( m_Pairs, m_Pairs[0] ); + return Iterator(); +} + + +#endif // __TEMPL_MULTIMAP_H diff --git a/C3d/Include/templ_p_array.h b/C3d/Include/templ_p_array.h index 0b9f935..518df40 100644 --- a/C3d/Include/templ_p_array.h +++ b/C3d/Include/templ_p_array.h @@ -17,10 +17,6 @@ #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - // \ru Реализация методов для чтения/записи массива лежит в templ_p_array_rw.h \en Implementation of methods for reading/writing of array is located in templ_p_array_rw.h @@ -262,22 +258,26 @@ template inline Type * PArray::RemoveInd( size_t delIndex, DelType del ) { PRECONDITION( delIndex < RPArray::count ); - const Type **d = RPArray::GetAddr() + delIndex; - Type *r = (Type*)*d; + Type * r = 0; - // \ru сначала приведем в порядок массив ... \en put an array in order at first ... - memmove( d, d+1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); - RPArray::count--; + if ( delIndex < RPArray::count ) { + const Type ** d = RPArray::GetAddr() + delIndex; + r = (Type *)*d; - // \ru ... а теперь будем удалять \en ... and now we will delete - if ( del==Delete || (del==defDelete && owns) ) { - PRECONDITION( !r || nowDeletedElem != r ); - nowDeletedElem = r; + // \ru сначала приведем в порядок массив ... \en put an array in order at first ... + memmove( d, d + 1, (RPArray::count - delIndex - 1) * SIZE_OF_POINTER ); + RPArray::count--; - delete r; - r = 0; + // \ru ... а теперь будем удалять \en ... and now we will delete + if ( del == Delete || ( del == defDelete && owns ) ) { + PRECONDITION( !r || nowDeletedElem != r ); + nowDeletedElem = r; - nowDeletedElem = 0; + delete r; + r = 0; + + nowDeletedElem = 0; + } } return r; @@ -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 { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == 0 ); 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 { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == 0 ); return first_that_in_array( *this, func, pars, from ); } @@ -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 { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == 0 ); 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 { - C3D_ASSERT( PArray::nowDeletedElem == 0 ); + PRECONDITION( PArray::nowDeletedElem == 0 ); return first_that_in_array( *this, func, pars, from ); } diff --git a/C3d/Include/templ_pointer.h b/C3d/Include/templ_pointer.h index 01b7469..dbcd2f3 100644 --- a/C3d/Include/templ_pointer.h +++ b/C3d/Include/templ_pointer.h @@ -61,7 +61,7 @@ private: // СМВ К15 MVS 2012 private: TPointerBase( const TPointerBase & other ); -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: TPointerBase( TPointerBase && _Right ): P( _Right.P ) { _Right.P = nullptr; } TPointerBase & operator = ( TPointerBase && _Right ) @@ -70,7 +70,7 @@ public: { P = _Right.P; _Right.P = nullptr; } return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -104,7 +104,7 @@ 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 + const T * operator ->() const { return TPointerBase::P; } // Could throw exception if P==0 // СМВ К15 MVS 2012 #ifndef __MOBILE_VERSION__ @@ -112,7 +112,7 @@ private: #endif // __MOBILE_VERSION__ TPointer( const TPointer & other ); -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: TPointer( TPointer && _Right ) : TPointerBase( std::move(_Right) ) @@ -127,7 +127,7 @@ public: } return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -173,7 +173,7 @@ public: private: TOwnPointer( const TOwnPointer & other ); TOwnPointer & operator = ( const TOwnPointer & _Right ); -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: TOwnPointer( TOwnPointer && _Right ) : TPointerBase( std::move(_Right) ) @@ -191,7 +191,7 @@ public: } return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -231,7 +231,7 @@ public: // СМВ К15 MVS 2012 //private: // g++4.7 KUbuntu TAPointer( const TAPointer & other ); -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: TAPointer(TAPointer && _Right) : TPointerBase( std::move(_Right) ) @@ -246,7 +246,7 @@ public: } return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -273,7 +273,7 @@ public: char * operator = ( char src[] ) { delete[] P; return P = src; } char * operator = ( const TPointer & src ) { delete[] P; return P = src.P; } char & operator []( size_t i ) { return P[i]; } -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: TPointer( TPointer && _Right ) : TPointerBase( std::move(_Right) ) @@ -288,7 +288,7 @@ public: } return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; diff --git a/C3d/Include/templ_psrt_array.h b/C3d/Include/templ_psrt_array.h index 0828801..bf87551 100644 --- a/C3d/Include/templ_psrt_array.h +++ b/C3d/Include/templ_psrt_array.h @@ -294,7 +294,7 @@ template inline void PArraySort::CatchMemory() { PRECONDITION( PArray::nowDeletedElem == 0 ); // \ru ЯТ - временно \en ЯТ - temporarily - if ( PArray::upper == PArray::count ) + if ( PArray::upper == PArray::count ) set_Parray_size( *this, PArray::upper + CalculateDelta(), false/*clear*/ ); } diff --git a/C3d/Include/templ_rp_array.h b/C3d/Include/templ_rp_array.h index 730c59c..bbf8b7e 100644 --- a/C3d/Include/templ_rp_array.h +++ b/C3d/Include/templ_rp_array.h @@ -18,10 +18,6 @@ #include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - FORVARD_DECL_TEMPLATE_TYPENAME( class RPArray ); FORVARD_DECL_TEMPLATE_TYPENAME( bool set_Rarray_size( RPArray &, size_t newSize ) ); @@ -107,7 +103,7 @@ public: void Sort ( CompFunc comp ); ///< \ru Сортировать массив. \en Sort the array. /// \ru Оператор доступа по индексу. \en Access by index operator. - Type *& operator []( size_t loc ) const { PRECONDITION( loc < count ); return parr[loc]; } + 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); } @@ -133,12 +129,12 @@ public: // \ru унификация с вектором STL \en unification with TPtr * end() { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. const TPtr * cbegin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. const TPtr * cend() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. - const value_type front() const { PRECONDITION(!empty()); return *parr; } - value_type & front() { PRECONDITION(!empty()); return *parr; } - const value_type back() const { PRECONDITION(!empty()); return *(parr + count - 1); } - value_type & back() { PRECONDITION(!empty()); return *(parr + count - 1); } - const_reference at( size_t idx ) const { PRECONDITION( idx < count ); return parr[idx]; } - reference at( size_t idx ) { PRECONDITION( idx < count ); return parr[idx]; } + const value_type front() const; + value_type & front(); + const value_type back() const; + value_type & back(); + const_reference at( size_t idx ) const; + reference at( size_t idx ); protected: const Type ** GetAddr() const { return (const Type **)parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. @@ -171,11 +167,11 @@ public: void operator delete ( void *, size_t ); #endif // __DEBUG_MEMORY_ALLOCATE_FREE_ -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: RPArray( RPArray && ); ///< \ru Конструктор перемещения массива. \en Constructor of an array moving. RPArray & operator = ( RPArray && ); ///< \ru Оператор перемещения массива. \en Operator of an array moving. -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -231,7 +227,7 @@ inline RPArray::RPArray( size_t i_upper, uint16 i_delta )//, bool shouldNu } -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ // \ru Конструктор перемещения массива. \en Constructor of an array moving. // --- @@ -261,7 +257,7 @@ RPArray & RPArray::operator = ( RPArray && _Right ) } return (*this); } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL //------------------------------------------------------------------------------ @@ -272,6 +268,72 @@ inline RPArray::~RPArray() { set_Rarray_size( *this, 0 ); //delete [] parr; } +//------------------------------------------------------------------------------ +// \ru Оператор доступа по индексу. \en Access by index operator. +// --- +template +inline Type *& RPArray::operator []( size_t loc ) const +{ + return parr[loc]; +} + +//------------------------------------------------------------------------------ +// \ru Доступ к первому элементу. \en Access to the first element. +// --- +template +inline const typename RPArray::value_type RPArray::front() const { + PRECONDITION( !empty() ); + return *parr; +} + +//------------------------------------------------------------------------------- +// \ru Доступ к первому элементу. \en Access to the first element. +// --- +template +inline typename RPArray::value_type & RPArray::front() { + PRECONDITION( !empty() ); + return *parr; +} + +//------------------------------------------------------------------------------- +// \ru Доступ к последнему элементу. \en Access to the last element. +// --- +template +inline const typename RPArray::value_type RPArray::back() const +{ + PRECONDITION( !empty() ); + return *( parr + count - 1 ); +} + +//------------------------------------------------------------------------------- +// \ru Доступ к последнему элементу. \en Access to the last element. +// --- +template +inline typename RPArray::value_type & RPArray::back() +{ + PRECONDITION( !empty() ); + return *( parr + count - 1 ); +} + +//------------------------------------------------------------------------------- +// \ru Доступ по индексу. \en Access by index operator. +// --- +template +inline typename RPArray::const_reference RPArray::at( size_t idx ) const +{ + PRECONDITION( idx < count ); + return parr[idx]; +} + +//------------------------------------------------------------------------------- +// \ru Доступ по индексу. \en Access by index operator. +// --- +template +inline typename RPArray::reference RPArray::at( size_t idx ) +{ + PRECONDITION( idx < count ); + return parr[idx]; +} //------------------------------------------------------------------------------- // \ru обнулить количество элементов \en set the number of elements to null @@ -443,8 +505,7 @@ template inline size_t RPArray::FindIt( const Type * el ) const { // \ru MA Linux return find_in_array( *this, el ); // ошибка при сопоставлении шаблонов для RPArray \en MA Linux return find_in_array( *this, el ); // an error in matching of templates for RPArray - if ( parr ) - { + if ( parr ) { TPtr * iterLast = parr+count; TPtr * iter = std::find( parr, iterLast, el ); if ( iter != iterLast ) @@ -475,8 +536,10 @@ inline Type * RPArray::DetachInd( size_t delIndex ) if ( parr ) { PRECONDITION( delIndex < count ); - r = parr[delIndex]; - memmove( parr+delIndex, parr+delIndex+1, (count-- - delIndex - 1)*SIZE_OF_POINTER ); + if ( delIndex < count ) { + r = parr[delIndex]; + memmove( parr + delIndex, parr + delIndex + 1, ( count-- - delIndex - 1 ) * SIZE_OF_POINTER ); + } } return r; @@ -496,7 +559,7 @@ void RPArray::insert( Iterator pos, const Type * e ) } if ( begin() ) { const ptrdiff_t k = std::distance( (Iterator)begin(), pos ); - if ( k >= 0 && k <= count ) + if ( k >= 0 && k <= (ptrdiff_t)count ) Insert( k, const_cast(e) ); } } @@ -511,7 +574,7 @@ void RPArray::erase( Iterator pos ) { if ( begin() ) { const ptrdiff_t k = std::distance( (Iterator)begin(), pos ); - if ( k >= 0 && k < count ) + if ( k >= 0 && k < (ptrdiff_t)count ) RemoveInd( k ); } } @@ -528,7 +591,7 @@ void RPArray::erase( Iterator first, Iterator last ) const ptrdiff_t k1 = std::distance( (Iterator)begin(), first ); const ptrdiff_t k2 = std::distance( (Iterator)begin(), last ); - if ( k1 >= 0 && k1 < k2 && k2 <= count ) { + if ( k1 >= 0 && k1 < k2 && k2 <= (ptrdiff_t)count ) { for ( ptrdiff_t k = k2-1; k >= k1; k-- ) { RemoveInd( k ); } @@ -619,7 +682,7 @@ bool set_Rarray_size( RPArray & arr, size_t newSize ) arr.count = newSize < arr.count ? newSize : arr.count; #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldSize * SIZE_OF_POINTER, arr.parr, newSize * SIZE_OF_POINTER, 1/*RParray*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldSize * SIZE_OF_POINTER, arr.parr, newSize * SIZE_OF_POINTER, 1/*RParray*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ } catch ( const std::bad_alloc & ) { diff --git a/C3d/Include/templ_rp_stack.h b/C3d/Include/templ_rp_stack.h index 7507e9f..0f01451 100644 --- a/C3d/Include/templ_rp_stack.h +++ b/C3d/Include/templ_rp_stack.h @@ -27,7 +27,7 @@ template class RPStack: private RPArray { public: - RPStack( size_t i_upper, uint16 i_delta = 1 ): RPArray( i_upper, i_delta ) {} + RPStack( size_t i_upper, uint16 i_delta = 1 ): RPArray( i_upper, i_delta ) {} public: void Push( Type & obj ); ///< \ru Добавить элемент в стек. \en Add an element to the stack. diff --git a/C3d/Include/templ_s_array.h b/C3d/Include/templ_s_array.h index c173f1b..7696137 100644 --- a/C3d/Include/templ_s_array.h +++ b/C3d/Include/templ_s_array.h @@ -21,25 +21,16 @@ #include #include -#if defined( __BORLANDC__ ) -#include -#endif - - -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - FORVARD_DECL_TEMPLATE_TYPENAME( class SArray ); -FORVARD_DECL_TEMPLATE_TYPENAME( bool set_array_size ( SArray &, size_t newSize, bool clear ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_n_to_array ( SArray &, size_t n ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( bool set_array_size ( SArray &, size_t newSize, bool clear ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_n_to_array ( SArray &, size_t n ) ); FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_in_array ( const SArray &, const Type & object ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( bool fill_array ( SArray &, size_t fillCount, const Type & fillData ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( bool fill_array_zero( SArray &, size_t fillCount, size_t startIndex ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( bool fill_array ( SArray &, size_t fillCount, const Type & fillData ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( bool fill_array_zero( SArray &, size_t fillCount, size_t startIndex ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SArray & ref ) ); FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const SArray & ref ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SArray *& ptr ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SArray *& ptr ) ); FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const SArray * ptr ) ); @@ -138,13 +129,13 @@ public: bool operator == ( const SArray& w ) const; ///< \ru Оператор равенства. \en Equality operator. /// \ru Оператор доступа по индексу. \en Access by index operator. - Type & operator []( size_t loc ) const { PRECONDITION( loc < upper ); return parr[loc]; } + Type & operator []( size_t loc ) const; typedef int (*CompFunc)( const Type *, const Type * ); ///< \ru Шаблон функции сортировки. \en A template of sorting function. void Sort ( CompFunc comp = CompareSArrayItems ); ///< \ru Сортировать массив. По умолчанию сортирует в порядке возрастания. \en Sort the array. Sort in ascending order by default. - const Type * GetAddr() const { return parr; } ///< \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. - const Type * GetEndAddr() const { return parr + count; } ///< \ru Выдать указатель конца (следующим за крайним). \en Get a pointer of the end (which follows the last element). + const Type * GetAddr() const { return parr; } ///< \ru Выдать адрес начала массива. \en Get the address of the beginning of the array. + const Type * GetEndAddr() const { return parr + count; } ///< \ru Выдать указатель конца (следующим за крайним). \en Get a pointer of the end (which follows the last element). /** \name \ru Унификация с контейнерами STL. @@ -172,16 +163,17 @@ public: template void assign ( Iterator first, Iterator last ); ///< \ru Присвоить массиву новое содержимое, заменив его текущее содержимое. \en Assign new contents to the array, replacing its current contents. void assign ( size_t n, const Type & val ) { resize( n, val ); } ///< \ru Присвоить массиву новое содержимое, заменив его текущее содержимое. \en Assign new contents to the array, replacing its current contents. - const Type * begin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. - Type * begin() { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. - const Type * end() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. - Type * end() { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. - const Type * cbegin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. - const Type * cend() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. - const Type & front() const { PRECONDITION(!empty()); return *parr; } - Type & front() { PRECONDITION(!empty()); return *parr; } - const Type & back() const { PRECONDITION(!empty()); return *(parr+count-1); } - Type & back() { PRECONDITION(!empty()); return *(parr+count-1); } + + const Type * begin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. + Type * begin() { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. + const Type * end() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. + Type * end() { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. + const Type * cbegin() const { return parr; } ///< \ru Получить указатель на первый элемент массива. \en Get the pointer to the first array element. + const Type * cend() const { return parr + count; } ///< \ru Получить указатель на участок памяти после массива. \en Get the pointer to the piece of memory after the array. + const Type & front() const; + Type & front(); + const Type & back() const; + Type & back(); /** \} @@ -193,22 +185,22 @@ protected : size_t AutoDelta() const { return ::KsAutoDelta( count, delta ); } ///< \ru Вычислить автоприращение. \en Calculate autoincrement. /// \ru Перезахватить память. \en Reallocate memory. - TEMPLATE_FRIEND bool set_array_size TEMPLATE_SUFFIX ( SArray &, size_t newSize, bool clear ); + TEMPLATE_FRIEND bool set_array_size TEMPLATE_SUFFIX ( SArray &, size_t newSize, bool clear ); /// \ru Добавить памяти под n элментов массива и вернуть указатель на начало выделеного участка памяти. \en Add memory for n elements of the array and return a pointer to the beginning of the selected piece of memory. - TEMPLATE_FRIEND Type * add_n_to_array TEMPLATE_SUFFIX ( SArray &, size_t n ); + TEMPLATE_FRIEND Type * add_n_to_array TEMPLATE_SUFFIX ( SArray &, size_t n ); /// \ru Найти элемент в массиве. \en Find an element in the array. - TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const SArray &, const Type &object ); + TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const SArray &, const Type & object ); /// \ru Заполнить fillCount элементов массива копиями объекта fillData. \en Fill fillCount elements of the array by copies of the object fillData. - TEMPLATE_FRIEND bool fill_array TEMPLATE_SUFFIX ( SArray &, size_t fillCount, const Type & fillData ); + TEMPLATE_FRIEND bool fill_array TEMPLATE_SUFFIX ( SArray &, size_t fillCount, const Type & fillData ); /// \ru Заполнить fillCount элементов массива нулями. \en Fill fillCount elements of the array by nulls. - TEMPLATE_FRIEND bool fill_array_zero TEMPLATE_SUFFIX ( SArray &, size_t fillCount, size_t startIndex ); + TEMPLATE_FRIEND bool fill_array_zero TEMPLATE_SUFFIX ( SArray &, size_t fillCount, size_t startIndex ); /// \ru Оператор чтения. \en Read operator. - TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SArray & ref ); + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SArray & ref ); /// \ru Оператор записи. \en Write operator. TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const SArray & ref ); /// \ru Оператор чтения. \en Read operator. - TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SArray *& ptr ); + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SArray *& ptr ); /// \ru Оператор записи. \en Write operator. TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const SArray * ptr ); @@ -298,6 +290,55 @@ inline SArray::SArray( const std::vector & o ) } } +//------------------------------------------------------------------------------ +// \ru Оператор доступа по индексу. \en Access by index operator. +// --- +template +inline Type & SArray::operator []( size_t loc ) const +{ + return parr[loc]; +} + +//------------------------------------------------------------------------------ +// \ru Доступ к первому элементу. \en Access to th first element. +// --- +template +inline const Type & SArray::front() const +{ + PRECONDITION( !empty() ); + return *parr; +} + +//------------------------------------------------------------------------------ +// \ru Доступ к первому элементу. \en Access to th first element. +// --- +template +inline Type & SArray::front() +{ + PRECONDITION( !empty() ); + return *parr; +} + + +//------------------------------------------------------------------------------ +// \ru Доступ к последнему элементу. \en Access to th last element. +// --- +template +inline const Type & SArray::back() const +{ + PRECONDITION( !empty() ); + return *( parr + count - 1 ); +} + +//------------------------------------------------------------------------------ +// \ru Доступ к последнему элементу. \en Access to th last element. +// --- +template +inline Type &SArray::back() +{ + PRECONDITION( !empty() ); + return *( parr + count - 1 ); +} //------------------------------------------------------------------------------ // \ru Указать новый размер массива. \en Set the new size of an array. @@ -407,7 +448,7 @@ inline Type * SArray::Add( const Type & ent ) template inline Type * SArray::AddAfter( const Type & ent, size_t index ) { PRECONDITION( index < count ); - if ( CatchMemory() ) { + if ( index < count && CatchMemory() ) { memmove( parr + index + 2, parr + index + 1, sizeof(Type)*(count - index - 1) ); count++; @@ -424,7 +465,7 @@ inline Type * SArray::AddAfter( const Type & ent, size_t index ) { template inline Type * SArray::InsertInd( size_t index, const Type & ent ) { PRECONDITION( index <= count ); - if ( CatchMemory() ) { // \ru добавить памяти, если все использовано \en add memory if whole allocated memory is used + if ( index <= count && CatchMemory() ) { // \ru добавить памяти, если все использовано \en add memory if whole allocated memory is used if ( index >= count ) index = count; @@ -446,7 +487,7 @@ inline Type * SArray::InsertInd( size_t index, const Type & ent ) { template inline Type * SArray::InsertInd( size_t index ) { PRECONDITION( index <= count ); - if ( CatchMemory() ) { // \ru добавить памяти, если все использовано \en add memory if whole allocated memory is used + if ( index <= count && CatchMemory() ) { // \ru добавить памяти, если все использовано \en add memory if whole allocated memory is used // \ru передвинем вправо все элементы массива с последнего до указанного \en move to the right all elements of the array from the last to the specified one memmove( parr + index + 1, parr + index, (count - index) * sizeof(Type) ); @@ -506,7 +547,7 @@ template inline void SArray::RemoveInd( size_t idx ) { // RemoveInd( idx, idx+1 ); - if ( parr ) { + if ( parr && idx < count ) { Type * ptr = parr + idx; Remove( ptr, ptr+1 ); } @@ -526,7 +567,7 @@ void SArray::insert( Iterator pos, const Type & e ) } if ( begin() ) { const ptrdiff_t k = std::distance( (Iterator)begin(), pos ); - if ( k >= 0 && k <= count ) + if ( k >= 0 && k <= (ptrdiff_t)count ) InsertInd( k, e ); } } @@ -541,7 +582,7 @@ void SArray::erase( Iterator pos ) { if ( begin() ) { const ptrdiff_t k = std::distance( (Iterator)begin(), pos ); - if ( k >= 0 && k < count ) + if ( k >= 0 && k < (ptrdiff_t)count ) RemoveInd( k ); } } @@ -557,7 +598,7 @@ void SArray::erase( Iterator first, Iterator last ) const ptrdiff_t k1 = std::distance( (Iterator)begin(), first ); const ptrdiff_t k2 = std::distance( (Iterator)begin(), last ); - if ( k1 >= 0 && k1 < k2 && k2 <= count ) { + if ( k1 >= 0 && k1 < k2 && k2 <= (ptrdiff_t)count ) { RemoveInd( k1, k2 ); } } @@ -581,12 +622,14 @@ template inline void SArray::Remove( Type * firstItr, Type * lastItr ) { PRECONDITION( firstItr >= parr && firstItr < lastItr && (lastItr - parr) <= (ptrdiff_t)count ); - ptrdiff_t cpyCount = (parr + count) - lastItr; - if ( cpyCount > 0 ) { - memmove( static_cast(firstItr), static_cast(lastItr), cpyCount*sizeof(Type) ); + if ( firstItr >= parr && firstItr < lastItr ) { + ptrdiff_t copyCount = ( parr + count ) - lastItr; + if ( copyCount >= 0 ) { + if ( copyCount > 0 ) + memmove( static_cast( firstItr ), static_cast( lastItr ), copyCount * sizeof( Type ) ); + count -= ( lastItr - firstItr ); + } } - if ( lastItr - firstItr > 0 ) - count -= (lastItr-firstItr); } @@ -735,7 +778,7 @@ void SArray::assign( Iterator first, Iterator last ) { const ptrdiff_t newCount = std::distance( first, last ); if ( set_array_size(*this, newCount, true) ) { - PRECONDITION( newCount <= upper && count == 0 ); + PRECONDITION( newCount <= (ptrdiff_t)upper && count == 0 ); for ( ; first != last; ++first, ++count ) { parr[count] = *first; } @@ -798,7 +841,7 @@ bool set_array_size( SArray & arr, size_t newSize, bool clear ) arr.upper = newSize; #ifdef __REALLOC_ARRAYS_STATISTIC_ - ::ReallocArrayStatistic( oldParr, oldSize * sizeOfType, arr.parr, newSize * sizeOfType, 0/*SArray*/ ); + REALLOC_ARRAY_STATISTICS( oldParr, oldSize * sizeOfType, arr.parr, newSize * sizeOfType, 0/*SArray*/ ); #endif // __REALLOC_ARRAYS_STATISTIC_ } catch ( const std::bad_alloc & ) { @@ -883,17 +926,33 @@ size_t find_in_array( const SArray & arr, const Type & object ) { //------------------------------------------------------------------------------- -// \ru оператор сравнения двух массивов \en an operator of two arrays comparison +// \ru Оператор сравнения двух массивов. \en An operator of two arrays comparison. +/** + \details + \ru Осуществляется поэлементной стравнение с возможностью перегрузки + операции сравния с помощью метода IsEqualSArrayItems. + \en An element-by-element comparison is performed with the ability to redefine the + comparison operation using the overloading global function IsEqualSArrayItems. +*/ // --- template -inline bool SArray::operator == ( const SArray & w ) const { +inline bool SArray::operator == ( const SArray & w ) const +{ if ( count != w.count ) return false; + /* + При размещении в памяти с выравниванием не равным 1, между элементами массива + возможно появление "дырок" заполненного случайным мусором, т.к. сравнивать этот мусор + нам незачем, будем сравнивать содержимое массивов поэлементно (через оператор == или + путем перегрузки IsEqualSArrayItems). - // \ru OV K6 При размещении в памяти с выравниванием не равным 1, между элементами массива \en OV K6 While the memory allocation with alignment which is not equal 1 between elements of the array - // \ru возможно появление "дырок" заполненного случайным мусором, т.к. сравнивать этот мусор \en may appear "holes" filled by random trash, since there is not reason to compare this trash - // \ru нам незачем, будем сравнивать содержимое массивов поэлементно (через оператор == объекта) \en we will compare the content of arrays element by element (using the operator == of an object) - for ( size_t i = 0; i < count; i++ ) { + While the memory allocation with alignment which is not equal 1 between elements of + the array may appear "holes" filled by random trash, since there is not reason to + compare this trash we will compare the content of arrays element by element + (using the operator == of an object or by overloading the func IsEqualSArrayItems). + */ + for ( size_t i = 0; i < count; i++ ) + { if ( !::IsEqualSArrayItems( (*this)[i], w[i] ) ) return false; } diff --git a/C3d/Include/templ_s_list.h b/C3d/Include/templ_s_list.h index f8d56ec..77af271 100644 --- a/C3d/Include/templ_s_list.h +++ b/C3d/Include/templ_s_list.h @@ -14,12 +14,9 @@ #include #include #include +#include -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ -#include -#endif //__DEBUG_MEMORY_ALLOCATE_FREE_ - //----------------------------------------------------------------------------- /** \brief \ru Элемент списка. @@ -149,7 +146,7 @@ public: PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); 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 + 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 ); @@ -319,9 +316,9 @@ inline void List::Add( Type* data, const Type* after ) { // \ru добавить элемент в конец списка с проверкой на существование \en add an element in the end of the list with existence validation //--- template -inline void List::Add( Type* data, bool /*check*/ ) { +inline void List::Add( Type * data, bool /*check*/ ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); - if ( !IsExist(data) ) Add( data ); } @@ -331,9 +328,9 @@ inline void List::Add( Type* data, bool /*check*/ ) { // \ru добавить элемент в конец списка \en add an element to the end of the list //--- template -inline void List::Add( ListItem &item ) { +inline void List::Add( ListItem & item ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); - item.next = 0; if ( last ) @@ -351,7 +348,8 @@ inline void List::Add( ListItem &item ) { // \ru list после добавления становится пустым! \en a list becomes empty after the adding of it! //--- template -inline void List::AddAndEat( List &list ) { +inline void List::AddAndEat( List & list ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); if ( list.first ) { @@ -376,7 +374,8 @@ inline void List::AddAndEat( List &list ) { // \ru вставить элемент в начало списка \en insert an element to the beginning of the list //--- template -inline void List::Insert( Type* data ) { +inline void List::Insert( Type * data ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); Insert( *new ListItem(data) ); } @@ -386,7 +385,8 @@ inline void List::Insert( Type* data ) { // \ru вставить элемент в начало списка \en insert an element to the beginning of the list //--- template -inline void List::Insert( ListItem &item ) { +inline void List::Insert( ListItem & item ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); ListItem* old = first; @@ -405,7 +405,8 @@ inline void List::Insert( ListItem &item ) { // \ru съесть список list в начало данного списка \en destroy and add a list to the beginning of the given list //--- template -inline void List::InsertAndEat( List &list ) { +inline void List::InsertAndEat( List & list ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); if ( list.first ) { @@ -430,7 +431,8 @@ inline void List::InsertAndEat( List &list ) { // \ru удалить один элемент списка \en delete one element of the list //--- template -inline bool List::Remove( Type *del, DelType shdl ) { +inline bool List::Remove( Type * del, DelType shdl ) +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); if ( Detach(del) ) { @@ -451,9 +453,9 @@ inline bool List::Remove( Type *del, DelType shdl ) { // \ru замкнуть список \en close the list //--- template -inline void List::Close() { +inline void List::Close() +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); - if ( last ) last->next = first; } @@ -463,9 +465,9 @@ inline void List::Close() { // \ru разомкнуть список \en split the list //--- template -inline void List::Split() { +inline void List::Split() +{ PRECONDITION( nowDelItem == 0 && nowDelElem == 0 ); - if ( last ) last->next = 0; } @@ -481,11 +483,12 @@ inline void List::Split() { // \ru взять данные и продвинуть итератор \en take the data and move the iterator. //--- template -inline Type* LIterator::GetDataAndGo() { +inline Type * LIterator::GetDataAndGo() +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); if ( curr ) { - Type* ret = curr->data; + Type * ret = curr->data; prev = curr; curr = curr->next; return ret; @@ -499,17 +502,20 @@ inline Type* LIterator::GetDataAndGo() { // \ru добавить элемент после текущего элемента \en add an element after the current element //--- template -inline void LIterator::Add( Type *data ) { +inline void LIterator::Add( Type * data ) +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( curr ) { - ListItem *newItem = new ListItem( data, *curr ); // \ru поставит себя после curr \en inserts itself after 'curr' - if ( list->last == curr ) - list->last = newItem; - list->count++; + if ( list ) { + if ( curr ) { + ListItem * newItem = new ListItem( data, *curr ); // \ru поставит себя после curr \en inserts itself after 'curr' + if ( list->last == curr ) + list->last = newItem; + list->count++; + } + else + list->Add( data ); } - else - list->Add( data ); } @@ -517,10 +523,11 @@ inline void LIterator::Add( Type *data ) { // \ru съесть list после текущего элемента \en destroy a list and add it after the current element //--- template -inline void LIterator::AddAndEat( List& l ) { +inline void LIterator::AddAndEat( List & l ) +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( l.first ) { + if ( list && l.first ) { if ( curr ) { PRECONDITION( l.last ); @@ -544,20 +551,23 @@ inline void LIterator::AddAndEat( List& l ) { // \ru вставить элемент перед текущим \en insert an element before the specified one //--- template -inline void LIterator::Insert( Type *data ) { +inline void LIterator::Insert( Type * data ) +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( prev ) { - ListItem *newItem = new ListItem( data, *prev ); // \ru ставит себя после prev \en inserts itself after 'prev' + if ( list ) { + if ( prev ) { + ListItem * newItem = new ListItem( data, *prev ); // \ru ставит себя после prev \en inserts itself after 'prev' - if ( list->last == prev ) - list->last = newItem; + if ( list->last == prev ) + list->last = newItem; - prev = newItem; - list->count++; + prev = newItem; + list->count++; + } + else + list->Insert( data ); // \ru вставить элемент в начало списка \en insert an element to the beginning of the list } - else - list->Insert( data ); // \ru вставить элемент в начало списка \en insert an element to the beginning of the list } @@ -565,10 +575,11 @@ inline void LIterator::Insert( Type *data ) { // \ru съесть list перед моим текущим элементом \en destroy a list and add it before mine current element //--- template -inline void LIterator::InsertAndEat( List& l ) { +inline void LIterator::InsertAndEat( List & l ) +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( l.first ) { + if ( list && l.first ) { if ( prev ) { PRECONDITION( l.last ); @@ -591,10 +602,11 @@ inline void LIterator::InsertAndEat( List& l ) { // \ru удалить текущий элемент итератора \en delete the current element of the iterator //--- template -inline void LIterator::Remove( DelType shdl ) { +inline void LIterator::Remove( DelType shdl ) +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( curr ) { + if ( list && curr ) { if ( shdl==Delete || (shdl==defDelete && list->owns) ) { list->nowDelElem = curr->data; delete curr->data; @@ -610,10 +622,11 @@ inline void LIterator::Remove( DelType shdl ) { // \ru отсоединить элемент списка \en detach an element from the list //--- template -inline void LIterator::Detach() { +inline void LIterator::Detach() +{ PRECONDITION( list && list->nowDelItem == 0 && list->nowDelElem == 0 ); - if ( curr ) { + if ( list && curr ) { ListItem* next = curr->next; if ( prev ) @@ -637,7 +650,8 @@ inline void LIterator::Detach() { //------------------------------------------------------------------------------ template -void add_to_list( List &list, Type *data, const Type *after ) { +void add_to_list( List & list, Type * data, const Type * after ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); if ( after ) { @@ -662,7 +676,8 @@ void add_to_list( List &list, Type *data, const Type *after ) { //------------------------------------------------------------------------------ template -void add_to_list( List &to, List &from ) { +void add_to_list( List & to, List & from ) +{ PRECONDITION( to.nowDelItem == 0 && to.nowDelElem == 0 ); PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); @@ -679,7 +694,8 @@ void add_to_list( List &to, List &from ) { //------------------------------------------------------------------------------ template -void insert_to_list( List &to, List &from ) { +void insert_to_list( List & to, List & from ) +{ PRECONDITION( to.nowDelItem == 0 && to.nowDelElem == 0 ); PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); @@ -698,7 +714,8 @@ void insert_to_list( List &to, List &from ) { // \ru Очистить лист с возможным удаленим данных \en Clear the list with data deletion // --- template -void remove_from_list( List &list, DelType shdl ) { +void remove_from_list( List & list, DelType shdl ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); bool del = shdl==Delete || (shdl==defDelete && list.owns); @@ -728,7 +745,8 @@ void remove_from_list( List &list, DelType shdl ) { // \ru Очистить лист с возможным удаленим данных \en Clear the list with data deletion // --- template -void remove_from_list_release( List &list ) { +void remove_from_list_release( List & list ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); ListItem *first = list.first; @@ -755,7 +773,8 @@ void remove_from_list_release( List &list ) { // \ru Отцепить один список от другого с возможным удалением данных \en Detach one list from another with data deletion // --- template -size_t remove_from_list( List &list, List &deList, DelType shdl ) { +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 ); @@ -849,7 +868,8 @@ size_t remove_from_list( List &list, List &deList, DelType shdl ) { //------------------------------------------------------------------------------ template -bool detach_from_list( List& from, const Type* del ) { +bool detach_from_list( List & from, const Type * del ) +{ PRECONDITION( from.nowDelItem == 0 && from.nowDelElem == 0 ); ListItem* curr = from.first; @@ -885,7 +905,8 @@ bool detach_from_list( List& from, const Type* del ) { //------------------------------------------------------------------------------ template -size_t recalc_list( List &list ) { +size_t recalc_list( List & list ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); list.count = 0; @@ -900,12 +921,12 @@ size_t recalc_list( List &list ) { //------------------------------------------------------------------------------ template -bool is_exist_in_list( const List& list, const Type* what ) { +bool is_exist_in_list( const List & list, const Type * what ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); - bool exist = false; - ListItem *curr = list.first; + ListItem * curr = list.first; while ( curr && !exist ) { exist = ( curr->data == what ); curr = curr->next; @@ -917,7 +938,8 @@ bool is_exist_in_list( const List& list, const Type* what ) { //------------------------------------------------------------------------------ template -ListItem* find_prev_in_list( const List& list, ListItem* now ) { +ListItem * find_prev_in_list( const List & list, ListItem * now ) +{ PRECONDITION( list.nowDelItem == 0 && list.nowDelElem == 0 ); if ( now ) { diff --git a/C3d/Include/templ_s_queue.h b/C3d/Include/templ_s_queue.h index 895f737..100802c 100644 --- a/C3d/Include/templ_s_queue.h +++ b/C3d/Include/templ_s_queue.h @@ -77,15 +77,15 @@ public: /// \ru Последний элемент очереди. \en The last element of the queue. const Type & Back() const; /// \ru Первый элемент очереди. \en The first element of the queue. - Type & Front() { PRECONDITION(Capacity() > 0 && !Empty() ); return *qp1; } + Type & Front(); /// \ru Первый элемент очереди. \en The first element of the queue. - const Type & Front() const { PRECONDITION(Capacity() > 0 && !Empty() ); return *qp1; } + const Type & Front() const; /// \ru Свойство пустого множества. \en A property of the empty set. bool Empty() const { return qp1 == qp2; } /// \ru Свойство исчерпанной памяти. \en An expended memory property. bool IsFull() const; /// \ru Самый первый, выходящий из очереди (корректно работает только для непустой очереди). \en The very first one outgoing from the queue (it works correctly only for nonempty queue). - Type & First() const { PRECONDITION( qp1 <= qlast && qp1 >= data && qp1 != qp2 ); return *qp1; } + Type & First() const; /// \ru Добавить в очередь и нарастить буфер выделенной памяти при необходимости. \en Add to the queue and increase the buffer of the allocated memory if it is necessary. void Push( const Type & obj ); /// \ru Вывести из очереди. \en Move out from queue. @@ -155,20 +155,49 @@ SQueue::~SQueue() // --- template inline const Type & SQueue::Back() const -{ +{ PRECONDITION( !Empty() && Capacity() > 0 ); - return qp2 == data ? *qlast : *(qp2-1); + return qp2 == data ? *qlast : *( qp2 - 1 ); } - //------------------------------------------------------------------------------- /// \ru Кто крайний? (корректно работает только для непустой очереди) \en Which is the last? (it works correctly only for nonempty queue) // --- template inline Type & SQueue::Back() -{ +{ PRECONDITION( !Empty() && Capacity() > 0 ); - return qp2 == data ? *qlast : *(qp2-1); + return qp2 == data ? *qlast : *( qp2 - 1 ); +} + +//------------------------------------------------------------------------------- +// \ru Первый элемент очереди. \en The first element of the queue. +// --- +template +inline Type & SQueue::Front() +{ + PRECONDITION( Capacity() > 0 && !Empty() ); + return *qp1; +} + +//------------------------------------------------------------------------------- +// \ru Первый элемент очереди. \en The first element of the queue. +// --- +template +inline const Type & SQueue::Front() const +{ + PRECONDITION( Capacity() > 0 && !Empty() ); + return *qp1; +} + +//------------------------------------------------------------------------------- +// \ru Самый первый, выходящий из очереди (корректно работает только для непустой очереди). \en The very first one outgoing from the queue (it works correctly only for nonempty queue). +// --- +template +inline Type & SQueue::First() const +{ + PRECONDITION( qp1 <= qlast && qp1 >= data && qp1 != qp2 ); + return *qp1; } @@ -183,7 +212,7 @@ inline Type & SQueue::Back() template inline bool SQueue::IsFull() const { - return _IncPtr( qp2 ) == qp1 || data == NULL; + return data == NULL || _IncPtr( qp2 ) == qp1; } @@ -207,10 +236,12 @@ template inline void SQueue::_Push( const Type & obj ) { PRECONDITION( !IsFull() && Size() < Capacity() ); - memcpy( qp2, &obj, sizeof(Type) ); - qp2 = _IncPtr( qp2 ); - PRECONDITION( !Empty() ); // \ru после добавления очередь не может быть пустой \en the queue may bacome empty after the adding - PRECONDITION( qp2 >= data && qp2 <= qlast ); + if ( !IsFull() && Size() < Capacity() ) { + memcpy( qp2, &obj, sizeof( Type ) ); + qp2 = _IncPtr( qp2 ); + PRECONDITION( !Empty() ); // \ru после добавления очередь не может быть пустой \en the queue may bacome empty after the adding + PRECONDITION( qp2 >= data && qp2 <= qlast ); + } } @@ -242,10 +273,12 @@ void SQueue::Push( const Type & obj ) template inline void SQueue::Pop( Type & obj ) { - PRECONDITION( qp2 != qp1 ); // \ru перед извлечением очередь не может быть пустой \en the queue may bacome empty before the extraction - memcpy( &obj, qp1, sizeof(Type) ); - qp1 = _IncPtr( qp1 ); - PRECONDITION( qp1 <= qlast && qp1 >= data ); + PRECONDITION( qp2 != qp1 ); // \ru перед извлечением очередь не может быть пустой \en the queue can't be empty before the extraction + if ( qp2 != qp1 ) { + memcpy( &obj, qp1, sizeof( Type ) ); + qp1 = _IncPtr( qp1 ); + PRECONDITION( qp1 <= qlast && qp1 >= data ); + } } @@ -255,9 +288,11 @@ inline void SQueue::Pop( Type & obj ) template inline void SQueue::Pop() { - PRECONDITION( qp2 != qp1 ); // \ru перед извлечением очередь не может быть пустой \en the queue may bacome empty before the extraction - qp1 = _IncPtr( qp1 ); - PRECONDITION( qp1 <= qlast && qp1 >= data ); + PRECONDITION( qp2 != qp1 ); // \ru перед извлечением очередь не может быть пустой \en the queue can't be empty before the extraction + if ( qp2 != qp1 ) { + qp1 = _IncPtr( qp1 ); + PRECONDITION( qp1 <= qlast && qp1 >= data ); + } } diff --git a/C3d/Include/templ_sfdp_array.h b/C3d/Include/templ_sfdp_array.h index 8a8ea3c..8afd418 100644 --- a/C3d/Include/templ_sfdp_array.h +++ b/C3d/Include/templ_sfdp_array.h @@ -138,7 +138,7 @@ using RPArray::back; \return \ru Вернет -1, если ближайший элемент, или индекс найденного элемента. \en Returns -1, if this is the nearest element, or the index of the same element.\~ */ - size_t FindNearest( const Type &el, Type *&found ) const; + size_t FindNearest( const Type & el, Type *& found ) const; /** \brief \ru Найти индекс элемента, используя функцию сравнения. @@ -148,7 +148,7 @@ using RPArray::back; \return \ru Вернет точно найденный элемент или NULL, если элемент не найден. \en Returns the found element or NULL, if element not found. */ - Type * FindExact ( const Type &el ) const; + Type * FindExact ( const Type & el ) const; /** \brief \ru Вернет true, если элемент найден, или false в противном случае. @@ -156,9 +156,9 @@ using RPArray::back; \details \ru Вернет true, если элемент найден, или false в противном случае. \en Returns true, if the element was found, or false otherwise. */ - bool IsExist ( const Type &el ) const; - Type* RemoveObj( Type *delObject, DelType=defDelete ); - bool DetachObj( const Type *delObject ); + bool IsExist ( const Type & el ) const; + Type* RemoveObj( Type * delObject, DelType=defDelete ); + bool DetachObj( const Type * delObject ); /** \brief \ru Найти индекс элемента, используя функцию поиска. @@ -170,21 +170,21 @@ using RPArray::back; \return \ru Вернет -1, если ближайший элемент, или индекс найденного элемента. \en Returns -1, if this is the nearest, or the index of the same element. */ - size_t SearchIt( size_t , SearchFunc, Type *&found ) const; + size_t SearchIt( size_t , SearchFunc, Type *& found ) const; /** \brief \ru Сортировать массив, используя функцию сравнения. \en Sort an array using the comparison function. */ - void Sort( size_t /*OV_x64 int*/ minInd = SYS_MAX_T/*OV_x64 -1*/, size_t /*OV_x64 int*/ maxInd = SYS_MAX_T/*OV_x64 -1*/ ); + void Sort( size_t minInd = SYS_MAX_T, size_t maxInd = SYS_MAX_T ); private: SFDPArray( const SFDPArray & ); // \ru запрещено !!! \en forbidden !!! SFDPArray& operator = ( const SFDPArray & ); // \ru запрещено !!! \en forbidden !!! - TEMPLATE_FRIEND size_t add_to_array TEMPLATE_SUFFIX ( SFDPArray& arr, Type& el, Type *&found, bool & added ); + TEMPLATE_FRIEND size_t add_to_array TEMPLATE_SUFFIX ( SFDPArray &, Type &, Type *& found, bool & added ); // \ru в found будет лежать найденный, или ближайший к искомому \en in the 'found' object the found element or the nearest to the required element will be stored - TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const SFDPArray&, const Type&, Type *&found ); + TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const SFDPArray &, const Type &, Type *& found ); // \ru Т.к. наследование от базового класса сделано private, то делаю доступ к операторам базового класса. // \en Since there is a private inheritance from the base class, I give an access to the operators of the base class. diff --git a/C3d/Include/templ_sfp_array.h b/C3d/Include/templ_sfp_array.h index 160ad1f..cb8f157 100644 --- a/C3d/Include/templ_sfp_array.h +++ b/C3d/Include/templ_sfp_array.h @@ -22,12 +22,12 @@ // //////////////////////////////////////////////////////////////////////////////// FORVARD_DECL_TEMPLATE_TYPENAME( class SFPArray ); -FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array ( SFPArray &, Type * ent, size_t & indexEnt ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array ( SFPArray &, const Type * ent ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( Type * find_from_array_by_key( SFPArray &, void * key, size_t & index ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( void qp_sort ( SFPArray &, bool always ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader& CALL_DECLARATION operator >> ( reader& in, SFPArray & ref ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( writer& CALL_DECLARATION operator << ( writer& out, const SFPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array ( SFPArray &, Type * ent, size_t & indexEnt ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array ( const SFPArray &, const Type * ent ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( Type * find_from_array_by_key( const SFPArray &, void * key, size_t & index ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( void qp_sort ( SFPArray &, bool always ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SFPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const SFPArray & ref ) ); template @@ -79,7 +79,7 @@ public : Type * Add( Type *, size_t & indexEnt );// \ru добавить элемент с упорядочиванием по массиву, возвращает индекс \en add element with sorting, returns index of the element. void AddSimple( Type * ent ) { m_sort = false; PArray::Add( ent ); } // \ru Доступ к функции базового класса - добавить элемент в конец массива \en An access to the function of the base class - add an element to the end of the array // \ru найти элемент в упорядоченном массиве \en find an element in ordered array - size_t /*OV_x64 int*/ Find( const Type * ); + size_t Find( const Type * ); // \ru найти элемент по ключевым полям \en find an element by the key fields Type * FindByKey( void * key, size_t & index ); // \ru удалить элемент из массива \en delete an element from array @@ -91,21 +91,21 @@ public : // \ru проверить на соответствие сортировке элемент массива \en check that an element of the array corresponds to the sorting // \ru если меняли значение полей Type - условие сортировки может быть не выполнено \en if the values of fields Type have been changed then the comparison condition may be not performed // \ru если это так - флаг сортировки у массива снимается \en if it is so then the flag of sorting is switched off - void SortCheckByIndex( size_t /*OV_x64 int*/ index ); + void SortCheckByIndex( size_t index ); - TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SFPArray &, Type * ent, size_t & indexEnt ); - TEMPLATE_FRIEND size_t find_from_array TEMPLATE_SUFFIX ( SFPArray &, const Type * ent ); - TEMPLATE_FRIEND Type * find_from_array_by_key TEMPLATE_SUFFIX ( SFPArray &, void * key, size_t & index ); - TEMPLATE_FRIEND void qp_sort TEMPLATE_SUFFIX ( SFPArray &, bool always ); + TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SFPArray &, Type * ent, size_t & indexEnt ); + TEMPLATE_FRIEND size_t find_from_array TEMPLATE_SUFFIX ( const SFPArray &, const Type * ent ); + TEMPLATE_FRIEND Type * find_from_array_by_key TEMPLATE_SUFFIX ( const SFPArray &, void * key, size_t & index ); + TEMPLATE_FRIEND void qp_sort TEMPLATE_SUFFIX ( SFPArray &, bool always ); private: OBVIOUS_PRIVATE_COPY( SFPArray ) // \ru Т.к. наследование private, то сделаем здесь операторы чтения-записи \en Since there is a private inheritance, then make here operators of reading/writing //ID K8 KNOWN_OBJECTS_RW_REF_OPERATORS( SFPArray ) - // \ru OV_x64 но коду не нашел реализации операторров чтения/записи \en OV_x64 implementation of reading/witing operators was not found - TEMPLATE_FRIEND reader& CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader& in, SFPArray & ref ); - TEMPLATE_FRIEND writer& CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer& out, const SFPArray & ref ); + // \ru OV_x64 но коду не нашел реализации операторов чтения/записи \en OV_x64 implementation of reading/writing operators was not found + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SFPArray & ref ); + TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const SFPArray & ref ); #ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ public: @@ -345,7 +345,7 @@ Type * add_to_array( SFPArray & arr, Type * el, size_t & indexEl ) { // \ru поиск ведется методом половинных делений \en a search is performed by the bisection method // --- template -size_t find_from_array( SFPArray &arr, const Type* el ) +size_t find_from_array( const SFPArray & arr, const Type * el ) { C3D_ASSERT( arr.fCompare_m ); // \ru без функции сравнения массив бессмысленнен \en the array is useless without comparison function // \ru общий случай - элементов больше двух \en the common case - the number of elements is more than two @@ -400,7 +400,8 @@ size_t find_from_array( SFPArray &arr, const Type* el ) // // --- template -Type * find_from_array_by_key( SFPArray & arr, void * key, size_t & index ) { +Type * find_from_array_by_key( const SFPArray & arr, void * key, size_t & index ) +{ PRECONDITION( arr.fSearch_m && key ); // \ru без функции сравнения массив бессмысленнен \en the array is useless without comparison function // \ru общий случай - элементов больше двух \en the common case - the number of elements is more than two int res = 0; @@ -454,7 +455,8 @@ Type * find_from_array_by_key( SFPArray & arr, void * key, size_t & index // \ru Н.Вирт "Алгоритмы и структуры данных" 2е издание, Санкт-Петербург, 2001г., стр.111 \en see N.Wirth "Algorithms and Data Structures" // --- template -void qp_sort_r( SFPArray & arr, ptrdiff_t minInd, ptrdiff_t maxInd ) { +void qp_sort_r( SFPArray & arr, ptrdiff_t minInd, ptrdiff_t maxInd ) +{ //OV_x64 ===================== if ( arr.Count() > 1 ) { @@ -494,7 +496,8 @@ void qp_sort_r( SFPArray & arr, ptrdiff_t minInd, ptrdiff_t maxInd ) { // // --- template -void qp_sort( SFPArray & arr, bool always ) { +void qp_sort( SFPArray & arr, bool always ) +{ if ( !arr.m_sort || always ) { //OV_x64 ===================== if ( arr.Count() > 1 ) diff --git a/C3d/Include/templ_sp_array.h b/C3d/Include/templ_sp_array.h index f12a6a2..b8213d0 100644 --- a/C3d/Include/templ_sp_array.h +++ b/C3d/Include/templ_sp_array.h @@ -23,11 +23,11 @@ //////////////////////////////////////////////////////////////////////////////// FORVARD_DECL_TEMPLATE_TYPENAME( class SPArray ); -FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array( SPArray&, Type* ent, size_t & indexEnt ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array( SPArray&, const Type* ent ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array_spec( SPArray&, const Type* ent, bool& isPresent ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader& CALL_DECLARATION operator >> ( reader& in, SPArray & ref ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( writer& CALL_DECLARATION operator << ( writer& out, const SPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array ( SPArray &, Type * ent, size_t & indexEnt ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array ( const SPArray &, const Type * ent ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array_spec( const SPArray &, const Type * ent, bool & isPresent ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SPArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const SPArray & ref ) ); template class SPArray : protected PArray { @@ -50,24 +50,25 @@ public : using PArray::GetLast; using PArray::FindIt; - Type * Add( Type * ); // \ru добавить элемент с упорядочиванием по массиву \en add element with sorting + Type * Add( Type * ); // \ru добавить элемент с упорядочиванием по массиву \en add element with sorting Type * Add( Type *, size_t & indexEnt );// \ru добавить элемент с упорядочиванием по массиву, возвращает индекс \en add element with sorting, returns index of the element // \ru После "простого" добавления нет возможности восстановить сортированность массива \en After a "simple" adding there is no possibility to recover the sorting of the array void AddSimple ( Type * ent ) { PArray::Add( ent ); } // \ru Доступ к функции базового класса - добавить элемент в конец массива \en An access to the function of the base class - add an element to the end of the array // \ru Доступ к функции базового класса - добавить массив в конец массива \en An access to the function of the base class - add an array to the end of the array bool AddArraySimple( const RPArray & arr ) { return PArray::AddArray( arr ); } - Type * RemoveObj( Type *delObject, DelType = defDelete ); // \ru удалить элемент из массива \en delete an element from array + Type * RemoveObj( Type * delObject, DelType = defDelete ); // \ru удалить элемент из массива \en delete an element from array // \ru Доступ к функции базового класса - удалить элемент из массива \en An access to the function of the base class - delete an element from the array - Type * RemoveObjSimple( Type *delObject, DelType delType = defDelete ) { return PArray::RemoveObj( delObject, delType ); } ; // \ru удалить элемент из массива \en delete an element from array - size_t /*OV_x64 int*/ Find( const Type * ); // \ru найти элемент в упорядоченном массиве \en find an element in ordered array - size_t /*OV_x64 int*/ PossibleIndex( const Type *, bool& isPresent ); // \ru найти место в массиве, куда будет добавлен элемент ( без добавления ) \en find a place in the array for adding ann element (adding is not performed) - // \ru на выходе : isPresent == true - элемент уже в массиве \en in output : isPresent == true - the element is already in the array - bool IsExist( const Type * ); // \ru true если элемент найден \en true if the element was found + Type * RemoveObjSimple( Type * delObject, DelType delType = defDelete ) { return PArray::RemoveObj( delObject, delType ); } ; // \ru удалить элемент из массива \en delete an element from array - TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SPArray&, Type* ent, size_t & indexEnt ); - TEMPLATE_FRIEND size_t /*OV_x64 int*/ find_from_array TEMPLATE_SUFFIX ( SPArray&, const Type* ent ); - TEMPLATE_FRIEND size_t /*OV_x64 int*/ find_from_array_spec TEMPLATE_SUFFIX ( SPArray&, const Type* ent, bool& isPresent ); + size_t Find( const Type * ) const; // \ru найти элемент в упорядоченном массиве \en find an element in ordered array + size_t PossibleIndex( const Type *, bool & isPresent ) const; // \ru найти место в массиве, куда будет добавлен элемент ( без добавления ) \en find a place in the array for adding an element (adding is not performed) + // \ru на выходе : isPresent == true - элемент уже в массиве \en in output : isPresent == true - the element is already in the array + bool IsExist( const Type * ) const; // \ru true если элемент найден \en true if the element was found + + TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SPArray &, Type * ent, size_t & indexEnt ); + TEMPLATE_FRIEND size_t find_from_array TEMPLATE_SUFFIX ( const SPArray &, const Type * ent ); + TEMPLATE_FRIEND size_t find_from_array_spec TEMPLATE_SUFFIX ( const SPArray &, const Type * ent, bool & isPresent ); private: SPArray( const SPArray & ); // \ru запрещено !!! \en forbidden !!! @@ -75,8 +76,8 @@ private: // \ru Т.к. наследование private, то сделаем здесь операторы чтения-записи \en Since there is a private inheritance, then make here operators of reading/writing //ID K8 KNOWN_OBJECTS_RW_REF_OPERATORS( SPArray ) - TEMPLATE_FRIEND reader& CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader& in, SPArray & ref ); - TEMPLATE_FRIEND writer& CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer& out, const SPArray & ref ); + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SPArray & ref ); + TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const SPArray & ref ); #ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ public: @@ -109,7 +110,8 @@ inline void SPArray::operator delete( void * ptr, size_t size ) { // \ru добавить элемент с упорядочиванием по массиву \en add element with sorting // --- template -inline Type* SPArray::Add( Type* el ) { +inline Type * SPArray::Add( Type * el ) +{ size_t index; return add_to_array( *this, el, index ); } @@ -119,8 +121,7 @@ inline Type* SPArray::Add( Type* el ) { // \ru добавить элемент с упорядочиванием по массиву, возвращает индекс \en add element with sorting, returns index of the element // --- template -inline Type* SPArray::Add( Type* el, size_t & indexEl ) -{ +inline Type* SPArray::Add( Type * el, size_t & indexEl ) { return add_to_array( *this, el, indexEl ); } @@ -129,8 +130,7 @@ inline Type* SPArray::Add( Type* el, size_t & indexEl ) // \ru поиск объекта в массиве \en search of an element in array // --- template -inline size_t /*OV_x64 int*/ SPArray::Find( const Type * el ) -{ +inline size_t SPArray::Find( const Type * el ) const { return find_from_array( *this, el ); } @@ -139,7 +139,7 @@ inline size_t /*OV_x64 int*/ SPArray::Find( const Type * el ) // \ru Есть ли в массиве такой указатель \en Whether such pointer exists in the array // --- template -inline bool SPArray::IsExist( const Type *el ) { +inline bool SPArray::IsExist( const Type * el ) const { return find_from_array( *this, el ) != SYS_MAX_T; } @@ -161,7 +161,7 @@ inline Type * SPArray::RemoveObj( Type * delObject, DelType del ) // \ru на выходе : isPresent == true - элемент уже в массиве \en in output : isPresent == true - the element is already in the array // --- template -inline size_t SPArray::PossibleIndex( const Type* el, bool& isPresent ) { +inline size_t SPArray::PossibleIndex( const Type * el, bool & isPresent ) const { return find_from_array_spec( *this, el, isPresent ); } @@ -192,7 +192,7 @@ Type * add_to_array( SPArray & arr, Type * el, size_t & indexEl ) // \ru по логике правильнее было бы проверять сначала меньше, потом тождественно, а затем, уже \en it would be better to check at first whether it is less, then whether it is equal and only after this // \ru без сравнения - делать вывод что больше. \en conclude which is greater without comparison. // \ru НО! оператор сравнения, как правило более быстрый, чем оператор тождественности, \en BUT! the comparison operator is generally faster than identity operator, - // \ru и заведомо более часто используется( тождественно - финишная опреация в поиске ) \en and it is used more often (identity check is the last operation in search) + // \ru и заведомо более часто используется( тождественно - финишная операция в поиске ) \en and it is used more often (identity check is the last operation in search) // \ru и если поставить проверку тождественности впереди "больше" - можно получить торможение \en and if the identity check will be placed before the "greater" check then there may occur an inhibition // \ru на тяжелых операторах \en on heavy operators // \ru Кроме того, все три проверки делаются, дабы не отказывать программистам в их праве делать \en - @@ -234,7 +234,7 @@ Type * add_to_array( SPArray & arr, Type * el, size_t & indexEl ) // \ru специальные случаи \en special cases // \ru массив пустой - просто добавляем \en the array is empty - simply add - // \ru проверку на пустоту массива нельзя переносить за проверку границ - \en a check for array emptyness should not be moved outside a boundary check - + // \ru проверку на пустоту массива нельзя переносить за проверку границ - \en a check for array emptiness should not be moved outside a boundary check - // \ru можно вылететь (из-за mxc = -1) \en the error may occur (because of mxc = -1) if ( !arr.count ) { arr.PArray::Add( el ); @@ -282,7 +282,7 @@ Type * add_to_array( SPArray & arr, Type * el, size_t & indexEl ) // \ru поиск ведется методом половинных делений \en a search is performed by the bisection method // --- template -size_t find_from_array_spec( SPArray & arr, const Type * el, bool & isPresent ) +size_t find_from_array_spec( const SPArray & arr, const Type * el, bool & isPresent ) { isPresent = false; @@ -320,13 +320,13 @@ size_t find_from_array_spec( SPArray & arr, const Type * el, bool & isPres isPresent = true; return mn; } - else - if (*el == *arr/*.parr*/[mx]) { + else { + if ( *el == *arr/*.parr*/[mx] ) { isPresent = true; return mx; } else { - size_t md = ( mn + mx ) / 2; + size_t md = (mn + mx) / 2; if ( *arr/*.parr*/[md] < *el ) mn = md; else if ( *el < *arr/*.parr*/[md] ) @@ -336,6 +336,7 @@ size_t find_from_array_spec( SPArray & arr, const Type * el, bool & isPres return md; } } + } } return mx; @@ -352,7 +353,7 @@ size_t find_from_array_spec( SPArray & arr, const Type * el, bool & isPres // \ru Индекс объекта в массиве. Если объект не был найден, то возращается SYS_MAX_T. \en index of an object in array If the object was not found then SYS_MAX_T is returned. // --- template -size_t find_from_array( SPArray & arr, const Type * el ) +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 return SYS_MAX_T; @@ -372,7 +373,7 @@ size_t find_from_array( SPArray & arr, const Type * el ) // \ru по логике правильнее было бы проверять сначала меньше, потом тождественно, а затем, уже \en it would be better to check at first whether it is less, then whether it is equal and only after this // \ru без сравнения - делать вывод что больше. \en conclude which is greater without comparison. // \ru НО! оператор сравнения, как правило более быстрый, чем оператор тождественности, \en BUT! the comparison operator is generally faster than identity operator, - // \ru и заведомо более часто используется( тождественно - финишная опреация в поиске ) \en and it is used more often (identity check is the last operation in search) + // \ru и заведомо более часто используется( тождественно - финишная операция в поиске ) \en and it is used more often (identity check is the last operation in search) // \ru и если поставить проверку тождественности впереди "больше" - можно получить торможение \en and if the identity check will be placed before the "greater" check then there may occur an inhibition // \ru на тяжелых операторах \en on heavy operators // \ru Кроме того, все три проверки делаются, дабы не отказывать программистам в их праве делать \en - diff --git a/C3d/Include/templ_sptr.h b/C3d/Include/templ_sptr.h index 9bd40ce..9fa0882 100644 --- a/C3d/Include/templ_sptr.h +++ b/C3d/Include/templ_sptr.h @@ -22,7 +22,7 @@ \ingroup Base_Tools_SmartPointers */ // --- -#define NULL_CHECK PRECONDITION( m_pI != NULL ); +#define NULL_CHECK PRECONDITION( m_pI != C3D_NULL_PTR ); //------------------------------------------------------------------------------ @@ -42,20 +42,20 @@ class SPtr public: /// \ru Конструктор. \en Constructor. - SPtr () : m_pI( NULL ) {} + SPtr () : m_pI( C3D_NULL_PTR ) {} /// \ru Конструктор по указателю. \en Constructor by pointer. explicit SPtr ( T * elem ) { - if ( (m_pI = elem) != NULL ) + if ( (m_pI = elem) != C3D_NULL_PTR ) m_pI->AddRef(); } /// \ru Конструктор копирования. \en Copy constructor. - SPtr( const SPtr & ptr ) : m_pI( NULL ) { assign(ptr.m_pI); } + SPtr( const SPtr & ptr ) : m_pI( C3D_NULL_PTR ) { assign(ptr.m_pI); } /// \ru Конструктор по совместимому указателю \en Constructor by compatible pointer template - SPtr( const SPtr<_T> & ptr ) : m_pI( ptr.get() ) { if ( m_pI != NULL ) { m_pI->AddRef();} } + SPtr( const SPtr<_T> & ptr ) : m_pI( ptr.get() ) { if ( m_pI != C3D_NULL_PTR ) { m_pI->AddRef();} } /// \ru Деструктор. \en Destructor. - ~SPtr() { if( m_pI != NULL ) m_pI->Release(); } + ~SPtr() { if( m_pI != C3D_NULL_PTR ) m_pI->Release(); } public: // \ru Перегрузка операторов \en Operators overloading /// \ru Оператор преобразования к типу T* . \en An operator for conversion to the type T*. @@ -102,16 +102,16 @@ public: // \ru Перегрузка операторов \en Operators overloadi 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 != NULL ) { m_pI->Release(); m_pI = NULL; } return *this; } + /// \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; } /// \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 = NULL; if ( obj != NULL ) obj->DecRef(); return obj; } + T * detach() { T * obj = m_pI; m_pI = C3D_NULL_PTR; if ( obj != C3D_NULL_PTR ) obj->DecRef(); return obj; } /// \ru Нулевой указатель? \en Is null pointer? - bool is_null() const { return (( NULL == m_pI ) ? true : false ); } + bool is_null() const { return (( C3D_NULL_PTR == m_pI ) ? true : false ); } -#ifdef STANDARD_CPP11_RVALUE_REFERENCES +#ifdef C3D_STANDARD_CXX_11_PARTIAL public: /// \ru Конструктор перемещения. \en Moving constructor. SPtr( SPtr && src ) : m_pI ( src.m_pI ) @@ -126,7 +126,7 @@ public: src.m_pI = tmp; return *this; } -#endif // STANDARD_CPP11_RVALUE_REFERENCES +#endif // C3D_STANDARD_CXX_11_PARTIAL }; @@ -138,8 +138,8 @@ inline SPtr & SPtr::assign( T * elem ) { if ( m_pI != elem ) { - if ( elem != NULL ) { elem->AddRef(); } - if ( m_pI != NULL ) { m_pI->Release(); } + if ( elem != C3D_NULL_PTR ) { elem->AddRef(); } + if ( m_pI != C3D_NULL_PTR ) { m_pI->Release(); } m_pI = elem; } return *this; @@ -170,7 +170,7 @@ public: m_pI->AddRef(); } /// \ru Конструктор копирования. \en Copy constructor. - SRef( const SRef & src ): m_pI( src.m_pI ) + SRef( const SRef & src ): m_pI( src.m_pI ) { m_pI->AddRef(); } @@ -187,7 +187,7 @@ public: /// \ru Оператор доступа. \en An access operator. T & operator()() const { return *m_pI; } /// \ru Оператор проверки на равенство. \en An operator for equality check. - bool operator == ( const SRef & src ) const { return ( m_pI == src.m_pI ); } + bool operator == ( const SRef & src ) const { return ( m_pI == src.m_pI ); } /// \ru Оператор проверки на равенство. \en An operator for equality check. bool operator == ( T & pObj ) const { return ( m_pI == &pObj ); } /// \ru Оператор проверки на неравенство. \en An operator for inequality check. @@ -234,5 +234,67 @@ struct SPtrPair SPtrPair & operator = ( const SPtrPair & sPair ) { first = sPair.first; second = sPair.second; } }; +namespace c3d { + +#ifdef C3D_STANDARD_CXX_11 +//------------------------------------------------------------------------------ +// \ru Создать объект по параметрам и вернуть автоматический указатель на него. +// \en Create an object by parameters and return a smart pointer to it. +//--- +template +inline SPtr make_sptr( Args && ... args ) +{ + return SPtr( new T(std::forward( args )...) ); +} +#else +//------------------------------------------------------------------------------ +// \ru Создать объект по параметрам и вернуть автоматический указатель на него (может быть неэффективной в отсутствие C++11). +// \en Create an object by parameters and return a smart pointer to it (might be ineffective in the absence of C++11).. +//--- +template +inline SPtr make_sptr() +{ + return SPtr( new T() ); +} + +template +inline SPtr make_sptr( Arg1 & arg1 ) +{ + return SPtr( new T( arg1 ) ); +} + +template +inline SPtr make_sptr( Arg1 & arg1, Arg2 & arg2 ) +{ + return SPtr( new T( arg1, arg2 ) ); +} + +template +inline SPtr make_sptr( Arg1 & arg1, Arg2 & arg2, Arg3 & arg3 ) +{ + return SPtr( new T( arg1, arg2, arg3 ) ); +} + +template +inline SPtr make_sptr( Arg1 & arg1, Arg2 & arg2, Arg3 & arg3, Arg4 & arg4 ) +{ + return SPtr( new T( arg1, arg2, arg3, arg4 ) ); +} + +template +inline SPtr make_sptr( Arg1 & arg1, Arg2 & arg2, Arg3 & arg3, Arg4 & arg4, Arg5 & arg5 ) +{ + return SPtr( new T( arg1, arg2, arg3, arg4, arg5 ) ); +} + +template +inline SPtr make_sptr( Arg1 & arg1, Arg2 & arg2, Arg3 & arg3, Arg4 & arg4, Arg5 & arg5, Arg6 & arg6 ) +{ + return SPtr( new T( arg1, arg2, arg3, arg4, arg5, arg6 ) ); +} + +#endif + +} // namespace c3d #endif // __TEMPL_SPTR_H diff --git a/C3d/Include/templ_ss_array.h b/C3d/Include/templ_ss_array.h index 11eb29d..7c6cc2a 100644 --- a/C3d/Include/templ_ss_array.h +++ b/C3d/Include/templ_ss_array.h @@ -15,11 +15,11 @@ FORVARD_DECL_TEMPLATE_TYPENAME( class SSArray ); -FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array ( SSArray & arr, const Type & el, size_t & indexEl ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_in_array ( const SSArray &, const Type & el ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array_spec ( const SSArray &, const Type & el, bool & isPresent ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( reader& CALL_DECLARATION operator >> ( reader& in, SSArray & ref ) ); -FORVARD_DECL_TEMPLATE_TYPENAME( writer& CALL_DECLARATION operator << ( writer& out, const SSArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( Type * add_to_array ( SSArray &, const Type & el, size_t & indexEl ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_in_array ( const SSArray &, const Type & el ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( size_t find_from_array_spec( const SSArray &, const Type & el, bool & isPresent ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( reader & CALL_DECLARATION operator >> ( reader & in, SSArray & ref ) ); +FORVARD_DECL_TEMPLATE_TYPENAME( writer & CALL_DECLARATION operator << ( writer & out, const SSArray & ref ) ); //------------------------------------------------------------------------------ /** \brief \ru Упорядоченный массив. @@ -69,10 +69,10 @@ public: Type * Add ( const Type &, size_t & indexEnt ); // \ru добавить элемент с упорядочиванием по массиву, возвращает индекс \en add element with sorting, returns index of the element // \ru используя эту функцию, пользователь несет всю ответственность за дальнейшую работу сортировки \en When using this function the user is fully responsible for the further work of the sorting process // \ru - сортировка может работать неправильно. \en - sorting may work incorrectly. - void AddSimple( const Type &ent ) { SArray::Add( ent ); } // \ru Доступ к функции базового класса - добавить элемент в конец массива \en An access to the function of the base class - add an element to the end of the array + void AddSimple( const Type & ent ) { SArray::Add( ent ); } // \ru Доступ к функции базового класса - добавить элемент в конец массива \en An access to the function of the base class - add an element to the end of the array size_t Find( const Type & ) const; // \ru найти элемент в упорядоченном массиве \en find an element in ordered array - size_t RemoveObj( const Type& delObject ); + size_t RemoveObj( const Type & delObject ); bool operator == ( const SSArray & ) const; // \ru сравнить два массива \en compare two arrays bool operator != ( const SSArray & ) const; // \ru сравнить два массива \en compare two arrays @@ -82,15 +82,15 @@ public: // \ru преобразование к базовому классу \en Convert to the base class const SArray & BaseClass() const { return *this; } - size_t PossibleIndex( const Type& ent, bool& isPresent ) const; // \ru найти место в массиве, куда будет добавлен элемент ( без добавления ) \en find a place in the array for adding ann element (adding is not performed) - // \ru на выходе : isPresent == true - элемент уже в массиве \en in output : isPresent == true - the element is already in the array + size_t PossibleIndex( const Type & ent, bool & isPresent ) const; // \ru найти место в массиве, куда будет добавлен элемент ( без добавления ) \en find a place in the array for adding ann element (adding is not performed) + // \ru на выходе : isPresent == true - элемент уже в массиве \en in output : isPresent == true - the element is already in the array - TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SSArray & arr, const Type & el, size_t & indexEl ); + TEMPLATE_FRIEND Type * add_to_array TEMPLATE_SUFFIX ( SSArray &, const Type & el, size_t & indexEl ); TEMPLATE_FRIEND size_t find_in_array TEMPLATE_SUFFIX ( const SSArray &, const Type & el ); TEMPLATE_FRIEND size_t find_from_array_spec TEMPLATE_SUFFIX ( const SSArray &, const Type & el, bool & isPresent ); - TEMPLATE_FRIEND reader& CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader& in, SSArray & ref ); - TEMPLATE_FRIEND writer& CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer& out, const SSArray & ref ); + TEMPLATE_FRIEND reader & CALL_DECLARATION operator >> TEMPLATE_SUFFIX ( reader & in, SSArray & ref ); + TEMPLATE_FRIEND writer & CALL_DECLARATION operator << TEMPLATE_SUFFIX ( writer & out, const SSArray & ref ); #ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ public: @@ -190,7 +190,8 @@ inline Type * SSArray::Add( const Type & el, size_t & indexEl ) { // \ru удалить элемент из массива \en delete an element from array // --- template -inline size_t SSArray::RemoveObj( const Type & delObject ) { +inline size_t SSArray::RemoveObj( const Type & delObject ) +{ size_t ind = Find( delObject ); if ( ind != SYS_MAX_T ) RemoveInd( ind ); @@ -347,7 +348,7 @@ size_t find_in_array( const SSArray & arr, const Type & el ) // \ru по логике правильнее было бы проверять сначала меньше, потом тождественно, а затем, уже \en it would be better to check at first whether it is less, then whether it is equal and only after this // \ru без сравнения - делать вывод что больше. \en conclude which is greater without comparison. // \ru НО! оператор сравнения, как правило более быстрый, чем оператор тождественности, \en BUT! the comparison operator is generally faster than identity operator, - // \ru и заведомо более часто используется( тождественно - финишная опреация в поиске ) \en and it is used more often (identity check is the last operation in search) + // \ru и заведомо более часто используется( тождественно - финишная операция в поиске ) \en and it is used more often (identity check is the last operation in search) // \ru и если поставить проверку тождественности впереди "больше" - можно получить торможение \en and if the identity check will be placed before the "greater" check then there may occur an inhibition // \ru на тяжелых операторах \en on heavy operators // \ru Кроме того, все три проверки делаются, дабы не отказывать программистам в их праве делать \en - @@ -395,7 +396,8 @@ size_t find_in_array( const SSArray & arr, const Type & el ) // \ru поиск ведется методом половинных делений \en a search is performed by the bisection method // --- template -size_t find_from_array_spec( const SSArray & arr, const Type & el, bool & isPresent ) { +size_t find_from_array_spec( const SSArray & arr, const Type & el, bool & isPresent ) +{ isPresent = false; if ( !arr.count || el < arr/*.parr*/[0] ) diff --git a/C3d/Include/templ_stack.h b/C3d/Include/templ_stack.h index 3822185..8b0011f 100644 --- a/C3d/Include/templ_stack.h +++ b/C3d/Include/templ_stack.h @@ -1,86 +1,86 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Стек объектов. - \en A stack of objects. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef __TEMPL_SSTACK_H -#define __TEMPL_SSTACK_H - - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Стек объектов. - \en A stack of objects. \~ - \details \ru Стек объектов. \n - Для организации стека используем в качестве строителя SArray, - и отсекаем лишнее с помощью приватного наследования. \n - \en A stack of objects. \n - To organize stack SArray is used as the builder, - and all redundant is cut by using a private inheritance. \n \~ - \ingroup Base_Tools_Containers -*/ -// --- -template -class SStack: private SArray { -public: - /// \ru Конструктор. \en Constructor. - SStack( size_t i_upper = 0, uint16 i_delta = 1 ) - : SArray( i_upper, i_delta ) - {} -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 & Top() const; ///< \ru Верхний элемент стека (последний внесенный). \en The top element of the stack (the last added). - - // \ru Оставить доступными следующие методы: \en Leave an access to the next methods: - using SArray::Flush; ///< \ru Очистить стек. \en Clear the stack. - using SArray::Count; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. - using SArray::IsExist; ///< \ru Существует ли элемент. \en Whether an element exists. - using SArray::operator[]; ///< \ru Оператор прямого доступа - работает, как для массива. \en An operator of a direct access - it works as for an array. - -private: - SStack( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation - void operator =( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation -}; - - -//------------------------------------------------------------------------------ -/// \ru Добавить элемент в стек \en Add an element to the stack -//--- -template -void SStack::Push( const Type & obj ) { - SArray::Add( obj ); -} - - -//------------------------------------------------------------------------------ -/// \ru Извлечь один элемент стека \en Retrieve one element from the stack -//--- -template -Type & SStack::Pop() { - if ( SArray::count > 0 ) { - Type & ret = (*this)[SArray::count-1]; - SArray::count--; - return ret; - } - return (*this)[0]; -} - - -//------------------------------------------------------------------------------ -/// \ru Верхний элемент стека \en The top element of the stack -//--- -template -Type & SStack::Top() const { - return (*this)[SArray::count-1]; -} - - -#endif // __TEMPL_SSTACK_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Стек объектов. + \en A stack of objects. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + + +#ifndef __TEMPL_SSTACK_H +#define __TEMPL_SSTACK_H + + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Стек объектов. + \en A stack of objects. \~ + \details \ru Стек объектов. \n + Для организации стека используем в качестве строителя SArray, + и отсекаем лишнее с помощью приватного наследования. \n + \en A stack of objects. \n + To organize stack SArray is used as the builder, + and all redundant is cut by using a private inheritance. \n \~ + \ingroup Base_Tools_Containers +*/ +// --- +template +class SStack: private SArray { +public: + /// \ru Конструктор. \en Constructor. + SStack( size_t i_upper = 0, uint16 i_delta = 1 ) + : SArray( i_upper, i_delta ) + {} +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 & Top() const; ///< \ru Верхний элемент стека (последний внесенный). \en The top element of the stack (the last added). + + // \ru Оставить доступными следующие методы: \en Leave an access to the next methods: + using SArray::Flush; ///< \ru Очистить стек. \en Clear the stack. + using SArray::Count; ///< \ru Количество элементов, содержащихся в стеке. \en The number of elements in stack. + using SArray::IsExist; ///< \ru Существует ли элемент. \en Whether an element exists. + using SArray::operator[]; ///< \ru Оператор прямого доступа - работает, как для массива. \en An operator of a direct access - it works as for an array. + +private: + SStack( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation + void operator =( const SStack & ); ///< \ru (!) Без реализации \en (!) There is no implementation +}; + + +//------------------------------------------------------------------------------ +/// \ru Добавить элемент в стек \en Add an element to the stack +//--- +template +void SStack::Push( const Type & obj ) { + SArray::Add( obj ); +} + + +//------------------------------------------------------------------------------ +/// \ru Извлечь один элемент стека \en Retrieve one element from the stack +//--- +template +Type & SStack::Pop() { + if ( SArray::count > 0 ) { + Type & ret = (*this)[SArray::count-1]; + SArray::count--; + return ret; + } + return (*this)[0]; +} + + +//------------------------------------------------------------------------------ +/// \ru Верхний элемент стека \en The top element of the stack +//--- +template +Type & SStack::Top() const { + return (*this)[SArray::count-1]; +} + + +#endif // __TEMPL_SSTACK_H diff --git a/C3d/Include/tool_cstring.h b/C3d/Include/tool_cstring.h index b201ab8..93f1052 100644 --- a/C3d/Include/tool_cstring.h +++ b/C3d/Include/tool_cstring.h @@ -244,16 +244,9 @@ #endif #define _acstoi strtol // char* -> int32 -#ifdef __BORLANDC__ - #define _acstoi64 strtoll // char* -> int64 (long long) - #define _acstoui64 strtoull // char* -> uint64 (unsigned long long) - #define _tcstoi64 wcstoll // TCHAR* -> int64 (long long) - #define _tcstoui64 wcstoull // TCHAR* -> uint64 (unsigned long long) - //#define _tcstod // TCHAR* -> double -#else #define _acstoi64 _strtoi64 // char* -> int64 #define _acstoui64 _strtoui64 // char* -> uint64 -#endif + #define _acstoui strtoul // char* -> uint32 #define _acstod strtod // char* -> double diff --git a/C3d/Include/tool_enabler.h b/C3d/Include/tool_enabler.h index 58c8372..5a7151f 100644 --- a/C3d/Include/tool_enabler.h +++ b/C3d/Include/tool_enabler.h @@ -1,104 +1,104 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Включатель модулей ядра. - \en Kernel modules enabler \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef _TOOL_ENABLER_H_ -#define _TOOL_ENABLER_H_ - -#include - - -//------------------------------------------------------------------------------ -/** \brief \ru Включить модули ядра. - \en Enable kernel modules. \~ - \details \ru Включить соответствующие модули ядра. - \en Enable the corresponding kernel modules. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (void) EnableMathModules( const char * name, int nameLength, const char * key, int keyLength ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить ключ активации на валидность. - \en Verify key. \~ - \details \ru Проверить ключ активации на валидность. - \en Verify key. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) VerifyLicenseKey( const char * name, const char * key, const char * pub_key ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить контроллер защиты моделировщика. - \en Check the controller of the Modeler. \~ - \details \ru Проверить контроллер защиты моделировщика. - \en Check the controller of the Modeler. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) IsMathModelerEnable(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить контроллер защиты конвертеров. - \en Check the controller of the Converter. \~ - \details \ru Проверить контроллер защиты конвертеров. - \en Check the controller of the Converter. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) IsMathConverterEnable(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить контроллер защиты решателя. - \en Check the controller of the Solver. \~ - \details \ru Проверить контроллер защиты решателя. - \en Check the controller of the Solver. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) IsMathSolverEnable(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить контроллер защиты визуализатора. - \en Check the controller of the Vision. \~ - \details \ru Проверить контроллер защиты визуализатора. - \en Check the controller of the Vision. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) IsMathVisionEnable(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Проверить контроллер защиты преобразователя сеток в BRep. - \en Check the controller of the BShaper. \~ - \details \ru Проверить контроллер защиты преобразователя сеток в BRep. - \en Check the controller of the BShaper. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (bool) IsMathBShaperEnable(); - - -//------------------------------------------------------------------------------ -/** \brief \ru Отпустить контролера работы модулей ядра. - \en Free the controller of the kernel modules work. \~ - \details \ru Отпустить контролера работы модулей ядра. - \en Free the controller of the kernel modules work. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC (void) FreeMathModulesChecker(); - - -#endif // _TOOL_ENABLER_H_ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Включатель модулей ядра. + \en Kernel modules enabler \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef _TOOL_ENABLER_H_ +#define _TOOL_ENABLER_H_ + +#include + + +//------------------------------------------------------------------------------ +/** \brief \ru Включить модули ядра. + \en Enable kernel modules. \~ + \details \ru Включить соответствующие модули ядра. + \en Enable the corresponding kernel modules. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (void) EnableMathModules( const char * name, int nameLength, const char * key, int keyLength ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить ключ активации на валидность. + \en Verify key. \~ + \details \ru Проверить ключ активации на валидность. + \en Verify key. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) VerifyLicenseKey( const char * name, const char * key, const char * pub_key ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить контроллер защиты моделировщика. + \en Check the controller of the Modeler. \~ + \details \ru Проверить контроллер защиты моделировщика. + \en Check the controller of the Modeler. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) IsMathModelerEnable(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить контроллер защиты конвертеров. + \en Check the controller of the Converter. \~ + \details \ru Проверить контроллер защиты конвертеров. + \en Check the controller of the Converter. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) IsMathConverterEnable(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить контроллер защиты решателя. + \en Check the controller of the Solver. \~ + \details \ru Проверить контроллер защиты решателя. + \en Check the controller of the Solver. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) IsMathSolverEnable(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить контроллер защиты визуализатора. + \en Check the controller of the Vision. \~ + \details \ru Проверить контроллер защиты визуализатора. + \en Check the controller of the Vision. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) IsMathVisionEnable(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Проверить контроллер защиты преобразователя сеток в BRep. + \en Check the controller of the BShaper. \~ + \details \ru Проверить контроллер защиты преобразователя сеток в BRep. + \en Check the controller of the BShaper. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (bool) IsMathBShaperEnable(); + + +//------------------------------------------------------------------------------ +/** \brief \ru Отпустить контролера работы модулей ядра. + \en Free the controller of the kernel modules work. \~ + \details \ru Отпустить контролера работы модулей ядра. + \en Free the controller of the kernel modules work. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC (void) FreeMathModulesChecker(); + + +#endif // _TOOL_ENABLER_H_ diff --git a/C3d/Include/tool_err_handling.h b/C3d/Include/tool_err_handling.h index 40f98ba..96c30f9 100644 --- a/C3d/Include/tool_err_handling.h +++ b/C3d/Include/tool_err_handling.h @@ -1,73 +1,137 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Сервис для обработки ошибок. - \en Error-handling services. \~ -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TOOL_ERR_HANDLING_H -#define __TOOL_ERR_HANDLING_H - -#include - - -//------------------------------------------------------------------------------ -/** - \brief \ru Определение режима обработки исключений. - \en Definition of mode for exception handling. \~ - \details \ru Определяет, пробрасывать ли исключение дальше после его обработки. По умолчанию исключения подавляются. \n - \en Defines, whether to throw exception further after its processing. By default, exceptions are suppressed. \~ - \ingroup Base_Tools -*/ -//--- -class MATH_CLASS ExceptionMode -{ - static bool sExptEnabled; -public: - // \ru Установить режим обработки исключений: true, чтобы пробрасывать исключения дальше; false, чтобы подавлять исключения. - // Возвращает предыдущий режим. - // \en Set mode for exception handling: true - to throw exceptions further; false - to suppress exceptions. - // Return the previous mode. - static bool Enable( bool enabled = true ); - - // \ru Получить текущий режим обработки исключений (true - пробрасывать исключение дальше; false - нет). - // \en Get current exception handling mode (true - to throw exception further; false - to not throw). - static bool IsEnabled(); -}; - -//------------------------------------------------------------------------------ -/** - \brief \ru Меняет режим обработки исключений в области видимости. - \en Alter mode for exception handling in a scope. \~ - \ingroup Base_Tools -*/ -//--- -class MATH_CLASS ScopedExceptionMode -{ - bool m_oldMode; -public: - ScopedExceptionMode( bool mode = true ) { m_oldMode = ExceptionMode::Enable( mode ); } - ~ScopedExceptionMode() { ExceptionMode::Enable( m_oldMode ); } -}; - - -//------------------------------------------------------------------------------ -/** - \brief \ru Бросить указанное исключение, если режим позволяет. - \en Throw the specified exception if allowed by the exception mode. \~ - \ingroup Base_Tools -*/ -//--- -#define C3D_CONTROLED_THROW_EX(expt) if( ExceptionMode::IsEnabled() ) throw expt; - -//------------------------------------------------------------------------------ -/** - \brief \ru Бросить исключение, если режим позволяет. - \en Throw exception if allowed by the mode for exception handling. \~ - \ingroup Base_Tools -*/ -//--- -#define C3D_CONTROLED_THROW if( ExceptionMode::IsEnabled() ) throw; - -#endif // __TOOL_ERR_HANDLING_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Сервис для обработки ошибок. + \en Error-handling services. \~ +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TOOL_ERR_HANDLING_H +#define __TOOL_ERR_HANDLING_H + +#include +#include +#include +#include + +#include // \ru Внимание! Читаем внимательно! Если вытереть отсюда, то подключить везде, где есть функции из этого файла! \en Attention! Read carefully! If remove this from here, then it should be included anywhere where the functions from this file exist! + + +//------------------------------------------------------------------------------ +/** + \brief \ru Определение режима обработки исключений. + \en Definition of mode for exception handling. \~ + \details \ru Определяет, пробрасывать ли исключение дальше после его обработки. По умолчанию исключения подавляются. \n + \en Defines, whether to throw exception further after its processing. By default, exceptions are suppressed. \~ + \ingroup Base_Tools +*/ +//--- +class MATH_CLASS ExceptionMode +{ + static bool sExptEnabled; +public: + /** \brief \ru Установить режим обработки исключений: true, чтобы пробрасывать исключения дальше; false, чтобы подавлять исключения. + Возвращает предыдущий режим. + \en Set mode for exception handling: true - to throw exceptions further; false - to suppress exceptions. + Return the previous mode. + */ + static bool Enable( bool enabled = true ); + + /** \brief \ru Получить текущий режим обработки исключений (true - пробрасывать исключение дальше; false - нет). + \en Get current exception handling mode (true - to throw exception further; false - to not throw). + */ + static bool IsEnabled(); +}; + +//------------------------------------------------------------------------------ +/** + \brief \ru Меняет режим обработки исключений в области видимости. + \en Alter mode for exception handling in a scope. \~ + \ingroup Base_Tools +*/ +//--- +class MATH_CLASS ScopedExceptionMode +{ + bool m_oldMode; +public: + ScopedExceptionMode( bool mode = true ) { m_oldMode = ExceptionMode::Enable( mode ); } + ~ScopedExceptionMode() { ExceptionMode::Enable( m_oldMode ); } +}; + + +//------------------------------------------------------------------------------ +/** + \brief \ru Бросить указанное исключение, если режим позволяет. + \en Throw the specified exception if allowed by the exception mode. \~ + \ingroup Base_Tools +*/ +//--- +#define C3D_CONTROLED_THROW_EX(expt) if( ExceptionMode::IsEnabled() ) throw expt; + +//------------------------------------------------------------------------------ +/** + \brief \ru Бросить исключение, если режим позволяет. + \en Throw exception if allowed by the mode for exception handling. \~ + \ingroup Base_Tools +*/ +//--- +#define C3D_CONTROLED_THROW if( ExceptionMode::IsEnabled() ) throw; + +//------------------------------------------------------------------------------ +/** + \brief \ru Обработчик фатальных ошибок. + \en Handler of fatal errors. \~ + \details \ru Обработчик фатальных ошибок. + Перед началом мониторинга должна вызываться функция Init(). + При выходе из проблемной области должна вызываться функция Recover(). \n + \en Handler of fatal errors. + Before starting error monitoring the Init() function should be called. + On exit a faulty region, the Recover() function should be called. \~ + \ingroup Base_Tools +*/ +//--- +class MATH_CLASS FatalErrorHandler +{ +public: + + /** \brief \ru Получить последнюю ошибку. \en Get the last error. + */ + static MbResultType GetError(); + + /** \brief \ru Есть ли фатальная ошибка. \en Is there a fatal error. + */ + static bool HasError(); + + /** \brief \ru Зарегистрировать фатальную ошибку. Возвращает эту ошибку. + \en Register a fatal error. Return this error. + */ + static MbResultType SetError( MbResultType ); + + /** \brief \ru Инициализировать обработчик перед началом мониторинга ошибок. + Возвращает true, если обработчик стартовал, или false, если обработчик уже работает. + Парная функция Recover() должна вызываться, только если Init() вернул true. + \en Initialize handler before starting error monitoring. + Returns true if the handler is started or false if the handler is already working. + The paired function Recover() should be called only if Init() returnes true. + */ + static bool Init(); + + /** \brief \ru Восстановиться, если обнаружена фатальная ошибка. + \en Recover if a fatal error is detected. + */ + static void Recover(); + + /** \brief \ru Достаточно ли памяти для работы. \en Whether is enough memory to work. + */ + static bool IsEnoughMemory(); + + /** \brief \ru Установить допустимый порог памяти для работы (Mb). \en Set an acceptable memory threshold for work (Mb). + */ + static void SetMemoryThreshold( double ); + + /** \brief \ru Установить порог памяти по умолчанию. \en Set default memory threshold. + */ + static void ResetMemoryThreshold(); +}; + +#endif // __TOOL_ERR_HANDLING_H diff --git a/C3d/Include/tool_log.h b/C3d/Include/tool_log.h index 7001f1c..55854c0 100644 --- a/C3d/Include/tool_log.h +++ b/C3d/Include/tool_log.h @@ -1,124 +1,124 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Логирование информации. - \en Information logging. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __TOOL_LOG_H -#define __TOOL_LOG_H - -#include -#include -#include - -//------------------------------------------------------------------------------ -// \ru Потокобезопасные интерфейсы для ведение журнала сообщений и записи его в файл. -// Для каждого потока ведется отдельный лог, который записывается в отдельный файл. -// Доступны в дебаге. -// \en Thread-safe interfaces for logging messages and writing the log to the file. -// Keep a separate log for each thread which is saved to a separate file. -// Available in debug configuration. -// -/* \ru Пример использования. \en Usage sample. - int k = 0; - START_LOGGING; // \ru Начинаем логирование. \en Start logging. - LOG_MSG( _T("Samplelog") ); // \ru Добавляем указанную строку в лог. \en Put a specified string to the log. - ... - // \ru Форматируем строку лога (оператор << Logger::Endl добавляет ее в лог). \en Format a log line (operator << Logger::Endl puts it to the log). - Logger::Get() << _T("Value ") << k << Logger::Endl; - ... - WRITE_LOG_FILE( _T("sample.log") ); // \ru Записываем лог в файл. \en Write the log to the file. - END_LOGGING; // \ru Заканчиваем логирование. \en Stop logging. -*/ -// --- -#ifdef C3D_DEBUG - -//------------------------------------------------------------------------------ -// \ru Класс позволяет форматировать строку для лога и добавлять ее в лог. -// \en Class allows to format a line to the log and put it to the log. -// --- -class MATH_CLASS Logger -{ -public: - // \ru Получить логгер. \en Get the logger. - static Logger& Get(); - - // \ru Следующие методы позволяют форматировать строку для лога. Работают с текущей строкой лога. - // \en Next methods allow to format a line to the log. Work with the current line of the log. - - // \ru Добавить строку в текущую строку лога. \en Add a string to the current line of the log. - virtual Logger& operator << ( const TCHAR * ) = 0; - // \ru Добавить integer в текущую строку лога. \en Add integer to the current line of the log. - virtual Logger& operator << ( const int & ) = 0; -#if defined(PLATFORM_64) // \ru x32 совпадение типов ptrdiff_t и int \en x32 coincidence of ptrdiff_t and int types - // \ru Добавить ptrdiff_t в текущую строку лога. \en Add ptrdiff_t to the current line of the log. - virtual Logger& operator << ( const ptrdiff_t & ) = 0; -#endif - // \ru Добавить size_t в текущую строку лога. \en Add size_t to the current line of the log. - virtual Logger& operator << ( const size_t & ) = 0; - // \ru Добавить double в текущую строку лога. \en Add double to the current line of the log. - virtual Logger& operator << ( const double & ) = 0; - // \ru Завершить форматирование текущей строки и добавить ее в лог. Следующий вызов оператора << создаст новую текущую строку. - // \en Finish formatting of the current line and add it to the log. Next call to the operator << will create new current line. - virtual Logger& operator << ( Logger& (*man)( Logger& ) ) = 0; - - // \ru Манипулятор-признак завершения форматирования текущей строки лога. - // \en Manipulator-indicator of finishing formatting of the current line of the log. - static Logger& Endl( Logger& ); -}; - -// \ru Начать или закончить логирование. \en Start or stop logging. -MATH_FUNC(void) SetLogging( bool allow ); - -// \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. -// \en Write the log to the file. Log of each thread writes to a separate file. -MATH_FUNC(void) WriteLog( const TCHAR *fileName ); - -// \ru Записать указанную строку в лог. \en Write a specified string to the log. -MATH_FUNC(void) LogMessage( const c3d::string_t &msg ); - -// \ru Макросы для операций логирования. \en Logging macros. - -// \ru Начать логирование. \en Start logging. -#define START_LOGGING SetLogging( true ); -// \ru Закончить логирование. \en Stop logging. -#define END_LOGGING SetLogging( false ); -// \ru Положить форматированную строку в лог. \en Put a formatted string to the log. -#define LOG_MSG(msg) LogMessage( msg ); -// \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. -// \en Write the log to the file. Log of each thread writes to a separate file. -#define WRITE_LOG_FILE(fileName) WriteLog( fileName ); - -#else -inline void CALL_DECLARATION SetLogging( bool ){} -inline void CALL_DECLARATION WriteLog( const TCHAR * ){} -inline void CALL_DECLARATION LogMessage( const c3d::string_t & ){} - -#define START_LOGGING -#define END_LOGGING -#define LOG_MSG(msg) -#define WRITE_LOG_FILE(fileName) - -#endif - - -namespace c3d //namespace c3d -{ - -//------------------------------------------------------------------------------ -/** \brief \ru Включить контроль утечек памяти. - \en Enable memory leakage control. \~ - \details \ru Включить контроль утечек памяти. - \en Enable memory leakage control. \~ - \ingroup Base_Tools -*/ -// --- -MATH_FUNC(void) EnableMemoryLeakDump(); - -} //namespace c3d - - -#endif // __TOOL_LOG_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Логирование информации. + \en Information logging. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __TOOL_LOG_H +#define __TOOL_LOG_H + +#include +#include +#include + +//------------------------------------------------------------------------------ +// \ru Потокобезопасные интерфейсы для ведение журнала сообщений и записи его в файл. +// Для каждого потока ведется отдельный лог, который записывается в отдельный файл. +// Доступны в дебаге. +// \en Thread-safe interfaces for logging messages and writing the log to the file. +// Keep a separate log for each thread which is saved to a separate file. +// Available in debug configuration. +// +/* \ru Пример использования. \en Usage sample. + int k = 0; + START_LOGGING; // \ru Начинаем логирование. \en Start logging. + LOG_MSG( _T("Samplelog") ); // \ru Добавляем указанную строку в лог. \en Put a specified string to the log. + ... + // \ru Форматируем строку лога (оператор << Logger::Endl добавляет ее в лог). \en Format a log line (operator << Logger::Endl puts it to the log). + Logger::Get() << _T("Value ") << k << Logger::Endl; + ... + WRITE_LOG_FILE( _T("sample.log") ); // \ru Записываем лог в файл. \en Write the log to the file. + END_LOGGING; // \ru Заканчиваем логирование. \en Stop logging. +*/ +// --- +#ifdef C3D_DEBUG + +//------------------------------------------------------------------------------ +// \ru Класс позволяет форматировать строку для лога и добавлять ее в лог. +// \en Class allows to format a line to the log and put it to the log. +// --- +class MATH_CLASS Logger +{ +public: + // \ru Получить логгер. \en Get the logger. + static Logger& Get(); + + // \ru Следующие методы позволяют форматировать строку для лога. Работают с текущей строкой лога. + // \en Next methods allow to format a line to the log. Work with the current line of the log. + + // \ru Добавить строку в текущую строку лога. \en Add a string to the current line of the log. + virtual Logger& operator << ( const TCHAR * ) = 0; + // \ru Добавить integer в текущую строку лога. \en Add integer to the current line of the log. + virtual Logger& operator << ( const int & ) = 0; +#if defined(PLATFORM_64) // \ru x32 совпадение типов ptrdiff_t и int \en x32 coincidence of ptrdiff_t and int types + // \ru Добавить ptrdiff_t в текущую строку лога. \en Add ptrdiff_t to the current line of the log. + virtual Logger& operator << ( const ptrdiff_t & ) = 0; +#endif + // \ru Добавить size_t в текущую строку лога. \en Add size_t to the current line of the log. + virtual Logger& operator << ( const size_t & ) = 0; + // \ru Добавить double в текущую строку лога. \en Add double to the current line of the log. + virtual Logger& operator << ( const double & ) = 0; + // \ru Завершить форматирование текущей строки и добавить ее в лог. Следующий вызов оператора << создаст новую текущую строку. + // \en Finish formatting of the current line and add it to the log. Next call to the operator << will create new current line. + virtual Logger& operator << ( Logger& (*man)( Logger& ) ) = 0; + + // \ru Манипулятор-признак завершения форматирования текущей строки лога. + // \en Manipulator-indicator of finishing formatting of the current line of the log. + static Logger& Endl( Logger& ); +}; + +// \ru Начать или закончить логирование. \en Start or stop logging. +MATH_FUNC(void) SetLogging( bool allow ); + +// \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. +// \en Write the log to the file. Log of each thread writes to a separate file. +MATH_FUNC(void) WriteLog( const TCHAR *fileName ); + +// \ru Записать указанную строку в лог. \en Write a specified string to the log. +MATH_FUNC(void) LogMessage( const c3d::string_t &msg ); + +// \ru Макросы для операций логирования. \en Logging macros. + +// \ru Начать логирование. \en Start logging. +#define START_LOGGING SetLogging( true ); +// \ru Закончить логирование. \en Stop logging. +#define END_LOGGING SetLogging( false ); +// \ru Положить форматированную строку в лог. \en Put a formatted string to the log. +#define LOG_MSG(msg) LogMessage( msg ); +// \ru Записать лог в файл. Лог для каждого потока записывается в отдельный файл. +// \en Write the log to the file. Log of each thread writes to a separate file. +#define WRITE_LOG_FILE(fileName) WriteLog( fileName ); + +#else +inline void CALL_DECLARATION SetLogging( bool ){} +inline void CALL_DECLARATION WriteLog( const TCHAR * ){} +inline void CALL_DECLARATION LogMessage( const c3d::string_t & ){} + +#define START_LOGGING +#define END_LOGGING +#define LOG_MSG(msg) +#define WRITE_LOG_FILE(fileName) + +#endif + + +namespace c3d //namespace c3d +{ + +//------------------------------------------------------------------------------ +/** \brief \ru Включить контроль утечек памяти. + \en Enable memory leakage control. \~ + \details \ru Включить контроль утечек памяти. + \en Enable memory leakage control. \~ + \ingroup Base_Tools +*/ +// --- +MATH_FUNC(void) EnableMemoryLeakDump(); + +} //namespace c3d + + +#endif // __TOOL_LOG_H diff --git a/C3d/Include/tool_memory_debug.h b/C3d/Include/tool_memory_debug.h index 9f6d8b9..fb2d0a7 100644 --- a/C3d/Include/tool_memory_debug.h +++ b/C3d/Include/tool_memory_debug.h @@ -1,421 +1,271 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Контроль выделения памяти под отладкой. - \en Memory allocation control during the debugging process. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __MEMORY_DEBUG_H -#define __MEMORY_DEBUG_H - -//#define __DEBUG_MEMORY_ALLOCATE_FREE_ -//#define __MEMSET_USED_FREE_HEAP_HEAR__ -//#define __REALLOC_ARRAYS_STATISTIC_ - -#include -#include -#include - -#ifdef C3D_DEBUG - #if defined(C3D_MacOS) // mac - #include - #elif defined(C3D_FreeBSD) - #include - #else - #include - #endif // mac - - #ifndef __DISABLE_MEMORY_CONTROL__ // \ru Чтобы можно было отключать в других проектах \en To allow to disable it in other projects - #ifndef __BORLANDC__ - #define USE_REALLOC_IN_ARRAYS // no _aligned_realloc in bcc32c - #endif - #endif // __DISABLE_MEMORY_CONTROL__ -#endif // C3D_DEBUG - -#ifdef __REALLOC_ARRAYS_STATISTIC_ -//#include -#include -#include -#endif - - -#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ - -//------------------------------------------------------------------------------ -/// \ru Проверить указатель и значение. \en Check pointer and value. \~ \ingroup Base_Tools -// --- -inline void CheckPointerAndValue( void * ptr, size_t size ) -{ -#if defined (C3D_WINDOWS) && !defined(ALL_WARNINGS) //_MSC_VER // Set warnings level -#pragma warning(disable: 4312) -#endif - C3D_ASSERT( ptr != (ptrdiff_t *)0xEEEEEEEE ); - C3D_ASSERT( ptr != (ptrdiff_t *)0xFFFFFFFF ); -#if defined (C3D_WINDOWS) && !defined(ALL_WARNINGS) //_MSC_VER // Set warnings level -#pragma warning(default: 4312) -#endif - - if ( ptr ) { - // \ru Надо доработать для 64-бит \en It should be adapted for the 64-bit version - if ( size > 11 ) { - uint32* _ptr = (uint32 *)ptr; - uint32 value1 = *_ptr++; - uint32 value2 = *_ptr++; - uint32 value3 = *_ptr; - C3D_ASSERT( value1 != 0xEEEEEEEE || value2 != 0xEEEEEEEE || value3 != 0xEEEEEEEE ); - C3D_ASSERT( value1 != 0xFFFFFFFF || value2 != 0xFFFFFFFF || value3 != 0xFFFFFFFF ); - } - else if ( size > 7 ) { - uint32 * _ptr = (uint32 *)ptr; - uint32 value1 = *_ptr++; - uint32 value2 = *_ptr; - C3D_ASSERT( value1 != 0xEEEEEEEE && value2 != 0xEEEEEEEE ); - C3D_ASSERT( value1 != 0xFFFFFFFF || value2 != 0xFFFFFFFF ); - } - else if ( size > 3 ) { - uint32 value = *(uint32 *)ptr; - C3D_ASSERT( value != 0xEEEEEEEE ); - C3D_ASSERT( value != 0xFFFFFFFF ); - } - else if ( size > 1 ) { - uint16 value = *(uint16 *)ptr; - C3D_ASSERT( value != 0xEEEE ); - C3D_ASSERT( value != 0xFFFF ); - } - } -} - -//------------------------------------------------------------------------------ -/// \ru Выделить память указанного размера. \en Allocate memory of the given size. \~ \ingroup Base_Tools -// --- -inline void * Allocate( size_t size, const char * ) // className ) -{ - void * ptr = ::malloc( size ); - // \ru Дабы работал _msize: void * ptr = ::operator new( size ); \en For working of _msize: void * ptr = ::operator new( size ); - - if ( ptr ) { - ::memset( ptr, 0xFF, size ); - } - return ptr; -} - -//------------------------------------------------------------------------------ -/// \ru Выделить память указанного размера под массив. \en Allocate memory of the given size for an array. \~ \ingroup Base_Tools -// --- -inline void * AllocateArray( size_t size, const char * ) // className ) -{ - void * ptr = ::malloc( size ); - // \ru Дабы работал _msize: void *ptr = ::operator new [] ( size ); \en For working of _msize: void *ptr = ::operator new [] ( size ); - - if ( ptr ) { -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ - ::memset( ptr, 0xFFFFFFFF, size ); // \ru OV - надо доработать для 64-бит \en OV - it should be adapted for the 64-bit version -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ - } - return ptr; -} - -//------------------------------------------------------------------------------ -/// \ru Освободить память указанного размера. \en Free memory of the given size. \~ \ingroup Base_Tools -// --- -inline void Free( void * ptr, size_t size, const char * ) // className ) -{ - if ( ptr ) { - ::CheckPointerAndValue( ptr, size ); - -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ - size_t ptr_size = ::_msize( ptr ); - C3D_ASSERT( ptr_size > 0 && ptr_size < 0xFFFFFFFF ); // \ru Надо доработать для 64-бит. \en It should be adapted for the 64-bit version. - if ( ptr_size ) { - C3D_ASSERT( size <= ptr_size ); - ::memset( ptr, 0xEE, ptr_size ); - } -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ - - ::free( ptr ); - } -} - -//------------------------------------------------------------------------------ -/// \ru Освободить память, выделенную под массив. \en Free the memory allocated for the array. \~ \ingroup Base_Tools -// --- -// \ru ЯТ можно перегрузить в классах operator delete [] ( void *, size_t ) и передать \en ЯТ it is pertinent to overload the operator delete [] ( void *, size_t ) and pass -// \ru в эту функцию size_t size, но это будет не размер массива, а размер Type, \en to this function size_t size, but this will be not the size of an array but the size of 'Type', -// \ru массив которых распределялся. То есть эта информация здесь не нужна (делать \en an array of which was not distribute. I.e. this information is not needed here ( -// \ru ::memset не нее НЕЛЬЗЯ!) \en it is forbidden to do ::memset here) -// --- -inline void FreeArray( void * ptr, const char * ) // className ) -{ - if ( ptr ) { - ::CheckPointerAndValue( ptr, 0/*size*/ ); - -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ - size_t size = ::_msize( ptr ); - C3D_ASSERT( size > 0 && size < 0xFFFFFFFF ); // \ru OV - надо доработать для 64-бит \en OV - it should be adapted for the 64-bit version - ::CheckPointerAndValue( ptr, size ); - if ( size ) - ::memset( ptr, 0xEE, size ); -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ - - ::free( ptr ); - } -} - -#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ - - -#ifdef __REALLOC_ARRAYS_STATISTIC_ - -struct OneArrayTypeStatistic { -public: - size_t reallocCountSuccess; // \ru кол-во успешных перераспределений памяти \en A number of successfully reallocations of the memory - size_t firstAlloc ; // \ru кол-во первичных распределений \en the number of primary allocations - size_t lastAlloc ; // \ru кол-во освобождений \en the number of releases - size_t realAllocIncremet ; // \ru кол-во запросов на увеличение \en the number of requests for an increment - size_t realAllocDecremet ; // \ru кол-во запросов на уменьшение \en the number of requests for a decrement - size_t fullLength ; // \ru суммарный размер в байтах \en the total size in bites - size_t maxOneArrayLength ; // \ru максимальный размер одного массива \en the minimal size of one array - size_t sumCurrLength ; // \ru суммарный размер памяти во всех массивах этого типа в данный момент \en the total size of the memory in all arrays of this type at this moment - size_t maxOneTimeLength ; // \ru максимальный одновременный размер памяти во всех массивах этого типа \en the maximum simultaneous size of the memory in all arrays of this type - size_t minDelta ; // \ru минимальное приращение \en minimum increment - size_t maxDelta ; // \ru максимальное приращение \en maximum increment -public: - OneArrayTypeStatistic() { Clear(); } - void Clear() { - reallocCountSuccess = 0; - firstAlloc = 0; - lastAlloc = 0; - realAllocIncremet = 0; - realAllocDecremet = 0; - fullLength = 0; - maxOneArrayLength = 0; - sumCurrLength = 0; - maxOneTimeLength = 0; - minDelta = SYS_MAX_T; // \ru минимальное приращение \en minimum increment - maxDelta = 0; // \ru максимальное приращение \en maximum increment - } -}; - -const size_t STAT_ARRAY_COUNT = 6; -static OneArrayTypeStatistic statisticArray[STAT_ARRAY_COUNT] - = { OneArrayTypeStatistic(), OneArrayTypeStatistic(), OneArrayTypeStatistic(), - OneArrayTypeStatistic(), OneArrayTypeStatistic(), OneArrayTypeStatistic() }; - -static size_t allReallocCount = 0; - -//------------------------------------------------------------------------------ -// \ru Уменьшение uint с проверкой \en A decrement of uint with the check -// --- -inline void DecrementUint( size_t & val, size_t delta ) { - val = (delta < val) ? (val - delta) : 0; -} - -//------------------------------------------------------------------------------ -/// \ru Статистика изменений размера массива. \en Statistics of array size changes. \~ \ingroup Base_Tools -// arrayType : -// \ru 0 - SArray (или наследники), \en 0 -SAray (or inheritors) -// \ru 1 - RParray (или наследники), \en 1 -RPAray (or inheritors) -// 2 - Array2, -// 3 - LiSArray, -// 4 - CcArray, -// \ru 5 - неопознанные (вообще-то, такого не должно быть) \en 5 - not defined (it should not happen) -// --- -inline void ReallocArrayStatistic( void * oldParr, size_t oldSize, - void * newParr, size_t newSize, - uint arrayType ) -{ - if ( oldParr || newSize ) { - allReallocCount++; - - // \ru найдем статистическую запись про данный тип массива \en find a statistic record about the given type of array - size_t index = (size_t)arrayType; - if ( index >= STAT_ARRAY_COUNT ) - index = STAT_ARRAY_COUNT - 1; - OneArrayTypeStatistic & stat = statisticArray[index]; - - if ( newSize > stat.maxOneArrayLength ) - stat.maxOneArrayLength = newSize; - - if ( !oldParr ) { // \ru первичное распределение \en primary allocation - stat.firstAlloc++; - stat.fullLength += newSize; // \ru общее кол-во байт в этом типе массива \en the total number of bites in this type of an array - stat.sumCurrLength += newSize; // \ru суммарный размер памяти во всех массивах этого типа в данный момент \en the total size of the memory in all arrays of this type at this moment - } - - if ( oldParr && !newSize ) { // \ru полное освобождение \en full release - stat.lastAlloc++; - // \ru максимальный одновременный размер памяти во всех массивах этого типа \en the maximum simultaneous size of the memory in all arrays of this type - if ( stat.sumCurrLength > stat.maxOneTimeLength ) - stat.maxOneTimeLength = stat.sumCurrLength; - // \ru суммарный размер памяти во всех массивах этого типа в данный момент \en the total size of the memory in all arrays of this type at this moment - ::DecrementUint( stat.sumCurrLength, oldSize ); - } - - if ( oldParr && newSize > oldSize ) { // \ru запрос на увеличение \en a request to increase - stat.realAllocIncremet++; - size_t delta = newSize - oldSize; - stat.fullLength += delta; // \ru общее кол-во байт в этом типе массива \en the total number of bites in this type of an array - stat.sumCurrLength += delta; // \ru суммарный размер памяти во всех массивах этого типа в данный момент \en the total size of the memory in all arrays of this type at this moment - - if ( delta < stat.minDelta ) - stat.minDelta = delta; // \ru минимальное приращение \en minimum increment - if ( delta > stat.minDelta ) - stat.maxDelta = delta; // \ru максимальное приращение \en maximum increment - } - - if ( oldParr && newSize && newSize < oldSize ) { // \ru запрос на уменьшение \en a request to decrease - stat.realAllocDecremet++; - // \ru максимальный одновременный размер памяти во всех массивах этого типа \en the maximum simultaneous size of the memory in all arrays of this type - if ( stat.sumCurrLength > stat.maxOneTimeLength ) - stat.maxOneTimeLength = stat.sumCurrLength; - // \ru суммарный размер памяти во всех массивах этого типа в данный момент \en the total size of the memory in all arrays of this type at this moment - ::DecrementUint( stat.sumCurrLength, oldSize - newSize ); - } - -#ifdef USE_REALLOC_IN_ARRAYS - if ( oldParr && oldParr == newParr && newSize != oldSize ) - stat.reallocCountSuccess++; -#endif // USE_REALLOC_IN_ARRAYS - } -} - - -//------------------------------------------------------------------------------ -/// \ru Отчет по статистике изменений размера массива. \en A report by the statistics of array size changes. \~ \ingroup Base_Tools -// --- -inline void ReallocReport( bool clear, const char * title = NULL ) -{ - std::string text( title ); - - if ( text.length() > 0 ) - text.append( "\n" ); - - char buf[256]; - ::sprintf( buf, "Общее кол-во realloc %d", ::LoUint32( allReallocCount ) ); - text.append( buf ); - - for ( size_t i = 0; i < STAT_ARRAY_COUNT; i++ ) { - OneArrayTypeStatistic & stat = statisticArray[i]; - - // \ru если данных нет, то и писать про них не будем \en if there is no data then we will not write about it - if ( stat.firstAlloc || stat.lastAlloc || stat.realAllocIncremet || stat.realAllocDecremet ) { - - switch ( i ) { - case 0 : text.append( "\n\n SArray (или наследники)" ); break; - case 1 : text.append( "\n\n RParray (или наследники)" ); break; - case 2 : text.append( "\n\n Array2" ); break; - case 3 : text.append( "\n\n LiSArray (или наследники)" ); break; - case 4 : text.append( "\n\n CcArray" ); break; - case 5 : text.append( "\n\n неопознанные" ); break; - } - - ::sprintf( buf, "\n всего байт \t %d", ::LoUint32( stat.fullLength ) ); - text.append( buf ); - ::sprintf( buf, "\n макс.размер \t %d", ::LoUint32( stat.maxOneArrayLength ) ); - text.append( buf ); - ::sprintf( buf, "\n первичных \t %d", ::LoUint32( stat.firstAlloc ) ); - text.append( buf ); - ::sprintf( buf, "\n освобождений \t %d", ::LoUint32( stat.lastAlloc ) ); - text.append( buf ); - if ( stat.realAllocIncremet ) { - ::sprintf( buf, "\n на увеличение \t %d", ::LoUint32( stat.realAllocIncremet ) ); - text.append( buf ); - } - if ( stat.realAllocDecremet ) { - ::sprintf( buf, "\n на уменьшение \t %d", ::LoUint32( stat.realAllocDecremet ) ); - text.append( buf ); - } -#ifdef USE_REALLOC_IN_ARRAYS - if ( stat.reallocCountSuccess ) { - ::sprintf( buf, "\n удачных realloc \t %d", ::LoUint32( stat.reallocCountSuccess ) ); - text.append( buf ); - } -#endif - ::sprintf( buf, "\n max одновременно %d", ::LoUint32( stat.maxOneTimeLength ) ); - text.append( buf ); - if ( stat.realAllocIncremet ) { - ::sprintf( buf, "\n Delta (min, max) \t %d, %d", ::LoUint32( stat.minDelta ), ::LoUint32( stat.maxDelta ) ); - text.append( buf ); - } - } - } - - { - const char * outName = "C:\\Logs\\ADRAFT_TTEST.txt"; - std::ofstream out( outName, std::ios::out|std::ios::app ); - out << "\n Статистика использования памяти \n"; - //out << text; - out << "\n"; - } - - if ( clear ) { - // \ru очистить, чтобы в следующий раз цифры были новые, а не накопленные \en clear to renew numbers - allReallocCount = 0; - for ( size_t i = 0; i < STAT_ARRAY_COUNT; i++ ) - statisticArray[i].Clear(); - } -} - -#endif // __REALLOC_ARRAYS_STATISTIC_ - - -//------------------------------------------------------------------------------ -// \ru Использовать realloc для изменения размера массивов \en Use realloc to change arrays sizes -// \ru (если не определено, то по-старому, через new и delete) \en (if it is not defined then use new and delete operators) -//--- -#ifdef USE_REALLOC_IN_ARRAYS - -#ifdef C3D_DEBUG - -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ -//------------------------------------------------------------------------------ -/// \ru Функция перезахватов памяти в массивах. \en Function of memory reallocation in arrays. \~ \ingroup Base_Tools -// --- -inline void * ReallocArraySize( void * arr_parr, size_t newBytesCount, bool clear ) -#else // __MEMSET_USED_FREE_HEAP_HEAR__ -//------------------------------------------------------------------------------ -/// \ru Функция перезахватов памяти в массивах. \en Function of memory reallocation in arrays. \~ \ingroup Base_Tools -// --- -inline void * ReallocArraySize( void * arr_parr, size_t newBytesCount, bool ) -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ -{ -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ - if ( newBytesCount == 0 || clear ) { - size_t arr_parr_size = ::_msize( arr_parr ); - C3D_ASSERT( arr_parr ? (arr_parr_size > 0 && arr_parr_size < 0xFFFFFFFF) : true ); // \ru OV - надо доработать для 64-бит \en OV - it should be adapted for the 64-bit version - if ( arr_parr_size ) - ::memset( arr_parr, 0xEE, arr_parr_size ); - } -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ - -#if defined( _AFXDLL ) && defined( C3D_DEBUG ) - void * tmp_parr = _realloc_dbg( arr_parr, newBytesCount, _NORMAL_BLOCK, __FILE__, __LINE__ ); -#else - void * tmp_parr = ::realloc( arr_parr, newBytesCount ); -#endif - - PRECONDITION( newBytesCount == 0 || tmp_parr != NULL ); // \ru проверка на нехватку памяти в массивах \en check the memory deficit in arrays - -#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ - if ( clear ) { - size_t tmp_parr_size = ::_msize( tmp_parr ); - C3D_ASSERT( tmp_parr ? (tmp_parr_size > 0 && tmp_parr_size < 0xFFFFFFFF) : true ); // \ru OV - надо доработать для 64-бит \en OV - it should be adapted for the 64-bit version - if ( tmp_parr_size ) - ::memset( tmp_parr, 0xEE, tmp_parr_size ); - } -#endif // __MEMSET_USED_FREE_HEAP_HEAR__ - - return tmp_parr; -} - -#define REALLOC_ARRAY_SIZE(p,s,c) ::ReallocArraySize((p),(s),(c)) -#else // C3D_DEBUG -#define REALLOC_ARRAY_SIZE(p,s,c) ::realloc((p),(s)) -#endif // C3D_DEBUG - -#endif // USE_REALLOC_IN_ARRAYS - - -#endif // __MEMORY_DEBUG_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Контроль выделения памяти под отладкой. + \en Memory allocation control during the debugging process. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef __MEMORY_DEBUG_H +#define __MEMORY_DEBUG_H + +#include +#include + +//////////////////////////////////////////////////////////////////////////////// +// \ru Макросы для переключения контроля выделения памяти находятся в math_cfg.h +// \en Macros for switching control of memory allocation are in math_cfg.h +//////////////////////////////////////////////////////////////////////////////// + +#ifdef C3D_DEBUG + #if defined(C3D_MacOS) // mac + #include + #elif defined(C3D_FreeBSD) + #include + #else + #include + #endif // mac + + #ifndef __DISABLE_MEMORY_CONTROL__ // \ru Чтобы можно было отключать в других проектах \en To allow to disable it in other projects + #define USE_REALLOC_IN_ARRAY + #endif // __DISABLE_MEMORY_CONTROL__ +#endif // C3D_DEBUG + + +#ifdef __REALLOC_ARRAYS_STATISTIC_ +#include +#include + +//------------------------------------------------------------------------------ +/** + \brief \ru Класс для контроля выделения памяти под отладкой. + \en Class for controling memory allocation during the debugging process.\~ + \ingroup Base_Tools +*/ +//--- +class MATH_CLASS MemoryChecker +{ +public: + + /// \ru Получить указатель на синглтон класса. \en Get pointer to the class singleton. + static MemoryChecker * Get(); + + /// \ru Перезапуск сбора статистики. Очистить, чтобы в следующий раз цифры были новые, а не накопленные. + /// \en Restart collecting statistics. Clear to renew numbers. + virtual void RestartStatistic() = 0; + + /// \ru Статистика изменений размера массива. \en Statistics of array size changes. + // arrayType : + // \ru 0 - SArray (или наследники), \en 0 -SAray (or inheritors) + // \ru 1 - RParray (или наследники), \en 1 -RPAray (or inheritors) + // 2 - Array2, + // 3 - LiSArray, + // 4 - CcArray, + // \ru 5 - неопознанные (вообще-то, такого не должно быть) \en 5 - not defined (it should not happen) + 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; + +}; + +//------------------------------------------------------------------------------ +/// \ru Дополнить статистику изменений размера массива. \en Add statistics of array size changes. +//--- +#define REALLOC_ARRAY_STATISTICS(oldParr,oldSize,newParr,newSize,arrayType) \ +MemoryChecker::Get()->ReallocArrayStatistic( oldParr, oldSize, newParr, newSize, arrayType ); + +#endif + +#if defined(__DEBUG_MEMORY_ALLOCATE_FREE_) || defined(USE_REALLOC_IN_ARRAYS) + #define C3D_INVALID_UINT32_1 SYS_MAX_UINT32 + #define C3D_INVALID_UINT32_2 0xEEEEEEEE + #define C3D_INVALID_UINT16_1 SYS_MAX_UINT16 + #define C3D_INVALID_UINT16_2 0xEEEE + #define C3D_MEMORY_FILL_VALUE 0xEE + #ifdef PLATFORM_64 + #define C3D_INVALID_ADDR_1 0xFFFFFFFFFFFFFFFF + #define C3D_INVALID_ADDR_2 0xEEEEEEEEEEEEEEEE + #else // PLATFORM_64 + #define C3D_INVALID_ADDR_1 0xFFFFFFFF + #define C3D_INVALID_ADDR_2 0xEEEEEEEE + #endif // PLATFORM_64 +#endif // (_DEBUG_MEMORY_ALLOCATE_FREE_ || USE_REALLOC_IN_ARRAYS) + +#ifdef __DEBUG_MEMORY_ALLOCATE_FREE_ + +//------------------------------------------------------------------------------ +/// \ru Проверить указатель и значение. \en Check pointer and value. \~ \ingroup Base_Tools +// --- +inline void CheckPointerAndValue( void * ptr, size_t size ) +{ +#if defined (C3D_WINDOWS) && !defined(ALL_WARNINGS) // Set warnings level +#pragma warning(disable: 4312) +#endif + PRECONDITION( ptr != (ptrdiff_t *)C3D_INVALID_ADDR_2 ); + PRECONDITION( ptr != (ptrdiff_t *)C3D_INVALID_ADDR_1 ); +#if defined (C3D_WINDOWS) && !defined(ALL_WARNINGS) // Set warnings level +#pragma warning(default: 4312) +#endif + + if ( ptr ) { + if ( size > 11 ) { + uint32 * _ptr = (uint32 *)ptr; + uint32 value1 = *_ptr++; + uint32 value2 = *_ptr++; + uint32 value3 = *_ptr; + PRECONDITION( value1 != C3D_INVALID_UINT32_2 || value2 != C3D_INVALID_UINT32_2 || value3 != C3D_INVALID_UINT32_2 ); + PRECONDITION( value1 != C3D_INVALID_UINT32_1 || value2 != C3D_INVALID_UINT32_1 || value3 != C3D_INVALID_UINT32_1 ); + } + else if ( size > 7 ) { + uint32 * _ptr = (uint32 *)ptr; + uint32 value1 = *_ptr++; + uint32 value2 = *_ptr; + PRECONDITION( value1 != C3D_INVALID_UINT32_2 && value2 != C3D_INVALID_UINT32_2 ); + PRECONDITION( value1 != C3D_INVALID_UINT32_1 || value2 != C3D_INVALID_UINT32_1 ); + } + else if ( size > 3 ) { + uint32 value = *(uint32 *)ptr; + PRECONDITION( value != C3D_INVALID_UINT32_2 ); + PRECONDITION( value != C3D_INVALID_ADDR_1 ); + } + else if ( size > 1 ) { + uint16 value = *(uint16 *)ptr; + PRECONDITION( value != C3D_INVALID_UINT16_2 ); + PRECONDITION( value != C3D_INVALID_UINT16_1 ); + } + } +} + + +//------------------------------------------------------------------------------ +/// \ru Выделить память указанного размера. \en Allocate memory of the given size. \~ \ingroup Base_Tools +// --- +inline void * Allocate( size_t size, const char * ) +{ + void * ptr = ::malloc( size ); + // \ru Дабы работал _msize: void * ptr = ::operator new( size ); \en For working of _msize: void * ptr = ::operator new( size ); + + if ( ptr ) { + ::memset( ptr, 0xFF, size ); + } + return ptr; +} + +//------------------------------------------------------------------------------ +/// \ru Выделить память указанного размера под массив. \en Allocate memory of the given size for an array. \~ \ingroup Base_Tools +// --- +inline void * AllocateArray( size_t size, const char * ) +{ + void * ptr = ::malloc( size ); + // \ru Дабы работал _msize: void *ptr = ::operator new [] ( size ); \en For working of _msize: void *ptr = ::operator new [] ( size ); + + if ( ptr ) { +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ + ::memset( ptr, C3D_INVALID_UINT32_1, size ); +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ + } + return ptr; +} + +//------------------------------------------------------------------------------ +/// \ru Освободить память указанного размера. \en Free memory of the given size. \~ \ingroup Base_Tools +// --- +inline void Free( void * ptr, size_t size, const char * ) +{ + if ( ptr ) { + ::CheckPointerAndValue( ptr, size ); + +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ + size_t ptr_size = ::_msize( ptr ); + PRECONDITION( ptr_size > 0 && ptr_size < SYS_MAX_T ); + if ( ptr_size ) { + PRECONDITION( size <= ptr_size ); + ::memset( ptr, C3D_MEMORY_FILL_VALUE, ptr_size ); + } +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ + + ::free( ptr ); + } +} + +//------------------------------------------------------------------------------ +/// \ru Освободить память, выделенную под массив. \en Free the memory allocated for the array. \~ \ingroup Base_Tools +// --- +// \ru ЯТ можно перегрузить в классах operator delete [] ( void *, size_t ) и передать \en ЯТ it is pertinent to overload the operator delete [] ( void *, size_t ) and pass +// \ru в эту функцию size_t size, но это будет не размер массива, а размер Type, \en to this function size_t size, but this will be not the size of an array but the size of 'Type', +// \ru массив которых распределялся. То есть эта информация здесь не нужна (делать \en an array of which was not distribute. I.e. this information is not needed here ( +// \ru ::memset не нее НЕЛЬЗЯ!) \en it is forbidden to do ::memset here) +// --- +inline void FreeArray( void * ptr, const char * ) +{ + if ( ptr ) { + ::CheckPointerAndValue( ptr, 0/*size*/ ); + +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ + size_t size = ::_msize( ptr ); + PRECONDITION( size > 0 && size < SYS_MAX_T ); + ::CheckPointerAndValue( ptr, size ); + if ( size ) + ::memset( ptr, C3D_MEMORY_FILL_VALUE, size ); +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ + + ::free( ptr ); + } +} +#endif // __DEBUG_MEMORY_ALLOCATE_FREE_ + + +#ifdef USE_REALLOC_IN_ARRAYS +//------------------------------------------------------------------------------ +/// \ru Функция перезахватов памяти в массивах. \en Function of memory reallocation in arrays. \~ \ingroup Base_Tools +// --- +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ +inline void * ReallocArraySize( void * arr_parr, size_t newBytesCount, bool clear ) +#else // __MEMSET_USED_FREE_HEAP_HEAR__ +inline void * ReallocArraySize( void * arr_parr, size_t newBytesCount, bool ) +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ +{ +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ + if ( newBytesCount == 0 || clear ) { + size_t arr_parr_size = arr_parr ? ::_msize( arr_parr ) : 0; + PRECONDITION( arr_parr ? ( arr_parr_size > 0 && arr_parr_size < SYS_MAX_T ) : true ); + if ( arr_parr_size ) + ::memset( arr_parr, C3D_MEMORY_FILL_VALUE, arr_parr_size ); + } +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ + +#if defined( _AFXDLL ) && defined( C3D_DEBUG ) + void * tmp_parr = _realloc_dbg( arr_parr, newBytesCount, _NORMAL_BLOCK, __FILE__, __LINE__ ); +#else + void * tmp_parr = ::realloc( arr_parr, newBytesCount ); +#endif + + PRECONDITION( newBytesCount == 0 || tmp_parr != NULL ); // \ru проверка на нехватку памяти в массивах \en check the memory deficit in arrays + +#ifdef __MEMSET_USED_FREE_HEAP_HEAR__ + if ( clear ) { + size_t tmp_parr_size = tmp_parr ? ::_msize( tmp_parr ) : 0; + PRECONDITION( tmp_parr ? ( tmp_parr_size > 0 && tmp_parr_size < SYS_MAX_T ) : true ); + if ( tmp_parr_size ) + ::memset( tmp_parr, C3D_MEMORY_FILL_VALUE, tmp_parr_size ); + } +#endif // __MEMSET_USED_FREE_HEAP_HEAR__ + + return tmp_parr; +} + +//------------------------------------------------------------------------------ +// \ru Использовать realloc для изменения размера массивов \en Use realloc to change arrays sizes +// \ru (если не определено, то по-старому, через new и delete) \en (if it is not defined then use new and delete operators) +//--- + +#define REALLOC_ARRAY_SIZE(p,s,c) ::ReallocArraySize((p),(s),(c)) +#else // USE_REALLOC_IN_ARRAYS +#define REALLOC_ARRAY_SIZE(p,s,c) ::realloc((p),(s)) + +#endif // USE_REALLOC_IN_ARRAYS + + +#endif // __MEMORY_DEBUG_H diff --git a/C3d/Include/tool_memory_leaks_check.h b/C3d/Include/tool_memory_leaks_check.h index 15c452e..30bb993 100644 --- a/C3d/Include/tool_memory_leaks_check.h +++ b/C3d/Include/tool_memory_leaks_check.h @@ -1,49 +1,49 @@ -//////////////////////////////////////////////////////////////////////////////// -/// Слежение за утечками -/** - \file - \brief Содержит класс MemoryLeaksVerifiable - базовый для контролируемых классов -*/ -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include - -#if ( defined(STANDARD_C11) && (_MSC_VER > 1800) ) -#define ENABLE_MEMORY_LEAKS_CHECK -#endif - - -namespace c3d // namespace C3D -{ - -#ifdef ENABLE_MEMORY_LEAKS_CHECK - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый класс для контролируемых классов. - \en . \~ - \details \ru На конструкторе объект регистрируется в менеджере утечек, в деструкторе удаляется из списка зарегистрированных. - Информация о всех объектах, которые остались в регистраторе, будет выведена. \n - \en . \n \~ - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS MemoryLeaksVerifiable -{ -protected: - MemoryLeaksVerifiable(); - virtual ~MemoryLeaksVerifiable(); -}; - -#else - -class MATH_CLASS MemoryLeaksVerifiable {}; - -#endif // ENABLE_MEMORY_LEAKS_CHECK - -} // namespace C3D - - - +//////////////////////////////////////////////////////////////////////////////// +/// Слежение за утечками +/** + \file + \brief Содержит класс MemoryLeaksVerifiable - базовый для контролируемых классов +*/ +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include + +#if ( defined(_MSC_VER) && (_MSC_VER > 1800) ) + #define ENABLE_MEMORY_LEAKS_CHECK +#endif + + +namespace c3d // namespace C3D +{ + +#ifdef ENABLE_MEMORY_LEAKS_CHECK + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый класс для контролируемых классов. + \en . \~ + \details \ru На конструкторе объект регистрируется в менеджере утечек, в деструкторе удаляется из списка зарегистрированных. + Информация о всех объектах, которые остались в регистраторе, будет выведена. \n + \en . \n \~ + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS MemoryLeaksVerifiable +{ +protected: + MemoryLeaksVerifiable(); + virtual ~MemoryLeaksVerifiable(); +}; + +#else + +class MATH_CLASS MemoryLeaksVerifiable {}; + +#endif // ENABLE_MEMORY_LEAKS_CHECK + +} // namespace C3D + + + diff --git a/C3d/Include/tool_memory_leaks_utils.h b/C3d/Include/tool_memory_leaks_utils.h index cf6659d..1becc43 100644 --- a/C3d/Include/tool_memory_leaks_utils.h +++ b/C3d/Include/tool_memory_leaks_utils.h @@ -1,64 +1,64 @@ -//////////////////////////////////////////////////////////////////////////////// -/// Утилиты Слежения за утечками -/** - \file - \brief Содержит интерфейс MemoryLeaksController - контроллер утечек памяти -*/ -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include -#include -#include - - -namespace c3d // namespace C3D -{ -#ifdef ENABLE_MEMORY_LEAKS_CHECK - -typedef std::unordered_map MemoryLeaksRegisteredData; -typedef std::unique_ptr MemoryLeaksControllerPtr; - -//---------------------------------------------------------------------------------------- -/** \brief \ru Контроллер утечек памяти. - \en Memory Leaks Controller. \~ - \details \ru Контроллер утечек памяти. При выходе из приложения, вызывается метод OnLeakDetect, в который передается информация об утечках. - \en Memory Leaks Controller. When you exit the application, the OnLeakDetect method is called, to which information about leaks is transmitted. \~ - \ingroup Base_Tools -*/ -//--- -struct MemoryLeaksController -{ - MemoryLeaksController() {} - virtual ~MemoryLeaksController() {} - virtual void OnLeakDetect( const MemoryLeaksRegisteredData & ) const = 0; -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Добавить контроллер утечек памяти. - \en Add memory leaks controller. \~ -\ingroup Base_Tools -*/ -// --- -MATH_FUNC( void ) AddController( MemoryLeaksControllerPtr ); - - -//------------------------------------------------------------------------------ -/** \brief \ru Собрать утечки. Необходимо вызвать перед выходом из приложения, чтобы выполнить именование утекающих объектов. - \en Collect leaks. The function should be called before exiting the application to names the leaking objects. \~ -\ingroup Base_Tools -*/ -// --- -MATH_FUNC( void ) CollectLeaks(); - -#else - -MATH_FUNC( void ) CollectLeaks() {} - -#endif // ENABLE_CHECK_MEMLEAK - -} // namespace c3d - +//////////////////////////////////////////////////////////////////////////////// +/// Утилиты Слежения за утечками +/** + \file + \brief Содержит интерфейс MemoryLeaksController - контроллер утечек памяти +*/ +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include +#include +#include + + +namespace c3d // namespace C3D +{ +#ifdef ENABLE_MEMORY_LEAKS_CHECK + +typedef std::unordered_map MemoryLeaksRegisteredData; +typedef std::unique_ptr MemoryLeaksControllerPtr; + +//---------------------------------------------------------------------------------------- +/** \brief \ru Контроллер утечек памяти. + \en Memory Leaks Controller. \~ + \details \ru Контроллер утечек памяти. При выходе из приложения, вызывается метод OnLeakDetect, в который передается информация об утечках. + \en Memory Leaks Controller. When you exit the application, the OnLeakDetect method is called, to which information about leaks is transmitted. \~ + \ingroup Base_Tools +*/ +//--- +struct MemoryLeaksController +{ + MemoryLeaksController() {} + virtual ~MemoryLeaksController() {} + virtual void OnLeakDetect( const MemoryLeaksRegisteredData & ) const = 0; +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Добавить контроллер утечек памяти. + \en Add memory leaks controller. \~ +\ingroup Base_Tools +*/ +// --- +MATH_FUNC( void ) AddController( MemoryLeaksControllerPtr ); + + +//------------------------------------------------------------------------------ +/** \brief \ru Собрать утечки. Необходимо вызвать перед выходом из приложения, чтобы выполнить именование утекающих объектов. + \en Collect leaks. The function should be called before exiting the application to names the leaking objects. \~ +\ingroup Base_Tools +*/ +// --- +MATH_FUNC( void ) CollectLeaks(); + +#else + +MATH_FUNC( void ) CollectLeaks() {} + +#endif // ENABLE_CHECK_MEMLEAK + +} // namespace c3d + diff --git a/C3d/Include/tool_multithreading.h b/C3d/Include/tool_multithreading.h index fd270a5..8715b2b 100644 --- a/C3d/Include/tool_multithreading.h +++ b/C3d/Include/tool_multithreading.h @@ -1,490 +1,571 @@ -//////////////////////////////////////////////////////////////////////////////// -/** -\file -\brief \ru Управление параллельной обработкой данных. - \en Managing of parallel data processing. \~ -\details \ru Управление параллельной обработкой данных.\n - \en Managing of parallel data processing. \n \~ -*/ -//////////////////////////////////////////////////////////////////////////////// -#ifndef __TOOL_MULTITHREADING_H -#define __TOOL_MULTITHREADING_H - -#include -#include - -//------------------------------------------------------------------------------ -/** -\brief \ru Режимы многопоточных вычислений. - \en Multithreading modes. \~ -\details \ru Режимы многопоточных вычислений. \n - \en Multithreading modes. \n \~ -\ingroup Data_Structures -*/ -//--- -enum MbeMultithreadedMode { - // \ru Многопоточность ядра отключена. \en Kernel multithreading is off. - mtm_Off = 0, - // \ru Включена многопоточность ядра при обработке независимых объектов (без общих данных). - // \en Kernel multithreading is ON for independent objects (without common data). - mtm_Standard = 1, - // \ru Обеспечивается потокобезопасность объектов типа MbItem. Выключена многопоточность ядра при обработке объектов, имеющих общие данные. - // \en Ensured thread-safety of objects MbItem. Kernel multithreading is OFF for objects with shared data. - mtm_SafeItems = 2, - // \ru Обеспечивается потокобезопасность объектов типа MbItem. Включена многопоточность ядра при обработке объектов с общими данными. - // \en Ensured thread-safety of objects MbItem. Kernel multithreading is ON for objects with shared data. - mtm_Items = 3, - // \ru Включена максимальная многопоточность ядра. \en Maximal kernel multithreading is ON. - mtm_Max = 31 -}; - -//------------------------------------------------------------------------------ -/** - \brief \ru Базовый класс для объектов, требующих сборки мусора. - \en Base class for objects which require a garbage collection. \~ -\details \ru Базовый класс для объектов, требующих сборки мусора. - Класс, наследующий от CacheCleaner, должен реализовать метод ResetCacheData, - который будет вызываться для сборки мусора. - \en Base class for objects which require a garbage collection. - A class, inheriting from CacheCleaner, should implement the method ResetCacheData, - which will be called for garbage collection. \~ -\ingroup Base_Tools -*/ -//--- -class MATH_CLASS CacheCleaner -{ - int subscribed; -public: - CacheCleaner(); - virtual ~CacheCleaner(); - - /** \brief \ru Подписан ли объект на сборку мусора. - \en Whether the object is subscribed for garbage collection. \~ - */ - bool IsSubscribed() { return subscribed > 0; } - - /** \brief \ru Очистить кэшированные данные. Возвращает true, если объект был отписан от сборки мусора. - \en Reset cached data. Return true if the object was unsubscribed from garbage collection.\~ - */ - virtual bool ResetCacheData() = 0; - - /** \brief \ru Подписаться на сборку мусора. - \en Subscribe for garbage collection. \~ - */ - void SubcribeOnCleaning(); - - /** \brief \ru Отписаться от сборки мусора. - \en Unsubscribe from garbage collection. \~ - */ - void UnsubcribeOnCleaning(); -}; - -//------------------------------------------------------------------------------ -/** - \brief \ru Сборщик мусора в объектах, использующих кэширование данных. - \en Garbage collector in objects which use data caching. \~ -\details \ru Сборщик мусора. По требованию очищает кэши в зарегистрированных объектах CacheCleaner, - вызывая метод ResetCacheData каждого объекта. \n - \en Garbage collector. At request clears caches in registered CacheCleaner objects - by calling the method ResetCacheData of each object. \n \~ -\ingroup Base_Tools -*/ -//--- -class MATH_CLASS MbGarbageCollection -{ -public: - - /** \brief \ru Подписать объект на сборку мусора. - \en Subscribe the object for garbage collection. \~ - */ - static void Subscribe( CacheCleaner * obj ); - - /** \brief \ru Отписать объект от сборки мусора. - \en Unsubscribe the object from garbage collection. \~ - */ - static void Unsubscribe( CacheCleaner * obj ); - - /** \brief \ru Выполнить сборку мусора. \en Perform garbage collection. - \details \ru Выполнить сборку мусора. Должна вызываться в последовательном участке кода. - При вызове в параллельном регионе ничего не делает. - \en Perform garbage collection. Should be called in sequential code. - When called in a parallel region, does nothing. - \param[in] force - \ru Если false, то инициируется сборка мусора в кэшах, созданных для потоков, которые уже завершены, - если true, то инициируется принудительная сборка мусора во всех кэшах. - \en If false, then run garbage collection in caches created for threads which are finished, - if true, then force garbage collection in all caches. - \return \ru Возвращает TRUE, если сборка проведена. \en Returns TRUE if the garbage collection is done. \~ - */ - static bool Run( bool force = false ); - - /** \brief \ru Активировать/деактивировать сбор данных для проведения сборки мусора. - По умолчанию, сбор данных для сборки мусора активирован. - \en Enable/disable collecting data for garbage collection. - By default, collecting data for garbage collection is enabled. \~ - */ - static void Enable( bool allow = true ); -}; - -//------------------------------------------------------------------------------ -// \ru Принудительно вернуть освобожденную динамическую память операционной системе. -// Может быть полезна после выполнения операций с интенсивным использованием памяти. -// \en Force to return freed heap memory to the operating system. -// May be useful after performing memory-intensive operations. -// --- -MATH_FUNC( void ) ReleaseMemory(); - -//------------------------------------------------------------------------------ -/** -\brief \ru Родительский класс данных для менеджера параллельной обработки. - \en Parent class of data for manager of parallel processing. \~ -\details \ru Родительский класс для данных, которые могут обрабатываться параллельно - с помощью менеджера кэшей. - \en Parent class for data which could be processed in parallel using the cache manager. \~ - \ingroup Base_Tools -*/ -// --- -class AuxiliaryData { -public: - AuxiliaryData() {} - AuxiliaryData( const AuxiliaryData & ) {} - virtual ~AuxiliaryData() {} - - /** \brief \ru Объединить с указанными данными. - \en Merge with specified data. - \details \ru Функция вызывается Менеджером кэшей для данных основного потока - с данными каждого многопоточного кэша в качестве параметра. - После завершения функции Менеджер кэшей удаляет многопоточный кэш. - \en The function is called by CacheManager for the main thread data with - each multithreaded cache data as a parameter. When the function completed, - the CacheManager deletes the multithreaded cache. \~ - */ - virtual void MergeWith( AuxiliaryData * ) {} -}; - -//#define CACHE_DELETE_LOCK -//------------------------------------------------------------------------------ -/** -\brief \ru Менеджер параллельной обработки данных (менеджер кэшей) с возможностью пост-обработки кэшей потоков. - \en Manager for parallel data processing (the cache manager) with support of caches post-processing. \~ -\details \ru Менеджер кэшей представляет шаблон, содержащий: - longTerm - данные главного потока при последовательном выполнении и - tcache - список кэшей с данными, которые используются при параллельном выполнении. - Каждый поток по идентификатору threadKey использует только свою копию данных. - Для многопоточной обработки зависимых (имеющих общие данные) объектов должен использоваться режим - многопоточных вычислений не ниже mtm_SafeItems. - Менеджер предоставляет функцию Postprocess() для пост-обработки кэшей, которая вызывается после - выхода из параллельных вычислений. Указанная функция итерируется по кэшам, использованным - при параллельных вычислениях, и вызывает функцию longTerm.MergeWith() с данными каждого кэша - в качестве параметра. После завершения работы функции Postprocess() кэши удаляются. \n - \en The cache manager is a template which contains: - longTerm - data of the main thread in sequential execution, and - tcache - a list of caches with data which are used in parallel calculations. - Each thread uses its own copy of data according to threadKey. - For multithreaded processing of dependent (with shared data) objects the multithreading mode mtm_SafeItems - or higher should be used. - The Manager provides a Postprocess() function for caches post-processing which is called - after exiting parallel computing. The specified function iterates through the caches used - in parallel computing and calls the function longTerm.MergeWith() with the data of the each cache - as a parameter. After the function Postprocess() finished the caches are destroyed. \n \~ -*/ -// --- -template -class CacheManager : public CacheCleaner { - struct List - { - unsigned int _id; - T* _data; - List* _next; - bool _valid; - List( unsigned int id, T* data ) : - _id( id ), - _data( data != NULL ? data : new T() ), // Always _data != NULL. - _next( NULL ), - _valid( true ) {} - ~List() { - if ( _data != NULL ) - delete _data; - _data = NULL; - if ( _next != NULL ) // Also deletes linked List. - delete _next; - _next = NULL; - } - private: - List() : _id( 0 ), _data( NULL ), _next( NULL ) {} - }; - -private: - T* longTerm; // \ru Данные главного потока при последовательном выполнении. \en Data of the main thread in sequential execution. - List* tcache; // \ru Данные, которые используются при параллельном выполнении. \en Caches which are used in parallel execution. - CommonMutex* lock; // \ru Блокировка для операций с кэшами. \en Lock for operations with caches. - -public: -#ifdef CACHE_DELETE_LOCK - CacheManager( bool createLock = false ); -#else - CacheManager( bool createLock = true ); -#endif - CacheManager( const CacheManager & ); - ~CacheManager(); - - /** \brief \ru Оператор (). Возвращает указатель на кэш (данные) текущего потока. Всегда возвращает ненулевое значение. - \en Operator (). Returns a pointer to the cache (data) of the current thread. Always returns non-null value. \~ - */ - T * operator ()(); - - /** \brief \ru Удалить данные в кэшах. Если resetLongTerm == true, удалить также данные кэша главного потока. - \en Delete caches data. If resetLongTerm == true, also delete data of the main thread cache. - */ - void Reset ( bool resetLongTerm = false ); - - /** \brief \ru Получить указатель на кэш (данные) главного потока. Всегда возвращает ненулевое значение. - Все операции с кэшем главного потока должны быть защищены блокировкой кэша. - \en Get a pointer to cache (data) of the main thread. Always returns non-null value. - All operations with the main thread cache should be protected by the cache lock. \~ - */ - T * LongTerm (); - - /** \brief \ru Получить указатель на блокировку для операций с кэшем главного потока, учитывая, исполняется ли код параллельно - Может возвращать нулевое значение (удобно для использования с ScopedLock). - \en Get a pointer to the lock for operations with the main thread cache, considering whether the code runs in parallel. - Can return null value (good for use with ScopedLock). \~ - */ - CommonMutex* GetLock() { if ( IsInParallel() ) return GetLockHard(); return lock; } - - /** \brief \ru Функция очистки, используемая сборщиком мусора. - \en Cleaning function, used by the garbage collector. \~ - */ - virtual bool ResetCacheData() { CleanAll(); return true; } - -private: - /** \brief \ru Удалить все кэши и отписаться от сборки мусора. Должна вызываться в последовательном участке кода. - \en Delete all caches and unsubscribe from the garbage collection. Should be called in sequential code. \~ - */ - void CleanAll( bool doPostproc = true ); - - /** \brief \ru Получить указатель на блокировку для операций с кэшем главного потока. Всегда возвращает ненулевое значение. - \en Get a pointer to the lock for operations with the main thread cache. Always returns non-null value. \~ - */ - CommonMutex* GetLockHard(); - - /** \brief \ru Пост-обработка кэшей после выхода из параллельных вычислений. - \en Caches post-processing after exiting the parallel calculations. \~ - */ - void Postprocess(); - - CacheManager & operator = ( const CacheManager & ); // \ru Не разрешен. \en Not allowed. -}; - - -//------------------------------------------------------------------------------ -// \ru Конструктор. \en Constructor. -// --- -template -inline CacheManager::CacheManager( bool createLock ) - : longTerm ( NULL ) - , tcache ( NULL ) - , lock ( NULL ) -{ - if ( createLock ) - lock = new CommonMutex(); -} - - -#define C3D_NULLKEY 0 - -//------------------------------------------------------------------------------ -// \ru Конструктор. \en Constructor. -// --- -template -inline CacheManager::CacheManager( const CacheManager & item ) - : longTerm ( NULL ) - , tcache ( NULL ) - , lock ( NULL ) -{ - if ( item.longTerm != NULL ) - longTerm = new T( *item.longTerm ); -#ifndef CACHE_DELETE_LOCK - lock = new CommonMutex(); -#endif -} - - -//------------------------------------------------------------------------------ -// \ru Деструктор. \en Destructor. -// --- -template -inline CacheManager::~CacheManager() -{ - CleanAll( false ); - if ( longTerm != NULL ) - delete longTerm; - if ( lock != NULL ) - delete lock; -} - -//------------------------------------------------------------------------------ -// \ru Получить указатель на кэш главного потока. Всегда возвращает ненулевое значение. -// Все операции с кэшем главного потока должны быть защищены блокировкой кэша. -// \en Get a pointer to the main thread cache. Always returns non-null value. -// All operations with the main thread cache should be protected by the cache lock. -// --- -template -inline T* CacheManager::LongTerm () -{ - if ( longTerm == NULL ) - longTerm = new T(); - return longTerm; -} - -//------------------------------------------------------------------------------ -// \ru Получить указатель на блокировку для операций с кэшем главного потока. Всегда возвращает ненулевое значение. -// \en Get a pointer to the lock for operations with the main thread cache. Always returns non-null value. -// --- -template -inline CommonMutex* CacheManager::GetLockHard() -{ - if ( lock == NULL ) { - CommonMutex* ll = GetGlobalLock(); - ll->lock(); - if ( lock == NULL ) - lock = new CommonMutex(); - ll->unlock(); - } - return lock; -} - -//------------------------------------------------------------------------------ -// \ru Оператор (). Возвращает указатель на кэш текущего потока (всегда ненулевое значение). -// \en Operator (). Returns a pointer to the current thread cache (always non-null value). -// --- -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() ) - - if ( !IsSafeMultithreading() || !IsInParallel() ) { - CleanAll(); - return LongTerm(); - } - - T * res = NULL; - unsigned int threadKey = GetThreadKey(); - - if ( tcache == 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 ) { - tcache = new List( threadKey, INIT_BY_LONGTERM ); - return tcache->_data; - } - } - } - - List* entry = tcache; - while( entry != NULL ) { - if ( entry->_id == threadKey ) { - if ( !entry->_valid ) { - delete entry->_data; - entry->_data = INIT_BY_LONGTERM; - entry->_valid = true; - } - return entry->_data; - } - // \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 ) - break; - entry = entry->_next; - } - res = INIT_BY_LONGTERM; - List* newList = new List( threadKey, res ); - { - // \ru Используется блокировка при изменении списка кэшей. \en Use lock when changing the cache list. - ScopedLock sl( GetLock(), false ); - // \ru На данный момент, entry может быть не последним элементом в списке. - // \en At that point, entry could be not a last element in the list. - while ( entry->_next != NULL ) { - entry = entry->_next; - } - entry->_next = newList; - } // ScopedLock - - return res; - -} - - -//------------------------------------------------------------------------------ -// \ru Удалить данные в кэшах. Если resetLongTerm == true, удалить также данные кэша главного потока. -// \en Delete caches data. If resetLongTerm == true, also delete data of the main thread cache. -// --- -template -inline void CacheManager::Reset( bool resetLongTerm ) -{ - if ( tcache != NULL ) { - ScopedLock sl( GetLock() ); - List* entry = tcache; - while ( entry != NULL ) { - entry->_valid = false; - entry = entry->_next; - } - } - if ( resetLongTerm ) { - ScopedLock sl( GetLock() ); - delete longTerm; - longTerm = NULL; - // \ru Если нет параллельности, удаляется блокировка. \en If no parallelism, delete the lock. -#ifdef CACHE_DELETE_LOCK - if ( !sl.IsLocked() ) { - if ( lock != NULL ) - delete lock; - lock = NULL; - } -#endif - } -} - -//------------------------------------------------------------------------------ -// \ru Удалить все кэши и отписаться от сборки мусора. Должна вызываться в последовательном участке кода. -// \en Delete all caches and unsubscribe from the garbage collection.Should be called in sequential code. -// --- -template -inline void CacheManager::CleanAll( bool doPostproc ) -{ - if ( tcache != NULL ) { - if ( IsSubscribed() ) - UnsubcribeOnCleaning(); - if ( doPostproc ) - Postprocess(); - delete tcache; - tcache = NULL; - } -#ifdef CACHE_DELETE_LOCK - if ( lock != NULL ) { - delete lock; - lock = NULL; - } -#endif -} - -//------------------------------------------------------------------------------ -// \ru Пост-обработка кэшей после выхода из параллельных вычислений. -// \en Caches post-processing after exiting the parallel calculations. \~ -// --- -template -inline void CacheManager::Postprocess() -{ - T * main = LongTerm(); - List * entry = tcache; - while ( entry != NULL ) { - main->MergeWith( entry->_data );// Incorporate thread data into main thread data. - entry = entry->_next; - } -} - -#endif // __TOOL_MULTITHREADING_H +//////////////////////////////////////////////////////////////////////////////// +/** +\file +\brief \ru Управление параллельной обработкой данных. + \en Managing of parallel data processing. \~ +\details \ru Управление параллельной обработкой данных.\n + \en Managing of parallel data processing. \n \~ +*/ +//////////////////////////////////////////////////////////////////////////////// +#ifndef __TOOL_MULTITHREADING_H +#define __TOOL_MULTITHREADING_H + +#include +#include +#include + +//------------------------------------------------------------------------------ +/** +\brief \ru Режимы многопоточных вычислений. + \en Multithreading modes. \~ +\details \ru Режимы многопоточных вычислений. Режим многопоточности ядра управляет механизмом потокобезопасности объектов ядра и определяет, какие операции ядра будут распараллеливаться. \n + \en Multithreading modes. Multithreading mode of the kernel manages the mechanism of thread-safity of the kernel objects and defines which \n \~ +\ingroup Data_Structures +*/ +//--- +enum MbeMultithreadedMode { + mtm_Off = 0, ///< \ru Многопоточность ядра отключена. \en Kernel multithreading is off. + mtm_Standard = 1, ///< \ru Включена многопоточность ядра при обработке независимых объектов (без общих данных). \en Kernel multithreading is ON for independent objects (without common data). + mtm_SafeItems = 2, ///< \ru Обеспечивается потокобезопасность объектов типа MbItem. Выключена многопоточность ядра при обработке объектов, имеющих общие данные. \en Ensured thread-safety of objects MbItem. Kernel multithreading is OFF for objects with shared data. + mtm_Items = 3, ///< \ru Обеспечивается потокобезопасность объектов типа MbItem. Включена многопоточность ядра при обработке объектов с общими данными. \en Ensured thread-safety of objects MbItem. Kernel multithreading is ON for objects with shared data. + mtm_Max = 31 ///< \ru Включена максимальная многопоточность ядра. \en Maximal kernel multithreading is ON. +}; + +//------------------------------------------------------------------------------ +/** + \brief \ru Базовый класс для объектов, требующих сборки мусора. + \en Base class for objects which require a garbage collection. \~ +\details \ru Базовый класс для объектов, требующих сборки мусора. + Класс, наследующий от CacheCleaner, должен реализовать метод ResetCacheData, + который будет вызываться для сборки мусора. + \en Base class for objects which require a garbage collection. + A class, inheriting from CacheCleaner, should implement the method ResetCacheData, + which will be called for garbage collection. \~ +\ingroup Base_Tools +*/ +//--- +class MATH_CLASS CacheCleaner +{ + int subscribed; +public: + CacheCleaner(); + virtual ~CacheCleaner(); + + /** \brief \ru Подписан ли объект на сборку мусора. + \en Whether the object is subscribed for garbage collection. \~ + */ + bool IsSubscribed() { return subscribed > 0; } + + /** \brief \ru Очистить кэшированные данные. Возвращает true, если объект был отписан от сборки мусора. + \en Reset cached data. Return true if the object was unsubscribed from garbage collection.\~ + */ + virtual bool ResetCacheData() = 0; + + /** \brief \ru Принудительное удаление всех кэшей (используется сборщиком мусора). + \en Forced deletion of all caches (used by the garbage collector). \~ + */ + virtual void HardReset() = 0; + + /** \brief \ru Подписаться на сборку мусора. + \en Subscribe for garbage collection. \~ + */ + void SubcribeOnCleaning(); + + /** \brief \ru Отписаться от сборки мусора. + \en Unsubscribe from garbage collection. \~ + */ + void UnsubcribeOnCleaning(); +}; + +//------------------------------------------------------------------------------ +/** + \brief \ru Сборщик мусора в объектах, использующих кэширование данных. + \en Garbage collector in objects which use data caching. \~ +\details \ru Сборщик мусора. По требованию очищает кэши в зарегистрированных объектах CacheCleaner, + вызывая метод ResetCacheData каждого объекта. \n + \en Garbage collector. At request clears caches in registered CacheCleaner objects + by calling the method ResetCacheData of each object. \n \~ +\ingroup Base_Tools +*/ +//--- +class MATH_CLASS MbGarbageCollection +{ +public: + + /** \brief \ru Подписать объект на сборку мусора. + \en Subscribe the object for garbage collection. \~ + */ + static void Subscribe( CacheCleaner * obj ); + + /** \brief \ru Отписать объект от сборки мусора. + \en Unsubscribe the object from garbage collection. \~ + */ + static void Unsubscribe( CacheCleaner * obj ); + + /** \brief \ru Выполнить сборку мусора. \en Perform garbage collection. + \details \ru Функция должна вызываться в последовательном участке кода. + При вызове в параллельном регионе ничего не делает. + Вызывает метод ResetCacheData каждого объекта. + \en The function should be called in sequential code. + When called in a parallel region, does nothing. + Calls method ResetCacheData of each object. + \param[in] force - \ru Если false, то инициируется сборка мусора в кэшах, созданных для потоков, которые уже завершены, + если true, то инициируется принудительная сборка мусора во всех кэшах. + \en If false, then run garbage collection in caches created for threads which are finished, + if true, then force garbage collection in all caches. + \return \ru Возвращает TRUE, если сборка проведена. \en Returns TRUE if the garbage collection is done. \~ + */ + static bool Run( bool force = false ); + + /** \brief \ru Сбросить все зарегистрированные кэши. \en Reset all registered caches. + \details \ru Сбросить все зарегистрированные кэш после фатальной ошибки. + Должна вызываться в последовательном участке кода. При вызове в параллельном регионе ничего не делает. + Вызывает метод HardReset каждого объекта. + \en Reset all registered caches after fatal error. Should be called in sequential code. + When called in a parallel region, does nothing. + Calls method HardReset of each object. + */ + static void Reset(); + + /** \brief \ru Активировать/деактивировать сбор данных для проведения сборки мусора. + По умолчанию, сбор данных для сборки мусора активирован. + \en Enable/disable collecting data for garbage collection. + By default, collecting data for garbage collection is enabled. \~ + */ + static void Enable( bool allow = true ); +}; + +//------------------------------------------------------------------------------ +// \ru Принудительно вернуть освобожденную динамическую память операционной системе. +// Может быть полезна после выполнения операций с интенсивным использованием памяти. +// \en Force to return freed heap memory to the operating system. +// May be useful after performing memory-intensive operations. +// --- +MATH_FUNC( void ) ReleaseMemory(); + +//------------------------------------------------------------------------------ +/** +\brief \ru Родительский класс данных для менеджера параллельной обработки. + \en Parent class of data for manager of parallel processing. \~ +\details \ru Родительский класс для данных, которые могут обрабатываться параллельно + с помощью менеджера кэшей. + \en Parent class for data which could be processed in parallel using the cache manager. \~ + \ingroup Base_Tools +*/ +// --- +class AuxiliaryData { +public: + AuxiliaryData() {} + AuxiliaryData( const AuxiliaryData & ) {} + virtual ~AuxiliaryData() {} + + /** \brief \ru Объединить с указанными данными. + \en Merge with specified data. + \details \ru Функция вызывается Менеджером кэшей для данных основного потока + с данными каждого многопоточного кэша в качестве параметра. + Должна возвращать true, если MergeWith() не пустая и объединение произошло, + или false в противном случае. + После завершения функции Менеджер кэшей удаляет многопоточный кэш. + \en The function is called by CacheManager for the main thread data with + each multithreaded cache data as a parameter. + Should return true if MergeWith() is not empty and the merge occurred, + or false otherwise. + When the function completed, the CacheManager deletes the multithreaded cache. \~ + */ + virtual bool MergeWith( AuxiliaryData * ) { return false; } +}; + +//#define CACHE_DELETE_LOCK +//------------------------------------------------------------------------------ +/** +\brief \ru Менеджер параллельной обработки данных (менеджер кэшей) с возможностью пост-обработки кэшей потоков. + \en Manager for parallel data processing (the cache manager) with support of caches post-processing. \~ +\details \ru Менеджер кэшей представляет шаблон, содержащий: + longTerm - данные главного потока при последовательном выполнении и + tcache - список кэшей с данными, которые используются при параллельном выполнении. + Каждый поток по идентификатору threadKey использует только свою копию данных. + Для многопоточной обработки зависимых (имеющих общие данные) объектов должен использоваться режим + многопоточных вычислений не ниже mtm_SafeItems. + Менеджер предоставляет функцию Postprocess() для пост-обработки кэшей, которая вызывается после + выхода из параллельных вычислений. Указанная функция итерируется по кэшам, использованным + при параллельных вычислениях, и вызывает функцию longTerm.MergeWith() с данными каждого кэша + в качестве параметра. После завершения работы функции Postprocess() кэши удаляются. \n + \en The cache manager is a template which contains: + longTerm - data of the main thread in sequential execution, and + tcache - a list of caches with data which are used in parallel calculations. + Each thread uses its own copy of data according to threadKey. + For multithreaded processing of dependent (with shared data) objects the multithreading mode mtm_SafeItems + or higher should be used. + The Manager provides a Postprocess() function for caches post-processing which is called + after exiting parallel computing. The specified function iterates through the caches used + in parallel computing and calls the function longTerm.MergeWith() with the data of the each cache + as a parameter. After the function Postprocess() finished the caches are destroyed. \n \~ +*/ +// --- +template +class CacheManager : public CacheCleaner { + struct List + { + unsigned int _id; + T* _data; + List* _next; + bool _valid; + List( unsigned int id, T* data ) : + _id( id ), + _data( data != NULL ? data : new T() ), // Always _data != NULL. + _next( NULL ), + _valid( true ) {} + ~List() { + if ( _data != NULL ) + delete _data; + _data = NULL; + if ( _next != NULL ) // Also deletes linked List. + delete _next; + _next = NULL; + } + private: + List() : _id( 0 ), _data( NULL ), _next( NULL ) {} + }; + +private: + T* longTerm; // \ru Данные главного потока при последовательном выполнении. \en Data of the main thread in sequential execution. + List* tcache; // \ru Данные, которые используются при параллельном выполнении. \en Caches which are used in parallel execution. + CommonMutex* lock; // \ru Блокировка для операций с кэшами. \en Lock for operations with caches. + +public: +#ifdef CACHE_DELETE_LOCK + CacheManager( bool createLock = false ); +#else + CacheManager( bool createLock = true ); +#endif + CacheManager( const CacheManager & ); + ~CacheManager(); + + /** \brief \ru Оператор (). Возвращает указатель на кэш (данные) текущего потока. Всегда возвращает ненулевое значение. + \en Operator (). Returns a pointer to the cache (data) of the current thread. Always returns non-null value. \~ + */ + T * operator ()(); + + /** \brief \ru Удалить данные в кэшах. Если resetLongTerm == true, удалить также данные кэша главного потока. + \en Delete caches data. If resetLongTerm == true, also delete data of the main thread cache. + */ + void Reset ( bool resetLongTerm = false ); + + /** \brief \ru Получить указатель на кэш (данные) главного потока. Всегда возвращает ненулевое значение. + Все операции с кэшем главного потока должны быть защищены блокировкой кэша. + \en Get a pointer to cache (data) of the main thread. Always returns non-null value. + All operations with the main thread cache should be protected by the cache lock. \~ + */ + T * LongTerm (); + + /** \brief \ru Получить указатель на блокировку для операций с кэшем главного потока, учитывая, исполняется ли код параллельно + Может возвращать нулевое значение (удобно для использования с ScopedLock). + \en Get a pointer to the lock for operations with the main thread cache, considering whether the code runs in parallel. + Can return null value (good for use with ScopedLock). \~ + */ + CommonMutex* GetLock() { if ( ::LocksEnabled() ) return GetLockHard(); return lock; } + + /** \brief \ru Функция очистки, используемая сборщиком мусора. + \en Cleaning function, used by the garbage collector. \~ + */ + virtual bool ResetCacheData() { CleanAll(); return true; } + + /** \brief \ru Принудительное удаление всех кэшей (используется сборщиком мусора). + \en Forced deletion of all caches (used by the garbage collector). \~ + */ + virtual void HardReset(); + +private: + /** \brief \ru Удалить все кэши и отписаться от сборки мусора. Должна вызываться в последовательном участке кода. + \en Delete all caches and unsubscribe from the garbage collection. Should be called in sequential code. \~ + */ + void CleanAll( bool doPostproc = true ); + + /** \brief \ru Получить указатель на блокировку для операций с кэшем главного потока. Всегда возвращает ненулевое значение. + \en Get a pointer to the lock for operations with the main thread cache. Always returns non-null value. \~ + */ + CommonMutex* GetLockHard(); + + /** \brief \ru Пост-обработка кэшей после выхода из параллельных вычислений. + \en Caches post-processing after exiting the parallel calculations. \~ + */ + void Postprocess(); + + CacheManager & operator = ( const CacheManager & ); // \ru Не разрешен. \en Not allowed. +}; + + +//------------------------------------------------------------------------------ +// \ru Конструктор. \en Constructor. +// --- +template +inline CacheManager::CacheManager( bool createLock ) + : longTerm ( NULL ) + , tcache ( NULL ) + , lock ( NULL ) +{ + if ( createLock ) { + lock = new CommonMutex(); + longTerm = new T(); + } +} + + + +//------------------------------------------------------------------------------ +// \ru Конструктор. \en Constructor. +// --- +template +inline CacheManager::CacheManager( const CacheManager & item ) + : longTerm ( NULL ) + , tcache ( NULL ) + , lock ( NULL ) +{ + if ( item.longTerm != NULL ) + longTerm = new T( *item.longTerm ); +#ifndef CACHE_DELETE_LOCK + lock = new CommonMutex(); +#endif +} + + +//------------------------------------------------------------------------------ +// \ru Деструктор. \en Destructor. +// --- +template +inline CacheManager::~CacheManager() +{ + CleanAll( false ); + if ( longTerm != NULL ) + delete longTerm; + if ( lock != NULL ) + delete lock; +} + +//------------------------------------------------------------------------------ +// \ru Получить указатель на кэш главного потока. Всегда возвращает ненулевое значение. +// Все операции с кэшем главного потока должны быть защищены блокировкой кэша. +// \en Get a pointer to the main thread cache. Always returns non-null value. +// All operations with the main thread cache should be protected by the cache lock. +// --- +template +inline T* CacheManager::LongTerm () +{ + try { + if ( longTerm == NULL ) + longTerm = new T(); + } + catch ( const std::bad_alloc & ) { + FatalErrorHandler::SetError( rt_NotEnoughMemory ); + } + return longTerm; +} + +//------------------------------------------------------------------------------ +// \ru Получить указатель на блокировку для операций с кэшем главного потока. Всегда возвращает ненулевое значение. +// \en Get a pointer to the lock for operations with the main thread cache. Always returns non-null value. +// --- +template +inline CommonMutex* CacheManager::GetLockHard() +{ + if ( lock == NULL ) { + CommonMutex* ll = GetGlobalLock(); + ll->lock(); + if ( lock == NULL ) + lock = new CommonMutex(); + ll->unlock(); + } + return lock; +} + +//------------------------------------------------------------------------------ +// \ru Оператор (). Возвращает указатель на кэш текущего потока (всегда ненулевое значение). +// \en Operator (). Returns a pointer to the current thread cache (always non-null value). +// --- +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() ) + + if ( !IsSafeMultithreading() || !IsInParallel() ) { + CleanAll(); + return LongTerm(); + } + + T * res = NULL; + unsigned int threadKey = GetThreadKey(); + + if ( FatalErrorHandler::HasError() ) + return LongTerm(); + + if ( tcache == 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 ) { + try { + tcache = new List( threadKey, INIT_BY_LONGTERM ); + return tcache->_data; + } + catch ( const std::bad_alloc & ) { + FatalErrorHandler::SetError( rt_NotEnoughMemory ); + return LongTerm(); + } + } + } + } + + List* entry = tcache; + while( entry != NULL ) { + if ( entry->_id == threadKey ) { + if ( !entry->_valid ) { + try { + delete entry->_data; + { + ScopedLock sl( GetLock(), false ); + entry->_data = INIT_BY_LONGTERM; + } + entry->_valid = true; + } + catch ( const std::bad_alloc & ) { + FatalErrorHandler::SetError( rt_NotEnoughMemory ); + return LongTerm(); + } + } + return entry->_data; + } + // \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 ) + break; + entry = entry->_next; + } + { + // \ru Используется блокировка при изменении списка кэшей. \en Use lock when changing the cache list. + ScopedLock sl( GetLock(), false ); + try { + res = INIT_BY_LONGTERM; + 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 ) { + entry = entry->_next; + } + entry->_next = newList; + } + catch ( const std::bad_alloc & ) { + FatalErrorHandler::SetError( rt_NotEnoughMemory ); + return LongTerm(); + } + } // ScopedLock + + return res; + +} + + +//------------------------------------------------------------------------------ +// \ru Удалить данные в кэшах. Если resetLongTerm == true, удалить также данные кэша главного потока. +// \en Delete caches data. If resetLongTerm == true, also delete data of the main thread cache. +// --- +template +inline void CacheManager::Reset( bool resetLongTerm ) +{ + if ( tcache != NULL ) { + ScopedLock sl( GetLock() ); + List* entry = tcache; + while ( entry != NULL ) { + entry->_valid = false; + entry = entry->_next; + } + } + if ( resetLongTerm ) { + ScopedLock sl( GetLock() ); + delete longTerm; + longTerm = NULL; + // \ru Если нет параллельности, удаляется блокировка. \en If no parallelism, delete the lock. +#ifdef CACHE_DELETE_LOCK + if ( !sl.IsLocked() ) { + if ( lock != NULL ) + delete lock; + lock = NULL; + } +#endif + } +} + +//------------------------------------------------------------------------------ +// \ru Удалить все кэши и отписаться от сборки мусора. Должна вызываться в последовательном участке кода. +// \en Delete all caches and unsubscribe from the garbage collection.Should be called in sequential code. +// --- +template +inline void CacheManager::CleanAll( bool doPostproc ) +{ + if ( CacheCleanupAllowed() ) { + if ( tcache != NULL ) { + if ( doPostproc ) + Postprocess(); + delete tcache; + tcache = NULL; + } +#ifdef CACHE_DELETE_LOCK + if ( lock != NULL ) { + delete lock; + lock = NULL; + } +#endif + if ( IsSubscribed() ) + UnsubcribeOnCleaning(); +#ifdef CACHE_DELETE_LOCK + if ( lock != NULL ) { + delete lock; + lock = NULL; + } +#endif + } +} + +//------------------------------------------------------------------------------ +// \ru Пост-обработка кэшей после выхода из параллельных вычислений. +// \en Caches post-processing after exiting the parallel calculations. \~ +// --- +template +inline void CacheManager::Postprocess() +{ + if ( tcache != NULL ) { + LongTerm(); // Create longTerm + List * entry = tcache; + // Incorporate thread data into main thread data. + while ( entry != NULL && longTerm->MergeWith( entry->_data ) ) { + entry = entry->_next; + } + } +} + +//------------------------------------------------------------------------------ +// \ru Принудительное удаление всех кэшей (используется сборщиком мусора). +// \en Forced deletion of all caches (used by the garbage collector). +//------------------------------------------------------------------------------ +template +inline void CacheManager::HardReset() +{ + if ( tcache != NULL ) { + delete tcache; + tcache = NULL; + } + if ( longTerm != NULL ) { + delete longTerm; + longTerm = NULL; + } + + if ( lock != NULL ) { + delete lock; + lock = NULL; + } +} + +#endif // __TOOL_MULTITHREADING_H diff --git a/C3d/Include/tool_mutex.h b/C3d/Include/tool_mutex.h index 32f8f0c..2695e20 100644 --- a/C3d/Include/tool_mutex.h +++ b/C3d/Include/tool_mutex.h @@ -1,478 +1,560 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Реализация блокировок на базе системных механизмов синхронизации - и OpenMP блокировок. - \en Locks implementation on base of system synchronization mechanisms - and OpenMP locks. \~ - details \ru Реализация блокировок (в том числе блокировки в области видимости) - на базе системных механизмов синхронизации и OpenMP блокировок.\n - \en Implementation of locks (including scoped lock) on base of - system synchronization mechanisms and OpenMP locks.\n \~ -*/ -//////////////////////////////////////////////////////////////////////////////// -#ifndef __TOOL_MUTEX_H -#define __TOOL_MUTEX_H - -#include - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Управление блокировками. -// \en Locks management. \~ -// -// \ru Переменная C3D_NATIVE_LOCK включает использование блокировок на базе -// \ru системных механизмов синхронизации вместо OpenMP, -// \ru что позволяет использование механизмов распараллеливания, отличных от OpenMP. -// -// \en The variable C3D_NATIVE_LOCK enables using locks on base of system -// \en synchronization mechanisms instead of OpenMP, that allows -// \en use of parallelization frameworks, other than OpenMP. \~ -// -//////////////////////////////////////////////////////////////////////////////// -#define C3D_NATIVE_LOCK - - -#ifdef C3D_NATIVE_LOCK -class ToolLock; - -//------------------------------------------------------------------------------ -/** \brief \ru Класс блокировки. \en Lock class. \~ - \details \ru Класс блокировки (реализация на базе системных механизмов синхронизации). - \en Lock class (implementation on base of system synchronization mechanisms). \~ - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS CommonMutex -{ - ToolLock* m_lock; -public: - CommonMutex(); - ~CommonMutex(); - - void lock(); - void unlock(); - -private: - // \ru Запрет копирования. \en Copy forbidden. - CommonMutex ( const CommonMutex& ); - CommonMutex& operator = ( const CommonMutex& ); -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Одинаковая реализация CommonMutex и CommonRecursiveMutex. - \en Same implementation of CommonMutex and CommonRecursiveMutex. \~ - \ingroup Base_Tools -*/ -#define CommonRecursiveMutex CommonMutex - -#else // C3D_NATIVE_LOCK - -//------------------------------------------------------------------------------ -/** \brief \ru Класс блокировки. - \en Lock class. \~ - \details \ru Класс блокировки на базе OpenMP lock. - \en Lock class on base of OpenMP lock. \~ - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS CommonMutex -{ - omp_lock_t m_lock; -public: - // For correct work, CommonMutex implementation should be encapsulated in cpp. - CommonMutex(); - ~CommonMutex(); - void lock(); - void unlock(); -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Класс блокировки на базе вложенного OpenMP lock. - \en Wrapper for nested OpenMP lock. \~ - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS CommonRecursiveMutex -{ - omp_nest_lock_t m_lock; -public: - // For correct work, CommonRecursiveMutex implementation should be encapsulated in cpp. - CommonRecursiveMutex(); - ~CommonRecursiveMutex(); - void lock(); - void unlock(); -}; - -#endif // C3D_NATIVE_LOCK - - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Поддержка многопоточности при использовании произвольного параллельного фреймворка -// \ru в пользовательском приложении. -// \ru Чтобы использовать интерфейсы ядра в нескольких потоках, -// \ru для ядра должен быть установлен режим многопоточных вычислений не ниже mtm_SafeItems. -// -// \ru При использовании параллельных механизмов, отличных от OpenMP, пользовательское приложение -// \ru обязано нотифицировать ядро о входе в каждый параллельный регион и выходе из него. -// \ru Для этого могут быть использованы класс ParallelRegionGuard (защитник параллельного региона -// \ru в области видимости), функции EnterParallelRegion и ExitParallelRegion -// или макросы ENTER_PARALLEL и EXIT_PARALLEL. -// \ru Примеры: -// { -// ParallelRegionGuard l; -// std::thread t1( function1 ); -// std::thread t2( function2 ); -// t1.join(); -// t2.join(); -// } -// { -// EnterParallelRegion(); -// std::thread t1( function1 ); -// std::thread t2( function2 ); -// t1.join(); -// t2.join(); -// ExitParallelRegion(); -// } -// -// -// \en Support of multithreading when using an arbitrary parallel framework in user application. -// -// \en For using the kernel interfaces in several threads, the multithreading mode mtm_SafeItems -// \en or higher should be defined for the kernel. -// -// \en When using a parallel framework other than OpenMP in user code, the application must notify -// \en the kernel about entering and exiting a parallel region. -// \en For that, the class ParallelRegionGuard (a scoped guard of parallel region), -// \en the functions EnterParallelRegion and ExitParallelRegion, -// or macros ENTER_PARALLEL and EXIT_PARALLEL could be used. -// \en Examples: -// { -// ParallelRegionGuard l; -// std::thread t1( function1 ); -// std::thread t2( function2 ); -// t1.join(); -// t2.join(); -// } -// { -// EnterParallelRegion(); -// std::thread t1( function1 ); -// std::thread t2( function2 ); -// t1.join(); -// t2.join(); -// ExitParallelRegion(); -// } -// -//////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------ -/** \brief \ru Защитник параллельного региона в области видимости. - \en Scoped guard of parallel region. \~ - \details \ru Класс защищает регион кода, выполняющийся параллельно. - Работает в области видимости. - Должен использоваться для защиты параллельного кода, - если используются средства распараллеливания, отличные от OpenMP. - Пример использования: - { - ParallelRegionGuard l; - std::thread t1( function1 ); - std::thread t2( function2 ); - t1.join(); - t2.join(); - } - \en The class guards a code region running in parallel. - Works in scope. - Should be used to protect parallel code if parallel framework other than OpenMP is used. - Example of use: - { - ParallelRegionGuard l; - std::thread t1( function1 ); - std::thread t2( function2 ); - t1.join(); - t2.join(); - } - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS ParallelRegionGuard -{ -public: - ParallelRegionGuard(); - ~ParallelRegionGuard(); -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Функция нотифицирует ядро о входе в параллельный блок кода. - Вызов функции должен стоять перед началом параллельного блока. - \en The function notifies the kernel about entering a parallel region. - The function call should be placed before the start of a parallel block -*/ -// --- -MATH_FUNC( void ) EnterParallelRegion(); - -//------------------------------------------------------------------------------ -/** \brief \ru Функция нотифицирует ядро о выходе из параллельного блока кода. - Вызов функции должен стоять после окончания параллельного блока. - \en The function notifies the kernel about exiting a parallel region. - The function call should be placed after the end of the parallel block. -*/ -// --- -MATH_FUNC( void ) ExitParallelRegion(); - - -//------------------------------------------------------------------------------ -// \ru Макросы для нотификации о входе и выходе из параллельного цикла. -// Вызов макросов при использовании OpenMP не обязателен, однако значительно ускоряет -// выполнение параллельного цикла. -// Вызов ENTER_PARALLEL должен стоять перед началом параллельного блока. -// Вызов EXIT_PARALLEL должен стоять после окончания параллельного блока. -// Пример использования: -// bool useParallel = Math::CheckMultithreadedMode( mtm_Items ); -// ENTER_PARALLEL( useParallel ); -// #pragma omp parallel for -// for ( ptrdiff_t i = 0; i < count; ++i ) { -// /* Cycle body */ -// } -// EXIT_PARALLEL( useParallel ); -// -/// \ru Macros for notification of entering and exiting a parallel block. -// Calling the macros when using OpenMP is not required, but significantly speeds up -// the execution of parallel cycle. -// The call ENTER_PARALLEL should be placed before the start of a parallel block. -// The call EXIT_PARALLEL should be placed after the end of the parallel block. -// Example of use: -// bool useParallel = Math::CheckMultithreadedMode( mtm_Items ); -// ENTER_PARALLEL( useParallel ); -// #pragma omp parallel for -// for ( ptrdiff_t i = 0; i < count; ++i ) { -// /* Cycle body */ -// } -// EXIT_PARALLEL( useParallel ); -// --- - -//------------------------------------------------------------------------------ -/** \brief \ru Если useParallel == true, нотифицирует ядро о входе в параллельный блок кода. - \en If useParallel == true, notifies the kernel about entering a parallel region. - \details \ru Если useParallel == true, нотифицирует ядро о входе в параллельный блок кода. - Вызов должен стоять перед началом параллельного блока (перед прагмой OpenMP). - Использование макроса значительно ускоряет параллельные циклы OpenMP. - \en If useParallel == true, notifies the kernel about entering a parallel region. - The call should be placed before the start of a parallel block (before OpenMP pragma). - Using a macro speeds up parallel OpenMP cycles significantly. -*/ -// --- -#define ENTER_PARALLEL(useParallel) if ( useParallel ) EnterParallelRegion(); - -//------------------------------------------------------------------------------ -/** \brief \ru Если useParallel == true, нотифицирует ядро о выходе из параллельного блока кода. - \en If useParallel == true, notifies the kernel about exiting a parallel region. - \details \ru Если useParallel == true, нотифицирует ядро о выходе из параллельного блока кода. - Вызов должен стоять после окончания параллельного блока. - Использование макроса значительно ускоряет параллельные циклы OpenMP. - \en If useParallel == true, notifies the kernel about exiting a parallel region. - The call should be placed after the end of the parallel block. - Using a macro speeds up parallel OpenMP cycles significantly. -*/ -// --- -#define EXIT_PARALLEL(useParallel) if ( useParallel ) ExitParallelRegion(); - -//------------------------------------------------------------------------------ -/** \brief \ru Функция определяет, выполняется ли код параллельно. - \en The function determines whether the code is executed in parallel. -*/ -// --- -MATH_FUNC( bool ) IsInParallel(); - -//////////////////////////////////////////////////////////////////////////////// -// -// \ru Блокировки и другие средства синхронизации. -// \en Locks and other synchronization objects. \~ - -// \ru В качестве блокировок должны использоваться CommonMutex и CommonRecursiveMutex -// \ru (OpenMP lock не должны использоваться напрямую). -// -// \en CommonMutex and CommonRecursiveMutex should be used as locks -// \en (OpenMP locks should not be used directly). -// -//////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------ -/** \brief \ru Блокировка в области видимости. Может принимать нулевой указатель на мьютекс. - Блокировка происходит, если указатель на мьютекс ненулевой и код выполняется параллельно. - \en Scoped lock. Can accept a null pointer to a mutex. - Locking occurs if the pointer to the mutex is nonzero and the code runs in parallel. \~ - \ingroup Base_Tools -*/ -// --- -class MATH_CLASS ScopedLock -{ - CommonMutex* m_mutex; -public: - ScopedLock( CommonMutex* mutex, bool parallelCheck = true ); - ~ScopedLock(); - - // \ru Выполнена ли реальная блокировка. \en Whether a real locking performed. - bool IsLocked(); - -private: - ScopedLock(); - ScopedLock ( const ScopedLock& ); - ScopedLock& operator = ( const ScopedLock& ); -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Рекурсивная блокировка в области видимости. Может принимать нулевой указатель на мьютекс. - Блокировка происходит, если указатель на мьютекс ненулевой и код выполняется параллельно. - \en Recursive scoped lock. Can accept a null pointer to a mutex. - Locking occurs if the pointer to the mutex is nonzero and the code runs in parallel. \~ -\ingroup Base_Tools -*/ -// --- -class MATH_CLASS ScopedRecursiveLock -{ - CommonRecursiveMutex* m_mutex; -public: - ScopedRecursiveLock( CommonRecursiveMutex* mutex, bool parallelCheck = true ); - ~ScopedRecursiveLock(); - - // \ru Выполнена ли реальная блокировка. \en Whether a real locking performed. - bool IsLocked(); - -private: - ScopedRecursiveLock(); - ScopedRecursiveLock ( const ScopedRecursiveLock& ); - ScopedRecursiveLock& operator = ( const ScopedRecursiveLock& ); -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый объект синхронизации с отложенной инициализацией. - \en Base synchronization object with lazy initialization. \~ - \details \ru Базовый объект, предоставляющий средства синхронизации и создающий блокировку при необходимости. \n - \en Base object which provides means of synchronization and creates a lock when needed. \n \~ -\ingroup Base_Tools -*/ -// --- -class MATH_CLASS MbSyncItem { -protected: - mutable CommonMutex * m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. - mutable bool m_locked; - -public: - MbSyncItem(); - virtual ~MbSyncItem(); - - // \ru Включить блокировку (блокировка происходит только при наличии параллельности). - // \en Switch lock on (locking happens only in parallel region). - void Lock() const; - // \ru Снять блокировку, если она была установлена. - // \en Switch lock off if locking has been set. - void Unlock() const; - - // \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. - // \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. - CommonMutex * GetLock() const; -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый объект синхронизации с отложенной инициализацией, поддерживающий множественные блокировки. - \en Base synchronization object with lazy initialization which supports nested locks. \~ - \details \ru Базовый объект синхронизации, поддерживающий множественные блокировки и создающий блокировку при необходимости. \n - \en Base synchronization object with support of nested locks which creates a lock if necessary. \n \~ -\ingroup Base_Tools -*/ -// --- -class MATH_CLASS MbNestSyncItem { -protected: - mutable CommonRecursiveMutex * m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. - mutable bool m_locked; - -public: - MbNestSyncItem(); - virtual ~MbNestSyncItem(); - - // \ru Включить блокировку (блокировка происходит только при наличии параллельности). - // \en Switch lock on (locking happens only in parallel region). - void Lock() const; - // \ru Снять блокировку, если она была установлена. - // \en Switch lock off if locking has been set. - void Unlock() const; - - // \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. - // \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. - CommonRecursiveMutex * GetLock() const; -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый объект, предоставляющий средства синхронизации. - \en Base object providing means of synchronization. \~ - \details \ru Базовый объект, предоставляющий средства синхронизации. \n - \en Base object providing means of synchronization. \n \~ -\ingroup Base_Tools -*/ -// --- -class MATH_CLASS MbPersistentSyncItem { -protected: - mutable CommonMutex m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. - -public: - MbPersistentSyncItem(); - virtual ~MbPersistentSyncItem(); - - void Lock() const; - void Unlock() const; -}; - -//------------------------------------------------------------------------------ -/** \brief \ru Базовый объект синхронизации, поддерживающий множественные блокировки. - \en Base synchronization object with support of nested locks. \~ - \details \ru Базовый объект синхронизации, поддерживающий множественные блокировки. \n - \en Base synchronization object with support of nested locks. \n \~ -\ingroup Base_Tools -*/ -// --- -class MATH_CLASS MbPersistentNestSyncItem { -protected: - mutable CommonRecursiveMutex m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. - -public: - MbPersistentNestSyncItem(); - virtual ~MbPersistentNestSyncItem(); - - void Lock() const; - void Unlock() const; -}; - - -//------------------------------------------------------------------------------ -// \ru Установлен ли режим безопасной многопоточности (используется в CacheManager). -// \en Whether is enabled a safe multithreading mode (used in CacheManager). -// --- -MATH_FUNC(bool) IsSafeMultithreading(); - -//------------------------------------------------------------------------------ -// \ru Получить идентификатор текущего потока. -// \en Get a current thread identifier. -// --- -MATH_FUNC( unsigned int ) GetThreadKey(); - -//------------------------------------------------------------------------------ -// \ru Получить указатель на глобальный мьютекс (используется в CacheManager). -// \en Get a pointer to the global mutex (used in CacheManager). -// --- -MATH_FUNC( CommonMutex* ) GetGlobalLock(); - -//------------------------------------------------------------------------------ -// \ru Получить указатель на глобальный рекурсивный мьютекс (используется для операций выделения и освобождения памяти). -// \en Get a pointer to the global recursive mutex (used for memory allocation and deallocation operations). -// --- -MATH_FUNC( CommonRecursiveMutex* ) GetGlobalRecursiveLock(); - -//------------------------------------------------------------------------------ -// \ru Установить блокировку в области видимости для операций выделения и освобождения памяти. -// \en Set scoped lock for memory allocation and deallocation operations. -// --- -#define SET_MEMORY_SCOPED_LOCK ScopedRecursiveLock memScopedLock( GetGlobalRecursiveLock() ); - -#endif // __TOOL_MUTEX_H +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Реализация блокировок на базе системных механизмов синхронизации + и OpenMP блокировок. + \en Locks implementation on base of system synchronization mechanisms + and OpenMP locks. \~ + details \ru Реализация блокировок (в том числе блокировки в области видимости) + на базе системных механизмов синхронизации и OpenMP блокировок.\n + \en Implementation of locks (including scoped lock) on base of + system synchronization mechanisms and OpenMP locks.\n \~ +*/ +//////////////////////////////////////////////////////////////////////////////// +#ifndef __TOOL_MUTEX_H +#define __TOOL_MUTEX_H + +#include + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru Управление блокировками. +// \en Locks management. \~ +// +// \ru Переменная C3D_NATIVE_LOCK включает использование блокировок на базе +// \ru системных механизмов синхронизации вместо OpenMP, +// \ru что позволяет использование механизмов распараллеливания, отличных от OpenMP. +// +// \en The variable C3D_NATIVE_LOCK enables using locks on base of system +// \en synchronization mechanisms instead of OpenMP, that allows +// \en use of parallelization frameworks, other than OpenMP. \~ +// +//////////////////////////////////////////////////////////////////////////////// +#define C3D_NATIVE_LOCK + + +#ifdef C3D_NATIVE_LOCK +class ToolLock; + +//------------------------------------------------------------------------------ +/** \brief \ru Класс блокировки. \en Lock class. \~ + \details \ru Класс блокировки (реализация на базе системных механизмов синхронизации). + \en Lock class (implementation on base of system synchronization mechanisms). \~ + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS CommonMutex +{ + ToolLock* m_lock; +public: + CommonMutex(); + ~CommonMutex(); + + /** \brief \ru Установить блокировку. \en Set a lock. \~ + */ + void lock(); + /** \brief \ru Снять блокировку. \en Unset a lock. \~ + */ + void unlock(); + +private: + // \ru Запрет копирования. \en Copy forbidden. + CommonMutex ( const CommonMutex& ); + CommonMutex& operator = ( const CommonMutex& ); +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Одинаковая реализация CommonMutex и CommonRecursiveMutex. + \en Same implementation of CommonMutex and CommonRecursiveMutex. \~ + \ingroup Base_Tools +*/ +#define CommonRecursiveMutex CommonMutex + +#else // C3D_NATIVE_LOCK + +//------------------------------------------------------------------------------ +/** \brief \ru Класс блокировки. + \en Lock class. \~ + \details \ru Класс блокировки на базе OpenMP lock. + \en Lock class on base of OpenMP lock. \~ + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS CommonMutex +{ + omp_lock_t m_lock; +public: + // For correct work, CommonMutex implementation should be encapsulated in cpp. + CommonMutex(); + ~CommonMutex(); + void lock(); + void unlock(); +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Класс блокировки на базе вложенного OpenMP lock. + \en Wrapper for nested OpenMP lock. \~ + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS CommonRecursiveMutex +{ + omp_nest_lock_t m_lock; +public: + // For correct work, CommonRecursiveMutex implementation should be encapsulated in cpp. + CommonRecursiveMutex(); + ~CommonRecursiveMutex(); + void lock(); + void unlock(); +}; + +#endif // C3D_NATIVE_LOCK + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru Поддержка многопоточности при использовании произвольного параллельного фреймворка +// \ru в пользовательском приложении. +// \ru Чтобы использовать интерфейсы ядра в нескольких потоках, +// \ru для ядра должен быть установлен режим многопоточных вычислений не ниже mtm_SafeItems. +// +// \ru При использовании параллельных механизмов, отличных от OpenMP, пользовательское приложение +// \ru обязано нотифицировать ядро о входе в каждый параллельный регион и выходе из него. +// \ru Для этого могут быть использованы класс ParallelRegionGuard (защитник параллельного региона +// \ru в области видимости), функции EnterParallelRegion и ExitParallelRegion +// или макросы ENTER_PARALLEL и EXIT_PARALLEL. +// \ru Примеры: +// { +// ParallelRegionGuard l; +// std::thread t1( function1 ); +// std::thread t2( function2 ); +// t1.join(); +// t2.join(); +// } +// { +// EnterParallelRegion(); +// std::thread t1( function1 ); +// std::thread t2( function2 ); +// t1.join(); +// t2.join(); +// ExitParallelRegion(); +// } +// +// +// \en Support of multithreading when using an arbitrary parallel framework in user application. +// +// \en For using the kernel interfaces in several threads, the multithreading mode mtm_SafeItems +// \en or higher should be defined for the kernel. +// +// \en When using a parallel framework other than OpenMP in user code, the application must notify +// \en the kernel about entering and exiting a parallel region. +// \en For that, the class ParallelRegionGuard (a scoped guard of parallel region), +// \en the functions EnterParallelRegion and ExitParallelRegion, +// or macros ENTER_PARALLEL and EXIT_PARALLEL could be used. +// \en Examples: +// { +// ParallelRegionGuard l; +// std::thread t1( function1 ); +// std::thread t2( function2 ); +// t1.join(); +// t2.join(); +// } +// { +// EnterParallelRegion(); +// std::thread t1( function1 ); +// std::thread t2( function2 ); +// t1.join(); +// t2.join(); +// ExitParallelRegion(); +// } +// +//////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------ +/** \brief \ru Защитник параллельного региона в области видимости. + \en Scoped guard of parallel region. \~ + \details \ru Класс защищает регион кода, выполняющийся параллельно. + Работает в области видимости. + Должен использоваться для защиты параллельного кода, + если используются средства распараллеливания, отличные от OpenMP. + Пример использования: + { + ParallelRegionGuard l; + std::thread t1( function1 ); + std::thread t2( function2 ); + t1.join(); + t2.join(); + } + \en The class guards a code region running in parallel. + Works in scope. + Should be used to protect parallel code if parallel framework other than OpenMP is used. + Example of use: + { + ParallelRegionGuard l; + std::thread t1( function1 ); + std::thread t2( function2 ); + t1.join(); + t2.join(); + } + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS ParallelRegionGuard +{ +public: + ParallelRegionGuard(); + ~ParallelRegionGuard(); +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Функция нотифицирует ядро о входе в параллельный блок кода. + Вызов функции должен стоять перед началом параллельного блока. + \en The function notifies the kernel about entering a parallel region. + The function call should be placed before the start of a parallel block +*/ +// --- +MATH_FUNC( void ) EnterParallelRegion(); + +//------------------------------------------------------------------------------ +/** \brief \ru Функция нотифицирует ядро о выходе из параллельного блока кода. + Вызов функции должен стоять после окончания параллельного блока. + \en The function notifies the kernel about exiting a parallel region. + The function call should be placed after the end of the parallel block. +*/ +// --- +MATH_FUNC( void ) ExitParallelRegion(); + + +//------------------------------------------------------------------------------ +// \ru Макросы для нотификации о входе и выходе из параллельного цикла. +// Вызов макросов при использовании OpenMP не обязателен, однако значительно ускоряет +// выполнение параллельного цикла. +// Вызов ENTER_PARALLEL должен стоять перед началом параллельного блока. +// Вызов EXIT_PARALLEL должен стоять после окончания параллельного блока. +// Пример использования: +// bool useParallel = Math::CheckMultithreadedMode( mtm_Items ); +// ENTER_PARALLEL( useParallel ); +// #pragma omp parallel for +// for ( ptrdiff_t i = 0; i < count; ++i ) { +// /* Cycle body */ +// } +// EXIT_PARALLEL( useParallel ); +// +/// \ru Macros for notification of entering and exiting a parallel block. +// Calling the macros when using OpenMP is not required, but significantly speeds up +// the execution of parallel cycle. +// The call ENTER_PARALLEL should be placed before the start of a parallel block. +// The call EXIT_PARALLEL should be placed after the end of the parallel block. +// Example of use: +// bool useParallel = Math::CheckMultithreadedMode( mtm_Items ); +// ENTER_PARALLEL( useParallel ); +// #pragma omp parallel for +// for ( ptrdiff_t i = 0; i < count; ++i ) { +// /* Cycle body */ +// } +// EXIT_PARALLEL( useParallel ); +// --- + +//------------------------------------------------------------------------------ +/** \brief \ru Если useParallel == true, нотифицирует ядро о входе в параллельный блок кода. + \en If useParallel == true, notifies the kernel about entering a parallel region. + \details \ru Если useParallel == true, нотифицирует ядро о входе в параллельный блок кода. + Вызов должен стоять перед началом параллельного блока (перед прагмой OpenMP). + Использование макроса значительно ускоряет параллельные циклы OpenMP. + \en If useParallel == true, notifies the kernel about entering a parallel region. + The call should be placed before the start of a parallel block (before OpenMP pragma). + Using a macro speeds up parallel OpenMP cycles significantly. +*/ +// --- +#define ENTER_PARALLEL(useParallel) if ( useParallel ) EnterParallelRegion(); + +//------------------------------------------------------------------------------ +/** \brief \ru Если useParallel == true, нотифицирует ядро о выходе из параллельного блока кода. + \en If useParallel == true, notifies the kernel about exiting a parallel region. + \details \ru Если useParallel == true, нотифицирует ядро о выходе из параллельного блока кода. + Вызов должен стоять после окончания параллельного блока. + Использование макроса значительно ускоряет параллельные циклы OpenMP. + \en If useParallel == true, notifies the kernel about exiting a parallel region. + The call should be placed after the end of the parallel block. + Using a macro speeds up parallel OpenMP cycles significantly. +*/ +// --- +#define EXIT_PARALLEL(useParallel) if ( useParallel ) ExitParallelRegion(); + +//------------------------------------------------------------------------------ +/** \brief \ru Нотифицирует ядро о входе в параллельный блок кода. + \en Notifies the kernel about entering a parallel region. + \details \ru Нотифицирует ядро о входе в параллельный блок кода. + Вызов должен стоять перед началом параллельного блока (перед прагмой OpenMP). + Использование макроса значительно ускоряет параллельные циклы OpenMP. + \en Notifies the kernel about entering a parallel region. + The call should be placed before the start of a parallel block (before OpenMP pragma). + Using a macro speeds up parallel OpenMP cycles significantly. +*/ +// --- +#define EXIT_PARALLEL_FORCED ExitParallelRegion(); + +//------------------------------------------------------------------------------ +/** \brief \ru Нотифицирует ядро о выходе из параллельного блока кода. + \en Notifiesotifies the kernel about exiting a parallel region. + \details \ru Нотифицирует ядро о выходе из параллельного блока кода. + Вызов должен стоять после окончания параллельного блока. + Использование макроса значительно ускоряет параллельные циклы OpenMP. + \en Notifies the kernel about exiting a parallel region. + The call should be placed after the end of the parallel block. + Using a macro speeds up parallel OpenMP cycles significantly. +*/ +// --- +#define ENTER_PARALLEL_FORCED EnterParallelRegion(); + +//------------------------------------------------------------------------------ +/** \brief \ru Функция определяет, выполняется ли код параллельно. + \en The function determines whether the code is executed in parallel. +*/ +// --- +MATH_FUNC( bool ) IsInParallel(); + +//------------------------------------------------------------------------------ +/** \brief \ru Функция определяет, разрешена ли очистка кэшей. + \en The function determines whether the caches cleanup is allowed. +*/ +// --- +MATH_FUNC( bool ) CacheCleanupAllowed(); + + +//////////////////////////////////////////////////////////////////////////////// +// +// \ru Блокировки и другие средства синхронизации. +// \en Locks and other synchronization objects. \~ + +// \ru В качестве блокировок должны использоваться CommonMutex и CommonRecursiveMutex +// \ru (OpenMP lock не должны использоваться напрямую). +// +// \en CommonMutex and CommonRecursiveMutex should be used as locks +// \en (OpenMP locks should not be used directly). +// +//////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------ +/** \brief \ru Блокировка в области видимости. Может принимать нулевой указатель на мьютекс. + Блокировка происходит, если указатель на мьютекс ненулевой и код выполняется параллельно. + \en Scoped lock. Can accept a null pointer to a mutex. + Locking occurs if the pointer to the mutex is nonzero and the code runs in parallel. \~ + \ingroup Base_Tools +*/ +// --- +class MATH_CLASS ScopedLock +{ + CommonMutex* m_mutex; +public: + ScopedLock( CommonMutex* mutex, bool parallelCheck = true ); + ~ScopedLock(); + + /** \brief \ru Выполнена ли реальная блокировка. \en Whether a real locking performed. \~ + */ + bool IsLocked(); + +private: + ScopedLock(); + ScopedLock ( const ScopedLock& ); + ScopedLock& operator = ( const ScopedLock& ); +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Рекурсивная блокировка в области видимости. Может принимать нулевой указатель на мьютекс. + Блокировка происходит, если указатель на мьютекс ненулевой и код выполняется параллельно. + \en Recursive scoped lock. Can accept a null pointer to a mutex. + Locking occurs if the pointer to the mutex is nonzero and the code runs in parallel. \~ +\ingroup Base_Tools +*/ +// --- +class MATH_CLASS ScopedRecursiveLock +{ + CommonRecursiveMutex* m_mutex; +public: + ScopedRecursiveLock( CommonRecursiveMutex* mutex, bool parallelCheck = true ); + ~ScopedRecursiveLock(); + + /** \brief \ru Выполнена ли реальная блокировка. \en Whether a real locking performed. \~ + */ + bool IsLocked(); + +private: + ScopedRecursiveLock(); + ScopedRecursiveLock ( const ScopedRecursiveLock& ); + ScopedRecursiveLock& operator = ( const ScopedRecursiveLock& ); +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый объект синхронизации с отложенной инициализацией. + \en Base synchronization object with lazy initialization. \~ + \details \ru Базовый объект, предоставляющий средства синхронизации и создающий блокировку при необходимости. \n + \en Base object which provides means of synchronization and creates a lock when needed. \n \~ +\ingroup Base_Tools +*/ +// --- +class MATH_CLASS MbSyncItem { +protected: + mutable CommonMutex * m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. + mutable int m_locked; + +public: + MbSyncItem(); + virtual ~MbSyncItem(); + + /** \brief \ru Включить блокировку (блокировка происходит только при наличии параллельности). + \en Switch lock on (locking happens only in parallel region). + */ + void Lock() const; + + /** \brief \ru Снять блокировку, если она была установлена. + \en Switch lock off if locking has been set. + */ + void Unlock() const; + + // \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. + // \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. + CommonMutex * GetLock() const; +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый объект синхронизации с отложенной инициализацией, поддерживающий множественные блокировки. + \en Base synchronization object with lazy initialization which supports nested locks. \~ + \details \ru Базовый объект синхронизации, поддерживающий множественные блокировки и создающий блокировку при необходимости. \n + \en Base synchronization object with support of nested locks which creates a lock if necessary. \n \~ +\ingroup Base_Tools +*/ +// --- +class MATH_CLASS MbNestSyncItem { +protected: + mutable CommonRecursiveMutex * m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. + mutable int m_locked; + +public: + MbNestSyncItem(); + virtual ~MbNestSyncItem(); + + /** \brief \ru Включить блокировку (блокировка происходит только при наличии параллельности). + \en Switch lock on (locking happens only in parallel region). + */ + void Lock() const; + + /** \brief \ru Снять блокировку, если она была установлена. + \en Switch lock off if locking has been set. + */ + void Unlock() const; + + /** \brief \ru Выдать указатель на объект мьютекса. Возращает NULL, если параллельности нет. Для использования в ScopedLock. + \en Get a pointer to the mutex object. Return NULL if no parallelism. For use in ScopedLock. + */ + CommonRecursiveMutex * GetLock() const; +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый объект, предоставляющий средства синхронизации. + \en Base object providing means of synchronization. \~ + \details \ru Базовый объект, предоставляющий средства синхронизации. \n + \en Base object providing means of synchronization. \n \~ +\ingroup Base_Tools +*/ +// --- +class MATH_CLASS MbPersistentSyncItem { +protected: + mutable CommonMutex m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. + mutable int m_locked; + +public: + MbPersistentSyncItem(); + virtual ~MbPersistentSyncItem(); + + /** \brief \ru Включить блокировку. + \en Switch lock on. + */ + void Lock() const; + + /** \brief \ru Снять блокировку, если она была установлена. + \en Switch lock off if locking has been set. + */ + void Unlock() const; + + /** \brief \ru Выдать указатель на объект мьютекса. + \en Get a pointer to the mutex object. + */ + CommonMutex * GetLock() const; + +}; + +//------------------------------------------------------------------------------ +/** \brief \ru Базовый объект синхронизации, поддерживающий множественные блокировки. + \en Base synchronization object with support of nested locks. \~ + \details \ru Базовый объект синхронизации, поддерживающий множественные блокировки. \n + \en Base synchronization object with support of nested locks. \n \~ +\ingroup Base_Tools +*/ +// --- +class MATH_CLASS MbPersistentNestSyncItem { +protected: + mutable CommonRecursiveMutex m_comLock; // \ru Критическая секция для монопольного доступа к объекту. \en The critical section for exclusive access to the object. + mutable int m_locked; + +public: + MbPersistentNestSyncItem(); + virtual ~MbPersistentNestSyncItem(); + + /** \brief \ru Включить блокировку. \en Switch lock on. + */ + void Lock() const; + + /** \brief \ru Снять блокировку, если она была установлена. + \en Switch lock off if locking has been set. + */ + void Unlock() const; + + /** \brief \ru Выдать указатель на объект мьютекса. + \en Get a pointer to the mutex object. + */ + CommonRecursiveMutex * GetLock() const; + +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Установлен ли режим безопасной многопоточности (используется в CacheManager). + \en Whether is enabled a safe multithreading mode (used in CacheManager). \~ + \ingroup Base_Tools +*/ +MATH_FUNC(bool) IsSafeMultithreading(); + +//------------------------------------------------------------------------------ +/** \brief \ru Включены ли блокировки (режим многопоточности >= mtm_Standard и код выполняется параллельно). + \en Whether locks are enabled (multithreading is on and code is executed in parallel). \~ + \ingroup Base_Tools +*/ +MATH_FUNC( bool ) LocksEnabled(); + +//------------------------------------------------------------------------------ +/** \brief \ru Получить псевдо-идентификатор текущего потока. + \en Get a current thread pseudo-identifier. +*/ +MATH_FUNC( unsigned int ) GetThreadKey(); + +//------------------------------------------------------------------------------ +/** \brief \ru Получить указатель на глобальный мьютекс (используется в CacheManager). + \en Get a pointer to the global mutex (used in CacheManager). +*/ +MATH_FUNC( CommonMutex* ) GetGlobalLock(); + +//------------------------------------------------------------------------------ +/** \brief \ru Получить указатель на глобальный рекурсивный мьютекс (используется для операций выделения и освобождения памяти). + \en Get a pointer to the global recursive mutex (used for memory allocation and deallocation operations). +*/ +MATH_FUNC( CommonRecursiveMutex* ) GetGlobalRecursiveLock(); + +//------------------------------------------------------------------------------ +/** \brief \ru Установить блокировку в области видимости для операций выделения и освобождения памяти. + \en Set scoped lock for memory allocation and deallocation operations. +*/ +#define SET_MEMORY_SCOPED_LOCK ScopedRecursiveLock memScopedLock( GetGlobalRecursiveLock() ); + +#endif // __TOOL_MUTEX_H diff --git a/C3d/Include/tool_time_test.h b/C3d/Include/tool_time_test.h index e0f5c74..6c6ec3e 100644 --- a/C3d/Include/tool_time_test.h +++ b/C3d/Include/tool_time_test.h @@ -224,11 +224,11 @@ MATH_FUNC(void) SortResultMeasuring( TimeTest &, std::vector & ) #define TB_MATH_CONVERTERS _T("MATH_CONVERTERS:") #define TB_TEST _T("Test.exe:") - #define SET_TIME_TEST(allow) ::SetTimeTest ( allow ); - #define CHECK_TIME_TEST() ::CheckTimeTest (); + #define SET_TIME_TEST(allow) ::SetTimeTest( allow ); + #define CHECK_TIME_TEST() ::CheckTimeTest(); - #define BEGIN_TIME1(name,attitude) ::BeginTime ( name, attitude ); // \ru копирование оболочек, методы пересечения \en copying of shells, intersection methods - #define END_TIME1(name) ::EndTime ( name ); + #define BEGIN_TIME1(name,attitude) ::BeginTime( name, attitude ); // \ru копирование оболочек, методы пересечения \en copying of shells, intersection methods + #define END_TIME1(name) ::EndTime( name ); #else // C3D_DEBUG @@ -251,7 +251,7 @@ MATH_FUNC(void) SortResultMeasuring( TimeTest &, std::vector & ) #define SET_TIME_TEST_REL(allow) ::SetTimeTest( allow ); -#define BEGIN_TIME_REL(name,attitude) ::BeginTime( name, attitude ); +#define BEGIN_TIME_REL(name, attitude) ::BeginTime( name, attitude ); #define END_TIME_REL(name) ::EndTime( name ); #define TIME_TEST_REPORT_REL(filename) ::TimeTestReport( filename ); diff --git a/C3d/Include/tool_uuid.h b/C3d/Include/tool_uuid.h index b194937..39f54cc 100644 --- a/C3d/Include/tool_uuid.h +++ b/C3d/Include/tool_uuid.h @@ -1,288 +1,288 @@ -//////////////////////////////////////////////////////////////////////////////// -/** - \file - \brief \ru Глобально уникальный идентификатор. - \en Global unique identifier. \~ - -*/ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef _TOOL_UUID_H_ -#define _TOOL_UUID_H_ - -#include -#include -#include -#include -#include - -class reader; -class writer; - - -const uint8 uuidSize = 16; - - -//------------------------------------------------------------------------------ -/** \brief \ru Глобально уникальный идентификатор. - \en Global unique identifier. \~ - \details \ru Глобально уникальный идентификатор - используется как идентификатор - типа пользовательского атрибута. - \en Global unique identifier - it is used as an identifier - of a type of user attribute. \~ - \ingroup Model_Attributes - */ -struct MbUuid -{ -protected: - uint8 data[uuidSize]; -private: - mutable ThreeStates isEmpty; - -public: - typedef uint8 * iterator; - typedef uint8 const * const_iterator; -public: - MbUuid() : isEmpty( ts_positive ) { ::memset( data, 0, uuidSize ); } - MbUuid( const MbUuid & id ) : isEmpty( id.isEmpty ) { ::memcpy( data, id.data, uuidSize ); } -public: - iterator begin() { isEmpty = ts_neutral; return data; } - iterator end() { isEmpty = ts_neutral; return data + uuidSize; } - - const_iterator cbegin() const { return data; } - const_iterator cend() const { return data + uuidSize; } - - size_t size() const { return uuidSize; } - - bool is_nil() const - { - if ( isEmpty == ts_neutral ) { - isEmpty = ts_positive; - for ( uint8 i = 0; i < uuidSize; i++ ) { - if ( data[i] != 0U ) { - isEmpty = ts_negative; - break; - } - } - } - return (isEmpty == ts_positive); - } - void swap( MbUuid & id ) - { - uint8 temp[16]; - ::memcpy( temp, data, uuidSize ); - ::memcpy( data, id.data, uuidSize ); - ::memcpy( id.data, temp, uuidSize ); - std::swap( isEmpty, id.isEmpty ); - } - -public: - MbUuid & operator = ( const MbUuid & id ) - { - ::memcpy( data, id.data, uuidSize ); - isEmpty = id.isEmpty; - return *this; - } - bool operator == ( const MbUuid & id ) const - { - //return std::equal( cbegin(), cend(), id.cbegin() ); - MbUuid::const_iterator first1 = cbegin(), last1 = cend(), first2 = id.cbegin(); - while ( first1 != last1 ) - { - if ( !(*first1 == *first2) ) - return false; - ++first1; ++first2; - } - return true; - } - bool operator != ( const MbUuid & id ) const { return !(*this == id); } - bool operator < ( const MbUuid & id ) const { return std::lexicographical_compare( cbegin(), cend(), id.cbegin(), id.cend() ); } - bool operator > ( const MbUuid & id ) const { return (id < *this); } - bool operator <= ( const MbUuid & id ) const { return !(id < *this); } - bool operator >= ( const MbUuid & id ) const { return !(*this < id); } - -public: - friend struct string_generator; - friend reader & CALL_DECLARATION operator >> ( reader & in, MbUuid & ref ); - friend writer & CALL_DECLARATION operator << ( writer & out, const MbUuid & ref ); - friend writer & CALL_DECLARATION operator << ( writer & out, MbUuid & ref ) { return operator << ( out, (const MbUuid &)ref ); } -}; - - -//------------------------------------------------------------------------------ -/** \brief \ru Генератор MbUuid из string. - \en Generator of MbUuid from string. \~ - \details \ru Генератор MbUuid из string. Принимает следующие формы: \n - 0123456789abcdef0123456789abcdef, \n - 01234567-89ab-cdef-0123456789abcdef, \n - {01234567-89ab-cdef-0123456789abcdef}, \n - {0123456789abcdef0123456789abcdef}. \n - \en Generator of MbUuid from string. It accepts the next format: \n - 0123456789abcdef0123456789abcdef, \n - 01234567-89ab-cdef-0123456789abcdef, \n - {01234567-89ab-cdef-0123456789abcdef}, \n - {0123456789abcdef0123456789abcdef}. \n - \~ - \ingroup Model_Attributes -*/ -//--- -struct string_generator -{ - template - MbUuid operator()( std::basic_string const & s ) const { - return operator()( s.begin(), s.end() ); - }; - - MbUuid operator()( char const * const s ) const { - return operator()( s, s+std::strlen(s) ); - } - - MbUuid operator()( wchar_t const * const s ) const { - return operator()( s, s+std::wcslen(s) ); - } - - template - MbUuid operator()( CharIterator begin, CharIterator end ) const - { - typedef typename std::iterator_traits::value_type char_type; - - // \ru Проверяем открывающую скобку \en Check an opening parenthesis. - char_type c = get_next_char( begin, end ); - bool has_open_brace = is_open_brace(c); - char_type open_brace_char = c; - if ( has_open_brace ) { - c = get_next_char( begin, end ); - } - - bool has_dashes = false; - - MbUuid u; - bool isEmpty = true; - - int i = 0; - for ( MbUuid::iterator it_byte = u.begin(); it_byte != u.end(); ++it_byte, ++i ) { - if ( it_byte != u.begin() ) { - c = get_next_char( begin, end ); - } - if ( i == 4 ) { - if ( is_dash(c) ) { - c = get_next_char( begin, end ); - has_dashes = true; - } - } - if ( has_dashes ) { - if ( is_dash(c) ) { - c = get_next_char( begin, end ); - } - } - - *it_byte = get_value(c); - - c = get_next_char( begin, end ); - *it_byte <<= 4; - *it_byte |= get_value(c); - if ( *it_byte != 0U ) - isEmpty = false; - } - - // \ru Проверяем закрывающую скобку \en Check a closing parenthesis - if ( has_open_brace ) { - c = get_next_char( begin, end ); - check_close_brace( c, open_brace_char ); - } - - u.isEmpty = isEmpty ? ts_positive : ts_negative; - return u; - } - -private: - template - typename std::iterator_traits::value_type - get_next_char( CharIterator & begin, CharIterator end ) const { - if ( begin == end ) { - _ASSERT( false ); - } - return *begin++; - } - - unsigned char get_value( char c ) const { - static char const*const digits_begin = "0123456789abcdefABCDEF"; - static char const*const digits_end = digits_begin + 22; - - static unsigned char const values[] = - { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,10,11,12,13,14,15 - , static_cast(-1) }; - - char const * d = std::find( digits_begin, digits_end, c ); - return values[d - digits_begin]; - } - - unsigned char get_value( wchar_t c ) const { - static wchar_t const*const digits_begin = L"0123456789abcdefABCDEF"; - static wchar_t const*const digits_end = digits_begin + 22; - - static unsigned char const values[] = - { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,10,11,12,13,14,15 - , static_cast(-1) }; - - wchar_t const * d = std::find( digits_begin, digits_end, c ); - return values[d - digits_begin]; - } - - bool is_dash( char c ) const { return c == '-'; } - bool is_dash( wchar_t c ) const { return c == L'-'; } - - // \ru Возвращаем открывающую скобку \en Return an opening parenthesis. - bool is_open_brace( char c ) const { return (c == '{'); } - bool is_open_brace( wchar_t c ) const { return (c == L'{'); } - - bool check_close_brace( char c, char open_brace ) const { - if ( open_brace == '{' && c == '}' ) - return true; - _ASSERT( false ); - return false; - } - - bool check_close_brace( wchar_t c, wchar_t open_brace ) const { - if ( open_brace == L'{' && c == L'}' ) - return true; - _ASSERT( false ); - return false; - } -}; - - -struct hash8_generator -{ - uint8 operator()( const MbUuid & trg ) const - { - static uint8 rand8[256] = - { - 1, 14, 110, 25, 97, 174, 132, 119, 138, 170, 125, 118, 27, 233, 140, 51, - 87, 197, 177, 107, 234, 169, 56, 68, 30, 7, 173, 73, 188, 40, 36, 65, - 49, 213, 104, 190, 57, 211, 148, 223, 48, 115, 15, 2, 67, 186, 210, 28, - 12, 181, 103, 70, 22, 58, 75, 78, 183, 167, 238, 157, 124, 147, 172, 144, - 176, 161, 141, 86, 60, 66, 128, 83, 156, 241, 79, 46, 168, 198, 41, 254, - 178, 85, 253, 237, 250, 154, 133, 88, 35, 206, 95, 116, 252, 192, 54, 221, - 102, 218, 255, 240, 82, 106, 158, 201, 61, 3, 89, 9, 42, 155, 159, 93, - 166, 80, 50, 34, 175, 195, 100, 99, 26, 150, 16, 145, 4, 33, 8, 189, - 121, 64, 77, 72, 208, 245, 130, 122, 143, 55, 105, 134, 29, 164, 185, 194, - 193, 239, 101, 242, 5, 171, 126, 11, 74, 59, 137, 228, 108, 191, 232, 139, - 6, 24, 81, 20, 127, 17, 91, 92, 251, 151, 225, 207, 21, 98, 113, 112, - 84, 226, 18, 214, 199, 187, 13, 32, 94, 220, 224, 212, 247, 204, 196, 43, - 249, 236, 45, 244, 111, 182, 153, 136, 129, 90, 217, 202, 19, 165, 231, 71, - 230, 142, 96, 227, 62, 179, 246, 114, 162, 53, 160, 215, 205, 180, 47, 109, - 44, 38, 31, 149, 135, 0, 216, 52, 63, 23, 37, 69, 39, 117, 146, 184, - 163, 200, 222, 235, 248, 243, 219, 10, 152, 131, 123, 229, 203, 76, 120, 209 - }; - - uint8 h = 0; - MbUuid::const_iterator curr_iter = trg.cbegin(), end_iter = trg.cend(); - while ( curr_iter != end_iter ) - h = rand8[h ^ *curr_iter++]; - return h; - } -}; - - -#endif // _TOOL_UUID_H_ +//////////////////////////////////////////////////////////////////////////////// +/** + \file + \brief \ru Глобально уникальный идентификатор. + \en Global unique identifier. \~ + +*/ +//////////////////////////////////////////////////////////////////////////////// + +#ifndef _TOOL_UUID_H_ +#define _TOOL_UUID_H_ + +#include +#include +#include +#include +#include + +class reader; +class writer; + + +const_expr uint8 uuidSize = 16; + + +//------------------------------------------------------------------------------ +/** \brief \ru Глобально уникальный идентификатор. + \en Global unique identifier. \~ + \details \ru Глобально уникальный идентификатор - используется как идентификатор + типа пользовательского атрибута. + \en Global unique identifier - it is used as an identifier + of a type of user attribute. \~ + \ingroup Model_Attributes + */ +struct MbUuid +{ +protected: + uint8 data[uuidSize]; +private: + mutable ThreeStates isEmpty; + +public: + typedef uint8 * iterator; + typedef uint8 const * const_iterator; +public: + MbUuid() : isEmpty( ts_positive ) { ::memset( data, 0, uuidSize ); } + MbUuid( const MbUuid & id ) : isEmpty( id.isEmpty ) { ::memcpy( data, id.data, uuidSize ); } +public: + iterator begin() { isEmpty = ts_neutral; return data; } + iterator end() { isEmpty = ts_neutral; return data + uuidSize; } + + const_iterator cbegin() const { return data; } + const_iterator cend() const { return data + uuidSize; } + + size_t size() const { return uuidSize; } + + bool is_nil() const + { + if ( isEmpty == ts_neutral ) { + isEmpty = ts_positive; + for ( uint8 i = 0; i < uuidSize; i++ ) { + if ( data[i] != 0U ) { + isEmpty = ts_negative; + break; + } + } + } + return (isEmpty == ts_positive); + } + void swap( MbUuid & id ) + { + uint8 temp[16]; + ::memcpy( temp, data, uuidSize ); + ::memcpy( data, id.data, uuidSize ); + ::memcpy( id.data, temp, uuidSize ); + std::swap( isEmpty, id.isEmpty ); + } + +public: + MbUuid & operator = ( const MbUuid & id ) + { + ::memcpy( data, id.data, uuidSize ); + isEmpty = id.isEmpty; + return *this; + } + bool operator == ( const MbUuid & id ) const + { + //return std::equal( cbegin(), cend(), id.cbegin() ); + MbUuid::const_iterator first1 = cbegin(), last1 = cend(), first2 = id.cbegin(); + while ( first1 != last1 ) + { + if ( !(*first1 == *first2) ) + return false; + ++first1; ++first2; + } + return true; + } + bool operator != ( const MbUuid & id ) const { return !(*this == id); } + bool operator < ( const MbUuid & id ) const { return std::lexicographical_compare( cbegin(), cend(), id.cbegin(), id.cend() ); } + bool operator > ( const MbUuid & id ) const { return (id < *this); } + bool operator <= ( const MbUuid & id ) const { return !(id < *this); } + bool operator >= ( const MbUuid & id ) const { return !(*this < id); } + +public: + friend struct string_generator; + friend reader & CALL_DECLARATION operator >> ( reader & in, MbUuid & ref ); + friend writer & CALL_DECLARATION operator << ( writer & out, const MbUuid & ref ); + friend writer & CALL_DECLARATION operator << ( writer & out, MbUuid & ref ) { return operator << ( out, (const MbUuid &)ref ); } +}; + + +//------------------------------------------------------------------------------ +/** \brief \ru Генератор MbUuid из string. + \en Generator of MbUuid from string. \~ + \details \ru Генератор MbUuid из string. Принимает следующие формы: \n + 0123456789abcdef0123456789abcdef, \n + 01234567-89ab-cdef-0123456789abcdef, \n + {01234567-89ab-cdef-0123456789abcdef}, \n + {0123456789abcdef0123456789abcdef}. \n + \en Generator of MbUuid from string. It accepts the next format: \n + 0123456789abcdef0123456789abcdef, \n + 01234567-89ab-cdef-0123456789abcdef, \n + {01234567-89ab-cdef-0123456789abcdef}, \n + {0123456789abcdef0123456789abcdef}. \n + \~ + \ingroup Model_Attributes +*/ +//--- +struct string_generator +{ + template + MbUuid operator()( std::basic_string const & s ) const { + return operator()( s.begin(), s.end() ); + }; + + MbUuid operator()( char const * const s ) const { + return operator()( s, s+std::strlen(s) ); + } + + MbUuid operator()( wchar_t const * const s ) const { + return operator()( s, s+std::wcslen(s) ); + } + + template + MbUuid operator()( CharIterator begin, CharIterator end ) const + { + typedef typename std::iterator_traits::value_type char_type; + + // \ru Проверяем открывающую скобку \en Check an opening parenthesis. + char_type c = get_next_char( begin, end ); + bool has_open_brace = is_open_brace(c); + char_type open_brace_char = c; + if ( has_open_brace ) { + c = get_next_char( begin, end ); + } + + bool has_dashes = false; + + MbUuid u; + bool isEmpty = true; + + int i = 0; + for ( MbUuid::iterator it_byte = u.begin(); it_byte != u.end(); ++it_byte, ++i ) { + if ( it_byte != u.begin() ) { + c = get_next_char( begin, end ); + } + if ( i == 4 ) { + if ( is_dash(c) ) { + c = get_next_char( begin, end ); + has_dashes = true; + } + } + if ( has_dashes ) { + if ( is_dash(c) ) { + c = get_next_char( begin, end ); + } + } + + *it_byte = get_value(c); + + c = get_next_char( begin, end ); + *it_byte <<= 4; + *it_byte |= get_value(c); + if ( *it_byte != 0U ) + isEmpty = false; + } + + // \ru Проверяем закрывающую скобку \en Check a closing parenthesis + if ( has_open_brace ) { + c = get_next_char( begin, end ); + check_close_brace( c, open_brace_char ); + } + + u.isEmpty = isEmpty ? ts_positive : ts_negative; + return u; + } + +private: + template + typename std::iterator_traits::value_type + get_next_char( CharIterator & begin, CharIterator end ) const { + if ( begin == end ) { + _ASSERT( false ); + } + return *begin++; + } + + unsigned char get_value( char c ) const { + static char const*const digits_begin = "0123456789abcdefABCDEF"; + static char const*const digits_end = digits_begin + 22; + + static unsigned char const values[] = + { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,10,11,12,13,14,15 + , static_cast(-1) }; + + char const * d = std::find( digits_begin, digits_end, c ); + return values[d - digits_begin]; + } + + unsigned char get_value( wchar_t c ) const { + static wchar_t const*const digits_begin = L"0123456789abcdefABCDEF"; + static wchar_t const*const digits_end = digits_begin + 22; + + static unsigned char const values[] = + { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,10,11,12,13,14,15 + , static_cast(-1) }; + + wchar_t const * d = std::find( digits_begin, digits_end, c ); + return values[d - digits_begin]; + } + + bool is_dash( char c ) const { return c == '-'; } + bool is_dash( wchar_t c ) const { return c == L'-'; } + + // \ru Возвращаем открывающую скобку \en Return an opening parenthesis. + bool is_open_brace( char c ) const { return (c == '{'); } + bool is_open_brace( wchar_t c ) const { return (c == L'{'); } + + bool check_close_brace( char c, char open_brace ) const { + if ( open_brace == '{' && c == '}' ) + return true; + _ASSERT( false ); + return false; + } + + bool check_close_brace( wchar_t c, wchar_t open_brace ) const { + if ( open_brace == L'{' && c == L'}' ) + return true; + _ASSERT( false ); + return false; + } +}; + + +struct hash8_generator +{ + uint8 operator()( const MbUuid & trg ) const + { + static uint8 rand8[256] = + { + 1, 14, 110, 25, 97, 174, 132, 119, 138, 170, 125, 118, 27, 233, 140, 51, + 87, 197, 177, 107, 234, 169, 56, 68, 30, 7, 173, 73, 188, 40, 36, 65, + 49, 213, 104, 190, 57, 211, 148, 223, 48, 115, 15, 2, 67, 186, 210, 28, + 12, 181, 103, 70, 22, 58, 75, 78, 183, 167, 238, 157, 124, 147, 172, 144, + 176, 161, 141, 86, 60, 66, 128, 83, 156, 241, 79, 46, 168, 198, 41, 254, + 178, 85, 253, 237, 250, 154, 133, 88, 35, 206, 95, 116, 252, 192, 54, 221, + 102, 218, 255, 240, 82, 106, 158, 201, 61, 3, 89, 9, 42, 155, 159, 93, + 166, 80, 50, 34, 175, 195, 100, 99, 26, 150, 16, 145, 4, 33, 8, 189, + 121, 64, 77, 72, 208, 245, 130, 122, 143, 55, 105, 134, 29, 164, 185, 194, + 193, 239, 101, 242, 5, 171, 126, 11, 74, 59, 137, 228, 108, 191, 232, 139, + 6, 24, 81, 20, 127, 17, 91, 92, 251, 151, 225, 207, 21, 98, 113, 112, + 84, 226, 18, 214, 199, 187, 13, 32, 94, 220, 224, 212, 247, 204, 196, 43, + 249, 236, 45, 244, 111, 182, 153, 136, 129, 90, 217, 202, 19, 165, 231, 71, + 230, 142, 96, 227, 62, 179, 246, 114, 162, 53, 160, 215, 205, 180, 47, 109, + 44, 38, 31, 149, 135, 0, 216, 52, 63, 23, 37, 69, 39, 117, 146, 184, + 163, 200, 222, 235, 248, 243, 219, 10, 152, 131, 123, 229, 203, 76, 120, 209 + }; + + uint8 h = 0; + MbUuid::const_iterator curr_iter = trg.cbegin(), end_iter = trg.cend(); + while ( curr_iter != end_iter ) + h = rand8[h ^ *curr_iter++]; + return h; + } +}; + + +#endif // _TOOL_UUID_H_ diff --git a/C3d/Include/topology.h b/C3d/Include/topology.h index 3b4955c..e30dd7c 100644 --- a/C3d/Include/topology.h +++ b/C3d/Include/topology.h @@ -56,6 +56,26 @@ typedef std::vector ConstVerticesVector; typedef std::vector VerticesSPtrVector; typedef std::vector ConstVerticesSPtrVector; +typedef std::set VerticesSet; +typedef VerticesSet::iterator VerticesSetIt; +typedef VerticesSet::const_iterator VerticesSetConstIt; +typedef std::pair VerticesSetRet; + +typedef std::set VerticesSPtrSet; +typedef VerticesSPtrSet::iterator VerticesSPtrSetIt; +typedef VerticesSPtrSet::const_iterator VerticesSPtrSetConstIt; +typedef std::pair VerticesSPtrSetRet; + +typedef std::set ConstVerticesSet; +typedef ConstVerticesSet::iterator ConstVerticesSetIt; +typedef ConstVerticesSet::const_iterator ConstVerticesSetConstIt; +typedef std::pair ConstVerticesSetRet; + +typedef std::set ConstVerticesSPtrSet; +typedef ConstVerticesSPtrSet::iterator ConstVerticesSPtrSetIt; +typedef ConstVerticesSPtrSet::const_iterator ConstVerticesSPtrSetConstIt; +typedef std::pair ConstVerticesSPtrSetRet; + // edges typedefs typedef SPtr WireEdgeSPtr; typedef SPtr ConstWireEdgeSPtr; @@ -267,7 +287,7 @@ private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. void operator = ( const MbVertex & ); - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVertex ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbVertex ) }; IMPL_PERSISTENT_OPS( MbVertex ) @@ -367,6 +387,10 @@ public : const MbVertex * GetBegVertexPointer() const { return begVertex; } /// \ru Выдать вершину-конец. \en Get the end vertex. const MbVertex * GetEndVertexPointer() const { return endVertex; } + /// \ru Выдать вершину-начало. \en Get the start vertex. + MbVertex * SetBegVertexPointer() { return begVertex; } + /// \ru Выдать вершину-конец. \en Get the end vertex. + MbVertex * SetEndVertexPointer() { return endVertex; } /// \ru Выдать вершину-начало. \en Get the start vertex. const MbVertex & GetBegVertex() const { return *begVertex; } @@ -473,8 +497,8 @@ public : /// \ru Установить свойства объекта. \en Set properties of the object. void SetProperties( const MbProperties & ); - OBVIOUS_PRIVATE_COPY( MbEdge ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbEdge ) +OBVIOUS_PRIVATE_COPY( MbEdge ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbEdge ) }; IMPL_PERSISTENT_OPS( MbEdge ) @@ -871,9 +895,9 @@ public : bool CutPeriodicEdge( const MbVector3D & eye, SSArray & trimParams, double & delT1, double & delT2 ) const; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - OBVIOUS_PRIVATE_COPY( MbCurveEdge ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveEdge ) +// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. +OBVIOUS_PRIVATE_COPY( MbCurveEdge ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbCurveEdge ) }; IMPL_PERSISTENT_OPS( MbCurveEdge ) @@ -1249,9 +1273,9 @@ public : /// \ru Удалить лишнюю память. \en Free the unnecessary memory. void EdgesAdjust () { edgeList.Adjust(); } - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - OBVIOUS_PRIVATE_COPY( MbLoop ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLoop ) +// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. +OBVIOUS_PRIVATE_COPY( MbLoop ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbLoop ) }; // MbLoop IMPL_PERSISTENT_OPS( MbLoop ) @@ -1473,9 +1497,11 @@ public: /// \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. 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 ); + void SetNullToFace( const MbFace * delFace ); + /// \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, bool setEdgeChanged ); /// \ru Установить указатели на грань слева или грань справа в ребрах циклов на данную грань и параметры поверхности по данным циклов грани (setBounds = true). \en Set the pointers to the face on the left or to the face on the right to the given face in edges of loops and parameters of surface by loops of face (setBounds = true). - void MakeRight( bool setBounds = false); + 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; @@ -1541,8 +1567,16 @@ public: bool FindEdgeIndex( const MbCurveEdge & edge, ThreeStates orient, size_t & loopIndex, size_t & edgeIndex ) const; /// \ru Дать ребро по индексам цикла грани и ребра в цикле. \en Get an edge by the indices of a face loop and an edge in the loop. MbCurveEdge * GetEdgeByIndex( size_t loopIndex, size_t edgeIndex ) const; - /// \ru Найти ориентированное ребро по ребру грани. \en Find an oriented edge by the edge of a face. - MbOrientedEdge * GetOrientedEdge( const MbCurveEdge & curveEdge ) const; + /// \ru Найти ориентированное ребро по индексам цикла грани и ребра в цикле. \en Find an oriented edge by the indices of a face loop and an edge in the loop. + const MbOrientedEdge * GetOrientedEdge( size_t loopIndex, size_t edgeIndex ) const; + MbOrientedEdge * SetOrientedEdge( size_t loopIndex, size_t edgeIndex ); + /// \ru Найти ориентированное ребро по ребру грани. Не ищет для швов. \en Find an oriented edge by the edge of a face. Don't seek if an edge is a seam. + const MbOrientedEdge * GetOrientedEdge( const MbCurveEdge & curveEdge ) const; + /// \ru Найти ориентированное ребро по ребру грани. Не ищет для швов. \en Find an oriented edge by the edge of a face. Don't seek if an edge is a seam. + MbOrientedEdge * SetOrientedEdge( const MbCurveEdge & curveEdge ); + /// \ru Удалить ориентированное ребро по ребру грани. \en Remove an oriented edge by the edge of a face. + bool DeleteOrientedEdge( MbCurveEdge * curveEdge ); + /// \ru Найти номера для рёбер. \en Find numbers for the edges. bool FindIndexByEdges( const RPArray & initEdges, SArray & indexes ) const; /// \ru Найти рёбра по номерам. \en Find edges by numbers. @@ -1739,9 +1773,9 @@ public: bool UpdateTemporal() const; - // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. - OBVIOUS_PRIVATE_COPY( MbFace ) - DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFace ) +// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default. +OBVIOUS_PRIVATE_COPY( MbFace ) +DECLARE_PERSISTENT_CLASS_NEW_DEL( MbFace ) }; IMPL_PERSISTENT_OPS( MbFace ) diff --git a/C3d/Include/topology_faceset.h b/C3d/Include/topology_faceset.h index 2fa50f8..4197b22 100644 --- a/C3d/Include/topology_faceset.h +++ b/C3d/Include/topology_faceset.h @@ -30,6 +30,7 @@ struct MATH_CLASS MbEdgeFunction; struct MATH_CLASS MbCheckTopologyParams; class MATH_CLASS MbFaceShell; class MATH_CLASS MbShellsDistanceData; +struct MATH_CLASS MbUnitInfo; namespace c3d // namespace C3D { @@ -153,10 +154,12 @@ public : sameShell == cm_Copy - an ordinary copying (the initial shell and its copy have no the common data). \n \~ \param[in] history - \ru История копий граней используется после операции для замены неизменённых копий граней их оригиналами. \en A history of faces copies is used after the operation for the replacement of unchanged copies by their originals. \~ + \param[in] iReg - \ru Регистратор копирования. + \en Copy registrator. \~ \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 ); + MbFaceShell * Copy( MbeCopyMode sameShell, MbShellHistory * history = NULL, MbRegDuplicate * iReg = NULL ); /** \brief \ru Создать копию. \en Create a copy. \~ @@ -201,11 +204,11 @@ public : /// \ru Вставить грань перед гранью с заданным индексом. \en Insert a face before the face with the given index. void InsertFace( size_t index, const MbFace & ); /// \ru Заменить грань с заданным индексом. \en Replace a face with the given index. - void ChangeFace( size_t index, const MbFace & ); + bool ChangeFace( size_t index, const MbFace & ); /// \ru Удалить грань с заданным индексом. \en Delete a face at the given index. - void DeleteFace( size_t index ); + bool DeleteFace( size_t index ); /// \ru Удалить грань. \en Delete a face. - void DeleteFace( const MbFace * ); + bool DeleteFace( const MbFace * ); /// \ru Отсоединить грань от оболочки с заданным индексом. \en Detach a face from a shell with the given index. MbFace * DetachFace( size_t index ); /// \ru Отсоединить грань. \en Detach face. @@ -214,8 +217,25 @@ public : void DeleteFaces(); /// \ru Отсоединить все грани оболочки. \en Detach all faces from shell. void DetachFaces(); + /// \ru Отсоединить все грани оболочки. \en Detach all faces from shell. + template + void DetachFaces( FacesVector & detachFaces ) + { + size_t facesCnt = faceSet.size(); + detachFaces.reserve( detachFaces.size() + facesCnt ); + c3d::FaceSPtr face; + for ( size_t k = 0; k < facesCnt; ++k ) { + face = faceSet[k]; + ::DecRefItem( faceSet[k] ); + faceSet[k] = C3D_NULL_PTR; + detachFaces.push_back( face ); + ::DetachItem( face ); + } + faceSet.clear(); + RemoveTemporal(); + } /// \ru Поменять местами грани оболочки. \en Swap shell faces. - void ExchangeFaces( size_t i1, size_t i2 ); + bool ExchangeFaces( size_t i1, size_t i2 ); /// \ru Установить правильную (текущую) информацию в ребрах о соединяемых ими гранях и параметры поверхностей по данным циклов граней (setBounds = true). \en Set the correct (the current) information in edges about the connected by them faces and parameters of surfaces by loops of faces (setBounds = true). void MakeRight( bool setBounds = false ); /// \ru Верно ли установлены указатели в ребрах на соединяемые ими грани. \en Are the pointers in edges to the connected by them faces correctly set? @@ -599,22 +619,53 @@ public : /// \ru Установить свойства объекта. \en Set properties of the object. void SetProperties( const MbProperties & ); - /// \ru Установить главное имя и вставить старое в индекс копирования. \en Set the main name and insert an old name to the copy index. - void SetMainName ( SimpleName mainName, bool addOldMainName ); + /** \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. \~ + \param[in] addOldMainName - \ru Вставить старое в индекс копирования. + \en Insert an old name to the copy index. \~ + */ + void SetMainName ( SimpleName newMainName, bool addOldMainName ); + /** \brief \ru Вставить индекс копирования. + \en Insert copying index. \~ + \details \ru Вставить индекс копирования. + \en Insert copying index. \~ + \param[in] index - \ru Индекс копирования. + \en Copying index. \~ + */ + void SetNamesCopyIndex( SimpleName index ); + /** \brief \ru Заменить главное имя, вставить старое главное имя и индекс копирования в индексы копирования. + \en Replace main name by new one, insert old main name and given copy index into name copy indices. \~ + \details \ru Заменить главное имя, вставить старое главное имя и индекс копирования в индексы копирования. Объекты с пустыми имена пропускаются. + \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. \~ + */ + void SetNamesCopyIndex( SimpleName index, const SimpleName & newMainName ); + /// \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 ); /// \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 ); + /// \ru Проименовать грани, рёбра и вершины оболочки. \en Rename faces, edges and vertices of the shell. - void SetShellNames ( const MbSNameMaker & names ); - /// \ru Заменить в имени метку копирования на index. \en Replace in a name a copying label by 'index'. - void SetNamesCopyIndex ( SimpleName index ); - /// \ru Проименовать грани оболочки именами оболочки s. \en Name shell faces by names of the shell 's'. - void SetShellNames ( const MbFaceShell * s ); - /// \ru Очистить все имена в оболочке. \en Clear all shell names. - void ClearShellNames (); + void SetShellNames( const MbSNameMaker & ); + /// \ru Проименовать элементы оболочки именами оболочки s. \en Name shell elements by names of the shell 's'. + void SetShellNames( const MbFaceShell & ); + + /** \brief \ru Очистить все имена в оболочке. + \en Clear all shell names. \~ + \details \ru Очистить имена всех элементов оболочки : граней, ребер и вершин. + \en Clear the names of all shell elements: faces, edges, and vertices. \~ + */ + void ClearShellNames(); /// \ru Очистить имена ребер в оболочке. \en Clear all shell edges names. - void ClearEdgesNames ( bool clearVerticesNames = true ); + void ClearEdgesNames( bool clearVerticesNames = true ); /** \brief \ru Проверка оболочки: вершин (удаление совпадающих и лишних), ребер (со слиянием). \en Validation of the shell: vertices (deletion of coincident and extra), edges (with merge). \~ @@ -630,18 +681,17 @@ public : /// \ru Найти граничные рёбра и сделать граничными их кривые. \en Find the boundary edges, make their curve boundary. bool MakeBoundaryCurve(); /// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell. - bool GetBoundaryEdges( RPArray & ) const; - /// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell. - bool GetBoundaryEdges( c3d::ConstEdgesVector & ) const; + template + bool GetBoundaryEdges( ConstEdgesVector & ) const; /// \ru Для множества ребер найти номера ребер и номера ее граней. \en For a set of edges find their indices and indices of their faces. bool FindFacesIndexByEdges( const RPArray & init, SArray & indexes, bool any = false ) const; /// \ru Для множества структур (ребер и функций изменения радиусов) найти номера ребер и номера ее граней. \en For a set of structures (edges and functions of radii changing) find indices of edges and their faces. bool FindFacesIndexByEdges( const SArray & init, - RPArray & functions, SArray & indexes ) const; + RPArray & functions, RPArray & slideways, SArray & indexes ) const; /// \ru Для множества номеров ребер и номеров ее граней найти ребра. \en For a set of edge indices and indices of their faces find edges. - bool FindEdgesByFacesIndex( const SArray & indexes, RPArray * functions, - RPArray & initCurves, RPArray & initFunctions ) const; + bool FindEdgesByFacesIndex( const SArray & indexes, RPArray * functions, RPArray * slideways, + RPArray & initCurves, RPArray & initFunctions, RPArray & initSlideways ) const; /// \ru Найти номера граней по ребру. \en Find faces indices by the edge. bool FindFacesIndexByEdge( const MbCurveEdge & edge, size_t & ind1, size_t & ind2, bool any = false ) const; /// \ru Для множества граней найти множество их номеров. \en For a set of faces find a set of their indices. @@ -688,8 +738,14 @@ public : /// \ru Найти грань по имени. \en Find face by name. MbFace * FindFaceByName ( const MbName & ); - /// \ru Объединить подобные грани. \en Merge similar faces. - bool MergeSimilarFaces(); + /** \brief \ru Объединить подобные грани. + \en Merge similar faces. \~ + \details \ru Объединить подобные грани. + \en Merge similar faces. \~ + \param[in] simMainName - \ru Новое главное имя для объединенных граней (если не равно c3d::SIMPLENAME_MAX). + \en The new primary name for the merged faces (if it is not equal to c3d::SIMPLENAME_MAX). \~ + */ + bool MergeSimilarFaces( SimpleName simMainName = c3d::SIMPLENAME_MAX ); /// \ru Создан ли временный объект сопровождения? \en Is a temporary object for the maintenance created? bool IsTemporal() const { return (temporal != NULL); } @@ -744,6 +800,7 @@ MbFaceShell::MbFaceShell( const Faces & initFaces ) } } + //------------------------------------------------------------------------------ // \ru Выдать множество вершин оболочки. \en Get a set of vertices of the shell. // --- @@ -791,13 +848,14 @@ void MbFaceShell::GetVertices( VerticesVector & vertices ) const } } + //------------------------------------------------------------------------------ // \ru Выдать множество вершин и множество ребер оболочки. \en Get a set of vertices and a set of edges of the shell. // --- template void MbFaceShell::GetItems( VerticesVector & vertices, EdgesVector & edges ) const { - if ( edges.size() == 0 && vertices.size() == 0 ) { + if ( edges.empty() && vertices.empty() ) { size_t maxCount = 1; size_t i, fcount; @@ -808,8 +866,8 @@ void MbFaceShell::GetItems( VerticesVector & vertices, EdgesVector & edges ) con const MbLoop * loop = face->_GetLoop( j ); size_t ecount = loop->GetEdgesCount(); - for ( size_t k = 0; k < ecount; k++ ) { - MbCurveEdge * edge = const_cast(&loop->_GetOrientedEdge( k )->GetCurveEdge()); + for ( size_t k = 0; k < ecount; ++k ) { + const MbCurveEdge * edge = const_cast(&loop->_GetOrientedEdge( k )->GetCurveEdge()); edge->SetOwnLabel( ls_Used ); edge->GetBegVertex().SetOwnLabel( ls_Used ); edge->GetEndVertex().SetOwnLabel( ls_Used ); @@ -833,8 +891,8 @@ void MbFaceShell::GetItems( VerticesVector & vertices, EdgesVector & edges ) con for ( size_t j = 0, lcount = face->GetLoopsCount(); j < lcount; ++j ) { const MbLoop * loop = face->_GetLoop( j ); - SPtr edge; - SPtr vertex; + c3d::EdgeSPtr edge; + c3d::VertexSPtr vertex; for ( size_t k = 0, ecount = loop->GetEdgesCount(); k < ecount; ++k ) { edge = const_cast(&loop->_GetOrientedEdge( k )->GetCurveEdge()); @@ -876,6 +934,7 @@ void MbFaceShell::GetItems( VerticesVector & vertices, EdgesVector & edges ) con } } + //------------------------------------------------------------------------------ // \ru Для множества граней найти множество их комбинированных номеров. \en For a set of faces find a set of their combined indices. // --- @@ -927,6 +986,7 @@ bool MbFaceShell::FindIndexByFaces( const FacesPointersVector & initFaces, ItemI return (indices.size() > 0); } + //------------------------------------------------------------------------------ // \ru Найти множество граней по множеству комбинированных индексов. \en Find a set of faces by a set of combined indices. // --- @@ -947,6 +1007,7 @@ bool MbFaceShell::FindConstFacesByIndex( const ItemIndices & indices, ConstFaces return initFaces.size() > 0; } + //------------------------------------------------------------------------------ // \ru Найти множество граней по множеству комбинированных индексов. \en Find a set of faces by a set of combined indices. // --- @@ -968,6 +1029,39 @@ bool MbFaceShell::FindFacesByIndex( const ItemIndices & indices, FacesPointersVe } +//------------------------------------------------------------------------------ +// \ru Получить краевые ребра оболочки. \en Get boundary edges of the shell. +// --- +template +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 ) + continue; + for ( size_t j = 0, loopsCnt = face->GetLoopsCount(); j < loopsCnt; ++j ) { + const MbLoop * loop = face->_GetLoop( j ); + if ( loop == NULL ) + continue; + for ( size_t k = 0, edgesCnt = loop->GetEdgesCount(); k < edgesCnt; ++k ) { + const MbOrientedEdge * orientEdge = loop->_GetOrientedEdge( k ); + if ( orientEdge != NULL ) { + c3d::ConstEdgeSPtr edge( &orientEdge->GetCurveEdge() ); + if ( edge->IsBoundaryFace() ) + boundaryEdges.push_back( edge ); + } + } + } + } + + if ( boundaryEdges.size() > boundaryCnt ) + return true; + + return false; +} + + //------------------------------------------------------------------------------ /** \brief \ru Параметры функции проверки топологии оболочки. \en Parameters of validation of the shell. \~ @@ -981,6 +1075,7 @@ 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. + 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: @@ -988,15 +1083,17 @@ public: : 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 ) - , controlFaces ( ) - , boundaryEdges ( ) + : mergeEdges ( doMergingEdges ) + , addNameAttributes( addNameAttrs ) + , version ( ver ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. + , controlFaces ( ) + , boundaryEdges ( ) {} template explicit MbCheckTopologyParams( bool doMergingEdges, const MbSNameMaker & nameMaker, @@ -1004,6 +1101,7 @@ public: : mergeEdges ( doMergingEdges ) , addNameAttributes( nameMaker.GetParentNamesAttributes() ) , version ( nameMaker.GetMathVersion() ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. , controlFaces ( ) , boundaryEdges ( ) { @@ -1018,11 +1116,12 @@ public: template explicit MbCheckTopologyParams( bool doMergingEdges, VERSION ver, bool addNameAttrs, const Faces & faces ) - : mergeEdges ( doMergingEdges ) - , addNameAttributes( addNameAttrs ) - , version ( ver ) - , controlFaces ( ) - , boundaryEdges ( ) + : mergeEdges ( doMergingEdges ) + , addNameAttributes( addNameAttrs ) + , version ( ver ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. + , controlFaces ( ) + , boundaryEdges ( ) { size_t facesCnt = faces.size(); if ( facesCnt > 0 ) { @@ -1038,6 +1137,7 @@ public: : mergeEdges ( doMergingEdges ) , addNameAttributes( nameMaker.GetParentNamesAttributes() ) , version ( nameMaker.GetMathVersion() ) + , lastMainName ( c3d::SIMPLENAME_MAX ) // \ru Неизвестно. \en Unknown. , controlFaces ( ) , boundaryEdges ( edges ) { @@ -1052,17 +1152,20 @@ public: } ~MbCheckTopologyParams() {} public: - bool MergeEdges () const { return mergeEdges; } - bool AddNameAttributes() const { return addNameAttributes; } - VERSION MathVersion () const { return version; } + bool MergeEdges () const { return mergeEdges; } + bool AddNameAttributes() const { return addNameAttributes; } + VERSION MathVersion () const { return version; } + SimpleName LastMainName() const { return lastMainName; } - void ClearControlFaces() { controlFaces.clear(); } - void SetControlFaces( const c3d::ConstFacesVector & faces ) + void SetLastMainName( const SimpleName & lmn ) { lastMainName = lmn; } + + void ClearControlFaces() { controlFaces.clear(); } + void SetControlFaces( const c3d::ConstFacesVector & faces ) { controlFaces = faces; std::sort( controlFaces.begin(), controlFaces.end() ); } - bool DeleteTheseSortedFaces( const c3d::ConstFacesVector & sortedDelFaces ) + bool DeleteTheseSortedFaces( const c3d::ConstFacesVector & sortedDelFaces ) { bool res = false; if ( controlFaces.size() > 0 && sortedDelFaces.size() > 0 ) { @@ -1088,13 +1191,13 @@ public: //------------------------------------------------------------------------------ -/** \brief \ru Структура для передачи ребра и функции. - \en A structure for edge and function transferring. \~ - \details \ru Структура передаёт информацию о ребре и функции изменения радиуса скругления ребра. +/** \brief \ru Структура для передачи ребра и функции или опорной кривой. + \en A structure for edge and function transferring or supporting curve. \~ + \details \ru Структура передаёт информацию о ребре и функции изменения радиуса скругления ребра или об опорной кривой для скругления. Структура используется в алгоритмах скругления ребер переменным радиусом. \n Начальный параметр функции изменения радиуса соответствует начальной вершине ребра. Конечный параметр функции изменения радиуса соответствует конечной вершине ребра. \n - \en A structure transmits an information about an edge and a function of edge fillet radius changing. + \en A structure transmits an information about an edge and a function of edge fillet radius changing or supporting curve for filliting. A structure is used in algorithms of edge fillet by the variable radius. \n The starting parameter of radius changing function corresponds to the starting vertex of the edge. The ending parameter of radius changing function corresponds to the ending vertex of the edge. \n \~ @@ -1105,24 +1208,31 @@ struct MATH_CLASS MbEdgeFunction { private: const MbCurveEdge * edge; ///< \ru Ребро. \en An edge. const MbFunction * function; ///< \ru Функция изменения радиуса по относительной длине ребра. \en A function of radius changing by relative edge length. + const MbCurve3D * slideway; ///< \ru Опорная кривая скругления. \en A supporting curve for fillet. public: /// \ru Конструктор по умолчанию \en Default constructor - MbEdgeFunction () : edge(NULL), function(NULL) {} + MbEdgeFunction () : edge(NULL), function(NULL), slideway(NULL) {} /// \ru Конструктор по ребру и функции. \en Constructor by an edge and function. - MbEdgeFunction ( const MbCurveEdge * e, const MbFunction * f ) : edge(e), function(f) {} + MbEdgeFunction ( const MbCurveEdge * e, const MbFunction * f ) : edge(e), function(f), slideway(NULL) {} + /// \ru Конструктор по ребру и опорной кривой. \en Constructor by an edge and a supporting curve. + MbEdgeFunction ( const MbCurveEdge * e, const MbCurve3D * c ) : edge(e), function(NULL), slideway(c) {} /// \ru Конструктор по другому ребру с функцией. \en Constructor by other edge with a function. - MbEdgeFunction ( const MbEdgeFunction & other ) : edge(other.edge), function(other.function) {} + MbEdgeFunction ( const MbEdgeFunction & other ) : edge(other.edge), function(other.function), slideway(other.slideway) {} ~MbEdgeFunction() {} public: - /// \ru Функция инициализации по ребру и функции. \en A function of initialization by an edge and a function. - void Init( const MbCurveEdge * e, const MbFunction * f ) { edge = e; function = f; } + /// \ru Инициализация по ребру и функции. \en Initialization by an edge and a function. + void Init( const MbCurveEdge * e, const MbFunction * f ) { edge = e; function = f; slideway = 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; } /// \ru Дать ребро. \en Get an edge. const MbCurveEdge * Edge() const { return edge; } /// \ru Дать функцию изменения радиуса. \en Get a function of radius changing. const MbFunction * Function() const { return function; } + /// \ru Дать опорную кривую скругления. \en Get a supporting curve for fillet. + const MbCurve3D * Slideway() const { return slideway; } /// \ru Оператор присваивания. \en Assignment operator. - void operator = ( const MbEdgeFunction & other ) { edge = other.edge; function = other.function; } + void operator = ( const MbEdgeFunction & other ) { edge = other.edge; function = other.function; slideway = other.slideway; } }; @@ -1237,6 +1347,55 @@ public: } }; + +//------------------------------------------------------------------------------ +/** \brief \ru Информация о произвольном элементе. + \en Information about arbitrary element. \~ + \details \ru В качестве произвольного элемента может выступить элемент массива. \n + \en Array element may be arbitrary element. \n \~ + \ingroup Data_Structures +*/ +//--- +struct MATH_CLASS MbUnitInfo { +public: + MbeItemLocation location; ///< \ru Положение элемента. \en Element location. + size_t index; ///< \ru Индекс элемента. \en Index of element. + +public: + /// \ru Конструктор по умолчанию. \en Default constructor. + MbUnitInfo() + : location( iloc_Undefined ) + , index ( SYS_MAX_T ) + {} + /// \ru Конструктор копирования. \en Copy-constructor. + MbUnitInfo( const MbUnitInfo & obj ) + : location( obj.location ) + , index ( obj.index ) + {} + /// \ru Конструктор по индексу. \en Constructor by index. + MbUnitInfo( size_t ind ) + : location( iloc_InItem ) + , index ( ind ) + {} + /// \ru Конструктор по положению элемента. \en Constructor by element location. + MbUnitInfo( MbeItemLocation loc ) + : location( loc ) + , index ( SYS_MAX_T ) + {} + +public: + /// \ru Сброс параметров. \en Parameter reset. + void Reset() { location = iloc_Undefined; index = SYS_MAX_T; } + /// \ru Оператор присваивания. \en Assignment operator. + MbUnitInfo & operator = ( const MbUnitInfo & unitInfo ) + { + location = unitInfo.location; + index = unitInfo.index; + return (*this); + } +}; + + //------------------------------------------------------------------------------ /** \brief \ru Объект с информацией о положении точки относительно оболочки. \en An object with information about the point location relative to the shell. \~ @@ -1402,13 +1561,15 @@ public: */ // --- inline -void SetMainName( MbName & name, SimpleName mainName, bool addOldMainName ) +bool SetMainName( MbName & name, SimpleName mainName, bool addOldMainName ) { if ( !name.IsEmpty() ) { if ( addOldMainName ) name.SetCopyIndex( name.GetMainName() ); name.SetMainName( mainName ); + return true; } + return false; } diff --git a/C3d/Include/topology_item.h b/C3d/Include/topology_item.h index 84fed69..57be739 100644 --- a/C3d/Include/topology_item.h +++ b/C3d/Include/topology_item.h @@ -42,6 +42,7 @@ enum MbeTopologyType { tt_Undefined = 0, ///< \ru Неизвестный объект. \en Unknown object. tt_TopItem = 1, ///< \ru Топологический объект. \en A topological object. \n + tt_Proxy = 10, ///< \ru Заменитель топологического объекта. \en A topological object proxy. \n tt_Vertex = 101, ///< \ru Вершина. \en A vertex. @@ -82,7 +83,7 @@ enum MbeChangedType { //------------------------------------------------------------------------------ -/** \brief \ru Метка для выполнения операция. +/** \brief \ru Метка для выполнения операций. \en A label for performing of operations. \~ \ingroup Topology_Items */ @@ -157,13 +158,14 @@ public: virtual MbeTopologyType IsA() const = 0; /// \ru Подготовить объект к записи. \en Prepare an object for writing. - void PrepareWrite() { SetRegistrable( GetUseCount() > 1 ? registrable : noRegistrable ); } + void PrepareWrite() const { SetRegistrable( GetUseCount() > 1 ? registrable : noRegistrable ); } bool IsAVertex() const { return (IsA() == tt_Vertex); } ///< \ru Это вершина? \en Is it a vertex? bool IsAWireEdge() const { return (IsA() == tt_Edge); } ///< \ru Это ребро каркаса? \en Is it an edge of wireframe? bool IsAnEdge() const { return (IsA() == tt_CurveEdge); } ///< \ru Это ребро? \en Is it an edge? bool IsAFace() const { return (IsA() == tt_Face); } ///< \ru Это грань? \en Is it a face? bool IsAShell() const { return (IsA() == tt_FaceShell); } ///< \ru Это оболочка? \en Is it a shell? + bool IsAProxy() const { return (IsA() == tt_Proxy); } ///< \ru Это заменитель? \en Is it a proxy? DECLARE_PERSISTENT_CLASS( MbTopItem ) OBVIOUS_PRIVATE_COPY( MbTopItem ) @@ -171,6 +173,7 @@ OBVIOUS_PRIVATE_COPY( MbTopItem ) IMPL_PERSISTENT_OPS( MbTopItem ) + //------------------------------------------------------------------------------ /** \brief \ru Топологический объект с именем. \en Topological object with name. \~ @@ -345,7 +348,8 @@ IMPL_PERSISTENT_OPS( MbTopologyItem ) //------------------------------------------------------------------------------ // \ru Установить флаг, свидетельствующий о том, что объект был (не был) изменен. \en Set flag which indicates that an object has (not) been changed. // --- -inline void MbTopologyItem::SetOwnChanged( MbeChangedType n ) +inline +void MbTopologyItem::SetOwnChanged( MbeChangedType n ) { if ( n != tct_Unchanged ) { changed |= n; @@ -359,7 +363,8 @@ inline void MbTopologyItem::SetOwnChanged( MbeChangedType n ) //------------------------------------------------------------------------------ // \ru Получить флаг, свидетельствующий о том, что объект был создан, переименован, трансформирован или переориентирован. \en Get flag which indicates that an object has been only created, renamed, transformed or reoriented. // --- -inline bool MbTopologyItem::IsOwnChangedWeakly() const +inline +bool MbTopologyItem::IsOwnChangedWeakly() const { uint16 wrkFlag = (tct_Created | tct_Renamed | tct_Transformed | tct_Reoriented | tct_Modified); wrkFlag = ~wrkFlag; @@ -372,7 +377,8 @@ inline bool MbTopologyItem::IsOwnChangedWeakly() const //------------------------------------------------------------------------------ // \ru Копирование данных. \en Data copying. // --- -inline void MbTopologyItem::Assign( const MbTopologyItem & other ) +inline +void MbTopologyItem::Assign( const MbTopologyItem & other ) { AttributesAssign( other ); name.SetName( other.GetName() ); @@ -381,4 +387,40 @@ inline void MbTopologyItem::Assign( const MbTopologyItem & other ) } +//------------------------------------------------------------------------------ +/** \brief \ru Заменитель топологического объекта. + \en Topology object proxy. \~ + \details \ru Заменитель топологического объекта. Используется в алгоритмах именования. + \en Proxy for a topology item. It's used in naming algorithms. \~ + \ingroup Topology_Items +*/ +// --- +class MATH_CLASS MbTopologyProxy : public MbTopologyItem { + friend class MbNameMaker; +protected: + MbTopologyProxy() : MbTopologyItem() {} +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 ); + // \ru Сдвинуть вдоль вектора. \en Move along a vector. + virtual void Move ( const MbVector3D &, MbRegTransform * = NULL ); + //\ru Повернуть вокруг оси. \en Rotate around an axis. + virtual void Rotate ( const MbAxis3D &, double, MbRegTransform * = NULL ); +public: + // \ru Вычислить расстояние до точки. \en Calculate the distance to a point. + virtual double DistanceToPoint( const MbCartPoint3D & ) const; + // \ru Добавить свой габарит в присланный габарит. \en Add your own bounding box into the sent bounding box. + virtual void AddYourGabaritTo( MbCube & ) const; + // \ru Рассчитать габарит в локальной системы координат, заданной матрицей преобразования в эту систему. \en Calculate bounding box in the local coordinate system which is given by the matrix of transformation to this system. + virtual void CalculateLocalGabarit( const MbMatrix3D &, MbCube & ) const; + // \ru Являются ли объекты равными? \en Determine whether objects are equal. + virtual bool IsSame( const MbTopologyItem &, double /*accuracy*/ ) const; + // \ru Построить полигональную копию объекта mesh. \en Construct a polygonal copy of an object mesh). + virtual void CalculateMesh( const MbStepData &, const MbFormNote &, MbMesh & ) const; + +OBVIOUS_PRIVATE_COPY( MbTopologyProxy ) +}; + #endif // __TOPOLOGY_ITEM_H diff --git a/C3d/Include/tri_ball_pivoting.h b/C3d/Include/tri_ball_pivoting.h index e1cbe66..ddd1d0c 100644 --- a/C3d/Include/tri_ball_pivoting.h +++ b/C3d/Include/tri_ball_pivoting.h @@ -1,249 +1,249 @@ -#ifndef __TRI_BALL_PIVOTING_H -#define __TRI_BALL_PIVOTING_H - -#include -#include -#include -#include -#include - - -class MATH_CLASS MbGrid; -class MATH_CLASS MbCollection; - - -//------------------------------------------------------------------------------ -// Облако точек -// --- -class MbPointCloud -{ -protected: - enum { - pnt_Deleted = 0x0001, // Точка удалена из сетки. - pnt_Visited = 0x0010, // Точка используется в сетке (является вершиной построенного треугольника). - pnt_Border = 0x0020, // Точка находится на внешней границе построенной сетки. - pnt_Processed = 0x0100 // Точка уже обработана алгоритмом. - }; - -public: - const std::vector & points; // Множество точек. - const std::vector & normals; // Множество нормалей в точках (согласовано с множеством точек). - std::vector flags; // Множество битовых флагов для точек. - -public: - /// Конструктор. - MbPointCloud( const MbCollection & collection ) - : points ( collection.GetPoints() ) - , normals ( collection.GetNormals() ) - , flags ( collection.PointsCount(), 0 ) - { } - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbPointCloud( const MbPointCloud & ); - -public: - /// Выдать количество точек. - size_t PointsCount() const { return points.size(); } - /// Выдать точку по её номеру. - MbCartPoint3D GetPoint ( size_t i ) const { return points[i]; } - /// Выдать нормаль по её номеру. - MbVector3D GetNormal( size_t i ) const { return normals[i]; } - /// Находится ли точка на границе построенной сетки. - bool IsBorder( size_t i ) const { return (flags[i] & pnt_Border) != 0; } - /// Установить признак того, что точка находится на границе построенной сетки. - void SetBorder( size_t i ) { flags[i] |= pnt_Border; } - /// Очистить признак того, что точка находится на границе построенной сетки. - void ClearBorder( size_t i ) { flags[i] &= ~pnt_Border;} - /// Обработана ли точка алгоритмом. - bool IsUsed( size_t i ) const { return (flags[i] & pnt_Processed) != 0; } - /// Установить признак того, что точка обработана алгоритмом. - void SetUsed( size_t i ) { flags[i] |= pnt_Processed; } - /// Очистить признак того, что точка обработана алгоритмом. - void ClearUsed( size_t i ) { flags[i] &= ~pnt_Processed;} - /// Удалена ли точка из сетки. - bool IsDeleted( size_t i ) const { return (flags[i] & pnt_Deleted) != 0; } - /// Установить признак того, что точка удалена из сетки. - void SetDeleted( size_t i ) { flags[i] |= pnt_Deleted; } - /// Является ли точка вершиной уже построенного треугольника. - bool IsVisited( size_t i ) const { return (flags[i] & pnt_Visited) != 0; } - /// Установить признак того, что точка является вершиной построенного треугольника. - void SetVisited( size_t i ) { flags[i] |= pnt_Visited; } - /// Очистить признак того, что точка является вершиной построенного треугольника. - void ClearVisite( size_t i ) { flags[i] &= ~pnt_Visited; } - -private: - // Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. - void operator = ( const MbPointCloud & ); -}; - - -//------------------------------------------------------------------------------ -// Граница фронта. -// --- -class MbFrontEdge -{ -public: - size_t v0, v1, v2; // v0, v1 - описывают отрезок - границу фронта, - // v2 - точка внутри области, ограниченной фронтом. - bool active; // Является ли ребро границей фронта или внутренним ребром. - - // Цикл границ фронта рассматривается как двусвязный список. - std::list::iterator next; - std::list::iterator previous; - -public: - /// Конструктор. - MbFrontEdge() - {} - /// Конструктор по параметрам. - MbFrontEdge( size_t _v0, size_t _v1, size_t _v2 ) - : v0 ( _v0 ) - , v1 ( _v1 ) - , v2 ( _v2 ) - , active( true ) - { - C3D_ASSERT( v0 != v1 && v1 != v2 && v0 != v2 ); - } - /// Оператор сравнения. - bool operator== ( const MbFrontEdge & f ) const - { - return ( (v0 == f.v0) && (v1 == f.v1) && (v2 == f.v2) ); - } -}; - - -//------------------------------------------------------------------------------- -// Алгоритм подвижного фронта (Advancing Front Algorithm, R. Lohner) -// Основной идеей является расширение границ области (фронта) путем -// присоединения точки из набора и построения новых границ области из вершин -// текущей актиной границы до этой точки. Активная граница при этом убирается из -// фронта. -// Наследник этого класса должен определить правила: -// 1) Seed - правило выбора трех точек из набора для построения начального треугольника; -// 2) Place- правило выбора точки из набора для построения новых границ области из вершин -// текущей активной границы до этой точки. -// --- -class MbAdvancingFront -{ -public: - typedef std::list::iterator ListIterator; - - std::list front; // Список границ фронта области. - std::list internal; // Список внутренних границ области. - std::vector nb; // Вектор со значениями, соответствующими числу границ фронта, проходящих через точку с данным индексом. - MbPointCloud pointCloud; // Облако точек. - MbGrid & grid; // Объект триангуляции, который необходимо наполнить. - -public: - /// Конструктор. - MbAdvancingFront( const MbCollection & coll, MbGrid & _grid ) ; - /// Деструктор. - virtual ~MbAdvancingFront(); - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbAdvancingFront( const MbAdvancingFront & ); - -public: - /// Построить сетку. - void BuildMesh(); - -protected: - enum ListID { - edge_Front, // Внешняя граница. - edge_Internal // Внутреннее ребро. - }; - - typedef std::pair ResultIterator; - - // Найти точки для исходного(порождающего фронт) треугольника. - virtual bool Seed( size_t & v0, size_t & v1, size_t & v2 ) = 0; - // Найти точку для построения треугольника по заданному ребру. - virtual bool Place( MbFrontEdge & e, ResultIterator & touch, size_t & v ) = 0; - // Построить новый фронт по треугольнику. - bool SeedFace(); - // Расширить фронт путем поиска, присоединения точки и построения треугольника по активному ребру фронта. - bool Advance(); - // Добавить треугольник в сетку. - void AddTriangleToMesh( size_t v0, size_t v1, size_t v2 ); - // Проверить ребро: - // 1. На правильность ориентации, т.е. ребро (v0,v1) может быть включено в другие треугольники только с обратным направлением. - // 2. Ребро существует по краней мере в единственном экземпляре. - bool CheckEdge( size_t v0, size_t v1 ); - // Добавить новое ребро фронта в конец очереди. - ListIterator addNewEdge( const MbFrontEdge & e ); - // Квалифицировать ребро как внутреннюю границу. - void MoveEdgeToInternals( ListIterator e ); - // Удалить ребро. - void EraseEdge( ListIterator e ); - // Перемесить ребро в конец очереди. - void MoveBack( ListIterator e ); - // Перемесить ребро в начало очереди. - void MoveFront( ListIterator e ); - // Проверить, может ли ребро быть сшито с одним из соседей. - bool Glue( ListIterator e ); - // Склеить вместе два ребра, если a.next = b. - bool Glue( ListIterator a, ListIterator b ); - // Разорвать фронт в точке. - void Detach( size_t v ); - -private: - void operator = ( const MbAdvancingFront & ); -}; - - -//------------------------------------------------------------------------------- -// Алгоритм поворотного шара (Ball pivoting algorithm) -// Reference: Bernardini F., Mittleman J., Rushmeier H., Silva C., Taubin G. -// "The ball-pivoting algorithm for surface reconstruction", IEEE TVCG, 1999 -// 1) Точки, использованные в алгоритме маркируются как pnt_Visited; -// 2) Граничные точки сетки маркируются как pnt_Border; -// 3) В векторе nb по индексу вершины хранится количество ребер, проходяших через нее; -// 4) Точки, обработанные в алгоритме маркируются как pnt_Processed. -// --- -class MbBallPivoting: public MbAdvancingFront -{ -public: - double radius; // Радиус поворотного шара (абсолютная величина в единицах измерения сетки). - double minEdge; // Минимальная длина ребра. - double maxEdge; // Максимальная длина ребра. - double maxAngle; // Максимальный угол между двумя гранями сетки (косинус). - -public: - /// Конструктор. - MbBallPivoting( const MbCollection & coll, // Объект с облаком точек, - MbGrid & grid, // триангуляция, которую нужно наполнить/дополнить, - double radBall = 0.0, // радиус поворотного шара, если 0 будет предпринята попытка его автоопределения, - double radMin = 0.2, // радиус кластеризации ( в % от радиуса поворотного шара ), - double angle = M_PI / 2 ); // максимальный угол между двумя элементами сетки. - /// Деструктор. - ~MbBallPivoting(); - -protected: - // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. - MbBallPivoting( const MbBallPivoting & ); - -private: - /// Найти точки начального треугольника по алгоритму поворотного шара. - bool Seed( size_t & v0, size_t & v1, size_t & v2 ); - /// Найти точку для построения треугольника по заданному ребру согласно алгоритму поворотного шара. - bool Place( MbFrontEdge & edge, MbAdvancingFront::ResultIterator & touch, size_t & v ); - /// Найти сферу, проходящую через три заданных точки, такую что нормаль к грани через эти три точки направлена в центр сферы. - bool FindSphere( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, MbCartPoint3D & center ); - /// Рассчитать угол между векторами, учитывая ориентацию axis. - double OrientedAngleRad( MbVector3D p, MbVector3D q, const MbVector3D & axis ); - /// Пометить точку и ее соседей. - void Mark( size_t idx ); - -private: - size_t last_seed; // Испольуется для поиска нового фронта когда текущий фронт пуст. - MbCartPoint3D baricenter; // Используется для первого поиска. - KdTree * tree; // К-мерное дерево для поиска N ближайших соседей точки. - -private: - void operator = ( const MbBallPivoting & ); -}; - - +#ifndef __TRI_BALL_PIVOTING_H +#define __TRI_BALL_PIVOTING_H + +#include +#include +#include +#include +#include + + +class MATH_CLASS MbGrid; +class MATH_CLASS MbCollection; + + +//------------------------------------------------------------------------------ +// Облако точек +// --- +class MbPointCloud +{ +protected: + enum { + pnt_Deleted = 0x0001, // Точка удалена из сетки. + pnt_Visited = 0x0010, // Точка используется в сетке (является вершиной построенного треугольника). + pnt_Border = 0x0020, // Точка находится на внешней границе построенной сетки. + pnt_Processed = 0x0100 // Точка уже обработана алгоритмом. + }; + +public: + const std::vector & points; // Множество точек. + const std::vector & normals; // Множество нормалей в точках (согласовано с множеством точек). + std::vector flags; // Множество битовых флагов для точек. + +public: + /// Конструктор. + MbPointCloud( const MbCollection & collection ) + : points ( collection.GetPoints() ) + , normals ( collection.GetNormals() ) + , flags ( collection.PointsCount(), 0 ) + { } + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbPointCloud( const MbPointCloud & ); + +public: + /// Выдать количество точек. + size_t PointsCount() const { return points.size(); } + /// Выдать точку по её номеру. + MbCartPoint3D GetPoint ( size_t i ) const { return points[i]; } + /// Выдать нормаль по её номеру. + MbVector3D GetNormal( size_t i ) const { return normals[i]; } + /// Находится ли точка на границе построенной сетки. + bool IsBorder( size_t i ) const { return (flags[i] & pnt_Border) != 0; } + /// Установить признак того, что точка находится на границе построенной сетки. + void SetBorder( size_t i ) { flags[i] |= pnt_Border; } + /// Очистить признак того, что точка находится на границе построенной сетки. + void ClearBorder( size_t i ) { flags[i] &= ~pnt_Border;} + /// Обработана ли точка алгоритмом. + bool IsUsed( size_t i ) const { return (flags[i] & pnt_Processed) != 0; } + /// Установить признак того, что точка обработана алгоритмом. + void SetUsed( size_t i ) { flags[i] |= pnt_Processed; } + /// Очистить признак того, что точка обработана алгоритмом. + void ClearUsed( size_t i ) { flags[i] &= ~pnt_Processed;} + /// Удалена ли точка из сетки. + bool IsDeleted( size_t i ) const { return (flags[i] & pnt_Deleted) != 0; } + /// Установить признак того, что точка удалена из сетки. + void SetDeleted( size_t i ) { flags[i] |= pnt_Deleted; } + /// Является ли точка вершиной уже построенного треугольника. + bool IsVisited( size_t i ) const { return (flags[i] & pnt_Visited) != 0; } + /// Установить признак того, что точка является вершиной построенного треугольника. + void SetVisited( size_t i ) { flags[i] |= pnt_Visited; } + /// Очистить признак того, что точка является вершиной построенного треугольника. + void ClearVisite( size_t i ) { flags[i] &= ~pnt_Visited; } + +private: + // Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. + void operator = ( const MbPointCloud & ); +}; + + +//------------------------------------------------------------------------------ +// Граница фронта. +// --- +class MbFrontEdge +{ +public: + size_t v0, v1, v2; // v0, v1 - описывают отрезок - границу фронта, + // v2 - точка внутри области, ограниченной фронтом. + bool active; // Является ли ребро границей фронта или внутренним ребром. + + // Цикл границ фронта рассматривается как двусвязный список. + std::list::iterator next; + std::list::iterator previous; + +public: + /// Конструктор. + MbFrontEdge() + {} + /// Конструктор по параметрам. + MbFrontEdge( size_t _v0, size_t _v1, size_t _v2 ) + : v0 ( _v0 ) + , v1 ( _v1 ) + , v2 ( _v2 ) + , active( true ) + { + C3D_ASSERT( v0 != v1 && v1 != v2 && v0 != v2 ); + } + /// Оператор сравнения. + bool operator== ( const MbFrontEdge & f ) const + { + return ( (v0 == f.v0) && (v1 == f.v1) && (v2 == f.v2) ); + } +}; + + +//------------------------------------------------------------------------------- +// Алгоритм подвижного фронта (Advancing Front Algorithm, R. Lohner) +// Основной идеей является расширение границ области (фронта) путем +// присоединения точки из набора и построения новых границ области из вершин +// текущей актиной границы до этой точки. Активная граница при этом убирается из +// фронта. +// Наследник этого класса должен определить правила: +// 1) Seed - правило выбора трех точек из набора для построения начального треугольника; +// 2) Place- правило выбора точки из набора для построения новых границ области из вершин +// текущей активной границы до этой точки. +// --- +class MbAdvancingFront +{ +public: + typedef std::list::iterator ListIterator; + + std::list front; // Список границ фронта области. + std::list internal; // Список внутренних границ области. + std::vector nb; // Вектор со значениями, соответствующими числу границ фронта, проходящих через точку с данным индексом. + MbPointCloud pointCloud; // Облако точек. + MbGrid & grid; // Объект триангуляции, который необходимо наполнить. + +public: + /// Конструктор. + MbAdvancingFront( const MbCollection & coll, MbGrid & _grid ) ; + /// Деструктор. + virtual ~MbAdvancingFront(); + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbAdvancingFront( const MbAdvancingFront & ); + +public: + /// Построить сетку. + void BuildMesh(); + +protected: + enum ListID { + edge_Front, // Внешняя граница. + edge_Internal // Внутреннее ребро. + }; + + typedef std::pair ResultIterator; + + // Найти точки для исходного(порождающего фронт) треугольника. + virtual bool Seed( size_t & v0, size_t & v1, size_t & v2 ) = 0; + // Найти точку для построения треугольника по заданному ребру. + virtual bool Place( MbFrontEdge & e, ResultIterator & touch, size_t & v ) = 0; + // Построить новый фронт по треугольнику. + bool SeedFace(); + // Расширить фронт путем поиска, присоединения точки и построения треугольника по активному ребру фронта. + bool Advance(); + // Добавить треугольник в сетку. + void AddTriangleToMesh( size_t v0, size_t v1, size_t v2 ); + // Проверить ребро: + // 1. На правильность ориентации, т.е. ребро (v0,v1) может быть включено в другие треугольники только с обратным направлением. + // 2. Ребро существует по краней мере в единственном экземпляре. + bool CheckEdge( size_t v0, size_t v1 ); + // Добавить новое ребро фронта в конец очереди. + ListIterator addNewEdge( const MbFrontEdge & e ); + // Квалифицировать ребро как внутреннюю границу. + void MoveEdgeToInternals( ListIterator e ); + // Удалить ребро. + void EraseEdge( ListIterator e ); + // Перемесить ребро в конец очереди. + void MoveBack( ListIterator e ); + // Перемесить ребро в начало очереди. + void MoveFront( ListIterator e ); + // Проверить, может ли ребро быть сшито с одним из соседей. + bool Glue( ListIterator e ); + // Склеить вместе два ребра, если a.next = b. + bool Glue( ListIterator a, ListIterator b ); + // Разорвать фронт в точке. + void Detach( size_t v ); + +private: + void operator = ( const MbAdvancingFront & ); +}; + + +//------------------------------------------------------------------------------- +// Алгоритм поворотного шара (Ball pivoting algorithm) +// Reference: Bernardini F., Mittleman J., Rushmeier H., Silva C., Taubin G. +// "The ball-pivoting algorithm for surface reconstruction", IEEE TVCG, 1999 +// 1) Точки, использованные в алгоритме маркируются как pnt_Visited; +// 2) Граничные точки сетки маркируются как pnt_Border; +// 3) В векторе nb по индексу вершины хранится количество ребер, проходяших через нее; +// 4) Точки, обработанные в алгоритме маркируются как pnt_Processed. +// --- +class MbBallPivoting: public MbAdvancingFront +{ +public: + double radius; // Радиус поворотного шара (абсолютная величина в единицах измерения сетки). + double minEdge; // Минимальная длина ребра. + double maxEdge; // Максимальная длина ребра. + double maxAngle; // Максимальный угол между двумя гранями сетки (косинус). + +public: + /// Конструктор. + MbBallPivoting( const MbCollection & coll, // Объект с облаком точек, + MbGrid & grid, // триангуляция, которую нужно наполнить/дополнить, + double radBall = 0.0, // радиус поворотного шара, если 0 будет предпринята попытка его автоопределения, + double radMin = 0.2, // радиус кластеризации ( в % от радиуса поворотного шара ), + double angle = M_PI / 2 ); // максимальный угол между двумя элементами сетки. + /// Деструктор. + ~MbBallPivoting(); + +protected: + // \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en The copy constructor without implementation prevents from copying by default. + MbBallPivoting( const MbBallPivoting & ); + +private: + /// Найти точки начального треугольника по алгоритму поворотного шара. + bool Seed( size_t & v0, size_t & v1, size_t & v2 ); + /// Найти точку для построения треугольника по заданному ребру согласно алгоритму поворотного шара. + bool Place( MbFrontEdge & edge, MbAdvancingFront::ResultIterator & touch, size_t & v ); + /// Найти сферу, проходящую через три заданных точки, такую что нормаль к грани через эти три точки направлена в центр сферы. + bool FindSphere( const MbCartPoint3D & p0, const MbCartPoint3D & p1, const MbCartPoint3D & p2, MbCartPoint3D & center ); + /// Рассчитать угол между векторами, учитывая ориентацию axis. + double OrientedAngleRad( MbVector3D p, MbVector3D q, const MbVector3D & axis ); + /// Пометить точку и ее соседей. + void Mark( size_t idx ); + +private: + size_t last_seed; // Испольуется для поиска нового фронта когда текущий фронт пуст. + MbCartPoint3D baricenter; // Используется для первого поиска. + KdTree * tree; // К-мерное дерево для поиска N ближайших соседей точки. + +private: + void operator = ( const MbBallPivoting & ); +}; + + #endif // __TRI_BALL_PIVOTING_H \ No newline at end of file diff --git a/C3d/Include/tri_face.h b/C3d/Include/tri_face.h index 901bda7..6be17c4 100644 --- a/C3d/Include/tri_face.h +++ b/C3d/Include/tri_face.h @@ -42,6 +42,8 @@ class MATH_CLASS MbCube; \en Whether to keep seam edges polygons and their coincident points. \~ \param[in] quad - \ru Строить четырёхугольники (true) при триангуляции поверхностей (по возможности). \en Whether to build quadrangles (true) in triangulations of surfaces (if possible). \~ + \param[in] fair - \ru Удалить вырожденные треугольники (true). + \en Degenerate triangles removing (if surface has pole). \~ \ingroup Triangulation */ // --- @@ -49,7 +51,8 @@ MATH_FUNC (void) CalculateGrid( const MbFace & face, const MbStepData & stepData, MbGrid & grid, bool dualSeams = true, - bool quad = false ); + bool quad = false, + bool fair = false ); //------------------------------------------------------------------------------ diff --git a/C3d/Include/tri_lump.h b/C3d/Include/tri_lump.h index b04cd0f..e2934f5 100644 --- a/C3d/Include/tri_lump.h +++ b/C3d/Include/tri_lump.h @@ -51,7 +51,15 @@ public: {} const MbFace & Face() const { return *face; } -//const MbGrid & Grid() const { return *grid; } + + /** \brief \ru Получить в виде пары указателей. + \en Get as a pair of pointers. + */ + template + void GetAsPair( std::pair & tied ) const + { + tied.first = face, tied.second = grid; + } MbFaceAndGrid & operator = ( const MbFaceAndGrid & faceGrid ) { diff --git a/C3d/Include/wire_frame.h b/C3d/Include/wire_frame.h index e1285cc..17f2cf9 100644 --- a/C3d/Include/wire_frame.h +++ b/C3d/Include/wire_frame.h @@ -12,6 +12,7 @@ #include +#include #include #include #include @@ -62,13 +63,17 @@ public : /// \ru Конструктор без параметров. \en Constructor without parameters. MbWireFrame(); /// \ru Конструктор по кривой и строителю. \en Constructor by a curve and creator. - MbWireFrame( const MbCurve3D &, MbCreator * = NULL ); + MbWireFrame( const MbCurve3D &, const MbCreator * = NULL ); /// \ru Конструктор по множеству кривых и строителю. \en Constructor by a set of curves and creator. - MbWireFrame( const RPArray &, MbCreator * = NULL ); + 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( MbEdge &, MbCreator * = NULL, bool same = true ); + MbWireFrame( const MbEdge &, const MbCreator * = NULL, bool same = true ); /// \ru Конструктор по множеству рёбер и строителю. \en Constructor by a set of edges and creator. - MbWireFrame( const RPArray &, MbCreator * = NULL, bool same = true ); + 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(); @@ -82,7 +87,7 @@ public : 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 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. @@ -109,17 +114,47 @@ public : /// \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 index ) const; + 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 index ); + 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( MbCurve3D &, bool sense = true ); + void AddEdge( const MbCurve3D &, bool sense = true ); /// \ru Добавить ребро (оригинал, не копию). \en Add an edge (an original, not a copy). - void AddEdge( MbEdge &, bool same = true ); + void AddEdge( const MbEdge &, bool same = true ); /// \ru Добавить массив ребер (оригиналы, не копии). \en Add an array of edges (originals, not copies). - void AddEdges( const RPArray &, bool same = true ); + 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, MbEdge & item, bool same = true ); + 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. @@ -133,6 +168,31 @@ public : 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; @@ -192,7 +252,7 @@ public : /// \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. - void NormalizeWire(); + bool NormalizeWire( double precision = METRIC_REGION ); /** \brief \ru Отделение частей каркаса. \en Detachment of frame parts \~ @@ -223,6 +283,7 @@ OBVIOUS_PRIVATE_COPY( MbWireFrame ) IMPL_PERSISTENT_OPS( MbWireFrame ) + //------------------------------------------------------------------------------ // \ru Положить в массив оригиналы кривых. \en Put originals of curves into an array. // --- @@ -231,7 +292,7 @@ void MbWireFrame::GetCurves( CurvesVector & curves ) const { size_t edgesCnt = edges.size(); curves.reserve( curves.size() + edgesCnt ); - SPtr curve; + c3d::SpaceCurveSPtr curve; for ( size_t k = 0; k < edgesCnt; ++k ) { const MbEdge * edge = edges[k]; if ( edge != NULL ) { @@ -243,6 +304,37 @@ void MbWireFrame::GetCurves( CurvesVector & curves ) const } +//------------------------------------------------------------------------------ +// \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. \~ @@ -255,24 +347,26 @@ void MbWireFrame::GetCurves( CurvesVector & curves ) const \ingroup Curve3D_Modeling */ // --- -inline -void ExtractCurvesDeleteFrame( MbWireFrame *& wireFrame, RPArray & curves ) +template +void ExtractCurvesDeleteFrame( MbWireFrame *& wireFrame, + CurvesVector & curves ) { if ( wireFrame != NULL ) { - c3d::SpaceCurvesSPtrVector curvesVect; - wireFrame->GetCurves( curvesVect ); - if ( curvesVect.size() > 0 ) { - curves.Reserve( curvesVect.size() ); - for ( size_t k = 0, cnt = curvesVect.size(); k < cnt; k++ ) { - MbCurve3D * curve = ::DetachItem( curvesVect[k] ); + 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.Add( curve ); + curves.push_back( curve ); } } } - ::AddRefItems( curves ); - ::DeleteItem( wireFrame ); - ::DecRefItems( curves ); } } @@ -290,19 +384,19 @@ void ExtractCurvesDeleteFrame( MbWireFrame *& wireFrame, RPArray & cu */ // --- inline -void ExtractCurveDeleteFrame( MbWireFrame *& wireFrame, MbCurve3D *& curve ) +void ExtractCurveDeleteFrame( MbWireFrame *& wireFrame, + MbCurve3D *& curve ) { if ( wireFrame != NULL ) { - MbEdge * edge = wireFrame->DetachEdge( 0 ); // \ru Отцепить объект \en Detach an object + c3d::WireEdgeSPtr edge( wireFrame->DetachEdge( 0 ) ); // \ru Отцепить объект \en Detach an object + ::DeleteItem( wireFrame ); + if ( edge != NULL ) { curve = &edge->SetCurve(); ::AddRefItem( curve ); - ::DeleteItem( edge ); - ::DeleteItem( wireFrame ); + edge = NULL; ::DecRefItem( curve ); } - else - ::DeleteItem( wireFrame ); } } @@ -328,7 +422,7 @@ void ExtractCurveDeleteFrame( MbWireFrame *& wireFrame, MbCurve3D *& curve ) MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, const RPArray & curves, const MbSNameMaker & snMaker, - MbCreator * creator = NULL ); + const MbCreator * creator = NULL ); //------------------------------------------------------------------------------ @@ -352,7 +446,7 @@ MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, MATH_FUNC (bool) CreateWireFrame( MbWireFrame *& result, const MbCurve3D & curve, const MbSNameMaker & snMaker, - MbCreator * creator = NULL ); + const MbCreator * creator = NULL ); #endif // __WIRE_FRAME_H diff --git a/C3d/Lib/x32/Debug/c3d.lib b/C3d/Lib/x32/Debug/c3d.lib index 66d8631..4f4bd2b 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 8cbecf6..79fe122 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 69909cd..396c4d3 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 1fb5ce1..73ad20e 100644 Binary files a/C3d/Lib/x64/Release/c3d.lib and b/C3d/Lib/x64/Release/c3d.lib differ