Files
Extern/C3d/Include/gce_kompas_interface.h
SaraP 827b79f766 Extern :
- C3d aggiornamento delle librerie ( 117987).
2024-04-16 14:59:59 +02:00

239 lines
14 KiB
C++

//////////////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief \ru Программный интерфейс для системы КОМПАС
\en Program interface for KOMPAS system. \~
\details \ru Данный файл содержит классы и методы, ориентированные на типы
данных CAD-системы КОМПАС. Для других приложений это API может оказаться
не удобным, а его методы могут быть удалены или изменены в будущих
версиях. Рекомендуется применять эту часть API решателя, только если
не удасться найти требуемую функциональность в заголовочных файлах
gce_api.h или gce_types.h.
\en This file contains classes and methods oriented to
data types of CAD-system KOMPAS. For other applications this API can be
inconvenient and its methods can be deleted or modified in future
versions. It is recommended to apply this part of solver API only if
the required functionality is not found in header files
gce_api.h or gce_types.h. \~
*/
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef __GCE_KOMPAS_INTERFACE_H
#define __GCE_KOMPAS_INTERFACE_H
#include <mt_ref_item.h>
#include <mb_cart_point.h>
#include <pars_tree_variable.h>
//
#include "gce_geom.h"
#include <vector>
class MtVectorN;
template <class Type> class RPArray;
//----------------------------------------------------------------------------------------
/** \brief \ru Интерфейс численного уравнения, выраженного через набо координат.
\en Interface of the numeric equation expressed via a set of coordinates.
\details \ru Как правило, это алгебраические уравнение общего вида f(x1,x2,..,xn) = g(x1,x2,..,xn)
явно-выраженной форме: x1 = g(x2,x3,..,xn).
\en As a rule, it is an algebraic equation of a general form f(x1,x2,..,xn) = g(x1,x2,..,xn)
or, as a special case, it is an equation in explicit form: x1 = g(x2,x3,..,xn). \~
*/
//---
struct GCE_CLASS ItNumericEquation
{
enum eval_result_code: char
{
EVAL_RESULT_Undefined = 0,
EVAL_RESULT_Ok,
EVAL_RESULT_OutOfDomaint
};
struct eval_result
{
eval_result_code resCode = EVAL_RESULT_Undefined;
double funDer = MB_MAXDOUBLE; // Derivative value.
double funVal = MB_MAXDOUBLE; // Function value.
};
/// \ru Выдать координату с индексом crdIdx. \en Get coordinate with crdIdx index.
virtual ItCoord* Coord( size_t crdIdx ) const = 0;
/// \ru Количество координат, связанных с уравнением. \en Count of coordinates connected with the equation.
virtual size_t NumCoords() const = 0;
/// \ru Вычисление первой производной по координате и значений функции. \en The first derivative by coordinate and the function values calculation.
virtual eval_result Evaluate(const ItCoord* crd, const std::vector<double>& crdVals) const;
/// \ru Выдать координату зависимой переменной (для уравнений заданных в явно-выраженной форме). \en Get the coordinate of dependent variable (for explicit equations).
virtual const ItCoord* DependedCoord() const = 0;
/** \brief \ru Признак уравнения, заданного в форме присвоения (начиная с Компас V12).
\en Flag of equation specified in form of assignment.
\details
\ru Уравнения, заданные в явно выраженной форме, считающиеся присвоением выражения зависимой переменной: x1 = g(x2,x3,..,xn).
Такие уравнения стремимся вычислять иерархическим способом, сверху-вниз.
\en Equations specified explicitly, considered to be the assignment of dependent variable: x1 = g(x2,x3,..,xn).
It is preferred to compute such equations by hierarchical top-down method. \~
*/
virtual bool IsExplicit() const = 0;
public:
virtual refcount_t AddRef() const = 0;
virtual refcount_t Release() const = 0;
private:
// It will be removed
virtual bool CalcDerive( ItGeomCoord &, const MtVectorN &, double &, double & ) const { return false; }
// It will be removed.
virtual ItGeomCoord * GetCoord( ptrdiff_t ) const { return nullptr; }
// It will be removed.
virtual bool CalcDerive( ItGeomCoord &, const std::vector<double> & /*argLine*/, double & /*fd*/, double & /*f*/ ) const { return false; }
// It will be removed.
virtual ptrdiff_t GetCoordCount() const { return 0; }
// It will be removed.
virtual ptrdiff_t GetDependedCoordIdx() const { return -1; }
protected:
~ItNumericEquation() {}
};
//----------------------------------------------------------------------------------------
// \ru Вычисление первой производной по координате и значений функции. \en The first derivative by coordinate and the function values calculation.
//---
inline ItNumericEquation::eval_result ItNumericEquation::Evaluate(const ItCoord* crd, const std::vector<double>& crdVals) const
{
eval_result res;
ItGeomCoord * gCrd = dynamic_cast<ItGeomCoord*>(const_cast<ItCoord*>(crd));
if ( gCrd!=nullptr && CalcDerive(*gCrd, crdVals, res.funDer, res.funVal))
{
res.resCode = EVAL_RESULT_Ok;
}
return res;
}
using ItAlgebraicConstraint = ItNumericEquation;
/**
\addtogroup Constraints2D_API
\{
*/
//----------------------------------------------------------------------------------------
/// \ru Задать ограничение, реализуемое на стороне клиента \en Specify a constraint implemented by the user
/**
\param \ru gSys контекст решателя
\en gSys the solver context \~
\param \ru iEqu интерфейс уравнения, заданного пользователем
\en iEqu interface of the equation specified by the user \~
\param \ru varsCount количество переменных
\en varsCount count of variables \~
\param \ru varsVector вектор переменных
\en varsVector vector of variables \~
\return \ru дескриптор нового ограничения
\en descriptor of a new constraint \~
*/
// ---
GCE_FUNC(constraint_item) GCE_AddEquation( GCE_system gSys
, ItAlgebraicConstraint & iEqu
, size_t varsCount
, const var_item * varsVector );
//----------------------------------------------------------------------------------------
/// \ru Определить смежные ли это ограничение и геометрический объект \en Determine whether the constraint and the geometric object are adjacent
//---
GCE_FUNC(bool) GCE_IsAdjacentConstraint( GCE_system gSys
, geom_item g
, constraint_item c );
//----------------------------------------------------------------------------------------
/// \ru Получить текущие координаты точки \en Get the current coordinates of point
/**
\param \ru gSys контекст решателя
\en gSys the solver context \~
\param \ru g дескриптор точки или иного геометрического объекта
\en g descriptor of a point or other geometric object \~
\param \ru pName идентификатор точки, принадлежащей объекту
\en pName identifier of a point belonging to the object \~
\return \ru координаты точки
\en point coordinates \~
*/
//---
GCE_FUNC(MbCartPoint) GCE_GetPoint( GCE_system gSys
, geom_item g
, point_type pName = GCE_PROPER_POINT );
/**
\}
Constraints2D_API
*/
//----------------------------------------------------------------------------------------
/*
\brief \ru Добавить геометрический объект. \en Add a geometric object. \~
\details \ru Регистрирует объект пользователя в контексе решателя.
Пользователь отвечает за время жизни этого объекта в контексте
решателя и обязан в нужный момент также и удалить (разрегистрировать)
объект (см. #GCE_RemoveGeom).
\en Register a user object in the solver context.
The user is responsible for the object life time in the context
of the solver and must delete (unregister) it at the appropriate time
object (see #GCE_RemoveGeom). \~
*/
/**
\attention \ru Устаревшая функция. Вызов будет удален в одной из следующих версий (2016).
\en An obsolete function. The call will be removed in one of the next versions. \~
*/
GCE_FUNC(geom_item) GCE_AddGeom( GCE_system gSys, IfGeom2d & );
//----------------------------------------------------------------------------------------
/** \brief \ru Варианты выравнивания направлений.
\en Variants of alignment. \~
\details \en Значение опции выравнивания используется для выбора из альтернативных решений
ограничения, такого как `GCE_TANGENT`.
\en The alignment value is used to alternate between solutions of a constraint such as `GCE_TANGENT`.
\note \ru Значения этого перечисления могут быть использованы для постоянного хранения и
останутся неизменными в следующих версиях.
\en Values of this enum can be used for permanent storage and will be kept
in the future versions. \~
*/
//---
typedef enum
{
GCE_NO_ALIGNMENT = 0, ///< \ru Неопределенное значение выравнивания (=не применима к данному ограничению). \en Undefined alignment value (=not applicable to this constraint).
GCE_COORIENTED, ///< \ru Для касания это сонаправленные касательные вектора (=нормали). \en For tangency, these are co-directional tangent vectors (=normal).
GCE_OPPOSITE, ///< \ru Для касания это противонаправленные касательные вектора (=нормали). \en For tangency, these are the opposing tangent vectors (=normal).
/** \brief \ru Поддерживать способ выравнивания согласно начальному или текущему положению геометрии (соответствует поведению прежних версий).
\en Maintain the alignment according to the initial or current position of the geometry (reproduces behaviour from previous versions). \~ */
GCE_CLOSEST,
/** \brief \ru Автоматически выбрать опцию выравнивания, используя начальное приближение геометрии.
\en Automatically determine alignment options using initial geometry approximation. \~ */
GCE_AUTO_ALIGNMENT,
} GCE_alignment;
//----------------------------------------------------------------------------------------
/// \ru Задать ориентацию касания. \en Set the tangent orientation.
/**
\param[in] \ru gSys Система ограничений.
\en gSys System of constraints. \~
\param[in] \ru constraint Дескриптор ограничения.
\en constraint Constraint's descriptor. \~
\param[in] \ru alignment Опция выравнивания касания кривых.
\en alignment Curve tangency alignment option. \~
\return \ru В случае успешного вызова функция вернет новое значение выравнивания, заданного вызовом.
\en If the call is successful, the function will return the new alignment value specified by the call. \~
\details
\ru В настоящее время функция применяется к ограничению касания (GCE_TANGENT). Данный вызов устанавливает
сонаправленность или противонаправленность касательных (GCE_COORIENTED, GCE_OPPOSITE),
либо делает выбор автоматически, если задать опцию GCE_AUTO_ALIGNMENT. Когда выбрана опцию GCE_CLOSEST,
солвер будет поддерживать взаимную ориентацию согласно текущего размещения геометрии.
\en The function currently applies to the tangency constraint (GCE_TANGENT). The call sets whether
the direction of the geometry tangents are cooriented/opposite or makes the selection automatically
if you set the GCE_AUTO_ALIGNMENT option. When the option GCE_CLOSEST is selected the C3D Solver
should maintain the current geometry positions. \~
*/
//---
GCE_FUNC(GCE_alignment) GCE_SetAlignment( GCE_system gSys, constraint_item constraint, GCE_alignment alignment = GCE_AUTO_ALIGNMENT );
#endif // __GCE_KOMPAS_INTERFACE_H
// eof